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 if (code == (BPF_JMP32 | BPF_JA))
2859 off = i + insn[i].imm + 1;
2861 off = i + insn[i].off + 1;
2862 if (off < subprog_start || off >= subprog_end) {
2863 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2867 if (i == subprog_end - 1) {
2868 /* to avoid fall-through from one subprog into another
2869 * the last insn of the subprog should be either exit
2870 * or unconditional jump back
2872 if (code != (BPF_JMP | BPF_EXIT) &&
2873 code != (BPF_JMP32 | BPF_JA) &&
2874 code != (BPF_JMP | BPF_JA)) {
2875 verbose(env, "last insn is not an exit or jmp\n");
2878 subprog_start = subprog_end;
2880 if (cur_subprog < env->subprog_cnt)
2881 subprog_end = subprog[cur_subprog + 1].start;
2887 /* Parentage chain of this register (or stack slot) should take care of all
2888 * issues like callee-saved registers, stack slot allocation time, etc.
2890 static int mark_reg_read(struct bpf_verifier_env *env,
2891 const struct bpf_reg_state *state,
2892 struct bpf_reg_state *parent, u8 flag)
2894 bool writes = parent == state->parent; /* Observe write marks */
2898 /* if read wasn't screened by an earlier write ... */
2899 if (writes && state->live & REG_LIVE_WRITTEN)
2901 if (parent->live & REG_LIVE_DONE) {
2902 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2903 reg_type_str(env, parent->type),
2904 parent->var_off.value, parent->off);
2907 /* The first condition is more likely to be true than the
2908 * second, checked it first.
2910 if ((parent->live & REG_LIVE_READ) == flag ||
2911 parent->live & REG_LIVE_READ64)
2912 /* The parentage chain never changes and
2913 * this parent was already marked as LIVE_READ.
2914 * There is no need to keep walking the chain again and
2915 * keep re-marking all parents as LIVE_READ.
2916 * This case happens when the same register is read
2917 * multiple times without writes into it in-between.
2918 * Also, if parent has the stronger REG_LIVE_READ64 set,
2919 * then no need to set the weak REG_LIVE_READ32.
2922 /* ... then we depend on parent's value */
2923 parent->live |= flag;
2924 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2925 if (flag == REG_LIVE_READ64)
2926 parent->live &= ~REG_LIVE_READ32;
2928 parent = state->parent;
2933 if (env->longest_mark_read_walk < cnt)
2934 env->longest_mark_read_walk = cnt;
2938 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2940 struct bpf_func_state *state = func(env, reg);
2943 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2944 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2947 if (reg->type == CONST_PTR_TO_DYNPTR)
2949 spi = dynptr_get_spi(env, reg);
2952 /* Caller ensures dynptr is valid and initialized, which means spi is in
2953 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2956 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2957 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2960 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2961 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2964 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2965 int spi, int nr_slots)
2967 struct bpf_func_state *state = func(env, reg);
2970 for (i = 0; i < nr_slots; i++) {
2971 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2973 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2977 mark_stack_slot_scratched(env, spi - i);
2983 /* This function is supposed to be used by the following 32-bit optimization
2984 * code only. It returns TRUE if the source or destination register operates
2985 * on 64-bit, otherwise return FALSE.
2987 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2988 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2993 class = BPF_CLASS(code);
2995 if (class == BPF_JMP) {
2996 /* BPF_EXIT for "main" will reach here. Return TRUE
3001 if (op == BPF_CALL) {
3002 /* BPF to BPF call will reach here because of marking
3003 * caller saved clobber with DST_OP_NO_MARK for which we
3004 * don't care the register def because they are anyway
3005 * marked as NOT_INIT already.
3007 if (insn->src_reg == BPF_PSEUDO_CALL)
3009 /* Helper call will reach here because of arg type
3010 * check, conservatively return TRUE.
3019 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3022 if (class == BPF_ALU64 || class == BPF_JMP ||
3023 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3026 if (class == BPF_ALU || class == BPF_JMP32)
3029 if (class == BPF_LDX) {
3031 return BPF_SIZE(code) == BPF_DW;
3032 /* LDX source must be ptr. */
3036 if (class == BPF_STX) {
3037 /* BPF_STX (including atomic variants) has multiple source
3038 * operands, one of which is a ptr. Check whether the caller is
3041 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3043 return BPF_SIZE(code) == BPF_DW;
3046 if (class == BPF_LD) {
3047 u8 mode = BPF_MODE(code);
3050 if (mode == BPF_IMM)
3053 /* Both LD_IND and LD_ABS return 32-bit data. */
3057 /* Implicit ctx ptr. */
3058 if (regno == BPF_REG_6)
3061 /* Explicit source could be any width. */
3065 if (class == BPF_ST)
3066 /* The only source register for BPF_ST is a ptr. */
3069 /* Conservatively return true at default. */
3073 /* Return the regno defined by the insn, or -1. */
3074 static int insn_def_regno(const struct bpf_insn *insn)
3076 switch (BPF_CLASS(insn->code)) {
3082 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3083 (insn->imm & BPF_FETCH)) {
3084 if (insn->imm == BPF_CMPXCHG)
3087 return insn->src_reg;
3092 return insn->dst_reg;
3096 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3097 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3099 int dst_reg = insn_def_regno(insn);
3104 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3107 static void mark_insn_zext(struct bpf_verifier_env *env,
3108 struct bpf_reg_state *reg)
3110 s32 def_idx = reg->subreg_def;
3112 if (def_idx == DEF_NOT_SUBREG)
3115 env->insn_aux_data[def_idx - 1].zext_dst = true;
3116 /* The dst will be zero extended, so won't be sub-register anymore. */
3117 reg->subreg_def = DEF_NOT_SUBREG;
3120 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3121 enum reg_arg_type t)
3123 struct bpf_verifier_state *vstate = env->cur_state;
3124 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3125 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3126 struct bpf_reg_state *reg, *regs = state->regs;
3129 if (regno >= MAX_BPF_REG) {
3130 verbose(env, "R%d is invalid\n", regno);
3134 mark_reg_scratched(env, regno);
3137 rw64 = is_reg64(env, insn, regno, reg, t);
3139 /* check whether register used as source operand can be read */
3140 if (reg->type == NOT_INIT) {
3141 verbose(env, "R%d !read_ok\n", regno);
3144 /* We don't need to worry about FP liveness because it's read-only */
3145 if (regno == BPF_REG_FP)
3149 mark_insn_zext(env, reg);
3151 return mark_reg_read(env, reg, reg->parent,
3152 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3154 /* check whether register used as dest operand can be written to */
3155 if (regno == BPF_REG_FP) {
3156 verbose(env, "frame pointer is read only\n");
3159 reg->live |= REG_LIVE_WRITTEN;
3160 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3162 mark_reg_unknown(env, regs, regno);
3167 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3169 env->insn_aux_data[idx].jmp_point = true;
3172 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3174 return env->insn_aux_data[insn_idx].jmp_point;
3177 /* for any branch, call, exit record the history of jmps in the given state */
3178 static int push_jmp_history(struct bpf_verifier_env *env,
3179 struct bpf_verifier_state *cur)
3181 u32 cnt = cur->jmp_history_cnt;
3182 struct bpf_idx_pair *p;
3185 if (!is_jmp_point(env, env->insn_idx))
3189 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3190 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3193 p[cnt - 1].idx = env->insn_idx;
3194 p[cnt - 1].prev_idx = env->prev_insn_idx;
3195 cur->jmp_history = p;
3196 cur->jmp_history_cnt = cnt;
3200 /* Backtrack one insn at a time. If idx is not at the top of recorded
3201 * history then previous instruction came from straight line execution.
3203 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3208 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3209 i = st->jmp_history[cnt - 1].prev_idx;
3217 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3219 const struct btf_type *func;
3220 struct btf *desc_btf;
3222 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3225 desc_btf = find_kfunc_desc_btf(data, insn->off);
3226 if (IS_ERR(desc_btf))
3229 func = btf_type_by_id(desc_btf, insn->imm);
3230 return btf_name_by_offset(desc_btf, func->name_off);
3233 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3238 static inline void bt_reset(struct backtrack_state *bt)
3240 struct bpf_verifier_env *env = bt->env;
3242 memset(bt, 0, sizeof(*bt));
3246 static inline u32 bt_empty(struct backtrack_state *bt)
3251 for (i = 0; i <= bt->frame; i++)
3252 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3257 static inline int bt_subprog_enter(struct backtrack_state *bt)
3259 if (bt->frame == MAX_CALL_FRAMES - 1) {
3260 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3261 WARN_ONCE(1, "verifier backtracking bug");
3268 static inline int bt_subprog_exit(struct backtrack_state *bt)
3270 if (bt->frame == 0) {
3271 verbose(bt->env, "BUG subprog exit from frame 0\n");
3272 WARN_ONCE(1, "verifier backtracking bug");
3279 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3281 bt->reg_masks[frame] |= 1 << reg;
3284 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3286 bt->reg_masks[frame] &= ~(1 << reg);
3289 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3291 bt_set_frame_reg(bt, bt->frame, reg);
3294 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3296 bt_clear_frame_reg(bt, bt->frame, reg);
3299 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3301 bt->stack_masks[frame] |= 1ull << slot;
3304 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3306 bt->stack_masks[frame] &= ~(1ull << slot);
3309 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3311 bt_set_frame_slot(bt, bt->frame, slot);
3314 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3316 bt_clear_frame_slot(bt, bt->frame, slot);
3319 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3321 return bt->reg_masks[frame];
3324 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3326 return bt->reg_masks[bt->frame];
3329 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3331 return bt->stack_masks[frame];
3334 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3336 return bt->stack_masks[bt->frame];
3339 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3341 return bt->reg_masks[bt->frame] & (1 << reg);
3344 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3346 return bt->stack_masks[bt->frame] & (1ull << slot);
3349 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3350 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3352 DECLARE_BITMAP(mask, 64);
3358 bitmap_from_u64(mask, reg_mask);
3359 for_each_set_bit(i, mask, 32) {
3360 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3368 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3369 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3371 DECLARE_BITMAP(mask, 64);
3377 bitmap_from_u64(mask, stack_mask);
3378 for_each_set_bit(i, mask, 64) {
3379 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3388 /* For given verifier state backtrack_insn() is called from the last insn to
3389 * the first insn. Its purpose is to compute a bitmask of registers and
3390 * stack slots that needs precision in the parent verifier state.
3392 * @idx is an index of the instruction we are currently processing;
3393 * @subseq_idx is an index of the subsequent instruction that:
3394 * - *would be* executed next, if jump history is viewed in forward order;
3395 * - *was* processed previously during backtracking.
3397 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3398 struct backtrack_state *bt)
3400 const struct bpf_insn_cbs cbs = {
3401 .cb_call = disasm_kfunc_name,
3402 .cb_print = verbose,
3403 .private_data = env,
3405 struct bpf_insn *insn = env->prog->insnsi + idx;
3406 u8 class = BPF_CLASS(insn->code);
3407 u8 opcode = BPF_OP(insn->code);
3408 u8 mode = BPF_MODE(insn->code);
3409 u32 dreg = insn->dst_reg;
3410 u32 sreg = insn->src_reg;
3413 if (insn->code == 0)
3415 if (env->log.level & BPF_LOG_LEVEL2) {
3416 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3417 verbose(env, "mark_precise: frame%d: regs=%s ",
3418 bt->frame, env->tmp_str_buf);
3419 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3420 verbose(env, "stack=%s before ", env->tmp_str_buf);
3421 verbose(env, "%d: ", idx);
3422 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3425 if (class == BPF_ALU || class == BPF_ALU64) {
3426 if (!bt_is_reg_set(bt, dreg))
3428 if (opcode == BPF_MOV) {
3429 if (BPF_SRC(insn->code) == BPF_X) {
3430 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3431 * dreg needs precision after this insn
3432 * sreg needs precision before this insn
3434 bt_clear_reg(bt, dreg);
3435 bt_set_reg(bt, sreg);
3438 * dreg needs precision after this insn.
3439 * Corresponding register is already marked
3440 * as precise=true in this verifier state.
3441 * No further markings in parent are necessary
3443 bt_clear_reg(bt, dreg);
3446 if (BPF_SRC(insn->code) == BPF_X) {
3448 * both dreg and sreg need precision
3451 bt_set_reg(bt, sreg);
3453 * dreg still needs precision before this insn
3456 } else if (class == BPF_LDX) {
3457 if (!bt_is_reg_set(bt, dreg))
3459 bt_clear_reg(bt, dreg);
3461 /* scalars can only be spilled into stack w/o losing precision.
3462 * Load from any other memory can be zero extended.
3463 * The desire to keep that precision is already indicated
3464 * by 'precise' mark in corresponding register of this state.
3465 * No further tracking necessary.
3467 if (insn->src_reg != BPF_REG_FP)
3470 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3471 * that [fp - off] slot contains scalar that needs to be
3472 * tracked with precision
3474 spi = (-insn->off - 1) / BPF_REG_SIZE;
3476 verbose(env, "BUG spi %d\n", spi);
3477 WARN_ONCE(1, "verifier backtracking bug");
3480 bt_set_slot(bt, spi);
3481 } else if (class == BPF_STX || class == BPF_ST) {
3482 if (bt_is_reg_set(bt, dreg))
3483 /* stx & st shouldn't be using _scalar_ dst_reg
3484 * to access memory. It means backtracking
3485 * encountered a case of pointer subtraction.
3488 /* scalars can only be spilled into stack */
3489 if (insn->dst_reg != BPF_REG_FP)
3491 spi = (-insn->off - 1) / BPF_REG_SIZE;
3493 verbose(env, "BUG spi %d\n", spi);
3494 WARN_ONCE(1, "verifier backtracking bug");
3497 if (!bt_is_slot_set(bt, spi))
3499 bt_clear_slot(bt, spi);
3500 if (class == BPF_STX)
3501 bt_set_reg(bt, sreg);
3502 } else if (class == BPF_JMP || class == BPF_JMP32) {
3503 if (bpf_pseudo_call(insn)) {
3504 int subprog_insn_idx, subprog;
3506 subprog_insn_idx = idx + insn->imm + 1;
3507 subprog = find_subprog(env, subprog_insn_idx);
3511 if (subprog_is_global(env, subprog)) {
3512 /* check that jump history doesn't have any
3513 * extra instructions from subprog; the next
3514 * instruction after call to global subprog
3515 * should be literally next instruction in
3518 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3519 /* r1-r5 are invalidated after subprog call,
3520 * so for global func call it shouldn't be set
3523 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3524 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3525 WARN_ONCE(1, "verifier backtracking bug");
3528 /* global subprog always sets R0 */
3529 bt_clear_reg(bt, BPF_REG_0);
3532 /* static subprog call instruction, which
3533 * means that we are exiting current subprog,
3534 * so only r1-r5 could be still requested as
3535 * precise, r0 and r6-r10 or any stack slot in
3536 * the current frame should be zero by now
3538 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3539 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3540 WARN_ONCE(1, "verifier backtracking bug");
3543 /* we don't track register spills perfectly,
3544 * so fallback to force-precise instead of failing */
3545 if (bt_stack_mask(bt) != 0)
3547 /* propagate r1-r5 to the caller */
3548 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3549 if (bt_is_reg_set(bt, i)) {
3550 bt_clear_reg(bt, i);
3551 bt_set_frame_reg(bt, bt->frame - 1, i);
3554 if (bt_subprog_exit(bt))
3558 } else if ((bpf_helper_call(insn) &&
3559 is_callback_calling_function(insn->imm) &&
3560 !is_async_callback_calling_function(insn->imm)) ||
3561 (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3562 /* callback-calling helper or kfunc call, which means
3563 * we are exiting from subprog, but unlike the subprog
3564 * call handling above, we shouldn't propagate
3565 * precision of r1-r5 (if any requested), as they are
3566 * not actually arguments passed directly to callback
3569 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3570 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3571 WARN_ONCE(1, "verifier backtracking bug");
3574 if (bt_stack_mask(bt) != 0)
3576 /* clear r1-r5 in callback subprog's mask */
3577 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3578 bt_clear_reg(bt, i);
3579 if (bt_subprog_exit(bt))
3582 } else if (opcode == BPF_CALL) {
3583 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3584 * catch this error later. Make backtracking conservative
3587 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3589 /* regular helper call sets R0 */
3590 bt_clear_reg(bt, BPF_REG_0);
3591 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3592 /* if backtracing was looking for registers R1-R5
3593 * they should have been found already.
3595 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3596 WARN_ONCE(1, "verifier backtracking bug");
3599 } else if (opcode == BPF_EXIT) {
3602 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3603 /* if backtracing was looking for registers R1-R5
3604 * they should have been found already.
3606 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3607 WARN_ONCE(1, "verifier backtracking bug");
3611 /* BPF_EXIT in subprog or callback always returns
3612 * right after the call instruction, so by checking
3613 * whether the instruction at subseq_idx-1 is subprog
3614 * call or not we can distinguish actual exit from
3615 * *subprog* from exit from *callback*. In the former
3616 * case, we need to propagate r0 precision, if
3617 * necessary. In the former we never do that.
3619 r0_precise = subseq_idx - 1 >= 0 &&
3620 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3621 bt_is_reg_set(bt, BPF_REG_0);
3623 bt_clear_reg(bt, BPF_REG_0);
3624 if (bt_subprog_enter(bt))
3628 bt_set_reg(bt, BPF_REG_0);
3629 /* r6-r9 and stack slots will stay set in caller frame
3630 * bitmasks until we return back from callee(s)
3633 } else if (BPF_SRC(insn->code) == BPF_X) {
3634 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3637 * Both dreg and sreg need precision before
3638 * this insn. If only sreg was marked precise
3639 * before it would be equally necessary to
3640 * propagate it to dreg.
3642 bt_set_reg(bt, dreg);
3643 bt_set_reg(bt, sreg);
3644 /* else dreg <cond> K
3645 * Only dreg still needs precision before
3646 * this insn, so for the K-based conditional
3647 * there is nothing new to be marked.
3650 } else if (class == BPF_LD) {
3651 if (!bt_is_reg_set(bt, dreg))
3653 bt_clear_reg(bt, dreg);
3654 /* It's ld_imm64 or ld_abs or ld_ind.
3655 * For ld_imm64 no further tracking of precision
3656 * into parent is necessary
3658 if (mode == BPF_IND || mode == BPF_ABS)
3659 /* to be analyzed */
3665 /* the scalar precision tracking algorithm:
3666 * . at the start all registers have precise=false.
3667 * . scalar ranges are tracked as normal through alu and jmp insns.
3668 * . once precise value of the scalar register is used in:
3669 * . ptr + scalar alu
3670 * . if (scalar cond K|scalar)
3671 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3672 * backtrack through the verifier states and mark all registers and
3673 * stack slots with spilled constants that these scalar regisers
3674 * should be precise.
3675 * . during state pruning two registers (or spilled stack slots)
3676 * are equivalent if both are not precise.
3678 * Note the verifier cannot simply walk register parentage chain,
3679 * since many different registers and stack slots could have been
3680 * used to compute single precise scalar.
3682 * The approach of starting with precise=true for all registers and then
3683 * backtrack to mark a register as not precise when the verifier detects
3684 * that program doesn't care about specific value (e.g., when helper
3685 * takes register as ARG_ANYTHING parameter) is not safe.
3687 * It's ok to walk single parentage chain of the verifier states.
3688 * It's possible that this backtracking will go all the way till 1st insn.
3689 * All other branches will be explored for needing precision later.
3691 * The backtracking needs to deal with cases like:
3692 * 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)
3695 * if r5 > 0x79f goto pc+7
3696 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3699 * call bpf_perf_event_output#25
3700 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3704 * call foo // uses callee's r6 inside to compute r0
3708 * to track above reg_mask/stack_mask needs to be independent for each frame.
3710 * Also if parent's curframe > frame where backtracking started,
3711 * the verifier need to mark registers in both frames, otherwise callees
3712 * may incorrectly prune callers. This is similar to
3713 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3715 * For now backtracking falls back into conservative marking.
3717 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3718 struct bpf_verifier_state *st)
3720 struct bpf_func_state *func;
3721 struct bpf_reg_state *reg;
3724 if (env->log.level & BPF_LOG_LEVEL2) {
3725 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3729 /* big hammer: mark all scalars precise in this path.
3730 * pop_stack may still get !precise scalars.
3731 * We also skip current state and go straight to first parent state,
3732 * because precision markings in current non-checkpointed state are
3733 * not needed. See why in the comment in __mark_chain_precision below.
3735 for (st = st->parent; st; st = st->parent) {
3736 for (i = 0; i <= st->curframe; i++) {
3737 func = st->frame[i];
3738 for (j = 0; j < BPF_REG_FP; j++) {
3739 reg = &func->regs[j];
3740 if (reg->type != SCALAR_VALUE || reg->precise)
3742 reg->precise = true;
3743 if (env->log.level & BPF_LOG_LEVEL2) {
3744 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3748 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3749 if (!is_spilled_reg(&func->stack[j]))
3751 reg = &func->stack[j].spilled_ptr;
3752 if (reg->type != SCALAR_VALUE || reg->precise)
3754 reg->precise = true;
3755 if (env->log.level & BPF_LOG_LEVEL2) {
3756 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3764 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3766 struct bpf_func_state *func;
3767 struct bpf_reg_state *reg;
3770 for (i = 0; i <= st->curframe; i++) {
3771 func = st->frame[i];
3772 for (j = 0; j < BPF_REG_FP; j++) {
3773 reg = &func->regs[j];
3774 if (reg->type != SCALAR_VALUE)
3776 reg->precise = false;
3778 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3779 if (!is_spilled_reg(&func->stack[j]))
3781 reg = &func->stack[j].spilled_ptr;
3782 if (reg->type != SCALAR_VALUE)
3784 reg->precise = false;
3789 static bool idset_contains(struct bpf_idset *s, u32 id)
3793 for (i = 0; i < s->count; ++i)
3794 if (s->ids[i] == id)
3800 static int idset_push(struct bpf_idset *s, u32 id)
3802 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3804 s->ids[s->count++] = id;
3808 static void idset_reset(struct bpf_idset *s)
3813 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3814 * Mark all registers with these IDs as precise.
3816 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3818 struct bpf_idset *precise_ids = &env->idset_scratch;
3819 struct backtrack_state *bt = &env->bt;
3820 struct bpf_func_state *func;
3821 struct bpf_reg_state *reg;
3822 DECLARE_BITMAP(mask, 64);
3825 idset_reset(precise_ids);
3827 for (fr = bt->frame; fr >= 0; fr--) {
3828 func = st->frame[fr];
3830 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3831 for_each_set_bit(i, mask, 32) {
3832 reg = &func->regs[i];
3833 if (!reg->id || reg->type != SCALAR_VALUE)
3835 if (idset_push(precise_ids, reg->id))
3839 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3840 for_each_set_bit(i, mask, 64) {
3841 if (i >= func->allocated_stack / BPF_REG_SIZE)
3843 if (!is_spilled_scalar_reg(&func->stack[i]))
3845 reg = &func->stack[i].spilled_ptr;
3848 if (idset_push(precise_ids, reg->id))
3853 for (fr = 0; fr <= st->curframe; ++fr) {
3854 func = st->frame[fr];
3856 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3857 reg = &func->regs[i];
3860 if (!idset_contains(precise_ids, reg->id))
3862 bt_set_frame_reg(bt, fr, i);
3864 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3865 if (!is_spilled_scalar_reg(&func->stack[i]))
3867 reg = &func->stack[i].spilled_ptr;
3870 if (!idset_contains(precise_ids, reg->id))
3872 bt_set_frame_slot(bt, fr, i);
3880 * __mark_chain_precision() backtracks BPF program instruction sequence and
3881 * chain of verifier states making sure that register *regno* (if regno >= 0)
3882 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3883 * SCALARS, as well as any other registers and slots that contribute to
3884 * a tracked state of given registers/stack slots, depending on specific BPF
3885 * assembly instructions (see backtrack_insns() for exact instruction handling
3886 * logic). This backtracking relies on recorded jmp_history and is able to
3887 * traverse entire chain of parent states. This process ends only when all the
3888 * necessary registers/slots and their transitive dependencies are marked as
3891 * One important and subtle aspect is that precise marks *do not matter* in
3892 * the currently verified state (current state). It is important to understand
3893 * why this is the case.
3895 * First, note that current state is the state that is not yet "checkpointed",
3896 * i.e., it is not yet put into env->explored_states, and it has no children
3897 * states as well. It's ephemeral, and can end up either a) being discarded if
3898 * compatible explored state is found at some point or BPF_EXIT instruction is
3899 * reached or b) checkpointed and put into env->explored_states, branching out
3900 * into one or more children states.
3902 * In the former case, precise markings in current state are completely
3903 * ignored by state comparison code (see regsafe() for details). Only
3904 * checkpointed ("old") state precise markings are important, and if old
3905 * state's register/slot is precise, regsafe() assumes current state's
3906 * register/slot as precise and checks value ranges exactly and precisely. If
3907 * states turn out to be compatible, current state's necessary precise
3908 * markings and any required parent states' precise markings are enforced
3909 * after the fact with propagate_precision() logic, after the fact. But it's
3910 * important to realize that in this case, even after marking current state
3911 * registers/slots as precise, we immediately discard current state. So what
3912 * actually matters is any of the precise markings propagated into current
3913 * state's parent states, which are always checkpointed (due to b) case above).
3914 * As such, for scenario a) it doesn't matter if current state has precise
3915 * markings set or not.
3917 * Now, for the scenario b), checkpointing and forking into child(ren)
3918 * state(s). Note that before current state gets to checkpointing step, any
3919 * processed instruction always assumes precise SCALAR register/slot
3920 * knowledge: if precise value or range is useful to prune jump branch, BPF
3921 * verifier takes this opportunity enthusiastically. Similarly, when
3922 * register's value is used to calculate offset or memory address, exact
3923 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3924 * what we mentioned above about state comparison ignoring precise markings
3925 * during state comparison, BPF verifier ignores and also assumes precise
3926 * markings *at will* during instruction verification process. But as verifier
3927 * assumes precision, it also propagates any precision dependencies across
3928 * parent states, which are not yet finalized, so can be further restricted
3929 * based on new knowledge gained from restrictions enforced by their children
3930 * states. This is so that once those parent states are finalized, i.e., when
3931 * they have no more active children state, state comparison logic in
3932 * is_state_visited() would enforce strict and precise SCALAR ranges, if
3933 * required for correctness.
3935 * To build a bit more intuition, note also that once a state is checkpointed,
3936 * the path we took to get to that state is not important. This is crucial
3937 * property for state pruning. When state is checkpointed and finalized at
3938 * some instruction index, it can be correctly and safely used to "short
3939 * circuit" any *compatible* state that reaches exactly the same instruction
3940 * index. I.e., if we jumped to that instruction from a completely different
3941 * code path than original finalized state was derived from, it doesn't
3942 * matter, current state can be discarded because from that instruction
3943 * forward having a compatible state will ensure we will safely reach the
3944 * exit. States describe preconditions for further exploration, but completely
3945 * forget the history of how we got here.
3947 * This also means that even if we needed precise SCALAR range to get to
3948 * finalized state, but from that point forward *that same* SCALAR register is
3949 * never used in a precise context (i.e., it's precise value is not needed for
3950 * correctness), it's correct and safe to mark such register as "imprecise"
3951 * (i.e., precise marking set to false). This is what we rely on when we do
3952 * not set precise marking in current state. If no child state requires
3953 * precision for any given SCALAR register, it's safe to dictate that it can
3954 * be imprecise. If any child state does require this register to be precise,
3955 * we'll mark it precise later retroactively during precise markings
3956 * propagation from child state to parent states.
3958 * Skipping precise marking setting in current state is a mild version of
3959 * relying on the above observation. But we can utilize this property even
3960 * more aggressively by proactively forgetting any precise marking in the
3961 * current state (which we inherited from the parent state), right before we
3962 * checkpoint it and branch off into new child state. This is done by
3963 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3964 * finalized states which help in short circuiting more future states.
3966 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3968 struct backtrack_state *bt = &env->bt;
3969 struct bpf_verifier_state *st = env->cur_state;
3970 int first_idx = st->first_insn_idx;
3971 int last_idx = env->insn_idx;
3972 int subseq_idx = -1;
3973 struct bpf_func_state *func;
3974 struct bpf_reg_state *reg;
3975 bool skip_first = true;
3978 if (!env->bpf_capable)
3981 /* set frame number from which we are starting to backtrack */
3982 bt_init(bt, env->cur_state->curframe);
3984 /* Do sanity checks against current state of register and/or stack
3985 * slot, but don't set precise flag in current state, as precision
3986 * tracking in the current state is unnecessary.
3988 func = st->frame[bt->frame];
3990 reg = &func->regs[regno];
3991 if (reg->type != SCALAR_VALUE) {
3992 WARN_ONCE(1, "backtracing misuse");
3995 bt_set_reg(bt, regno);
4002 DECLARE_BITMAP(mask, 64);
4003 u32 history = st->jmp_history_cnt;
4005 if (env->log.level & BPF_LOG_LEVEL2) {
4006 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4007 bt->frame, last_idx, first_idx, subseq_idx);
4010 /* If some register with scalar ID is marked as precise,
4011 * make sure that all registers sharing this ID are also precise.
4012 * This is needed to estimate effect of find_equal_scalars().
4013 * Do this at the last instruction of each state,
4014 * bpf_reg_state::id fields are valid for these instructions.
4016 * Allows to track precision in situation like below:
4018 * r2 = unknown value
4022 * r1 = r2 // r1 and r2 now share the same ID
4024 * --- state #1 {r1.id = A, r2.id = A} ---
4026 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4028 * --- state #2 {r1.id = A, r2.id = A} ---
4030 * r3 += r1 // need to mark both r1 and r2
4032 if (mark_precise_scalar_ids(env, st))
4036 /* we are at the entry into subprog, which
4037 * is expected for global funcs, but only if
4038 * requested precise registers are R1-R5
4039 * (which are global func's input arguments)
4041 if (st->curframe == 0 &&
4042 st->frame[0]->subprogno > 0 &&
4043 st->frame[0]->callsite == BPF_MAIN_FUNC &&
4044 bt_stack_mask(bt) == 0 &&
4045 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4046 bitmap_from_u64(mask, bt_reg_mask(bt));
4047 for_each_set_bit(i, mask, 32) {
4048 reg = &st->frame[0]->regs[i];
4049 if (reg->type != SCALAR_VALUE) {
4050 bt_clear_reg(bt, i);
4053 reg->precise = true;
4058 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4059 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4060 WARN_ONCE(1, "verifier backtracking bug");
4064 for (i = last_idx;;) {
4069 err = backtrack_insn(env, i, subseq_idx, bt);
4071 if (err == -ENOTSUPP) {
4072 mark_all_scalars_precise(env, env->cur_state);
4079 /* Found assignment(s) into tracked register in this state.
4080 * Since this state is already marked, just return.
4081 * Nothing to be tracked further in the parent state.
4087 i = get_prev_insn_idx(st, i, &history);
4088 if (i >= env->prog->len) {
4089 /* This can happen if backtracking reached insn 0
4090 * and there are still reg_mask or stack_mask
4092 * It means the backtracking missed the spot where
4093 * particular register was initialized with a constant.
4095 verbose(env, "BUG backtracking idx %d\n", i);
4096 WARN_ONCE(1, "verifier backtracking bug");
4104 for (fr = bt->frame; fr >= 0; fr--) {
4105 func = st->frame[fr];
4106 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4107 for_each_set_bit(i, mask, 32) {
4108 reg = &func->regs[i];
4109 if (reg->type != SCALAR_VALUE) {
4110 bt_clear_frame_reg(bt, fr, i);
4114 bt_clear_frame_reg(bt, fr, i);
4116 reg->precise = true;
4119 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4120 for_each_set_bit(i, mask, 64) {
4121 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4122 /* the sequence of instructions:
4124 * 3: (7b) *(u64 *)(r3 -8) = r0
4125 * 4: (79) r4 = *(u64 *)(r10 -8)
4126 * doesn't contain jmps. It's backtracked
4127 * as a single block.
4128 * During backtracking insn 3 is not recognized as
4129 * stack access, so at the end of backtracking
4130 * stack slot fp-8 is still marked in stack_mask.
4131 * However the parent state may not have accessed
4132 * fp-8 and it's "unallocated" stack space.
4133 * In such case fallback to conservative.
4135 mark_all_scalars_precise(env, env->cur_state);
4140 if (!is_spilled_scalar_reg(&func->stack[i])) {
4141 bt_clear_frame_slot(bt, fr, i);
4144 reg = &func->stack[i].spilled_ptr;
4146 bt_clear_frame_slot(bt, fr, i);
4148 reg->precise = true;
4150 if (env->log.level & BPF_LOG_LEVEL2) {
4151 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4152 bt_frame_reg_mask(bt, fr));
4153 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4154 fr, env->tmp_str_buf);
4155 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4156 bt_frame_stack_mask(bt, fr));
4157 verbose(env, "stack=%s: ", env->tmp_str_buf);
4158 print_verifier_state(env, func, true);
4165 subseq_idx = first_idx;
4166 last_idx = st->last_insn_idx;
4167 first_idx = st->first_insn_idx;
4170 /* if we still have requested precise regs or slots, we missed
4171 * something (e.g., stack access through non-r10 register), so
4172 * fallback to marking all precise
4174 if (!bt_empty(bt)) {
4175 mark_all_scalars_precise(env, env->cur_state);
4182 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4184 return __mark_chain_precision(env, regno);
4187 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4188 * desired reg and stack masks across all relevant frames
4190 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4192 return __mark_chain_precision(env, -1);
4195 static bool is_spillable_regtype(enum bpf_reg_type type)
4197 switch (base_type(type)) {
4198 case PTR_TO_MAP_VALUE:
4202 case PTR_TO_PACKET_META:
4203 case PTR_TO_PACKET_END:
4204 case PTR_TO_FLOW_KEYS:
4205 case CONST_PTR_TO_MAP:
4207 case PTR_TO_SOCK_COMMON:
4208 case PTR_TO_TCP_SOCK:
4209 case PTR_TO_XDP_SOCK:
4214 case PTR_TO_MAP_KEY:
4221 /* Does this register contain a constant zero? */
4222 static bool register_is_null(struct bpf_reg_state *reg)
4224 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4227 static bool register_is_const(struct bpf_reg_state *reg)
4229 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4232 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4234 return tnum_is_unknown(reg->var_off) &&
4235 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4236 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4237 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4238 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4241 static bool register_is_bounded(struct bpf_reg_state *reg)
4243 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4246 static bool __is_pointer_value(bool allow_ptr_leaks,
4247 const struct bpf_reg_state *reg)
4249 if (allow_ptr_leaks)
4252 return reg->type != SCALAR_VALUE;
4255 /* Copy src state preserving dst->parent and dst->live fields */
4256 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4258 struct bpf_reg_state *parent = dst->parent;
4259 enum bpf_reg_liveness live = dst->live;
4262 dst->parent = parent;
4266 static void save_register_state(struct bpf_func_state *state,
4267 int spi, struct bpf_reg_state *reg,
4272 copy_register_state(&state->stack[spi].spilled_ptr, reg);
4273 if (size == BPF_REG_SIZE)
4274 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4276 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4277 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4279 /* size < 8 bytes spill */
4281 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4284 static bool is_bpf_st_mem(struct bpf_insn *insn)
4286 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4289 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4290 * stack boundary and alignment are checked in check_mem_access()
4292 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4293 /* stack frame we're writing to */
4294 struct bpf_func_state *state,
4295 int off, int size, int value_regno,
4298 struct bpf_func_state *cur; /* state of the current function */
4299 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4300 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4301 struct bpf_reg_state *reg = NULL;
4302 u32 dst_reg = insn->dst_reg;
4304 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4307 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4308 * so it's aligned access and [off, off + size) are within stack limits
4310 if (!env->allow_ptr_leaks &&
4311 state->stack[spi].slot_type[0] == STACK_SPILL &&
4312 size != BPF_REG_SIZE) {
4313 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4317 cur = env->cur_state->frame[env->cur_state->curframe];
4318 if (value_regno >= 0)
4319 reg = &cur->regs[value_regno];
4320 if (!env->bypass_spec_v4) {
4321 bool sanitize = reg && is_spillable_regtype(reg->type);
4323 for (i = 0; i < size; i++) {
4324 u8 type = state->stack[spi].slot_type[i];
4326 if (type != STACK_MISC && type != STACK_ZERO) {
4333 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4336 err = destroy_if_dynptr_stack_slot(env, state, spi);
4340 mark_stack_slot_scratched(env, spi);
4341 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4342 !register_is_null(reg) && env->bpf_capable) {
4343 if (dst_reg != BPF_REG_FP) {
4344 /* The backtracking logic can only recognize explicit
4345 * stack slot address like [fp - 8]. Other spill of
4346 * scalar via different register has to be conservative.
4347 * Backtrack from here and mark all registers as precise
4348 * that contributed into 'reg' being a constant.
4350 err = mark_chain_precision(env, value_regno);
4354 save_register_state(state, spi, reg, size);
4355 /* Break the relation on a narrowing spill. */
4356 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4357 state->stack[spi].spilled_ptr.id = 0;
4358 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4359 insn->imm != 0 && env->bpf_capable) {
4360 struct bpf_reg_state fake_reg = {};
4362 __mark_reg_known(&fake_reg, (u32)insn->imm);
4363 fake_reg.type = SCALAR_VALUE;
4364 save_register_state(state, spi, &fake_reg, size);
4365 } else if (reg && is_spillable_regtype(reg->type)) {
4366 /* register containing pointer is being spilled into stack */
4367 if (size != BPF_REG_SIZE) {
4368 verbose_linfo(env, insn_idx, "; ");
4369 verbose(env, "invalid size of register spill\n");
4372 if (state != cur && reg->type == PTR_TO_STACK) {
4373 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4376 save_register_state(state, spi, reg, size);
4378 u8 type = STACK_MISC;
4380 /* regular write of data into stack destroys any spilled ptr */
4381 state->stack[spi].spilled_ptr.type = NOT_INIT;
4382 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4383 if (is_stack_slot_special(&state->stack[spi]))
4384 for (i = 0; i < BPF_REG_SIZE; i++)
4385 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4387 /* only mark the slot as written if all 8 bytes were written
4388 * otherwise read propagation may incorrectly stop too soon
4389 * when stack slots are partially written.
4390 * This heuristic means that read propagation will be
4391 * conservative, since it will add reg_live_read marks
4392 * to stack slots all the way to first state when programs
4393 * writes+reads less than 8 bytes
4395 if (size == BPF_REG_SIZE)
4396 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4398 /* when we zero initialize stack slots mark them as such */
4399 if ((reg && register_is_null(reg)) ||
4400 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4401 /* backtracking doesn't work for STACK_ZERO yet. */
4402 err = mark_chain_precision(env, value_regno);
4408 /* Mark slots affected by this stack write. */
4409 for (i = 0; i < size; i++)
4410 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4416 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4417 * known to contain a variable offset.
4418 * This function checks whether the write is permitted and conservatively
4419 * tracks the effects of the write, considering that each stack slot in the
4420 * dynamic range is potentially written to.
4422 * 'off' includes 'regno->off'.
4423 * 'value_regno' can be -1, meaning that an unknown value is being written to
4426 * Spilled pointers in range are not marked as written because we don't know
4427 * what's going to be actually written. This means that read propagation for
4428 * future reads cannot be terminated by this write.
4430 * For privileged programs, uninitialized stack slots are considered
4431 * initialized by this write (even though we don't know exactly what offsets
4432 * are going to be written to). The idea is that we don't want the verifier to
4433 * reject future reads that access slots written to through variable offsets.
4435 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4436 /* func where register points to */
4437 struct bpf_func_state *state,
4438 int ptr_regno, int off, int size,
4439 int value_regno, int insn_idx)
4441 struct bpf_func_state *cur; /* state of the current function */
4442 int min_off, max_off;
4444 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4445 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4446 bool writing_zero = false;
4447 /* set if the fact that we're writing a zero is used to let any
4448 * stack slots remain STACK_ZERO
4450 bool zero_used = false;
4452 cur = env->cur_state->frame[env->cur_state->curframe];
4453 ptr_reg = &cur->regs[ptr_regno];
4454 min_off = ptr_reg->smin_value + off;
4455 max_off = ptr_reg->smax_value + off + size;
4456 if (value_regno >= 0)
4457 value_reg = &cur->regs[value_regno];
4458 if ((value_reg && register_is_null(value_reg)) ||
4459 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4460 writing_zero = true;
4462 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4466 for (i = min_off; i < max_off; i++) {
4470 err = destroy_if_dynptr_stack_slot(env, state, spi);
4475 /* Variable offset writes destroy any spilled pointers in range. */
4476 for (i = min_off; i < max_off; i++) {
4477 u8 new_type, *stype;
4481 spi = slot / BPF_REG_SIZE;
4482 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4483 mark_stack_slot_scratched(env, spi);
4485 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4486 /* Reject the write if range we may write to has not
4487 * been initialized beforehand. If we didn't reject
4488 * here, the ptr status would be erased below (even
4489 * though not all slots are actually overwritten),
4490 * possibly opening the door to leaks.
4492 * We do however catch STACK_INVALID case below, and
4493 * only allow reading possibly uninitialized memory
4494 * later for CAP_PERFMON, as the write may not happen to
4497 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4502 /* Erase all spilled pointers. */
4503 state->stack[spi].spilled_ptr.type = NOT_INIT;
4505 /* Update the slot type. */
4506 new_type = STACK_MISC;
4507 if (writing_zero && *stype == STACK_ZERO) {
4508 new_type = STACK_ZERO;
4511 /* If the slot is STACK_INVALID, we check whether it's OK to
4512 * pretend that it will be initialized by this write. The slot
4513 * might not actually be written to, and so if we mark it as
4514 * initialized future reads might leak uninitialized memory.
4515 * For privileged programs, we will accept such reads to slots
4516 * that may or may not be written because, if we're reject
4517 * them, the error would be too confusing.
4519 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4520 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4527 /* backtracking doesn't work for STACK_ZERO yet. */
4528 err = mark_chain_precision(env, value_regno);
4535 /* When register 'dst_regno' is assigned some values from stack[min_off,
4536 * max_off), we set the register's type according to the types of the
4537 * respective stack slots. If all the stack values are known to be zeros, then
4538 * so is the destination reg. Otherwise, the register is considered to be
4539 * SCALAR. This function does not deal with register filling; the caller must
4540 * ensure that all spilled registers in the stack range have been marked as
4543 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4544 /* func where src register points to */
4545 struct bpf_func_state *ptr_state,
4546 int min_off, int max_off, int dst_regno)
4548 struct bpf_verifier_state *vstate = env->cur_state;
4549 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4554 for (i = min_off; i < max_off; i++) {
4556 spi = slot / BPF_REG_SIZE;
4557 mark_stack_slot_scratched(env, spi);
4558 stype = ptr_state->stack[spi].slot_type;
4559 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4563 if (zeros == max_off - min_off) {
4564 /* any access_size read into register is zero extended,
4565 * so the whole register == const_zero
4567 __mark_reg_const_zero(&state->regs[dst_regno]);
4568 /* backtracking doesn't support STACK_ZERO yet,
4569 * so mark it precise here, so that later
4570 * backtracking can stop here.
4571 * Backtracking may not need this if this register
4572 * doesn't participate in pointer adjustment.
4573 * Forward propagation of precise flag is not
4574 * necessary either. This mark is only to stop
4575 * backtracking. Any register that contributed
4576 * to const 0 was marked precise before spill.
4578 state->regs[dst_regno].precise = true;
4580 /* have read misc data from the stack */
4581 mark_reg_unknown(env, state->regs, dst_regno);
4583 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4586 /* Read the stack at 'off' and put the results into the register indicated by
4587 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4590 * 'dst_regno' can be -1, meaning that the read value is not going to a
4593 * The access is assumed to be within the current stack bounds.
4595 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4596 /* func where src register points to */
4597 struct bpf_func_state *reg_state,
4598 int off, int size, int dst_regno)
4600 struct bpf_verifier_state *vstate = env->cur_state;
4601 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4602 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4603 struct bpf_reg_state *reg;
4606 stype = reg_state->stack[spi].slot_type;
4607 reg = ®_state->stack[spi].spilled_ptr;
4609 mark_stack_slot_scratched(env, spi);
4611 if (is_spilled_reg(®_state->stack[spi])) {
4614 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4617 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4618 if (reg->type != SCALAR_VALUE) {
4619 verbose_linfo(env, env->insn_idx, "; ");
4620 verbose(env, "invalid size of register fill\n");
4624 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4628 if (!(off % BPF_REG_SIZE) && size == spill_size) {
4629 /* The earlier check_reg_arg() has decided the
4630 * subreg_def for this insn. Save it first.
4632 s32 subreg_def = state->regs[dst_regno].subreg_def;
4634 copy_register_state(&state->regs[dst_regno], reg);
4635 state->regs[dst_regno].subreg_def = subreg_def;
4637 for (i = 0; i < size; i++) {
4638 type = stype[(slot - i) % BPF_REG_SIZE];
4639 if (type == STACK_SPILL)
4641 if (type == STACK_MISC)
4643 if (type == STACK_INVALID && env->allow_uninit_stack)
4645 verbose(env, "invalid read from stack off %d+%d size %d\n",
4649 mark_reg_unknown(env, state->regs, dst_regno);
4651 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4655 if (dst_regno >= 0) {
4656 /* restore register state from stack */
4657 copy_register_state(&state->regs[dst_regno], reg);
4658 /* mark reg as written since spilled pointer state likely
4659 * has its liveness marks cleared by is_state_visited()
4660 * which resets stack/reg liveness for state transitions
4662 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4663 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4664 /* If dst_regno==-1, the caller is asking us whether
4665 * it is acceptable to use this value as a SCALAR_VALUE
4667 * We must not allow unprivileged callers to do that
4668 * with spilled pointers.
4670 verbose(env, "leaking pointer from stack off %d\n",
4674 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4676 for (i = 0; i < size; i++) {
4677 type = stype[(slot - i) % BPF_REG_SIZE];
4678 if (type == STACK_MISC)
4680 if (type == STACK_ZERO)
4682 if (type == STACK_INVALID && env->allow_uninit_stack)
4684 verbose(env, "invalid read from stack off %d+%d size %d\n",
4688 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4690 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4695 enum bpf_access_src {
4696 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4697 ACCESS_HELPER = 2, /* the access is performed by a helper */
4700 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4701 int regno, int off, int access_size,
4702 bool zero_size_allowed,
4703 enum bpf_access_src type,
4704 struct bpf_call_arg_meta *meta);
4706 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4708 return cur_regs(env) + regno;
4711 /* Read the stack at 'ptr_regno + off' and put the result into the register
4713 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4714 * but not its variable offset.
4715 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4717 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4718 * filling registers (i.e. reads of spilled register cannot be detected when
4719 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4720 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4721 * offset; for a fixed offset check_stack_read_fixed_off should be used
4724 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4725 int ptr_regno, int off, int size, int dst_regno)
4727 /* The state of the source register. */
4728 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4729 struct bpf_func_state *ptr_state = func(env, reg);
4731 int min_off, max_off;
4733 /* Note that we pass a NULL meta, so raw access will not be permitted.
4735 err = check_stack_range_initialized(env, ptr_regno, off, size,
4736 false, ACCESS_DIRECT, NULL);
4740 min_off = reg->smin_value + off;
4741 max_off = reg->smax_value + off;
4742 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4746 /* check_stack_read dispatches to check_stack_read_fixed_off or
4747 * check_stack_read_var_off.
4749 * The caller must ensure that the offset falls within the allocated stack
4752 * 'dst_regno' is a register which will receive the value from the stack. It
4753 * can be -1, meaning that the read value is not going to a register.
4755 static int check_stack_read(struct bpf_verifier_env *env,
4756 int ptr_regno, int off, int size,
4759 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4760 struct bpf_func_state *state = func(env, reg);
4762 /* Some accesses are only permitted with a static offset. */
4763 bool var_off = !tnum_is_const(reg->var_off);
4765 /* The offset is required to be static when reads don't go to a
4766 * register, in order to not leak pointers (see
4767 * check_stack_read_fixed_off).
4769 if (dst_regno < 0 && var_off) {
4772 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4773 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4777 /* Variable offset is prohibited for unprivileged mode for simplicity
4778 * since it requires corresponding support in Spectre masking for stack
4779 * ALU. See also retrieve_ptr_limit(). The check in
4780 * check_stack_access_for_ptr_arithmetic() called by
4781 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4782 * with variable offsets, therefore no check is required here. Further,
4783 * just checking it here would be insufficient as speculative stack
4784 * writes could still lead to unsafe speculative behaviour.
4787 off += reg->var_off.value;
4788 err = check_stack_read_fixed_off(env, state, off, size,
4791 /* Variable offset stack reads need more conservative handling
4792 * than fixed offset ones. Note that dst_regno >= 0 on this
4795 err = check_stack_read_var_off(env, ptr_regno, off, size,
4802 /* check_stack_write dispatches to check_stack_write_fixed_off or
4803 * check_stack_write_var_off.
4805 * 'ptr_regno' is the register used as a pointer into the stack.
4806 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4807 * 'value_regno' is the register whose value we're writing to the stack. It can
4808 * be -1, meaning that we're not writing from a register.
4810 * The caller must ensure that the offset falls within the maximum stack size.
4812 static int check_stack_write(struct bpf_verifier_env *env,
4813 int ptr_regno, int off, int size,
4814 int value_regno, int insn_idx)
4816 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4817 struct bpf_func_state *state = func(env, reg);
4820 if (tnum_is_const(reg->var_off)) {
4821 off += reg->var_off.value;
4822 err = check_stack_write_fixed_off(env, state, off, size,
4823 value_regno, insn_idx);
4825 /* Variable offset stack reads need more conservative handling
4826 * than fixed offset ones.
4828 err = check_stack_write_var_off(env, state,
4829 ptr_regno, off, size,
4830 value_regno, insn_idx);
4835 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4836 int off, int size, enum bpf_access_type type)
4838 struct bpf_reg_state *regs = cur_regs(env);
4839 struct bpf_map *map = regs[regno].map_ptr;
4840 u32 cap = bpf_map_flags_to_cap(map);
4842 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4843 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4844 map->value_size, off, size);
4848 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4849 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4850 map->value_size, off, size);
4857 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4858 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4859 int off, int size, u32 mem_size,
4860 bool zero_size_allowed)
4862 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4863 struct bpf_reg_state *reg;
4865 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4868 reg = &cur_regs(env)[regno];
4869 switch (reg->type) {
4870 case PTR_TO_MAP_KEY:
4871 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4872 mem_size, off, size);
4874 case PTR_TO_MAP_VALUE:
4875 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4876 mem_size, off, size);
4879 case PTR_TO_PACKET_META:
4880 case PTR_TO_PACKET_END:
4881 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4882 off, size, regno, reg->id, off, mem_size);
4886 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4887 mem_size, off, size);
4893 /* check read/write into a memory region with possible variable offset */
4894 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4895 int off, int size, u32 mem_size,
4896 bool zero_size_allowed)
4898 struct bpf_verifier_state *vstate = env->cur_state;
4899 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4900 struct bpf_reg_state *reg = &state->regs[regno];
4903 /* We may have adjusted the register pointing to memory region, so we
4904 * need to try adding each of min_value and max_value to off
4905 * to make sure our theoretical access will be safe.
4907 * The minimum value is only important with signed
4908 * comparisons where we can't assume the floor of a
4909 * value is 0. If we are using signed variables for our
4910 * index'es we need to make sure that whatever we use
4911 * will have a set floor within our range.
4913 if (reg->smin_value < 0 &&
4914 (reg->smin_value == S64_MIN ||
4915 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4916 reg->smin_value + off < 0)) {
4917 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4921 err = __check_mem_access(env, regno, reg->smin_value + off, size,
4922 mem_size, zero_size_allowed);
4924 verbose(env, "R%d min value is outside of the allowed memory range\n",
4929 /* If we haven't set a max value then we need to bail since we can't be
4930 * sure we won't do bad things.
4931 * If reg->umax_value + off could overflow, treat that as unbounded too.
4933 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4934 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4938 err = __check_mem_access(env, regno, reg->umax_value + off, size,
4939 mem_size, zero_size_allowed);
4941 verbose(env, "R%d max value is outside of the allowed memory range\n",
4949 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4950 const struct bpf_reg_state *reg, int regno,
4953 /* Access to this pointer-typed register or passing it to a helper
4954 * is only allowed in its original, unmodified form.
4958 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4959 reg_type_str(env, reg->type), regno, reg->off);
4963 if (!fixed_off_ok && reg->off) {
4964 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4965 reg_type_str(env, reg->type), regno, reg->off);
4969 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4972 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4973 verbose(env, "variable %s access var_off=%s disallowed\n",
4974 reg_type_str(env, reg->type), tn_buf);
4981 int check_ptr_off_reg(struct bpf_verifier_env *env,
4982 const struct bpf_reg_state *reg, int regno)
4984 return __check_ptr_off_reg(env, reg, regno, false);
4987 static int map_kptr_match_type(struct bpf_verifier_env *env,
4988 struct btf_field *kptr_field,
4989 struct bpf_reg_state *reg, u32 regno)
4991 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4992 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4993 const char *reg_name = "";
4995 /* Only unreferenced case accepts untrusted pointers */
4996 if (kptr_field->type == BPF_KPTR_UNREF)
4997 perm_flags |= PTR_UNTRUSTED;
4999 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5002 if (!btf_is_kernel(reg->btf)) {
5003 verbose(env, "R%d must point to kernel BTF\n", regno);
5006 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5007 reg_name = btf_type_name(reg->btf, reg->btf_id);
5009 /* For ref_ptr case, release function check should ensure we get one
5010 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5011 * normal store of unreferenced kptr, we must ensure var_off is zero.
5012 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5013 * reg->off and reg->ref_obj_id are not needed here.
5015 if (__check_ptr_off_reg(env, reg, regno, true))
5018 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
5019 * we also need to take into account the reg->off.
5021 * We want to support cases like:
5029 * v = func(); // PTR_TO_BTF_ID
5030 * val->foo = v; // reg->off is zero, btf and btf_id match type
5031 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5032 * // first member type of struct after comparison fails
5033 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5036 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5037 * is zero. We must also ensure that btf_struct_ids_match does not walk
5038 * the struct to match type against first member of struct, i.e. reject
5039 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5040 * strict mode to true for type match.
5042 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5043 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5044 kptr_field->type == BPF_KPTR_REF))
5048 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5049 reg_type_str(env, reg->type), reg_name);
5050 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5051 if (kptr_field->type == BPF_KPTR_UNREF)
5052 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5059 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5060 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5062 static bool in_rcu_cs(struct bpf_verifier_env *env)
5064 return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
5067 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5068 BTF_SET_START(rcu_protected_types)
5069 BTF_ID(struct, prog_test_ref_kfunc)
5070 BTF_ID(struct, cgroup)
5071 BTF_ID(struct, bpf_cpumask)
5072 BTF_ID(struct, task_struct)
5073 BTF_SET_END(rcu_protected_types)
5075 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5077 if (!btf_is_kernel(btf))
5079 return btf_id_set_contains(&rcu_protected_types, btf_id);
5082 static bool rcu_safe_kptr(const struct btf_field *field)
5084 const struct btf_field_kptr *kptr = &field->kptr;
5086 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5089 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5090 int value_regno, int insn_idx,
5091 struct btf_field *kptr_field)
5093 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5094 int class = BPF_CLASS(insn->code);
5095 struct bpf_reg_state *val_reg;
5097 /* Things we already checked for in check_map_access and caller:
5098 * - Reject cases where variable offset may touch kptr
5099 * - size of access (must be BPF_DW)
5100 * - tnum_is_const(reg->var_off)
5101 * - kptr_field->offset == off + reg->var_off.value
5103 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5104 if (BPF_MODE(insn->code) != BPF_MEM) {
5105 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5109 /* We only allow loading referenced kptr, since it will be marked as
5110 * untrusted, similar to unreferenced kptr.
5112 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5113 verbose(env, "store to referenced kptr disallowed\n");
5117 if (class == BPF_LDX) {
5118 val_reg = reg_state(env, value_regno);
5119 /* We can simply mark the value_regno receiving the pointer
5120 * value from map as PTR_TO_BTF_ID, with the correct type.
5122 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5123 kptr_field->kptr.btf_id,
5124 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5125 PTR_MAYBE_NULL | MEM_RCU :
5126 PTR_MAYBE_NULL | PTR_UNTRUSTED);
5127 /* For mark_ptr_or_null_reg */
5128 val_reg->id = ++env->id_gen;
5129 } else if (class == BPF_STX) {
5130 val_reg = reg_state(env, value_regno);
5131 if (!register_is_null(val_reg) &&
5132 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5134 } else if (class == BPF_ST) {
5136 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5137 kptr_field->offset);
5141 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5147 /* check read/write into a map element with possible variable offset */
5148 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5149 int off, int size, bool zero_size_allowed,
5150 enum bpf_access_src src)
5152 struct bpf_verifier_state *vstate = env->cur_state;
5153 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5154 struct bpf_reg_state *reg = &state->regs[regno];
5155 struct bpf_map *map = reg->map_ptr;
5156 struct btf_record *rec;
5159 err = check_mem_region_access(env, regno, off, size, map->value_size,
5164 if (IS_ERR_OR_NULL(map->record))
5167 for (i = 0; i < rec->cnt; i++) {
5168 struct btf_field *field = &rec->fields[i];
5169 u32 p = field->offset;
5171 /* If any part of a field can be touched by load/store, reject
5172 * this program. To check that [x1, x2) overlaps with [y1, y2),
5173 * it is sufficient to check x1 < y2 && y1 < x2.
5175 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5176 p < reg->umax_value + off + size) {
5177 switch (field->type) {
5178 case BPF_KPTR_UNREF:
5180 if (src != ACCESS_DIRECT) {
5181 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5184 if (!tnum_is_const(reg->var_off)) {
5185 verbose(env, "kptr access cannot have variable offset\n");
5188 if (p != off + reg->var_off.value) {
5189 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5190 p, off + reg->var_off.value);
5193 if (size != bpf_size_to_bytes(BPF_DW)) {
5194 verbose(env, "kptr access size must be BPF_DW\n");
5199 verbose(env, "%s cannot be accessed directly by load/store\n",
5200 btf_field_type_name(field->type));
5208 #define MAX_PACKET_OFF 0xffff
5210 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5211 const struct bpf_call_arg_meta *meta,
5212 enum bpf_access_type t)
5214 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5216 switch (prog_type) {
5217 /* Program types only with direct read access go here! */
5218 case BPF_PROG_TYPE_LWT_IN:
5219 case BPF_PROG_TYPE_LWT_OUT:
5220 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5221 case BPF_PROG_TYPE_SK_REUSEPORT:
5222 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5223 case BPF_PROG_TYPE_CGROUP_SKB:
5228 /* Program types with direct read + write access go here! */
5229 case BPF_PROG_TYPE_SCHED_CLS:
5230 case BPF_PROG_TYPE_SCHED_ACT:
5231 case BPF_PROG_TYPE_XDP:
5232 case BPF_PROG_TYPE_LWT_XMIT:
5233 case BPF_PROG_TYPE_SK_SKB:
5234 case BPF_PROG_TYPE_SK_MSG:
5236 return meta->pkt_access;
5238 env->seen_direct_write = true;
5241 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5243 env->seen_direct_write = true;
5252 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5253 int size, bool zero_size_allowed)
5255 struct bpf_reg_state *regs = cur_regs(env);
5256 struct bpf_reg_state *reg = ®s[regno];
5259 /* We may have added a variable offset to the packet pointer; but any
5260 * reg->range we have comes after that. We are only checking the fixed
5264 /* We don't allow negative numbers, because we aren't tracking enough
5265 * detail to prove they're safe.
5267 if (reg->smin_value < 0) {
5268 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5273 err = reg->range < 0 ? -EINVAL :
5274 __check_mem_access(env, regno, off, size, reg->range,
5277 verbose(env, "R%d offset is outside of the packet\n", regno);
5281 /* __check_mem_access has made sure "off + size - 1" is within u16.
5282 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5283 * otherwise find_good_pkt_pointers would have refused to set range info
5284 * that __check_mem_access would have rejected this pkt access.
5285 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5287 env->prog->aux->max_pkt_offset =
5288 max_t(u32, env->prog->aux->max_pkt_offset,
5289 off + reg->umax_value + size - 1);
5294 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
5295 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5296 enum bpf_access_type t, enum bpf_reg_type *reg_type,
5297 struct btf **btf, u32 *btf_id)
5299 struct bpf_insn_access_aux info = {
5300 .reg_type = *reg_type,
5304 if (env->ops->is_valid_access &&
5305 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5306 /* A non zero info.ctx_field_size indicates that this field is a
5307 * candidate for later verifier transformation to load the whole
5308 * field and then apply a mask when accessed with a narrower
5309 * access than actual ctx access size. A zero info.ctx_field_size
5310 * will only allow for whole field access and rejects any other
5311 * type of narrower access.
5313 *reg_type = info.reg_type;
5315 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5317 *btf_id = info.btf_id;
5319 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5321 /* remember the offset of last byte accessed in ctx */
5322 if (env->prog->aux->max_ctx_offset < off + size)
5323 env->prog->aux->max_ctx_offset = off + size;
5327 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5331 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5334 if (size < 0 || off < 0 ||
5335 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5336 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5343 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5344 u32 regno, int off, int size,
5345 enum bpf_access_type t)
5347 struct bpf_reg_state *regs = cur_regs(env);
5348 struct bpf_reg_state *reg = ®s[regno];
5349 struct bpf_insn_access_aux info = {};
5352 if (reg->smin_value < 0) {
5353 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5358 switch (reg->type) {
5359 case PTR_TO_SOCK_COMMON:
5360 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5363 valid = bpf_sock_is_valid_access(off, size, t, &info);
5365 case PTR_TO_TCP_SOCK:
5366 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5368 case PTR_TO_XDP_SOCK:
5369 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5377 env->insn_aux_data[insn_idx].ctx_field_size =
5378 info.ctx_field_size;
5382 verbose(env, "R%d invalid %s access off=%d size=%d\n",
5383 regno, reg_type_str(env, reg->type), off, size);
5388 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5390 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5393 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5395 const struct bpf_reg_state *reg = reg_state(env, regno);
5397 return reg->type == PTR_TO_CTX;
5400 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5402 const struct bpf_reg_state *reg = reg_state(env, regno);
5404 return type_is_sk_pointer(reg->type);
5407 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5409 const struct bpf_reg_state *reg = reg_state(env, regno);
5411 return type_is_pkt_pointer(reg->type);
5414 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5416 const struct bpf_reg_state *reg = reg_state(env, regno);
5418 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5419 return reg->type == PTR_TO_FLOW_KEYS;
5422 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5424 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5425 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5426 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5428 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5431 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5433 /* A referenced register is always trusted. */
5434 if (reg->ref_obj_id)
5437 /* Types listed in the reg2btf_ids are always trusted */
5438 if (reg2btf_ids[base_type(reg->type)])
5441 /* If a register is not referenced, it is trusted if it has the
5442 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5443 * other type modifiers may be safe, but we elect to take an opt-in
5444 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5447 * Eventually, we should make PTR_TRUSTED the single source of truth
5448 * for whether a register is trusted.
5450 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5451 !bpf_type_has_unsafe_modifiers(reg->type);
5454 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5456 return reg->type & MEM_RCU;
5459 static void clear_trusted_flags(enum bpf_type_flag *flag)
5461 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5464 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5465 const struct bpf_reg_state *reg,
5466 int off, int size, bool strict)
5468 struct tnum reg_off;
5471 /* Byte size accesses are always allowed. */
5472 if (!strict || size == 1)
5475 /* For platforms that do not have a Kconfig enabling
5476 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5477 * NET_IP_ALIGN is universally set to '2'. And on platforms
5478 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5479 * to this code only in strict mode where we want to emulate
5480 * the NET_IP_ALIGN==2 checking. Therefore use an
5481 * unconditional IP align value of '2'.
5485 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5486 if (!tnum_is_aligned(reg_off, size)) {
5489 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5491 "misaligned packet access off %d+%s+%d+%d size %d\n",
5492 ip_align, tn_buf, reg->off, off, size);
5499 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5500 const struct bpf_reg_state *reg,
5501 const char *pointer_desc,
5502 int off, int size, bool strict)
5504 struct tnum reg_off;
5506 /* Byte size accesses are always allowed. */
5507 if (!strict || size == 1)
5510 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5511 if (!tnum_is_aligned(reg_off, size)) {
5514 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5515 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5516 pointer_desc, tn_buf, reg->off, off, size);
5523 static int check_ptr_alignment(struct bpf_verifier_env *env,
5524 const struct bpf_reg_state *reg, int off,
5525 int size, bool strict_alignment_once)
5527 bool strict = env->strict_alignment || strict_alignment_once;
5528 const char *pointer_desc = "";
5530 switch (reg->type) {
5532 case PTR_TO_PACKET_META:
5533 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5534 * right in front, treat it the very same way.
5536 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5537 case PTR_TO_FLOW_KEYS:
5538 pointer_desc = "flow keys ";
5540 case PTR_TO_MAP_KEY:
5541 pointer_desc = "key ";
5543 case PTR_TO_MAP_VALUE:
5544 pointer_desc = "value ";
5547 pointer_desc = "context ";
5550 pointer_desc = "stack ";
5551 /* The stack spill tracking logic in check_stack_write_fixed_off()
5552 * and check_stack_read_fixed_off() relies on stack accesses being
5558 pointer_desc = "sock ";
5560 case PTR_TO_SOCK_COMMON:
5561 pointer_desc = "sock_common ";
5563 case PTR_TO_TCP_SOCK:
5564 pointer_desc = "tcp_sock ";
5566 case PTR_TO_XDP_SOCK:
5567 pointer_desc = "xdp_sock ";
5572 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5576 static int update_stack_depth(struct bpf_verifier_env *env,
5577 const struct bpf_func_state *func,
5580 u16 stack = env->subprog_info[func->subprogno].stack_depth;
5585 /* update known max for given subprogram */
5586 env->subprog_info[func->subprogno].stack_depth = -off;
5590 /* starting from main bpf function walk all instructions of the function
5591 * and recursively walk all callees that given function can call.
5592 * Ignore jump and exit insns.
5593 * Since recursion is prevented by check_cfg() this algorithm
5594 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5596 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5598 struct bpf_subprog_info *subprog = env->subprog_info;
5599 struct bpf_insn *insn = env->prog->insnsi;
5600 int depth = 0, frame = 0, i, subprog_end;
5601 bool tail_call_reachable = false;
5602 int ret_insn[MAX_CALL_FRAMES];
5603 int ret_prog[MAX_CALL_FRAMES];
5606 i = subprog[idx].start;
5608 /* protect against potential stack overflow that might happen when
5609 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5610 * depth for such case down to 256 so that the worst case scenario
5611 * would result in 8k stack size (32 which is tailcall limit * 256 =
5614 * To get the idea what might happen, see an example:
5615 * func1 -> sub rsp, 128
5616 * subfunc1 -> sub rsp, 256
5617 * tailcall1 -> add rsp, 256
5618 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5619 * subfunc2 -> sub rsp, 64
5620 * subfunc22 -> sub rsp, 128
5621 * tailcall2 -> add rsp, 128
5622 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5624 * tailcall will unwind the current stack frame but it will not get rid
5625 * of caller's stack as shown on the example above.
5627 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5629 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5633 /* round up to 32-bytes, since this is granularity
5634 * of interpreter stack size
5636 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5637 if (depth > MAX_BPF_STACK) {
5638 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5643 subprog_end = subprog[idx + 1].start;
5644 for (; i < subprog_end; i++) {
5645 int next_insn, sidx;
5647 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5649 /* remember insn and function to return to */
5650 ret_insn[frame] = i + 1;
5651 ret_prog[frame] = idx;
5653 /* find the callee */
5654 next_insn = i + insn[i].imm + 1;
5655 sidx = find_subprog(env, next_insn);
5657 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5661 if (subprog[sidx].is_async_cb) {
5662 if (subprog[sidx].has_tail_call) {
5663 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5666 /* async callbacks don't increase bpf prog stack size unless called directly */
5667 if (!bpf_pseudo_call(insn + i))
5673 if (subprog[idx].has_tail_call)
5674 tail_call_reachable = true;
5677 if (frame >= MAX_CALL_FRAMES) {
5678 verbose(env, "the call stack of %d frames is too deep !\n",
5684 /* if tail call got detected across bpf2bpf calls then mark each of the
5685 * currently present subprog frames as tail call reachable subprogs;
5686 * this info will be utilized by JIT so that we will be preserving the
5687 * tail call counter throughout bpf2bpf calls combined with tailcalls
5689 if (tail_call_reachable)
5690 for (j = 0; j < frame; j++)
5691 subprog[ret_prog[j]].tail_call_reachable = true;
5692 if (subprog[0].tail_call_reachable)
5693 env->prog->aux->tail_call_reachable = true;
5695 /* end of for() loop means the last insn of the 'subprog'
5696 * was reached. Doesn't matter whether it was JA or EXIT
5700 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5702 i = ret_insn[frame];
5703 idx = ret_prog[frame];
5707 static int check_max_stack_depth(struct bpf_verifier_env *env)
5709 struct bpf_subprog_info *si = env->subprog_info;
5712 for (int i = 0; i < env->subprog_cnt; i++) {
5713 if (!i || si[i].is_async_cb) {
5714 ret = check_max_stack_depth_subprog(env, i);
5723 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5724 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5725 const struct bpf_insn *insn, int idx)
5727 int start = idx + insn->imm + 1, subprog;
5729 subprog = find_subprog(env, start);
5731 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5735 return env->subprog_info[subprog].stack_depth;
5739 static int __check_buffer_access(struct bpf_verifier_env *env,
5740 const char *buf_info,
5741 const struct bpf_reg_state *reg,
5742 int regno, int off, int size)
5746 "R%d invalid %s buffer access: off=%d, size=%d\n",
5747 regno, buf_info, off, size);
5750 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5753 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5755 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5756 regno, off, tn_buf);
5763 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5764 const struct bpf_reg_state *reg,
5765 int regno, int off, int size)
5769 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5773 if (off + size > env->prog->aux->max_tp_access)
5774 env->prog->aux->max_tp_access = off + size;
5779 static int check_buffer_access(struct bpf_verifier_env *env,
5780 const struct bpf_reg_state *reg,
5781 int regno, int off, int size,
5782 bool zero_size_allowed,
5785 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5788 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5792 if (off + size > *max_access)
5793 *max_access = off + size;
5798 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5799 static void zext_32_to_64(struct bpf_reg_state *reg)
5801 reg->var_off = tnum_subreg(reg->var_off);
5802 __reg_assign_32_into_64(reg);
5805 /* truncate register to smaller size (in bytes)
5806 * must be called with size < BPF_REG_SIZE
5808 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5812 /* clear high bits in bit representation */
5813 reg->var_off = tnum_cast(reg->var_off, size);
5815 /* fix arithmetic bounds */
5816 mask = ((u64)1 << (size * 8)) - 1;
5817 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5818 reg->umin_value &= mask;
5819 reg->umax_value &= mask;
5821 reg->umin_value = 0;
5822 reg->umax_value = mask;
5824 reg->smin_value = reg->umin_value;
5825 reg->smax_value = reg->umax_value;
5827 /* If size is smaller than 32bit register the 32bit register
5828 * values are also truncated so we push 64-bit bounds into
5829 * 32-bit bounds. Above were truncated < 32-bits already.
5833 __reg_combine_64_into_32(reg);
5836 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5839 reg->smin_value = reg->s32_min_value = S8_MIN;
5840 reg->smax_value = reg->s32_max_value = S8_MAX;
5841 } else if (size == 2) {
5842 reg->smin_value = reg->s32_min_value = S16_MIN;
5843 reg->smax_value = reg->s32_max_value = S16_MAX;
5846 reg->smin_value = reg->s32_min_value = S32_MIN;
5847 reg->smax_value = reg->s32_max_value = S32_MAX;
5849 reg->umin_value = reg->u32_min_value = 0;
5850 reg->umax_value = U64_MAX;
5851 reg->u32_max_value = U32_MAX;
5852 reg->var_off = tnum_unknown;
5855 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5857 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5858 u64 top_smax_value, top_smin_value;
5859 u64 num_bits = size * 8;
5861 if (tnum_is_const(reg->var_off)) {
5862 u64_cval = reg->var_off.value;
5864 reg->var_off = tnum_const((s8)u64_cval);
5866 reg->var_off = tnum_const((s16)u64_cval);
5869 reg->var_off = tnum_const((s32)u64_cval);
5871 u64_cval = reg->var_off.value;
5872 reg->smax_value = reg->smin_value = u64_cval;
5873 reg->umax_value = reg->umin_value = u64_cval;
5874 reg->s32_max_value = reg->s32_min_value = u64_cval;
5875 reg->u32_max_value = reg->u32_min_value = u64_cval;
5879 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
5880 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
5882 if (top_smax_value != top_smin_value)
5885 /* find the s64_min and s64_min after sign extension */
5887 init_s64_max = (s8)reg->smax_value;
5888 init_s64_min = (s8)reg->smin_value;
5889 } else if (size == 2) {
5890 init_s64_max = (s16)reg->smax_value;
5891 init_s64_min = (s16)reg->smin_value;
5893 init_s64_max = (s32)reg->smax_value;
5894 init_s64_min = (s32)reg->smin_value;
5897 s64_max = max(init_s64_max, init_s64_min);
5898 s64_min = min(init_s64_max, init_s64_min);
5900 /* both of s64_max/s64_min positive or negative */
5901 if (s64_max >= 0 == s64_min >= 0) {
5902 reg->smin_value = reg->s32_min_value = s64_min;
5903 reg->smax_value = reg->s32_max_value = s64_max;
5904 reg->umin_value = reg->u32_min_value = s64_min;
5905 reg->umax_value = reg->u32_max_value = s64_max;
5906 reg->var_off = tnum_range(s64_min, s64_max);
5911 set_sext64_default_val(reg, size);
5914 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
5917 reg->s32_min_value = S8_MIN;
5918 reg->s32_max_value = S8_MAX;
5921 reg->s32_min_value = S16_MIN;
5922 reg->s32_max_value = S16_MAX;
5924 reg->u32_min_value = 0;
5925 reg->u32_max_value = U32_MAX;
5928 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
5930 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
5931 u32 top_smax_value, top_smin_value;
5932 u32 num_bits = size * 8;
5934 if (tnum_is_const(reg->var_off)) {
5935 u32_val = reg->var_off.value;
5937 reg->var_off = tnum_const((s8)u32_val);
5939 reg->var_off = tnum_const((s16)u32_val);
5941 u32_val = reg->var_off.value;
5942 reg->s32_min_value = reg->s32_max_value = u32_val;
5943 reg->u32_min_value = reg->u32_max_value = u32_val;
5947 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
5948 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
5950 if (top_smax_value != top_smin_value)
5953 /* find the s32_min and s32_min after sign extension */
5955 init_s32_max = (s8)reg->s32_max_value;
5956 init_s32_min = (s8)reg->s32_min_value;
5959 init_s32_max = (s16)reg->s32_max_value;
5960 init_s32_min = (s16)reg->s32_min_value;
5962 s32_max = max(init_s32_max, init_s32_min);
5963 s32_min = min(init_s32_max, init_s32_min);
5965 if (s32_min >= 0 == s32_max >= 0) {
5966 reg->s32_min_value = s32_min;
5967 reg->s32_max_value = s32_max;
5968 reg->u32_min_value = (u32)s32_min;
5969 reg->u32_max_value = (u32)s32_max;
5974 set_sext32_default_val(reg, size);
5977 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5979 /* A map is considered read-only if the following condition are true:
5981 * 1) BPF program side cannot change any of the map content. The
5982 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5983 * and was set at map creation time.
5984 * 2) The map value(s) have been initialized from user space by a
5985 * loader and then "frozen", such that no new map update/delete
5986 * operations from syscall side are possible for the rest of
5987 * the map's lifetime from that point onwards.
5988 * 3) Any parallel/pending map update/delete operations from syscall
5989 * side have been completed. Only after that point, it's safe to
5990 * assume that map value(s) are immutable.
5992 return (map->map_flags & BPF_F_RDONLY_PROG) &&
5993 READ_ONCE(map->frozen) &&
5994 !bpf_map_write_active(map);
5997 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6004 err = map->ops->map_direct_value_addr(map, &addr, off);
6007 ptr = (void *)(long)addr + off;
6011 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6014 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6017 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6028 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
6029 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6030 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
6033 * Allow list few fields as RCU trusted or full trusted.
6034 * This logic doesn't allow mix tagging and will be removed once GCC supports
6038 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6039 BTF_TYPE_SAFE_RCU(struct task_struct) {
6040 const cpumask_t *cpus_ptr;
6041 struct css_set __rcu *cgroups;
6042 struct task_struct __rcu *real_parent;
6043 struct task_struct *group_leader;
6046 BTF_TYPE_SAFE_RCU(struct cgroup) {
6047 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6048 struct kernfs_node *kn;
6051 BTF_TYPE_SAFE_RCU(struct css_set) {
6052 struct cgroup *dfl_cgrp;
6055 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6056 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6057 struct file __rcu *exe_file;
6060 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6061 * because bpf prog accessible sockets are SOCK_RCU_FREE.
6063 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6067 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6071 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6072 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6073 struct seq_file *seq;
6076 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6077 struct bpf_iter_meta *meta;
6078 struct task_struct *task;
6081 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6085 BTF_TYPE_SAFE_TRUSTED(struct file) {
6086 struct inode *f_inode;
6089 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6090 /* no negative dentry-s in places where bpf can see it */
6091 struct inode *d_inode;
6094 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6098 static bool type_is_rcu(struct bpf_verifier_env *env,
6099 struct bpf_reg_state *reg,
6100 const char *field_name, u32 btf_id)
6102 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6103 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6104 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6106 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6109 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6110 struct bpf_reg_state *reg,
6111 const char *field_name, u32 btf_id)
6113 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6114 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6115 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6117 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6120 static bool type_is_trusted(struct bpf_verifier_env *env,
6121 struct bpf_reg_state *reg,
6122 const char *field_name, u32 btf_id)
6124 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6125 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6126 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6127 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6128 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6129 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6131 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6134 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6135 struct bpf_reg_state *regs,
6136 int regno, int off, int size,
6137 enum bpf_access_type atype,
6140 struct bpf_reg_state *reg = regs + regno;
6141 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6142 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6143 const char *field_name = NULL;
6144 enum bpf_type_flag flag = 0;
6148 if (!env->allow_ptr_leaks) {
6150 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6154 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6156 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6162 "R%d is ptr_%s invalid negative access: off=%d\n",
6166 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6169 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6171 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6172 regno, tname, off, tn_buf);
6176 if (reg->type & MEM_USER) {
6178 "R%d is ptr_%s access user memory: off=%d\n",
6183 if (reg->type & MEM_PERCPU) {
6185 "R%d is ptr_%s access percpu memory: off=%d\n",
6190 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6191 if (!btf_is_kernel(reg->btf)) {
6192 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6195 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6197 /* Writes are permitted with default btf_struct_access for
6198 * program allocated objects (which always have ref_obj_id > 0),
6199 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6201 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6202 verbose(env, "only read is supported\n");
6206 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6208 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6212 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6218 if (ret != PTR_TO_BTF_ID) {
6221 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6222 /* If this is an untrusted pointer, all pointers formed by walking it
6223 * also inherit the untrusted flag.
6225 flag = PTR_UNTRUSTED;
6227 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6228 /* By default any pointer obtained from walking a trusted pointer is no
6229 * longer trusted, unless the field being accessed has explicitly been
6230 * marked as inheriting its parent's state of trust (either full or RCU).
6232 * 'cgroups' pointer is untrusted if task->cgroups dereference
6233 * happened in a sleepable program outside of bpf_rcu_read_lock()
6234 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6235 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6237 * A regular RCU-protected pointer with __rcu tag can also be deemed
6238 * trusted if we are in an RCU CS. Such pointer can be NULL.
6240 if (type_is_trusted(env, reg, field_name, btf_id)) {
6241 flag |= PTR_TRUSTED;
6242 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6243 if (type_is_rcu(env, reg, field_name, btf_id)) {
6244 /* ignore __rcu tag and mark it MEM_RCU */
6246 } else if (flag & MEM_RCU ||
6247 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6248 /* __rcu tagged pointers can be NULL */
6249 flag |= MEM_RCU | PTR_MAYBE_NULL;
6251 /* We always trust them */
6252 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6253 flag & PTR_UNTRUSTED)
6254 flag &= ~PTR_UNTRUSTED;
6255 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6258 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6259 clear_trusted_flags(&flag);
6263 * If not in RCU CS or MEM_RCU pointer can be NULL then
6264 * aggressively mark as untrusted otherwise such
6265 * pointers will be plain PTR_TO_BTF_ID without flags
6266 * and will be allowed to be passed into helpers for
6269 flag = PTR_UNTRUSTED;
6272 /* Old compat. Deprecated */
6273 clear_trusted_flags(&flag);
6276 if (atype == BPF_READ && value_regno >= 0)
6277 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6282 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6283 struct bpf_reg_state *regs,
6284 int regno, int off, int size,
6285 enum bpf_access_type atype,
6288 struct bpf_reg_state *reg = regs + regno;
6289 struct bpf_map *map = reg->map_ptr;
6290 struct bpf_reg_state map_reg;
6291 enum bpf_type_flag flag = 0;
6292 const struct btf_type *t;
6298 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6302 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6303 verbose(env, "map_ptr access not supported for map type %d\n",
6308 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6309 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6311 if (!env->allow_ptr_leaks) {
6313 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6319 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6324 if (atype != BPF_READ) {
6325 verbose(env, "only read from %s is supported\n", tname);
6329 /* Simulate access to a PTR_TO_BTF_ID */
6330 memset(&map_reg, 0, sizeof(map_reg));
6331 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6332 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6336 if (value_regno >= 0)
6337 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6342 /* Check that the stack access at the given offset is within bounds. The
6343 * maximum valid offset is -1.
6345 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6346 * -state->allocated_stack for reads.
6348 static int check_stack_slot_within_bounds(int off,
6349 struct bpf_func_state *state,
6350 enum bpf_access_type t)
6355 min_valid_off = -MAX_BPF_STACK;
6357 min_valid_off = -state->allocated_stack;
6359 if (off < min_valid_off || off > -1)
6364 /* Check that the stack access at 'regno + off' falls within the maximum stack
6367 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6369 static int check_stack_access_within_bounds(
6370 struct bpf_verifier_env *env,
6371 int regno, int off, int access_size,
6372 enum bpf_access_src src, enum bpf_access_type type)
6374 struct bpf_reg_state *regs = cur_regs(env);
6375 struct bpf_reg_state *reg = regs + regno;
6376 struct bpf_func_state *state = func(env, reg);
6377 int min_off, max_off;
6381 if (src == ACCESS_HELPER)
6382 /* We don't know if helpers are reading or writing (or both). */
6383 err_extra = " indirect access to";
6384 else if (type == BPF_READ)
6385 err_extra = " read from";
6387 err_extra = " write to";
6389 if (tnum_is_const(reg->var_off)) {
6390 min_off = reg->var_off.value + off;
6391 if (access_size > 0)
6392 max_off = min_off + access_size - 1;
6396 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6397 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6398 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6402 min_off = reg->smin_value + off;
6403 if (access_size > 0)
6404 max_off = reg->smax_value + off + access_size - 1;
6409 err = check_stack_slot_within_bounds(min_off, state, type);
6411 err = check_stack_slot_within_bounds(max_off, state, type);
6414 if (tnum_is_const(reg->var_off)) {
6415 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6416 err_extra, regno, off, access_size);
6420 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6421 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6422 err_extra, regno, tn_buf, access_size);
6428 /* check whether memory at (regno + off) is accessible for t = (read | write)
6429 * if t==write, value_regno is a register which value is stored into memory
6430 * if t==read, value_regno is a register which will receive the value from memory
6431 * if t==write && value_regno==-1, some unknown value is stored into memory
6432 * if t==read && value_regno==-1, don't care what we read from memory
6434 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6435 int off, int bpf_size, enum bpf_access_type t,
6436 int value_regno, bool strict_alignment_once, bool is_ldsx)
6438 struct bpf_reg_state *regs = cur_regs(env);
6439 struct bpf_reg_state *reg = regs + regno;
6440 struct bpf_func_state *state;
6443 size = bpf_size_to_bytes(bpf_size);
6447 /* alignment checks will add in reg->off themselves */
6448 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6452 /* for access checks, reg->off is just part of off */
6455 if (reg->type == PTR_TO_MAP_KEY) {
6456 if (t == BPF_WRITE) {
6457 verbose(env, "write to change key R%d not allowed\n", regno);
6461 err = check_mem_region_access(env, regno, off, size,
6462 reg->map_ptr->key_size, false);
6465 if (value_regno >= 0)
6466 mark_reg_unknown(env, regs, value_regno);
6467 } else if (reg->type == PTR_TO_MAP_VALUE) {
6468 struct btf_field *kptr_field = NULL;
6470 if (t == BPF_WRITE && value_regno >= 0 &&
6471 is_pointer_value(env, value_regno)) {
6472 verbose(env, "R%d leaks addr into map\n", value_regno);
6475 err = check_map_access_type(env, regno, off, size, t);
6478 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6481 if (tnum_is_const(reg->var_off))
6482 kptr_field = btf_record_find(reg->map_ptr->record,
6483 off + reg->var_off.value, BPF_KPTR);
6485 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6486 } else if (t == BPF_READ && value_regno >= 0) {
6487 struct bpf_map *map = reg->map_ptr;
6489 /* if map is read-only, track its contents as scalars */
6490 if (tnum_is_const(reg->var_off) &&
6491 bpf_map_is_rdonly(map) &&
6492 map->ops->map_direct_value_addr) {
6493 int map_off = off + reg->var_off.value;
6496 err = bpf_map_direct_read(map, map_off, size,
6501 regs[value_regno].type = SCALAR_VALUE;
6502 __mark_reg_known(®s[value_regno], val);
6504 mark_reg_unknown(env, regs, value_regno);
6507 } else if (base_type(reg->type) == PTR_TO_MEM) {
6508 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6510 if (type_may_be_null(reg->type)) {
6511 verbose(env, "R%d invalid mem access '%s'\n", regno,
6512 reg_type_str(env, reg->type));
6516 if (t == BPF_WRITE && rdonly_mem) {
6517 verbose(env, "R%d cannot write into %s\n",
6518 regno, reg_type_str(env, reg->type));
6522 if (t == BPF_WRITE && value_regno >= 0 &&
6523 is_pointer_value(env, value_regno)) {
6524 verbose(env, "R%d leaks addr into mem\n", value_regno);
6528 err = check_mem_region_access(env, regno, off, size,
6529 reg->mem_size, false);
6530 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6531 mark_reg_unknown(env, regs, value_regno);
6532 } else if (reg->type == PTR_TO_CTX) {
6533 enum bpf_reg_type reg_type = SCALAR_VALUE;
6534 struct btf *btf = NULL;
6537 if (t == BPF_WRITE && value_regno >= 0 &&
6538 is_pointer_value(env, value_regno)) {
6539 verbose(env, "R%d leaks addr into ctx\n", value_regno);
6543 err = check_ptr_off_reg(env, reg, regno);
6547 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
6550 verbose_linfo(env, insn_idx, "; ");
6551 if (!err && t == BPF_READ && value_regno >= 0) {
6552 /* ctx access returns either a scalar, or a
6553 * PTR_TO_PACKET[_META,_END]. In the latter
6554 * case, we know the offset is zero.
6556 if (reg_type == SCALAR_VALUE) {
6557 mark_reg_unknown(env, regs, value_regno);
6559 mark_reg_known_zero(env, regs,
6561 if (type_may_be_null(reg_type))
6562 regs[value_regno].id = ++env->id_gen;
6563 /* A load of ctx field could have different
6564 * actual load size with the one encoded in the
6565 * insn. When the dst is PTR, it is for sure not
6568 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6569 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6570 regs[value_regno].btf = btf;
6571 regs[value_regno].btf_id = btf_id;
6574 regs[value_regno].type = reg_type;
6577 } else if (reg->type == PTR_TO_STACK) {
6578 /* Basic bounds checks. */
6579 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6583 state = func(env, reg);
6584 err = update_stack_depth(env, state, off);
6589 err = check_stack_read(env, regno, off, size,
6592 err = check_stack_write(env, regno, off, size,
6593 value_regno, insn_idx);
6594 } else if (reg_is_pkt_pointer(reg)) {
6595 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6596 verbose(env, "cannot write into packet\n");
6599 if (t == BPF_WRITE && value_regno >= 0 &&
6600 is_pointer_value(env, value_regno)) {
6601 verbose(env, "R%d leaks addr into packet\n",
6605 err = check_packet_access(env, regno, off, size, false);
6606 if (!err && t == BPF_READ && value_regno >= 0)
6607 mark_reg_unknown(env, regs, value_regno);
6608 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6609 if (t == BPF_WRITE && value_regno >= 0 &&
6610 is_pointer_value(env, value_regno)) {
6611 verbose(env, "R%d leaks addr into flow keys\n",
6616 err = check_flow_keys_access(env, off, size);
6617 if (!err && t == BPF_READ && value_regno >= 0)
6618 mark_reg_unknown(env, regs, value_regno);
6619 } else if (type_is_sk_pointer(reg->type)) {
6620 if (t == BPF_WRITE) {
6621 verbose(env, "R%d cannot write into %s\n",
6622 regno, reg_type_str(env, reg->type));
6625 err = check_sock_access(env, insn_idx, regno, off, size, t);
6626 if (!err && value_regno >= 0)
6627 mark_reg_unknown(env, regs, value_regno);
6628 } else if (reg->type == PTR_TO_TP_BUFFER) {
6629 err = check_tp_buffer_access(env, reg, regno, off, size);
6630 if (!err && t == BPF_READ && value_regno >= 0)
6631 mark_reg_unknown(env, regs, value_regno);
6632 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6633 !type_may_be_null(reg->type)) {
6634 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6636 } else if (reg->type == CONST_PTR_TO_MAP) {
6637 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6639 } else if (base_type(reg->type) == PTR_TO_BUF) {
6640 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6644 if (t == BPF_WRITE) {
6645 verbose(env, "R%d cannot write into %s\n",
6646 regno, reg_type_str(env, reg->type));
6649 max_access = &env->prog->aux->max_rdonly_access;
6651 max_access = &env->prog->aux->max_rdwr_access;
6654 err = check_buffer_access(env, reg, regno, off, size, false,
6657 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6658 mark_reg_unknown(env, regs, value_regno);
6660 verbose(env, "R%d invalid mem access '%s'\n", regno,
6661 reg_type_str(env, reg->type));
6665 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6666 regs[value_regno].type == SCALAR_VALUE) {
6668 /* b/h/w load zero-extends, mark upper bits as known 0 */
6669 coerce_reg_to_size(®s[value_regno], size);
6671 coerce_reg_to_size_sx(®s[value_regno], size);
6676 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6681 switch (insn->imm) {
6683 case BPF_ADD | BPF_FETCH:
6685 case BPF_AND | BPF_FETCH:
6687 case BPF_OR | BPF_FETCH:
6689 case BPF_XOR | BPF_FETCH:
6694 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6698 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6699 verbose(env, "invalid atomic operand size\n");
6703 /* check src1 operand */
6704 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6708 /* check src2 operand */
6709 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6713 if (insn->imm == BPF_CMPXCHG) {
6714 /* Check comparison of R0 with memory location */
6715 const u32 aux_reg = BPF_REG_0;
6717 err = check_reg_arg(env, aux_reg, SRC_OP);
6721 if (is_pointer_value(env, aux_reg)) {
6722 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6727 if (is_pointer_value(env, insn->src_reg)) {
6728 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6732 if (is_ctx_reg(env, insn->dst_reg) ||
6733 is_pkt_reg(env, insn->dst_reg) ||
6734 is_flow_key_reg(env, insn->dst_reg) ||
6735 is_sk_reg(env, insn->dst_reg)) {
6736 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6738 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6742 if (insn->imm & BPF_FETCH) {
6743 if (insn->imm == BPF_CMPXCHG)
6744 load_reg = BPF_REG_0;
6746 load_reg = insn->src_reg;
6748 /* check and record load of old value */
6749 err = check_reg_arg(env, load_reg, DST_OP);
6753 /* This instruction accesses a memory location but doesn't
6754 * actually load it into a register.
6759 /* Check whether we can read the memory, with second call for fetch
6760 * case to simulate the register fill.
6762 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6763 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6764 if (!err && load_reg >= 0)
6765 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6766 BPF_SIZE(insn->code), BPF_READ, load_reg,
6771 /* Check whether we can write into the same memory. */
6772 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6773 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6780 /* When register 'regno' is used to read the stack (either directly or through
6781 * a helper function) make sure that it's within stack boundary and, depending
6782 * on the access type, that all elements of the stack are initialized.
6784 * 'off' includes 'regno->off', but not its dynamic part (if any).
6786 * All registers that have been spilled on the stack in the slots within the
6787 * read offsets are marked as read.
6789 static int check_stack_range_initialized(
6790 struct bpf_verifier_env *env, int regno, int off,
6791 int access_size, bool zero_size_allowed,
6792 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6794 struct bpf_reg_state *reg = reg_state(env, regno);
6795 struct bpf_func_state *state = func(env, reg);
6796 int err, min_off, max_off, i, j, slot, spi;
6797 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6798 enum bpf_access_type bounds_check_type;
6799 /* Some accesses can write anything into the stack, others are
6802 bool clobber = false;
6804 if (access_size == 0 && !zero_size_allowed) {
6805 verbose(env, "invalid zero-sized read\n");
6809 if (type == ACCESS_HELPER) {
6810 /* The bounds checks for writes are more permissive than for
6811 * reads. However, if raw_mode is not set, we'll do extra
6814 bounds_check_type = BPF_WRITE;
6817 bounds_check_type = BPF_READ;
6819 err = check_stack_access_within_bounds(env, regno, off, access_size,
6820 type, bounds_check_type);
6825 if (tnum_is_const(reg->var_off)) {
6826 min_off = max_off = reg->var_off.value + off;
6828 /* Variable offset is prohibited for unprivileged mode for
6829 * simplicity since it requires corresponding support in
6830 * Spectre masking for stack ALU.
6831 * See also retrieve_ptr_limit().
6833 if (!env->bypass_spec_v1) {
6836 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6837 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6838 regno, err_extra, tn_buf);
6841 /* Only initialized buffer on stack is allowed to be accessed
6842 * with variable offset. With uninitialized buffer it's hard to
6843 * guarantee that whole memory is marked as initialized on
6844 * helper return since specific bounds are unknown what may
6845 * cause uninitialized stack leaking.
6847 if (meta && meta->raw_mode)
6850 min_off = reg->smin_value + off;
6851 max_off = reg->smax_value + off;
6854 if (meta && meta->raw_mode) {
6855 /* Ensure we won't be overwriting dynptrs when simulating byte
6856 * by byte access in check_helper_call using meta.access_size.
6857 * This would be a problem if we have a helper in the future
6860 * helper(uninit_mem, len, dynptr)
6862 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6863 * may end up writing to dynptr itself when touching memory from
6864 * arg 1. This can be relaxed on a case by case basis for known
6865 * safe cases, but reject due to the possibilitiy of aliasing by
6868 for (i = min_off; i < max_off + access_size; i++) {
6869 int stack_off = -i - 1;
6872 /* raw_mode may write past allocated_stack */
6873 if (state->allocated_stack <= stack_off)
6875 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6876 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6880 meta->access_size = access_size;
6881 meta->regno = regno;
6885 for (i = min_off; i < max_off + access_size; i++) {
6889 spi = slot / BPF_REG_SIZE;
6890 if (state->allocated_stack <= slot)
6892 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6893 if (*stype == STACK_MISC)
6895 if ((*stype == STACK_ZERO) ||
6896 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6898 /* helper can write anything into the stack */
6899 *stype = STACK_MISC;
6904 if (is_spilled_reg(&state->stack[spi]) &&
6905 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6906 env->allow_ptr_leaks)) {
6908 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6909 for (j = 0; j < BPF_REG_SIZE; j++)
6910 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6916 if (tnum_is_const(reg->var_off)) {
6917 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6918 err_extra, regno, min_off, i - min_off, access_size);
6922 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6923 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6924 err_extra, regno, tn_buf, i - min_off, access_size);
6928 /* reading any byte out of 8-byte 'spill_slot' will cause
6929 * the whole slot to be marked as 'read'
6931 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6932 state->stack[spi].spilled_ptr.parent,
6934 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6935 * be sure that whether stack slot is written to or not. Hence,
6936 * we must still conservatively propagate reads upwards even if
6937 * helper may write to the entire memory range.
6940 return update_stack_depth(env, state, min_off);
6943 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6944 int access_size, bool zero_size_allowed,
6945 struct bpf_call_arg_meta *meta)
6947 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6950 switch (base_type(reg->type)) {
6952 case PTR_TO_PACKET_META:
6953 return check_packet_access(env, regno, reg->off, access_size,
6955 case PTR_TO_MAP_KEY:
6956 if (meta && meta->raw_mode) {
6957 verbose(env, "R%d cannot write into %s\n", regno,
6958 reg_type_str(env, reg->type));
6961 return check_mem_region_access(env, regno, reg->off, access_size,
6962 reg->map_ptr->key_size, false);
6963 case PTR_TO_MAP_VALUE:
6964 if (check_map_access_type(env, regno, reg->off, access_size,
6965 meta && meta->raw_mode ? BPF_WRITE :
6968 return check_map_access(env, regno, reg->off, access_size,
6969 zero_size_allowed, ACCESS_HELPER);
6971 if (type_is_rdonly_mem(reg->type)) {
6972 if (meta && meta->raw_mode) {
6973 verbose(env, "R%d cannot write into %s\n", regno,
6974 reg_type_str(env, reg->type));
6978 return check_mem_region_access(env, regno, reg->off,
6979 access_size, reg->mem_size,
6982 if (type_is_rdonly_mem(reg->type)) {
6983 if (meta && meta->raw_mode) {
6984 verbose(env, "R%d cannot write into %s\n", regno,
6985 reg_type_str(env, reg->type));
6989 max_access = &env->prog->aux->max_rdonly_access;
6991 max_access = &env->prog->aux->max_rdwr_access;
6993 return check_buffer_access(env, reg, regno, reg->off,
6994 access_size, zero_size_allowed,
6997 return check_stack_range_initialized(
6999 regno, reg->off, access_size,
7000 zero_size_allowed, ACCESS_HELPER, meta);
7002 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7003 access_size, BPF_READ, -1);
7005 /* in case the function doesn't know how to access the context,
7006 * (because we are in a program of type SYSCALL for example), we
7007 * can not statically check its size.
7008 * Dynamically check it now.
7010 if (!env->ops->convert_ctx_access) {
7011 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7012 int offset = access_size - 1;
7014 /* Allow zero-byte read from PTR_TO_CTX */
7015 if (access_size == 0)
7016 return zero_size_allowed ? 0 : -EACCES;
7018 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7019 atype, -1, false, false);
7023 default: /* scalar_value or invalid ptr */
7024 /* Allow zero-byte read from NULL, regardless of pointer type */
7025 if (zero_size_allowed && access_size == 0 &&
7026 register_is_null(reg))
7029 verbose(env, "R%d type=%s ", regno,
7030 reg_type_str(env, reg->type));
7031 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7036 static int check_mem_size_reg(struct bpf_verifier_env *env,
7037 struct bpf_reg_state *reg, u32 regno,
7038 bool zero_size_allowed,
7039 struct bpf_call_arg_meta *meta)
7043 /* This is used to refine r0 return value bounds for helpers
7044 * that enforce this value as an upper bound on return values.
7045 * See do_refine_retval_range() for helpers that can refine
7046 * the return value. C type of helper is u32 so we pull register
7047 * bound from umax_value however, if negative verifier errors
7048 * out. Only upper bounds can be learned because retval is an
7049 * int type and negative retvals are allowed.
7051 meta->msize_max_value = reg->umax_value;
7053 /* The register is SCALAR_VALUE; the access check
7054 * happens using its boundaries.
7056 if (!tnum_is_const(reg->var_off))
7057 /* For unprivileged variable accesses, disable raw
7058 * mode so that the program is required to
7059 * initialize all the memory that the helper could
7060 * just partially fill up.
7064 if (reg->smin_value < 0) {
7065 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7070 if (reg->umin_value == 0) {
7071 err = check_helper_mem_access(env, regno - 1, 0,
7078 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7079 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7083 err = check_helper_mem_access(env, regno - 1,
7085 zero_size_allowed, meta);
7087 err = mark_chain_precision(env, regno);
7091 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7092 u32 regno, u32 mem_size)
7094 bool may_be_null = type_may_be_null(reg->type);
7095 struct bpf_reg_state saved_reg;
7096 struct bpf_call_arg_meta meta;
7099 if (register_is_null(reg))
7102 memset(&meta, 0, sizeof(meta));
7103 /* Assuming that the register contains a value check if the memory
7104 * access is safe. Temporarily save and restore the register's state as
7105 * the conversion shouldn't be visible to a caller.
7109 mark_ptr_not_null_reg(reg);
7112 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7113 /* Check access for BPF_WRITE */
7114 meta.raw_mode = true;
7115 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7123 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7126 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7127 bool may_be_null = type_may_be_null(mem_reg->type);
7128 struct bpf_reg_state saved_reg;
7129 struct bpf_call_arg_meta meta;
7132 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7134 memset(&meta, 0, sizeof(meta));
7137 saved_reg = *mem_reg;
7138 mark_ptr_not_null_reg(mem_reg);
7141 err = check_mem_size_reg(env, reg, regno, true, &meta);
7142 /* Check access for BPF_WRITE */
7143 meta.raw_mode = true;
7144 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7147 *mem_reg = saved_reg;
7151 /* Implementation details:
7152 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7153 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7154 * Two bpf_map_lookups (even with the same key) will have different reg->id.
7155 * Two separate bpf_obj_new will also have different reg->id.
7156 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7157 * clears reg->id after value_or_null->value transition, since the verifier only
7158 * cares about the range of access to valid map value pointer and doesn't care
7159 * about actual address of the map element.
7160 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7161 * reg->id > 0 after value_or_null->value transition. By doing so
7162 * two bpf_map_lookups will be considered two different pointers that
7163 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7164 * returned from bpf_obj_new.
7165 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7167 * Since only one bpf_spin_lock is allowed the checks are simpler than
7168 * reg_is_refcounted() logic. The verifier needs to remember only
7169 * one spin_lock instead of array of acquired_refs.
7170 * cur_state->active_lock remembers which map value element or allocated
7171 * object got locked and clears it after bpf_spin_unlock.
7173 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7176 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7177 struct bpf_verifier_state *cur = env->cur_state;
7178 bool is_const = tnum_is_const(reg->var_off);
7179 u64 val = reg->var_off.value;
7180 struct bpf_map *map = NULL;
7181 struct btf *btf = NULL;
7182 struct btf_record *rec;
7186 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7190 if (reg->type == PTR_TO_MAP_VALUE) {
7194 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7202 rec = reg_btf_record(reg);
7203 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7204 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7205 map ? map->name : "kptr");
7208 if (rec->spin_lock_off != val + reg->off) {
7209 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7210 val + reg->off, rec->spin_lock_off);
7214 if (cur->active_lock.ptr) {
7216 "Locking two bpf_spin_locks are not allowed\n");
7220 cur->active_lock.ptr = map;
7222 cur->active_lock.ptr = btf;
7223 cur->active_lock.id = reg->id;
7232 if (!cur->active_lock.ptr) {
7233 verbose(env, "bpf_spin_unlock without taking a lock\n");
7236 if (cur->active_lock.ptr != ptr ||
7237 cur->active_lock.id != reg->id) {
7238 verbose(env, "bpf_spin_unlock of different lock\n");
7242 invalidate_non_owning_refs(env);
7244 cur->active_lock.ptr = NULL;
7245 cur->active_lock.id = 0;
7250 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7251 struct bpf_call_arg_meta *meta)
7253 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7254 bool is_const = tnum_is_const(reg->var_off);
7255 struct bpf_map *map = reg->map_ptr;
7256 u64 val = reg->var_off.value;
7260 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7265 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7269 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7270 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7273 if (map->record->timer_off != val + reg->off) {
7274 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7275 val + reg->off, map->record->timer_off);
7278 if (meta->map_ptr) {
7279 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7282 meta->map_uid = reg->map_uid;
7283 meta->map_ptr = map;
7287 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7288 struct bpf_call_arg_meta *meta)
7290 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7291 struct bpf_map *map_ptr = reg->map_ptr;
7292 struct btf_field *kptr_field;
7295 if (!tnum_is_const(reg->var_off)) {
7297 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7301 if (!map_ptr->btf) {
7302 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7306 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7307 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7311 meta->map_ptr = map_ptr;
7312 kptr_off = reg->off + reg->var_off.value;
7313 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7315 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7318 if (kptr_field->type != BPF_KPTR_REF) {
7319 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7322 meta->kptr_field = kptr_field;
7326 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7327 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7329 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7330 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7331 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7333 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7334 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7335 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7336 * mutate the view of the dynptr and also possibly destroy it. In the latter
7337 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7338 * memory that dynptr points to.
7340 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7341 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7342 * readonly dynptr view yet, hence only the first case is tracked and checked.
7344 * This is consistent with how C applies the const modifier to a struct object,
7345 * where the pointer itself inside bpf_dynptr becomes const but not what it
7348 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7349 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7351 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7352 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7354 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7357 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7358 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7360 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7361 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7365 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7366 * constructing a mutable bpf_dynptr object.
7368 * Currently, this is only possible with PTR_TO_STACK
7369 * pointing to a region of at least 16 bytes which doesn't
7370 * contain an existing bpf_dynptr.
7372 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7373 * mutated or destroyed. However, the memory it points to
7376 * None - Points to a initialized dynptr that can be mutated and
7377 * destroyed, including mutation of the memory it points
7380 if (arg_type & MEM_UNINIT) {
7383 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7384 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7388 /* we write BPF_DW bits (8 bytes) at a time */
7389 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7390 err = check_mem_access(env, insn_idx, regno,
7391 i, BPF_DW, BPF_WRITE, -1, false, false);
7396 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7397 } else /* MEM_RDONLY and None case from above */ {
7398 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7399 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7400 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7404 if (!is_dynptr_reg_valid_init(env, reg)) {
7406 "Expected an initialized dynptr as arg #%d\n",
7411 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7412 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7414 "Expected a dynptr of type %s as arg #%d\n",
7415 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7419 err = mark_dynptr_read(env, reg);
7424 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7426 struct bpf_func_state *state = func(env, reg);
7428 return state->stack[spi].spilled_ptr.ref_obj_id;
7431 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7433 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7436 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7438 return meta->kfunc_flags & KF_ITER_NEW;
7441 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7443 return meta->kfunc_flags & KF_ITER_NEXT;
7446 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7448 return meta->kfunc_flags & KF_ITER_DESTROY;
7451 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7453 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7454 * kfunc is iter state pointer
7456 return arg == 0 && is_iter_kfunc(meta);
7459 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7460 struct bpf_kfunc_call_arg_meta *meta)
7462 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7463 const struct btf_type *t;
7464 const struct btf_param *arg;
7465 int spi, err, i, nr_slots;
7468 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7469 arg = &btf_params(meta->func_proto)[0];
7470 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7471 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7472 nr_slots = t->size / BPF_REG_SIZE;
7474 if (is_iter_new_kfunc(meta)) {
7475 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7476 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7477 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7478 iter_type_str(meta->btf, btf_id), regno);
7482 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7483 err = check_mem_access(env, insn_idx, regno,
7484 i, BPF_DW, BPF_WRITE, -1, false, false);
7489 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7493 /* iter_next() or iter_destroy() expect initialized iter state*/
7494 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7495 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7496 iter_type_str(meta->btf, btf_id), regno);
7500 spi = iter_get_spi(env, reg, nr_slots);
7504 err = mark_iter_read(env, reg, spi, nr_slots);
7508 /* remember meta->iter info for process_iter_next_call() */
7509 meta->iter.spi = spi;
7510 meta->iter.frameno = reg->frameno;
7511 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7513 if (is_iter_destroy_kfunc(meta)) {
7514 err = unmark_stack_slots_iter(env, reg, nr_slots);
7523 /* process_iter_next_call() is called when verifier gets to iterator's next
7524 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7525 * to it as just "iter_next()" in comments below.
7527 * BPF verifier relies on a crucial contract for any iter_next()
7528 * implementation: it should *eventually* return NULL, and once that happens
7529 * it should keep returning NULL. That is, once iterator exhausts elements to
7530 * iterate, it should never reset or spuriously return new elements.
7532 * With the assumption of such contract, process_iter_next_call() simulates
7533 * a fork in the verifier state to validate loop logic correctness and safety
7534 * without having to simulate infinite amount of iterations.
7536 * In current state, we first assume that iter_next() returned NULL and
7537 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7538 * conditions we should not form an infinite loop and should eventually reach
7541 * Besides that, we also fork current state and enqueue it for later
7542 * verification. In a forked state we keep iterator state as ACTIVE
7543 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7544 * also bump iteration depth to prevent erroneous infinite loop detection
7545 * later on (see iter_active_depths_differ() comment for details). In this
7546 * state we assume that we'll eventually loop back to another iter_next()
7547 * calls (it could be in exactly same location or in some other instruction,
7548 * it doesn't matter, we don't make any unnecessary assumptions about this,
7549 * everything revolves around iterator state in a stack slot, not which
7550 * instruction is calling iter_next()). When that happens, we either will come
7551 * to iter_next() with equivalent state and can conclude that next iteration
7552 * will proceed in exactly the same way as we just verified, so it's safe to
7553 * assume that loop converges. If not, we'll go on another iteration
7554 * simulation with a different input state, until all possible starting states
7555 * are validated or we reach maximum number of instructions limit.
7557 * This way, we will either exhaustively discover all possible input states
7558 * that iterator loop can start with and eventually will converge, or we'll
7559 * effectively regress into bounded loop simulation logic and either reach
7560 * maximum number of instructions if loop is not provably convergent, or there
7561 * is some statically known limit on number of iterations (e.g., if there is
7562 * an explicit `if n > 100 then break;` statement somewhere in the loop).
7564 * One very subtle but very important aspect is that we *always* simulate NULL
7565 * condition first (as the current state) before we simulate non-NULL case.
7566 * This has to do with intricacies of scalar precision tracking. By simulating
7567 * "exit condition" of iter_next() returning NULL first, we make sure all the
7568 * relevant precision marks *that will be set **after** we exit iterator loop*
7569 * are propagated backwards to common parent state of NULL and non-NULL
7570 * branches. Thanks to that, state equivalence checks done later in forked
7571 * state, when reaching iter_next() for ACTIVE iterator, can assume that
7572 * precision marks are finalized and won't change. Because simulating another
7573 * ACTIVE iterator iteration won't change them (because given same input
7574 * states we'll end up with exactly same output states which we are currently
7575 * comparing; and verification after the loop already propagated back what
7576 * needs to be **additionally** tracked as precise). It's subtle, grok
7577 * precision tracking for more intuitive understanding.
7579 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7580 struct bpf_kfunc_call_arg_meta *meta)
7582 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7583 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7584 struct bpf_reg_state *cur_iter, *queued_iter;
7585 int iter_frameno = meta->iter.frameno;
7586 int iter_spi = meta->iter.spi;
7588 BTF_TYPE_EMIT(struct bpf_iter);
7590 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7592 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7593 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7594 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7595 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7599 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7600 /* branch out active iter state */
7601 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7605 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7606 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7607 queued_iter->iter.depth++;
7609 queued_fr = queued_st->frame[queued_st->curframe];
7610 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7613 /* switch to DRAINED state, but keep the depth unchanged */
7614 /* mark current iter state as drained and assume returned NULL */
7615 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7616 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7621 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7623 return type == ARG_CONST_SIZE ||
7624 type == ARG_CONST_SIZE_OR_ZERO;
7627 static bool arg_type_is_release(enum bpf_arg_type type)
7629 return type & OBJ_RELEASE;
7632 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7634 return base_type(type) == ARG_PTR_TO_DYNPTR;
7637 static int int_ptr_type_to_size(enum bpf_arg_type type)
7639 if (type == ARG_PTR_TO_INT)
7641 else if (type == ARG_PTR_TO_LONG)
7647 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7648 const struct bpf_call_arg_meta *meta,
7649 enum bpf_arg_type *arg_type)
7651 if (!meta->map_ptr) {
7652 /* kernel subsystem misconfigured verifier */
7653 verbose(env, "invalid map_ptr to access map->type\n");
7657 switch (meta->map_ptr->map_type) {
7658 case BPF_MAP_TYPE_SOCKMAP:
7659 case BPF_MAP_TYPE_SOCKHASH:
7660 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7661 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7663 verbose(env, "invalid arg_type for sockmap/sockhash\n");
7667 case BPF_MAP_TYPE_BLOOM_FILTER:
7668 if (meta->func_id == BPF_FUNC_map_peek_elem)
7669 *arg_type = ARG_PTR_TO_MAP_VALUE;
7677 struct bpf_reg_types {
7678 const enum bpf_reg_type types[10];
7682 static const struct bpf_reg_types sock_types = {
7692 static const struct bpf_reg_types btf_id_sock_common_types = {
7699 PTR_TO_BTF_ID | PTR_TRUSTED,
7701 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7705 static const struct bpf_reg_types mem_types = {
7713 PTR_TO_MEM | MEM_RINGBUF,
7715 PTR_TO_BTF_ID | PTR_TRUSTED,
7719 static const struct bpf_reg_types int_ptr_types = {
7729 static const struct bpf_reg_types spin_lock_types = {
7732 PTR_TO_BTF_ID | MEM_ALLOC,
7736 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7737 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7738 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7739 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7740 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7741 static const struct bpf_reg_types btf_ptr_types = {
7744 PTR_TO_BTF_ID | PTR_TRUSTED,
7745 PTR_TO_BTF_ID | MEM_RCU,
7748 static const struct bpf_reg_types percpu_btf_ptr_types = {
7750 PTR_TO_BTF_ID | MEM_PERCPU,
7751 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7754 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7755 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7756 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7757 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7758 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7759 static const struct bpf_reg_types dynptr_types = {
7762 CONST_PTR_TO_DYNPTR,
7766 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7767 [ARG_PTR_TO_MAP_KEY] = &mem_types,
7768 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
7769 [ARG_CONST_SIZE] = &scalar_types,
7770 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
7771 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
7772 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
7773 [ARG_PTR_TO_CTX] = &context_types,
7774 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
7776 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7778 [ARG_PTR_TO_SOCKET] = &fullsock_types,
7779 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
7780 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
7781 [ARG_PTR_TO_MEM] = &mem_types,
7782 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
7783 [ARG_PTR_TO_INT] = &int_ptr_types,
7784 [ARG_PTR_TO_LONG] = &int_ptr_types,
7785 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
7786 [ARG_PTR_TO_FUNC] = &func_ptr_types,
7787 [ARG_PTR_TO_STACK] = &stack_ptr_types,
7788 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
7789 [ARG_PTR_TO_TIMER] = &timer_types,
7790 [ARG_PTR_TO_KPTR] = &kptr_types,
7791 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
7794 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7795 enum bpf_arg_type arg_type,
7796 const u32 *arg_btf_id,
7797 struct bpf_call_arg_meta *meta)
7799 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7800 enum bpf_reg_type expected, type = reg->type;
7801 const struct bpf_reg_types *compatible;
7804 compatible = compatible_reg_types[base_type(arg_type)];
7806 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7810 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7811 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7813 * Same for MAYBE_NULL:
7815 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7816 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7818 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7820 * Therefore we fold these flags depending on the arg_type before comparison.
7822 if (arg_type & MEM_RDONLY)
7823 type &= ~MEM_RDONLY;
7824 if (arg_type & PTR_MAYBE_NULL)
7825 type &= ~PTR_MAYBE_NULL;
7826 if (base_type(arg_type) == ARG_PTR_TO_MEM)
7827 type &= ~DYNPTR_TYPE_FLAG_MASK;
7829 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7832 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7833 expected = compatible->types[i];
7834 if (expected == NOT_INIT)
7837 if (type == expected)
7841 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7842 for (j = 0; j + 1 < i; j++)
7843 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7844 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7848 if (base_type(reg->type) != PTR_TO_BTF_ID)
7851 if (compatible == &mem_types) {
7852 if (!(arg_type & MEM_RDONLY)) {
7854 "%s() may write into memory pointed by R%d type=%s\n",
7855 func_id_name(meta->func_id),
7856 regno, reg_type_str(env, reg->type));
7862 switch ((int)reg->type) {
7864 case PTR_TO_BTF_ID | PTR_TRUSTED:
7865 case PTR_TO_BTF_ID | MEM_RCU:
7866 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7867 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7869 /* For bpf_sk_release, it needs to match against first member
7870 * 'struct sock_common', hence make an exception for it. This
7871 * allows bpf_sk_release to work for multiple socket types.
7873 bool strict_type_match = arg_type_is_release(arg_type) &&
7874 meta->func_id != BPF_FUNC_sk_release;
7876 if (type_may_be_null(reg->type) &&
7877 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7878 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7883 if (!compatible->btf_id) {
7884 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7887 arg_btf_id = compatible->btf_id;
7890 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7891 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7894 if (arg_btf_id == BPF_PTR_POISON) {
7895 verbose(env, "verifier internal error:");
7896 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7901 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7902 btf_vmlinux, *arg_btf_id,
7903 strict_type_match)) {
7904 verbose(env, "R%d is of type %s but %s is expected\n",
7905 regno, btf_type_name(reg->btf, reg->btf_id),
7906 btf_type_name(btf_vmlinux, *arg_btf_id));
7912 case PTR_TO_BTF_ID | MEM_ALLOC:
7913 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7914 meta->func_id != BPF_FUNC_kptr_xchg) {
7915 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7918 /* Handled by helper specific checks */
7920 case PTR_TO_BTF_ID | MEM_PERCPU:
7921 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7922 /* Handled by helper specific checks */
7925 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7931 static struct btf_field *
7932 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7934 struct btf_field *field;
7935 struct btf_record *rec;
7937 rec = reg_btf_record(reg);
7941 field = btf_record_find(rec, off, fields);
7948 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7949 const struct bpf_reg_state *reg, int regno,
7950 enum bpf_arg_type arg_type)
7952 u32 type = reg->type;
7954 /* When referenced register is passed to release function, its fixed
7957 * We will check arg_type_is_release reg has ref_obj_id when storing
7958 * meta->release_regno.
7960 if (arg_type_is_release(arg_type)) {
7961 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7962 * may not directly point to the object being released, but to
7963 * dynptr pointing to such object, which might be at some offset
7964 * on the stack. In that case, we simply to fallback to the
7967 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7970 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7971 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7972 return __check_ptr_off_reg(env, reg, regno, true);
7974 verbose(env, "R%d must have zero offset when passed to release func\n",
7976 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7977 btf_type_name(reg->btf, reg->btf_id), reg->off);
7981 /* Doing check_ptr_off_reg check for the offset will catch this
7982 * because fixed_off_ok is false, but checking here allows us
7983 * to give the user a better error message.
7986 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7990 return __check_ptr_off_reg(env, reg, regno, false);
7994 /* Pointer types where both fixed and variable offset is explicitly allowed: */
7997 case PTR_TO_PACKET_META:
7998 case PTR_TO_MAP_KEY:
7999 case PTR_TO_MAP_VALUE:
8001 case PTR_TO_MEM | MEM_RDONLY:
8002 case PTR_TO_MEM | MEM_RINGBUF:
8004 case PTR_TO_BUF | MEM_RDONLY:
8007 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8011 case PTR_TO_BTF_ID | MEM_ALLOC:
8012 case PTR_TO_BTF_ID | PTR_TRUSTED:
8013 case PTR_TO_BTF_ID | MEM_RCU:
8014 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8015 /* When referenced PTR_TO_BTF_ID is passed to release function,
8016 * its fixed offset must be 0. In the other cases, fixed offset
8017 * can be non-zero. This was already checked above. So pass
8018 * fixed_off_ok as true to allow fixed offset for all other
8019 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8020 * still need to do checks instead of returning.
8022 return __check_ptr_off_reg(env, reg, regno, true);
8024 return __check_ptr_off_reg(env, reg, regno, false);
8028 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8029 const struct bpf_func_proto *fn,
8030 struct bpf_reg_state *regs)
8032 struct bpf_reg_state *state = NULL;
8035 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8036 if (arg_type_is_dynptr(fn->arg_type[i])) {
8038 verbose(env, "verifier internal error: multiple dynptr args\n");
8041 state = ®s[BPF_REG_1 + i];
8045 verbose(env, "verifier internal error: no dynptr arg found\n");
8050 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8052 struct bpf_func_state *state = func(env, reg);
8055 if (reg->type == CONST_PTR_TO_DYNPTR)
8057 spi = dynptr_get_spi(env, reg);
8060 return state->stack[spi].spilled_ptr.id;
8063 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8065 struct bpf_func_state *state = func(env, reg);
8068 if (reg->type == CONST_PTR_TO_DYNPTR)
8069 return reg->ref_obj_id;
8070 spi = dynptr_get_spi(env, reg);
8073 return state->stack[spi].spilled_ptr.ref_obj_id;
8076 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8077 struct bpf_reg_state *reg)
8079 struct bpf_func_state *state = func(env, reg);
8082 if (reg->type == CONST_PTR_TO_DYNPTR)
8083 return reg->dynptr.type;
8085 spi = __get_spi(reg->off);
8087 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8088 return BPF_DYNPTR_TYPE_INVALID;
8091 return state->stack[spi].spilled_ptr.dynptr.type;
8094 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8095 struct bpf_call_arg_meta *meta,
8096 const struct bpf_func_proto *fn,
8099 u32 regno = BPF_REG_1 + arg;
8100 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8101 enum bpf_arg_type arg_type = fn->arg_type[arg];
8102 enum bpf_reg_type type = reg->type;
8103 u32 *arg_btf_id = NULL;
8106 if (arg_type == ARG_DONTCARE)
8109 err = check_reg_arg(env, regno, SRC_OP);
8113 if (arg_type == ARG_ANYTHING) {
8114 if (is_pointer_value(env, regno)) {
8115 verbose(env, "R%d leaks addr into helper function\n",
8122 if (type_is_pkt_pointer(type) &&
8123 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8124 verbose(env, "helper access to the packet is not allowed\n");
8128 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8129 err = resolve_map_arg_type(env, meta, &arg_type);
8134 if (register_is_null(reg) && type_may_be_null(arg_type))
8135 /* A NULL register has a SCALAR_VALUE type, so skip
8138 goto skip_type_check;
8140 /* arg_btf_id and arg_size are in a union. */
8141 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8142 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8143 arg_btf_id = fn->arg_btf_id[arg];
8145 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8149 err = check_func_arg_reg_off(env, reg, regno, arg_type);
8154 if (arg_type_is_release(arg_type)) {
8155 if (arg_type_is_dynptr(arg_type)) {
8156 struct bpf_func_state *state = func(env, reg);
8159 /* Only dynptr created on stack can be released, thus
8160 * the get_spi and stack state checks for spilled_ptr
8161 * should only be done before process_dynptr_func for
8164 if (reg->type == PTR_TO_STACK) {
8165 spi = dynptr_get_spi(env, reg);
8166 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8167 verbose(env, "arg %d is an unacquired reference\n", regno);
8171 verbose(env, "cannot release unowned const bpf_dynptr\n");
8174 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8175 verbose(env, "R%d must be referenced when passed to release function\n",
8179 if (meta->release_regno) {
8180 verbose(env, "verifier internal error: more than one release argument\n");
8183 meta->release_regno = regno;
8186 if (reg->ref_obj_id) {
8187 if (meta->ref_obj_id) {
8188 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8189 regno, reg->ref_obj_id,
8193 meta->ref_obj_id = reg->ref_obj_id;
8196 switch (base_type(arg_type)) {
8197 case ARG_CONST_MAP_PTR:
8198 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8199 if (meta->map_ptr) {
8200 /* Use map_uid (which is unique id of inner map) to reject:
8201 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8202 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8203 * if (inner_map1 && inner_map2) {
8204 * timer = bpf_map_lookup_elem(inner_map1);
8206 * // mismatch would have been allowed
8207 * bpf_timer_init(timer, inner_map2);
8210 * Comparing map_ptr is enough to distinguish normal and outer maps.
8212 if (meta->map_ptr != reg->map_ptr ||
8213 meta->map_uid != reg->map_uid) {
8215 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8216 meta->map_uid, reg->map_uid);
8220 meta->map_ptr = reg->map_ptr;
8221 meta->map_uid = reg->map_uid;
8223 case ARG_PTR_TO_MAP_KEY:
8224 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8225 * check that [key, key + map->key_size) are within
8226 * stack limits and initialized
8228 if (!meta->map_ptr) {
8229 /* in function declaration map_ptr must come before
8230 * map_key, so that it's verified and known before
8231 * we have to check map_key here. Otherwise it means
8232 * that kernel subsystem misconfigured verifier
8234 verbose(env, "invalid map_ptr to access map->key\n");
8237 err = check_helper_mem_access(env, regno,
8238 meta->map_ptr->key_size, false,
8241 case ARG_PTR_TO_MAP_VALUE:
8242 if (type_may_be_null(arg_type) && register_is_null(reg))
8245 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8246 * check [value, value + map->value_size) validity
8248 if (!meta->map_ptr) {
8249 /* kernel subsystem misconfigured verifier */
8250 verbose(env, "invalid map_ptr to access map->value\n");
8253 meta->raw_mode = arg_type & MEM_UNINIT;
8254 err = check_helper_mem_access(env, regno,
8255 meta->map_ptr->value_size, false,
8258 case ARG_PTR_TO_PERCPU_BTF_ID:
8260 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8263 meta->ret_btf = reg->btf;
8264 meta->ret_btf_id = reg->btf_id;
8266 case ARG_PTR_TO_SPIN_LOCK:
8267 if (in_rbtree_lock_required_cb(env)) {
8268 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8271 if (meta->func_id == BPF_FUNC_spin_lock) {
8272 err = process_spin_lock(env, regno, true);
8275 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8276 err = process_spin_lock(env, regno, false);
8280 verbose(env, "verifier internal error\n");
8284 case ARG_PTR_TO_TIMER:
8285 err = process_timer_func(env, regno, meta);
8289 case ARG_PTR_TO_FUNC:
8290 meta->subprogno = reg->subprogno;
8292 case ARG_PTR_TO_MEM:
8293 /* The access to this pointer is only checked when we hit the
8294 * next is_mem_size argument below.
8296 meta->raw_mode = arg_type & MEM_UNINIT;
8297 if (arg_type & MEM_FIXED_SIZE) {
8298 err = check_helper_mem_access(env, regno,
8299 fn->arg_size[arg], false,
8303 case ARG_CONST_SIZE:
8304 err = check_mem_size_reg(env, reg, regno, false, meta);
8306 case ARG_CONST_SIZE_OR_ZERO:
8307 err = check_mem_size_reg(env, reg, regno, true, meta);
8309 case ARG_PTR_TO_DYNPTR:
8310 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8314 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8315 if (!tnum_is_const(reg->var_off)) {
8316 verbose(env, "R%d is not a known constant'\n",
8320 meta->mem_size = reg->var_off.value;
8321 err = mark_chain_precision(env, regno);
8325 case ARG_PTR_TO_INT:
8326 case ARG_PTR_TO_LONG:
8328 int size = int_ptr_type_to_size(arg_type);
8330 err = check_helper_mem_access(env, regno, size, false, meta);
8333 err = check_ptr_alignment(env, reg, 0, size, true);
8336 case ARG_PTR_TO_CONST_STR:
8338 struct bpf_map *map = reg->map_ptr;
8343 if (!bpf_map_is_rdonly(map)) {
8344 verbose(env, "R%d does not point to a readonly map'\n", regno);
8348 if (!tnum_is_const(reg->var_off)) {
8349 verbose(env, "R%d is not a constant address'\n", regno);
8353 if (!map->ops->map_direct_value_addr) {
8354 verbose(env, "no direct value access support for this map type\n");
8358 err = check_map_access(env, regno, reg->off,
8359 map->value_size - reg->off, false,
8364 map_off = reg->off + reg->var_off.value;
8365 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8367 verbose(env, "direct value access on string failed\n");
8371 str_ptr = (char *)(long)(map_addr);
8372 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8373 verbose(env, "string is not zero-terminated\n");
8378 case ARG_PTR_TO_KPTR:
8379 err = process_kptr_func(env, regno, meta);
8388 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8390 enum bpf_attach_type eatype = env->prog->expected_attach_type;
8391 enum bpf_prog_type type = resolve_prog_type(env->prog);
8393 if (func_id != BPF_FUNC_map_update_elem)
8396 /* It's not possible to get access to a locked struct sock in these
8397 * contexts, so updating is safe.
8400 case BPF_PROG_TYPE_TRACING:
8401 if (eatype == BPF_TRACE_ITER)
8404 case BPF_PROG_TYPE_SOCKET_FILTER:
8405 case BPF_PROG_TYPE_SCHED_CLS:
8406 case BPF_PROG_TYPE_SCHED_ACT:
8407 case BPF_PROG_TYPE_XDP:
8408 case BPF_PROG_TYPE_SK_REUSEPORT:
8409 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8410 case BPF_PROG_TYPE_SK_LOOKUP:
8416 verbose(env, "cannot update sockmap in this context\n");
8420 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8422 return env->prog->jit_requested &&
8423 bpf_jit_supports_subprog_tailcalls();
8426 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8427 struct bpf_map *map, int func_id)
8432 /* We need a two way check, first is from map perspective ... */
8433 switch (map->map_type) {
8434 case BPF_MAP_TYPE_PROG_ARRAY:
8435 if (func_id != BPF_FUNC_tail_call)
8438 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8439 if (func_id != BPF_FUNC_perf_event_read &&
8440 func_id != BPF_FUNC_perf_event_output &&
8441 func_id != BPF_FUNC_skb_output &&
8442 func_id != BPF_FUNC_perf_event_read_value &&
8443 func_id != BPF_FUNC_xdp_output)
8446 case BPF_MAP_TYPE_RINGBUF:
8447 if (func_id != BPF_FUNC_ringbuf_output &&
8448 func_id != BPF_FUNC_ringbuf_reserve &&
8449 func_id != BPF_FUNC_ringbuf_query &&
8450 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8451 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8452 func_id != BPF_FUNC_ringbuf_discard_dynptr)
8455 case BPF_MAP_TYPE_USER_RINGBUF:
8456 if (func_id != BPF_FUNC_user_ringbuf_drain)
8459 case BPF_MAP_TYPE_STACK_TRACE:
8460 if (func_id != BPF_FUNC_get_stackid)
8463 case BPF_MAP_TYPE_CGROUP_ARRAY:
8464 if (func_id != BPF_FUNC_skb_under_cgroup &&
8465 func_id != BPF_FUNC_current_task_under_cgroup)
8468 case BPF_MAP_TYPE_CGROUP_STORAGE:
8469 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8470 if (func_id != BPF_FUNC_get_local_storage)
8473 case BPF_MAP_TYPE_DEVMAP:
8474 case BPF_MAP_TYPE_DEVMAP_HASH:
8475 if (func_id != BPF_FUNC_redirect_map &&
8476 func_id != BPF_FUNC_map_lookup_elem)
8479 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8482 case BPF_MAP_TYPE_CPUMAP:
8483 if (func_id != BPF_FUNC_redirect_map)
8486 case BPF_MAP_TYPE_XSKMAP:
8487 if (func_id != BPF_FUNC_redirect_map &&
8488 func_id != BPF_FUNC_map_lookup_elem)
8491 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8492 case BPF_MAP_TYPE_HASH_OF_MAPS:
8493 if (func_id != BPF_FUNC_map_lookup_elem)
8496 case BPF_MAP_TYPE_SOCKMAP:
8497 if (func_id != BPF_FUNC_sk_redirect_map &&
8498 func_id != BPF_FUNC_sock_map_update &&
8499 func_id != BPF_FUNC_map_delete_elem &&
8500 func_id != BPF_FUNC_msg_redirect_map &&
8501 func_id != BPF_FUNC_sk_select_reuseport &&
8502 func_id != BPF_FUNC_map_lookup_elem &&
8503 !may_update_sockmap(env, func_id))
8506 case BPF_MAP_TYPE_SOCKHASH:
8507 if (func_id != BPF_FUNC_sk_redirect_hash &&
8508 func_id != BPF_FUNC_sock_hash_update &&
8509 func_id != BPF_FUNC_map_delete_elem &&
8510 func_id != BPF_FUNC_msg_redirect_hash &&
8511 func_id != BPF_FUNC_sk_select_reuseport &&
8512 func_id != BPF_FUNC_map_lookup_elem &&
8513 !may_update_sockmap(env, func_id))
8516 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8517 if (func_id != BPF_FUNC_sk_select_reuseport)
8520 case BPF_MAP_TYPE_QUEUE:
8521 case BPF_MAP_TYPE_STACK:
8522 if (func_id != BPF_FUNC_map_peek_elem &&
8523 func_id != BPF_FUNC_map_pop_elem &&
8524 func_id != BPF_FUNC_map_push_elem)
8527 case BPF_MAP_TYPE_SK_STORAGE:
8528 if (func_id != BPF_FUNC_sk_storage_get &&
8529 func_id != BPF_FUNC_sk_storage_delete &&
8530 func_id != BPF_FUNC_kptr_xchg)
8533 case BPF_MAP_TYPE_INODE_STORAGE:
8534 if (func_id != BPF_FUNC_inode_storage_get &&
8535 func_id != BPF_FUNC_inode_storage_delete &&
8536 func_id != BPF_FUNC_kptr_xchg)
8539 case BPF_MAP_TYPE_TASK_STORAGE:
8540 if (func_id != BPF_FUNC_task_storage_get &&
8541 func_id != BPF_FUNC_task_storage_delete &&
8542 func_id != BPF_FUNC_kptr_xchg)
8545 case BPF_MAP_TYPE_CGRP_STORAGE:
8546 if (func_id != BPF_FUNC_cgrp_storage_get &&
8547 func_id != BPF_FUNC_cgrp_storage_delete &&
8548 func_id != BPF_FUNC_kptr_xchg)
8551 case BPF_MAP_TYPE_BLOOM_FILTER:
8552 if (func_id != BPF_FUNC_map_peek_elem &&
8553 func_id != BPF_FUNC_map_push_elem)
8560 /* ... and second from the function itself. */
8562 case BPF_FUNC_tail_call:
8563 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8565 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8566 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8570 case BPF_FUNC_perf_event_read:
8571 case BPF_FUNC_perf_event_output:
8572 case BPF_FUNC_perf_event_read_value:
8573 case BPF_FUNC_skb_output:
8574 case BPF_FUNC_xdp_output:
8575 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8578 case BPF_FUNC_ringbuf_output:
8579 case BPF_FUNC_ringbuf_reserve:
8580 case BPF_FUNC_ringbuf_query:
8581 case BPF_FUNC_ringbuf_reserve_dynptr:
8582 case BPF_FUNC_ringbuf_submit_dynptr:
8583 case BPF_FUNC_ringbuf_discard_dynptr:
8584 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8587 case BPF_FUNC_user_ringbuf_drain:
8588 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8591 case BPF_FUNC_get_stackid:
8592 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8595 case BPF_FUNC_current_task_under_cgroup:
8596 case BPF_FUNC_skb_under_cgroup:
8597 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8600 case BPF_FUNC_redirect_map:
8601 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8602 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8603 map->map_type != BPF_MAP_TYPE_CPUMAP &&
8604 map->map_type != BPF_MAP_TYPE_XSKMAP)
8607 case BPF_FUNC_sk_redirect_map:
8608 case BPF_FUNC_msg_redirect_map:
8609 case BPF_FUNC_sock_map_update:
8610 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8613 case BPF_FUNC_sk_redirect_hash:
8614 case BPF_FUNC_msg_redirect_hash:
8615 case BPF_FUNC_sock_hash_update:
8616 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8619 case BPF_FUNC_get_local_storage:
8620 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8621 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8624 case BPF_FUNC_sk_select_reuseport:
8625 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8626 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8627 map->map_type != BPF_MAP_TYPE_SOCKHASH)
8630 case BPF_FUNC_map_pop_elem:
8631 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8632 map->map_type != BPF_MAP_TYPE_STACK)
8635 case BPF_FUNC_map_peek_elem:
8636 case BPF_FUNC_map_push_elem:
8637 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8638 map->map_type != BPF_MAP_TYPE_STACK &&
8639 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8642 case BPF_FUNC_map_lookup_percpu_elem:
8643 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8644 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8645 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8648 case BPF_FUNC_sk_storage_get:
8649 case BPF_FUNC_sk_storage_delete:
8650 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8653 case BPF_FUNC_inode_storage_get:
8654 case BPF_FUNC_inode_storage_delete:
8655 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8658 case BPF_FUNC_task_storage_get:
8659 case BPF_FUNC_task_storage_delete:
8660 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8663 case BPF_FUNC_cgrp_storage_get:
8664 case BPF_FUNC_cgrp_storage_delete:
8665 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8674 verbose(env, "cannot pass map_type %d into func %s#%d\n",
8675 map->map_type, func_id_name(func_id), func_id);
8679 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8683 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8685 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8687 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8689 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8691 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8694 /* We only support one arg being in raw mode at the moment,
8695 * which is sufficient for the helper functions we have
8701 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8703 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8704 bool has_size = fn->arg_size[arg] != 0;
8705 bool is_next_size = false;
8707 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8708 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8710 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8711 return is_next_size;
8713 return has_size == is_next_size || is_next_size == is_fixed;
8716 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8718 /* bpf_xxx(..., buf, len) call will access 'len'
8719 * bytes from memory 'buf'. Both arg types need
8720 * to be paired, so make sure there's no buggy
8721 * helper function specification.
8723 if (arg_type_is_mem_size(fn->arg1_type) ||
8724 check_args_pair_invalid(fn, 0) ||
8725 check_args_pair_invalid(fn, 1) ||
8726 check_args_pair_invalid(fn, 2) ||
8727 check_args_pair_invalid(fn, 3) ||
8728 check_args_pair_invalid(fn, 4))
8734 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8738 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8739 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8740 return !!fn->arg_btf_id[i];
8741 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8742 return fn->arg_btf_id[i] == BPF_PTR_POISON;
8743 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8744 /* arg_btf_id and arg_size are in a union. */
8745 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8746 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8753 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8755 return check_raw_mode_ok(fn) &&
8756 check_arg_pair_ok(fn) &&
8757 check_btf_id_ok(fn) ? 0 : -EINVAL;
8760 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8761 * are now invalid, so turn them into unknown SCALAR_VALUE.
8763 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8764 * since these slices point to packet data.
8766 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8768 struct bpf_func_state *state;
8769 struct bpf_reg_state *reg;
8771 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8772 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8773 mark_reg_invalid(env, reg);
8779 BEYOND_PKT_END = -2,
8782 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8784 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8785 struct bpf_reg_state *reg = &state->regs[regn];
8787 if (reg->type != PTR_TO_PACKET)
8788 /* PTR_TO_PACKET_META is not supported yet */
8791 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8792 * How far beyond pkt_end it goes is unknown.
8793 * if (!range_open) it's the case of pkt >= pkt_end
8794 * if (range_open) it's the case of pkt > pkt_end
8795 * hence this pointer is at least 1 byte bigger than pkt_end
8798 reg->range = BEYOND_PKT_END;
8800 reg->range = AT_PKT_END;
8803 /* The pointer with the specified id has released its reference to kernel
8804 * resources. Identify all copies of the same pointer and clear the reference.
8806 static int release_reference(struct bpf_verifier_env *env,
8809 struct bpf_func_state *state;
8810 struct bpf_reg_state *reg;
8813 err = release_reference_state(cur_func(env), ref_obj_id);
8817 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8818 if (reg->ref_obj_id == ref_obj_id)
8819 mark_reg_invalid(env, reg);
8825 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8827 struct bpf_func_state *unused;
8828 struct bpf_reg_state *reg;
8830 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8831 if (type_is_non_owning_ref(reg->type))
8832 mark_reg_invalid(env, reg);
8836 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8837 struct bpf_reg_state *regs)
8841 /* after the call registers r0 - r5 were scratched */
8842 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8843 mark_reg_not_init(env, regs, caller_saved[i]);
8844 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8848 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8849 struct bpf_func_state *caller,
8850 struct bpf_func_state *callee,
8853 static int set_callee_state(struct bpf_verifier_env *env,
8854 struct bpf_func_state *caller,
8855 struct bpf_func_state *callee, int insn_idx);
8857 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8858 int *insn_idx, int subprog,
8859 set_callee_state_fn set_callee_state_cb)
8861 struct bpf_verifier_state *state = env->cur_state;
8862 struct bpf_func_state *caller, *callee;
8865 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8866 verbose(env, "the call stack of %d frames is too deep\n",
8867 state->curframe + 2);
8871 caller = state->frame[state->curframe];
8872 if (state->frame[state->curframe + 1]) {
8873 verbose(env, "verifier bug. Frame %d already allocated\n",
8874 state->curframe + 1);
8878 err = btf_check_subprog_call(env, subprog, caller->regs);
8881 if (subprog_is_global(env, subprog)) {
8883 verbose(env, "Caller passes invalid args into func#%d\n",
8887 if (env->log.level & BPF_LOG_LEVEL)
8889 "Func#%d is global and valid. Skipping.\n",
8891 clear_caller_saved_regs(env, caller->regs);
8893 /* All global functions return a 64-bit SCALAR_VALUE */
8894 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8895 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8897 /* continue with next insn after call */
8902 /* set_callee_state is used for direct subprog calls, but we are
8903 * interested in validating only BPF helpers that can call subprogs as
8906 if (set_callee_state_cb != set_callee_state) {
8907 if (bpf_pseudo_kfunc_call(insn) &&
8908 !is_callback_calling_kfunc(insn->imm)) {
8909 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8910 func_id_name(insn->imm), insn->imm);
8912 } else if (!bpf_pseudo_kfunc_call(insn) &&
8913 !is_callback_calling_function(insn->imm)) { /* helper */
8914 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8915 func_id_name(insn->imm), insn->imm);
8920 if (insn->code == (BPF_JMP | BPF_CALL) &&
8921 insn->src_reg == 0 &&
8922 insn->imm == BPF_FUNC_timer_set_callback) {
8923 struct bpf_verifier_state *async_cb;
8925 /* there is no real recursion here. timer callbacks are async */
8926 env->subprog_info[subprog].is_async_cb = true;
8927 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8928 *insn_idx, subprog);
8931 callee = async_cb->frame[0];
8932 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8934 /* Convert bpf_timer_set_callback() args into timer callback args */
8935 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8939 clear_caller_saved_regs(env, caller->regs);
8940 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8941 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8942 /* continue with next insn after call */
8946 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8949 state->frame[state->curframe + 1] = callee;
8951 /* callee cannot access r0, r6 - r9 for reading and has to write
8952 * into its own stack before reading from it.
8953 * callee can read/write into caller's stack
8955 init_func_state(env, callee,
8956 /* remember the callsite, it will be used by bpf_exit */
8957 *insn_idx /* callsite */,
8958 state->curframe + 1 /* frameno within this callchain */,
8959 subprog /* subprog number within this prog */);
8961 /* Transfer references to the callee */
8962 err = copy_reference_state(callee, caller);
8966 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8970 clear_caller_saved_regs(env, caller->regs);
8972 /* only increment it after check_reg_arg() finished */
8975 /* and go analyze first insn of the callee */
8976 *insn_idx = env->subprog_info[subprog].start - 1;
8978 if (env->log.level & BPF_LOG_LEVEL) {
8979 verbose(env, "caller:\n");
8980 print_verifier_state(env, caller, true);
8981 verbose(env, "callee:\n");
8982 print_verifier_state(env, callee, true);
8987 free_func_state(callee);
8988 state->frame[state->curframe + 1] = NULL;
8992 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8993 struct bpf_func_state *caller,
8994 struct bpf_func_state *callee)
8996 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8997 * void *callback_ctx, u64 flags);
8998 * callback_fn(struct bpf_map *map, void *key, void *value,
8999 * void *callback_ctx);
9001 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9003 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9004 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9005 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9007 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9008 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9009 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9011 /* pointer to stack or null */
9012 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9015 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9019 static int set_callee_state(struct bpf_verifier_env *env,
9020 struct bpf_func_state *caller,
9021 struct bpf_func_state *callee, int insn_idx)
9025 /* copy r1 - r5 args that callee can access. The copy includes parent
9026 * pointers, which connects us up to the liveness chain
9028 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9029 callee->regs[i] = caller->regs[i];
9033 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9036 int subprog, target_insn;
9038 target_insn = *insn_idx + insn->imm + 1;
9039 subprog = find_subprog(env, target_insn);
9041 verbose(env, "verifier bug. No program starts at insn %d\n",
9046 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
9049 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9050 struct bpf_func_state *caller,
9051 struct bpf_func_state *callee,
9054 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9055 struct bpf_map *map;
9058 if (bpf_map_ptr_poisoned(insn_aux)) {
9059 verbose(env, "tail_call abusing map_ptr\n");
9063 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9064 if (!map->ops->map_set_for_each_callback_args ||
9065 !map->ops->map_for_each_callback) {
9066 verbose(env, "callback function not allowed for map\n");
9070 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9074 callee->in_callback_fn = true;
9075 callee->callback_ret_range = tnum_range(0, 1);
9079 static int set_loop_callback_state(struct bpf_verifier_env *env,
9080 struct bpf_func_state *caller,
9081 struct bpf_func_state *callee,
9084 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9086 * callback_fn(u32 index, void *callback_ctx);
9088 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9089 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9092 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9093 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9094 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9096 callee->in_callback_fn = true;
9097 callee->callback_ret_range = tnum_range(0, 1);
9101 static int set_timer_callback_state(struct bpf_verifier_env *env,
9102 struct bpf_func_state *caller,
9103 struct bpf_func_state *callee,
9106 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9108 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9109 * callback_fn(struct bpf_map *map, void *key, void *value);
9111 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9112 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9113 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9115 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9116 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9117 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9119 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9120 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9121 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9124 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9125 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9126 callee->in_async_callback_fn = true;
9127 callee->callback_ret_range = tnum_range(0, 1);
9131 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9132 struct bpf_func_state *caller,
9133 struct bpf_func_state *callee,
9136 /* bpf_find_vma(struct task_struct *task, u64 addr,
9137 * void *callback_fn, void *callback_ctx, u64 flags)
9138 * (callback_fn)(struct task_struct *task,
9139 * struct vm_area_struct *vma, void *callback_ctx);
9141 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9143 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9144 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9145 callee->regs[BPF_REG_2].btf = btf_vmlinux;
9146 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9148 /* pointer to stack or null */
9149 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9152 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9153 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9154 callee->in_callback_fn = true;
9155 callee->callback_ret_range = tnum_range(0, 1);
9159 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9160 struct bpf_func_state *caller,
9161 struct bpf_func_state *callee,
9164 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9165 * callback_ctx, u64 flags);
9166 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9168 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9169 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9170 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9173 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9174 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9175 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9177 callee->in_callback_fn = true;
9178 callee->callback_ret_range = tnum_range(0, 1);
9182 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9183 struct bpf_func_state *caller,
9184 struct bpf_func_state *callee,
9187 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9188 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9190 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9191 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9192 * by this point, so look at 'root'
9194 struct btf_field *field;
9196 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9198 if (!field || !field->graph_root.value_btf_id)
9201 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9202 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9203 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9204 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9206 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9207 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9208 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9209 callee->in_callback_fn = true;
9210 callee->callback_ret_range = tnum_range(0, 1);
9214 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9216 /* Are we currently verifying the callback for a rbtree helper that must
9217 * be called with lock held? If so, no need to complain about unreleased
9220 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9222 struct bpf_verifier_state *state = env->cur_state;
9223 struct bpf_insn *insn = env->prog->insnsi;
9224 struct bpf_func_state *callee;
9227 if (!state->curframe)
9230 callee = state->frame[state->curframe];
9232 if (!callee->in_callback_fn)
9235 kfunc_btf_id = insn[callee->callsite].imm;
9236 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9239 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9241 struct bpf_verifier_state *state = env->cur_state;
9242 struct bpf_func_state *caller, *callee;
9243 struct bpf_reg_state *r0;
9246 callee = state->frame[state->curframe];
9247 r0 = &callee->regs[BPF_REG_0];
9248 if (r0->type == PTR_TO_STACK) {
9249 /* technically it's ok to return caller's stack pointer
9250 * (or caller's caller's pointer) back to the caller,
9251 * since these pointers are valid. Only current stack
9252 * pointer will be invalid as soon as function exits,
9253 * but let's be conservative
9255 verbose(env, "cannot return stack pointer to the caller\n");
9259 caller = state->frame[state->curframe - 1];
9260 if (callee->in_callback_fn) {
9261 /* enforce R0 return value range [0, 1]. */
9262 struct tnum range = callee->callback_ret_range;
9264 if (r0->type != SCALAR_VALUE) {
9265 verbose(env, "R0 not a scalar value\n");
9268 if (!tnum_in(range, r0->var_off)) {
9269 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9273 /* return to the caller whatever r0 had in the callee */
9274 caller->regs[BPF_REG_0] = *r0;
9277 /* callback_fn frame should have released its own additions to parent's
9278 * reference state at this point, or check_reference_leak would
9279 * complain, hence it must be the same as the caller. There is no need
9282 if (!callee->in_callback_fn) {
9283 /* Transfer references to the caller */
9284 err = copy_reference_state(caller, callee);
9289 *insn_idx = callee->callsite + 1;
9290 if (env->log.level & BPF_LOG_LEVEL) {
9291 verbose(env, "returning from callee:\n");
9292 print_verifier_state(env, callee, true);
9293 verbose(env, "to caller at %d:\n", *insn_idx);
9294 print_verifier_state(env, caller, true);
9296 /* clear everything in the callee */
9297 free_func_state(callee);
9298 state->frame[state->curframe--] = NULL;
9302 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9304 struct bpf_call_arg_meta *meta)
9306 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
9308 if (ret_type != RET_INTEGER)
9312 case BPF_FUNC_get_stack:
9313 case BPF_FUNC_get_task_stack:
9314 case BPF_FUNC_probe_read_str:
9315 case BPF_FUNC_probe_read_kernel_str:
9316 case BPF_FUNC_probe_read_user_str:
9317 ret_reg->smax_value = meta->msize_max_value;
9318 ret_reg->s32_max_value = meta->msize_max_value;
9319 ret_reg->smin_value = -MAX_ERRNO;
9320 ret_reg->s32_min_value = -MAX_ERRNO;
9321 reg_bounds_sync(ret_reg);
9323 case BPF_FUNC_get_smp_processor_id:
9324 ret_reg->umax_value = nr_cpu_ids - 1;
9325 ret_reg->u32_max_value = nr_cpu_ids - 1;
9326 ret_reg->smax_value = nr_cpu_ids - 1;
9327 ret_reg->s32_max_value = nr_cpu_ids - 1;
9328 ret_reg->umin_value = 0;
9329 ret_reg->u32_min_value = 0;
9330 ret_reg->smin_value = 0;
9331 ret_reg->s32_min_value = 0;
9332 reg_bounds_sync(ret_reg);
9338 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9339 int func_id, int insn_idx)
9341 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9342 struct bpf_map *map = meta->map_ptr;
9344 if (func_id != BPF_FUNC_tail_call &&
9345 func_id != BPF_FUNC_map_lookup_elem &&
9346 func_id != BPF_FUNC_map_update_elem &&
9347 func_id != BPF_FUNC_map_delete_elem &&
9348 func_id != BPF_FUNC_map_push_elem &&
9349 func_id != BPF_FUNC_map_pop_elem &&
9350 func_id != BPF_FUNC_map_peek_elem &&
9351 func_id != BPF_FUNC_for_each_map_elem &&
9352 func_id != BPF_FUNC_redirect_map &&
9353 func_id != BPF_FUNC_map_lookup_percpu_elem)
9357 verbose(env, "kernel subsystem misconfigured verifier\n");
9361 /* In case of read-only, some additional restrictions
9362 * need to be applied in order to prevent altering the
9363 * state of the map from program side.
9365 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9366 (func_id == BPF_FUNC_map_delete_elem ||
9367 func_id == BPF_FUNC_map_update_elem ||
9368 func_id == BPF_FUNC_map_push_elem ||
9369 func_id == BPF_FUNC_map_pop_elem)) {
9370 verbose(env, "write into map forbidden\n");
9374 if (!BPF_MAP_PTR(aux->map_ptr_state))
9375 bpf_map_ptr_store(aux, meta->map_ptr,
9376 !meta->map_ptr->bypass_spec_v1);
9377 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9378 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9379 !meta->map_ptr->bypass_spec_v1);
9384 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9385 int func_id, int insn_idx)
9387 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9388 struct bpf_reg_state *regs = cur_regs(env), *reg;
9389 struct bpf_map *map = meta->map_ptr;
9393 if (func_id != BPF_FUNC_tail_call)
9395 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9396 verbose(env, "kernel subsystem misconfigured verifier\n");
9400 reg = ®s[BPF_REG_3];
9401 val = reg->var_off.value;
9402 max = map->max_entries;
9404 if (!(register_is_const(reg) && val < max)) {
9405 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9409 err = mark_chain_precision(env, BPF_REG_3);
9412 if (bpf_map_key_unseen(aux))
9413 bpf_map_key_store(aux, val);
9414 else if (!bpf_map_key_poisoned(aux) &&
9415 bpf_map_key_immediate(aux) != val)
9416 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9420 static int check_reference_leak(struct bpf_verifier_env *env)
9422 struct bpf_func_state *state = cur_func(env);
9423 bool refs_lingering = false;
9426 if (state->frameno && !state->in_callback_fn)
9429 for (i = 0; i < state->acquired_refs; i++) {
9430 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9432 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9433 state->refs[i].id, state->refs[i].insn_idx);
9434 refs_lingering = true;
9436 return refs_lingering ? -EINVAL : 0;
9439 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9440 struct bpf_reg_state *regs)
9442 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
9443 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
9444 struct bpf_map *fmt_map = fmt_reg->map_ptr;
9445 struct bpf_bprintf_data data = {};
9446 int err, fmt_map_off, num_args;
9450 /* data must be an array of u64 */
9451 if (data_len_reg->var_off.value % 8)
9453 num_args = data_len_reg->var_off.value / 8;
9455 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9456 * and map_direct_value_addr is set.
9458 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9459 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9462 verbose(env, "verifier bug\n");
9465 fmt = (char *)(long)fmt_addr + fmt_map_off;
9467 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9468 * can focus on validating the format specifiers.
9470 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9472 verbose(env, "Invalid format string\n");
9477 static int check_get_func_ip(struct bpf_verifier_env *env)
9479 enum bpf_prog_type type = resolve_prog_type(env->prog);
9480 int func_id = BPF_FUNC_get_func_ip;
9482 if (type == BPF_PROG_TYPE_TRACING) {
9483 if (!bpf_prog_has_trampoline(env->prog)) {
9484 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9485 func_id_name(func_id), func_id);
9489 } else if (type == BPF_PROG_TYPE_KPROBE) {
9493 verbose(env, "func %s#%d not supported for program type %d\n",
9494 func_id_name(func_id), func_id, type);
9498 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9500 return &env->insn_aux_data[env->insn_idx];
9503 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9505 struct bpf_reg_state *regs = cur_regs(env);
9506 struct bpf_reg_state *reg = ®s[BPF_REG_4];
9507 bool reg_is_null = register_is_null(reg);
9510 mark_chain_precision(env, BPF_REG_4);
9515 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9517 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9519 if (!state->initialized) {
9520 state->initialized = 1;
9521 state->fit_for_inline = loop_flag_is_zero(env);
9522 state->callback_subprogno = subprogno;
9526 if (!state->fit_for_inline)
9529 state->fit_for_inline = (loop_flag_is_zero(env) &&
9530 state->callback_subprogno == subprogno);
9533 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9536 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9537 const struct bpf_func_proto *fn = NULL;
9538 enum bpf_return_type ret_type;
9539 enum bpf_type_flag ret_flag;
9540 struct bpf_reg_state *regs;
9541 struct bpf_call_arg_meta meta;
9542 int insn_idx = *insn_idx_p;
9544 int i, err, func_id;
9546 /* find function prototype */
9547 func_id = insn->imm;
9548 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9549 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9554 if (env->ops->get_func_proto)
9555 fn = env->ops->get_func_proto(func_id, env->prog);
9557 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9562 /* eBPF programs must be GPL compatible to use GPL-ed functions */
9563 if (!env->prog->gpl_compatible && fn->gpl_only) {
9564 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9568 if (fn->allowed && !fn->allowed(env->prog)) {
9569 verbose(env, "helper call is not allowed in probe\n");
9573 if (!env->prog->aux->sleepable && fn->might_sleep) {
9574 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9578 /* With LD_ABS/IND some JITs save/restore skb from r1. */
9579 changes_data = bpf_helper_changes_pkt_data(fn->func);
9580 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9581 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9582 func_id_name(func_id), func_id);
9586 memset(&meta, 0, sizeof(meta));
9587 meta.pkt_access = fn->pkt_access;
9589 err = check_func_proto(fn, func_id);
9591 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9592 func_id_name(func_id), func_id);
9596 if (env->cur_state->active_rcu_lock) {
9597 if (fn->might_sleep) {
9598 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9599 func_id_name(func_id), func_id);
9603 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9604 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9607 meta.func_id = func_id;
9609 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9610 err = check_func_arg(env, i, &meta, fn, insn_idx);
9615 err = record_func_map(env, &meta, func_id, insn_idx);
9619 err = record_func_key(env, &meta, func_id, insn_idx);
9623 /* Mark slots with STACK_MISC in case of raw mode, stack offset
9624 * is inferred from register state.
9626 for (i = 0; i < meta.access_size; i++) {
9627 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9628 BPF_WRITE, -1, false, false);
9633 regs = cur_regs(env);
9635 if (meta.release_regno) {
9637 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9638 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9639 * is safe to do directly.
9641 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9642 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9643 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9646 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
9647 } else if (meta.ref_obj_id) {
9648 err = release_reference(env, meta.ref_obj_id);
9649 } else if (register_is_null(®s[meta.release_regno])) {
9650 /* meta.ref_obj_id can only be 0 if register that is meant to be
9651 * released is NULL, which must be > R0.
9656 verbose(env, "func %s#%d reference has not been acquired before\n",
9657 func_id_name(func_id), func_id);
9663 case BPF_FUNC_tail_call:
9664 err = check_reference_leak(env);
9666 verbose(env, "tail_call would lead to reference leak\n");
9670 case BPF_FUNC_get_local_storage:
9671 /* check that flags argument in get_local_storage(map, flags) is 0,
9672 * this is required because get_local_storage() can't return an error.
9674 if (!register_is_null(®s[BPF_REG_2])) {
9675 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9679 case BPF_FUNC_for_each_map_elem:
9680 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9681 set_map_elem_callback_state);
9683 case BPF_FUNC_timer_set_callback:
9684 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9685 set_timer_callback_state);
9687 case BPF_FUNC_find_vma:
9688 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9689 set_find_vma_callback_state);
9691 case BPF_FUNC_snprintf:
9692 err = check_bpf_snprintf_call(env, regs);
9695 update_loop_inline_state(env, meta.subprogno);
9696 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9697 set_loop_callback_state);
9699 case BPF_FUNC_dynptr_from_mem:
9700 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9701 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9702 reg_type_str(env, regs[BPF_REG_1].type));
9706 case BPF_FUNC_set_retval:
9707 if (prog_type == BPF_PROG_TYPE_LSM &&
9708 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9709 if (!env->prog->aux->attach_func_proto->type) {
9710 /* Make sure programs that attach to void
9711 * hooks don't try to modify return value.
9713 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9718 case BPF_FUNC_dynptr_data:
9720 struct bpf_reg_state *reg;
9723 reg = get_dynptr_arg_reg(env, fn, regs);
9728 if (meta.dynptr_id) {
9729 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9732 if (meta.ref_obj_id) {
9733 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9737 id = dynptr_id(env, reg);
9739 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9743 ref_obj_id = dynptr_ref_obj_id(env, reg);
9744 if (ref_obj_id < 0) {
9745 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9749 meta.dynptr_id = id;
9750 meta.ref_obj_id = ref_obj_id;
9754 case BPF_FUNC_dynptr_write:
9756 enum bpf_dynptr_type dynptr_type;
9757 struct bpf_reg_state *reg;
9759 reg = get_dynptr_arg_reg(env, fn, regs);
9763 dynptr_type = dynptr_get_type(env, reg);
9764 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9767 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9768 /* this will trigger clear_all_pkt_pointers(), which will
9769 * invalidate all dynptr slices associated with the skb
9771 changes_data = true;
9775 case BPF_FUNC_user_ringbuf_drain:
9776 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9777 set_user_ringbuf_callback_state);
9784 /* reset caller saved regs */
9785 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9786 mark_reg_not_init(env, regs, caller_saved[i]);
9787 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9790 /* helper call returns 64-bit value. */
9791 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9793 /* update return register (already marked as written above) */
9794 ret_type = fn->ret_type;
9795 ret_flag = type_flag(ret_type);
9797 switch (base_type(ret_type)) {
9799 /* sets type to SCALAR_VALUE */
9800 mark_reg_unknown(env, regs, BPF_REG_0);
9803 regs[BPF_REG_0].type = NOT_INIT;
9805 case RET_PTR_TO_MAP_VALUE:
9806 /* There is no offset yet applied, variable or fixed */
9807 mark_reg_known_zero(env, regs, BPF_REG_0);
9808 /* remember map_ptr, so that check_map_access()
9809 * can check 'value_size' boundary of memory access
9810 * to map element returned from bpf_map_lookup_elem()
9812 if (meta.map_ptr == NULL) {
9814 "kernel subsystem misconfigured verifier\n");
9817 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9818 regs[BPF_REG_0].map_uid = meta.map_uid;
9819 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9820 if (!type_may_be_null(ret_type) &&
9821 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9822 regs[BPF_REG_0].id = ++env->id_gen;
9825 case RET_PTR_TO_SOCKET:
9826 mark_reg_known_zero(env, regs, BPF_REG_0);
9827 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9829 case RET_PTR_TO_SOCK_COMMON:
9830 mark_reg_known_zero(env, regs, BPF_REG_0);
9831 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9833 case RET_PTR_TO_TCP_SOCK:
9834 mark_reg_known_zero(env, regs, BPF_REG_0);
9835 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9837 case RET_PTR_TO_MEM:
9838 mark_reg_known_zero(env, regs, BPF_REG_0);
9839 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9840 regs[BPF_REG_0].mem_size = meta.mem_size;
9842 case RET_PTR_TO_MEM_OR_BTF_ID:
9844 const struct btf_type *t;
9846 mark_reg_known_zero(env, regs, BPF_REG_0);
9847 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9848 if (!btf_type_is_struct(t)) {
9850 const struct btf_type *ret;
9853 /* resolve the type size of ksym. */
9854 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9856 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9857 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9858 tname, PTR_ERR(ret));
9861 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9862 regs[BPF_REG_0].mem_size = tsize;
9864 /* MEM_RDONLY may be carried from ret_flag, but it
9865 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9866 * it will confuse the check of PTR_TO_BTF_ID in
9867 * check_mem_access().
9869 ret_flag &= ~MEM_RDONLY;
9871 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9872 regs[BPF_REG_0].btf = meta.ret_btf;
9873 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9877 case RET_PTR_TO_BTF_ID:
9879 struct btf *ret_btf;
9882 mark_reg_known_zero(env, regs, BPF_REG_0);
9883 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9884 if (func_id == BPF_FUNC_kptr_xchg) {
9885 ret_btf = meta.kptr_field->kptr.btf;
9886 ret_btf_id = meta.kptr_field->kptr.btf_id;
9887 if (!btf_is_kernel(ret_btf))
9888 regs[BPF_REG_0].type |= MEM_ALLOC;
9890 if (fn->ret_btf_id == BPF_PTR_POISON) {
9891 verbose(env, "verifier internal error:");
9892 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9893 func_id_name(func_id));
9896 ret_btf = btf_vmlinux;
9897 ret_btf_id = *fn->ret_btf_id;
9899 if (ret_btf_id == 0) {
9900 verbose(env, "invalid return type %u of func %s#%d\n",
9901 base_type(ret_type), func_id_name(func_id),
9905 regs[BPF_REG_0].btf = ret_btf;
9906 regs[BPF_REG_0].btf_id = ret_btf_id;
9910 verbose(env, "unknown return type %u of func %s#%d\n",
9911 base_type(ret_type), func_id_name(func_id), func_id);
9915 if (type_may_be_null(regs[BPF_REG_0].type))
9916 regs[BPF_REG_0].id = ++env->id_gen;
9918 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9919 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9920 func_id_name(func_id), func_id);
9924 if (is_dynptr_ref_function(func_id))
9925 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9927 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9928 /* For release_reference() */
9929 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9930 } else if (is_acquire_function(func_id, meta.map_ptr)) {
9931 int id = acquire_reference_state(env, insn_idx);
9935 /* For mark_ptr_or_null_reg() */
9936 regs[BPF_REG_0].id = id;
9937 /* For release_reference() */
9938 regs[BPF_REG_0].ref_obj_id = id;
9941 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9943 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9947 if ((func_id == BPF_FUNC_get_stack ||
9948 func_id == BPF_FUNC_get_task_stack) &&
9949 !env->prog->has_callchain_buf) {
9950 const char *err_str;
9952 #ifdef CONFIG_PERF_EVENTS
9953 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9954 err_str = "cannot get callchain buffer for func %s#%d\n";
9957 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9960 verbose(env, err_str, func_id_name(func_id), func_id);
9964 env->prog->has_callchain_buf = true;
9967 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9968 env->prog->call_get_stack = true;
9970 if (func_id == BPF_FUNC_get_func_ip) {
9971 if (check_get_func_ip(env))
9973 env->prog->call_get_func_ip = true;
9977 clear_all_pkt_pointers(env);
9981 /* mark_btf_func_reg_size() is used when the reg size is determined by
9982 * the BTF func_proto's return value size and argument.
9984 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9987 struct bpf_reg_state *reg = &cur_regs(env)[regno];
9989 if (regno == BPF_REG_0) {
9990 /* Function return value */
9991 reg->live |= REG_LIVE_WRITTEN;
9992 reg->subreg_def = reg_size == sizeof(u64) ?
9993 DEF_NOT_SUBREG : env->insn_idx + 1;
9995 /* Function argument */
9996 if (reg_size == sizeof(u64)) {
9997 mark_insn_zext(env, reg);
9998 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10000 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10005 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10007 return meta->kfunc_flags & KF_ACQUIRE;
10010 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10012 return meta->kfunc_flags & KF_RELEASE;
10015 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10017 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10020 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10022 return meta->kfunc_flags & KF_SLEEPABLE;
10025 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10027 return meta->kfunc_flags & KF_DESTRUCTIVE;
10030 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10032 return meta->kfunc_flags & KF_RCU;
10035 static bool __kfunc_param_match_suffix(const struct btf *btf,
10036 const struct btf_param *arg,
10037 const char *suffix)
10039 int suffix_len = strlen(suffix), len;
10040 const char *param_name;
10042 /* In the future, this can be ported to use BTF tagging */
10043 param_name = btf_name_by_offset(btf, arg->name_off);
10044 if (str_is_empty(param_name))
10046 len = strlen(param_name);
10047 if (len < suffix_len)
10049 param_name += len - suffix_len;
10050 return !strncmp(param_name, suffix, suffix_len);
10053 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10054 const struct btf_param *arg,
10055 const struct bpf_reg_state *reg)
10057 const struct btf_type *t;
10059 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10060 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10063 return __kfunc_param_match_suffix(btf, arg, "__sz");
10066 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10067 const struct btf_param *arg,
10068 const struct bpf_reg_state *reg)
10070 const struct btf_type *t;
10072 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10073 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10076 return __kfunc_param_match_suffix(btf, arg, "__szk");
10079 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10081 return __kfunc_param_match_suffix(btf, arg, "__opt");
10084 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10086 return __kfunc_param_match_suffix(btf, arg, "__k");
10089 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10091 return __kfunc_param_match_suffix(btf, arg, "__ign");
10094 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10096 return __kfunc_param_match_suffix(btf, arg, "__alloc");
10099 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10101 return __kfunc_param_match_suffix(btf, arg, "__uninit");
10104 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10106 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10109 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10110 const struct btf_param *arg,
10113 int len, target_len = strlen(name);
10114 const char *param_name;
10116 param_name = btf_name_by_offset(btf, arg->name_off);
10117 if (str_is_empty(param_name))
10119 len = strlen(param_name);
10120 if (len != target_len)
10122 if (strcmp(param_name, name))
10130 KF_ARG_LIST_HEAD_ID,
10131 KF_ARG_LIST_NODE_ID,
10136 BTF_ID_LIST(kf_arg_btf_ids)
10137 BTF_ID(struct, bpf_dynptr_kern)
10138 BTF_ID(struct, bpf_list_head)
10139 BTF_ID(struct, bpf_list_node)
10140 BTF_ID(struct, bpf_rb_root)
10141 BTF_ID(struct, bpf_rb_node)
10143 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10144 const struct btf_param *arg, int type)
10146 const struct btf_type *t;
10149 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10152 if (!btf_type_is_ptr(t))
10154 t = btf_type_skip_modifiers(btf, t->type, &res_id);
10157 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10160 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10162 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10165 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10167 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10170 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10172 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10175 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10177 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10180 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10182 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10185 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10186 const struct btf_param *arg)
10188 const struct btf_type *t;
10190 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10197 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10198 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10199 const struct btf *btf,
10200 const struct btf_type *t, int rec)
10202 const struct btf_type *member_type;
10203 const struct btf_member *member;
10206 if (!btf_type_is_struct(t))
10209 for_each_member(i, t, member) {
10210 const struct btf_array *array;
10212 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10213 if (btf_type_is_struct(member_type)) {
10215 verbose(env, "max struct nesting depth exceeded\n");
10218 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10222 if (btf_type_is_array(member_type)) {
10223 array = btf_array(member_type);
10224 if (!array->nelems)
10226 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10227 if (!btf_type_is_scalar(member_type))
10231 if (!btf_type_is_scalar(member_type))
10237 enum kfunc_ptr_arg_type {
10239 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10240 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10241 KF_ARG_PTR_TO_DYNPTR,
10242 KF_ARG_PTR_TO_ITER,
10243 KF_ARG_PTR_TO_LIST_HEAD,
10244 KF_ARG_PTR_TO_LIST_NODE,
10245 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
10247 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
10248 KF_ARG_PTR_TO_CALLBACK,
10249 KF_ARG_PTR_TO_RB_ROOT,
10250 KF_ARG_PTR_TO_RB_NODE,
10253 enum special_kfunc_type {
10254 KF_bpf_obj_new_impl,
10255 KF_bpf_obj_drop_impl,
10256 KF_bpf_refcount_acquire_impl,
10257 KF_bpf_list_push_front_impl,
10258 KF_bpf_list_push_back_impl,
10259 KF_bpf_list_pop_front,
10260 KF_bpf_list_pop_back,
10261 KF_bpf_cast_to_kern_ctx,
10262 KF_bpf_rdonly_cast,
10263 KF_bpf_rcu_read_lock,
10264 KF_bpf_rcu_read_unlock,
10265 KF_bpf_rbtree_remove,
10266 KF_bpf_rbtree_add_impl,
10267 KF_bpf_rbtree_first,
10268 KF_bpf_dynptr_from_skb,
10269 KF_bpf_dynptr_from_xdp,
10270 KF_bpf_dynptr_slice,
10271 KF_bpf_dynptr_slice_rdwr,
10272 KF_bpf_dynptr_clone,
10275 BTF_SET_START(special_kfunc_set)
10276 BTF_ID(func, bpf_obj_new_impl)
10277 BTF_ID(func, bpf_obj_drop_impl)
10278 BTF_ID(func, bpf_refcount_acquire_impl)
10279 BTF_ID(func, bpf_list_push_front_impl)
10280 BTF_ID(func, bpf_list_push_back_impl)
10281 BTF_ID(func, bpf_list_pop_front)
10282 BTF_ID(func, bpf_list_pop_back)
10283 BTF_ID(func, bpf_cast_to_kern_ctx)
10284 BTF_ID(func, bpf_rdonly_cast)
10285 BTF_ID(func, bpf_rbtree_remove)
10286 BTF_ID(func, bpf_rbtree_add_impl)
10287 BTF_ID(func, bpf_rbtree_first)
10288 BTF_ID(func, bpf_dynptr_from_skb)
10289 BTF_ID(func, bpf_dynptr_from_xdp)
10290 BTF_ID(func, bpf_dynptr_slice)
10291 BTF_ID(func, bpf_dynptr_slice_rdwr)
10292 BTF_ID(func, bpf_dynptr_clone)
10293 BTF_SET_END(special_kfunc_set)
10295 BTF_ID_LIST(special_kfunc_list)
10296 BTF_ID(func, bpf_obj_new_impl)
10297 BTF_ID(func, bpf_obj_drop_impl)
10298 BTF_ID(func, bpf_refcount_acquire_impl)
10299 BTF_ID(func, bpf_list_push_front_impl)
10300 BTF_ID(func, bpf_list_push_back_impl)
10301 BTF_ID(func, bpf_list_pop_front)
10302 BTF_ID(func, bpf_list_pop_back)
10303 BTF_ID(func, bpf_cast_to_kern_ctx)
10304 BTF_ID(func, bpf_rdonly_cast)
10305 BTF_ID(func, bpf_rcu_read_lock)
10306 BTF_ID(func, bpf_rcu_read_unlock)
10307 BTF_ID(func, bpf_rbtree_remove)
10308 BTF_ID(func, bpf_rbtree_add_impl)
10309 BTF_ID(func, bpf_rbtree_first)
10310 BTF_ID(func, bpf_dynptr_from_skb)
10311 BTF_ID(func, bpf_dynptr_from_xdp)
10312 BTF_ID(func, bpf_dynptr_slice)
10313 BTF_ID(func, bpf_dynptr_slice_rdwr)
10314 BTF_ID(func, bpf_dynptr_clone)
10316 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10318 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10319 meta->arg_owning_ref) {
10323 return meta->kfunc_flags & KF_RET_NULL;
10326 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10328 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10331 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10333 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10336 static enum kfunc_ptr_arg_type
10337 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10338 struct bpf_kfunc_call_arg_meta *meta,
10339 const struct btf_type *t, const struct btf_type *ref_t,
10340 const char *ref_tname, const struct btf_param *args,
10341 int argno, int nargs)
10343 u32 regno = argno + 1;
10344 struct bpf_reg_state *regs = cur_regs(env);
10345 struct bpf_reg_state *reg = ®s[regno];
10346 bool arg_mem_size = false;
10348 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10349 return KF_ARG_PTR_TO_CTX;
10351 /* In this function, we verify the kfunc's BTF as per the argument type,
10352 * leaving the rest of the verification with respect to the register
10353 * type to our caller. When a set of conditions hold in the BTF type of
10354 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10356 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10357 return KF_ARG_PTR_TO_CTX;
10359 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10360 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10362 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10363 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10365 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10366 return KF_ARG_PTR_TO_DYNPTR;
10368 if (is_kfunc_arg_iter(meta, argno))
10369 return KF_ARG_PTR_TO_ITER;
10371 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10372 return KF_ARG_PTR_TO_LIST_HEAD;
10374 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10375 return KF_ARG_PTR_TO_LIST_NODE;
10377 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10378 return KF_ARG_PTR_TO_RB_ROOT;
10380 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10381 return KF_ARG_PTR_TO_RB_NODE;
10383 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10384 if (!btf_type_is_struct(ref_t)) {
10385 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10386 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10389 return KF_ARG_PTR_TO_BTF_ID;
10392 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10393 return KF_ARG_PTR_TO_CALLBACK;
10396 if (argno + 1 < nargs &&
10397 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
10398 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
10399 arg_mem_size = true;
10401 /* This is the catch all argument type of register types supported by
10402 * check_helper_mem_access. However, we only allow when argument type is
10403 * pointer to scalar, or struct composed (recursively) of scalars. When
10404 * arg_mem_size is true, the pointer can be void *.
10406 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10407 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10408 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10409 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10412 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10415 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10416 struct bpf_reg_state *reg,
10417 const struct btf_type *ref_t,
10418 const char *ref_tname, u32 ref_id,
10419 struct bpf_kfunc_call_arg_meta *meta,
10422 const struct btf_type *reg_ref_t;
10423 bool strict_type_match = false;
10424 const struct btf *reg_btf;
10425 const char *reg_ref_tname;
10428 if (base_type(reg->type) == PTR_TO_BTF_ID) {
10429 reg_btf = reg->btf;
10430 reg_ref_id = reg->btf_id;
10432 reg_btf = btf_vmlinux;
10433 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10436 /* Enforce strict type matching for calls to kfuncs that are acquiring
10437 * or releasing a reference, or are no-cast aliases. We do _not_
10438 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10439 * as we want to enable BPF programs to pass types that are bitwise
10440 * equivalent without forcing them to explicitly cast with something
10441 * like bpf_cast_to_kern_ctx().
10443 * For example, say we had a type like the following:
10445 * struct bpf_cpumask {
10446 * cpumask_t cpumask;
10447 * refcount_t usage;
10450 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10451 * to a struct cpumask, so it would be safe to pass a struct
10452 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10454 * The philosophy here is similar to how we allow scalars of different
10455 * types to be passed to kfuncs as long as the size is the same. The
10456 * only difference here is that we're simply allowing
10457 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10460 if (is_kfunc_acquire(meta) ||
10461 (is_kfunc_release(meta) && reg->ref_obj_id) ||
10462 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10463 strict_type_match = true;
10465 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10467 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
10468 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10469 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10470 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10471 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10472 btf_type_str(reg_ref_t), reg_ref_tname);
10478 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10480 struct bpf_verifier_state *state = env->cur_state;
10482 if (!state->active_lock.ptr) {
10483 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10487 if (type_flag(reg->type) & NON_OWN_REF) {
10488 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10492 reg->type |= NON_OWN_REF;
10496 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10498 struct bpf_func_state *state, *unused;
10499 struct bpf_reg_state *reg;
10502 state = cur_func(env);
10505 verbose(env, "verifier internal error: ref_obj_id is zero for "
10506 "owning -> non-owning conversion\n");
10510 for (i = 0; i < state->acquired_refs; i++) {
10511 if (state->refs[i].id != ref_obj_id)
10514 /* Clear ref_obj_id here so release_reference doesn't clobber
10517 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10518 if (reg->ref_obj_id == ref_obj_id) {
10519 reg->ref_obj_id = 0;
10520 ref_set_non_owning(env, reg);
10526 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10530 /* Implementation details:
10532 * Each register points to some region of memory, which we define as an
10533 * allocation. Each allocation may embed a bpf_spin_lock which protects any
10534 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10535 * allocation. The lock and the data it protects are colocated in the same
10538 * Hence, everytime a register holds a pointer value pointing to such
10539 * allocation, the verifier preserves a unique reg->id for it.
10541 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10542 * bpf_spin_lock is called.
10544 * To enable this, lock state in the verifier captures two values:
10545 * active_lock.ptr = Register's type specific pointer
10546 * active_lock.id = A unique ID for each register pointer value
10548 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10549 * supported register types.
10551 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10552 * allocated objects is the reg->btf pointer.
10554 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10555 * can establish the provenance of the map value statically for each distinct
10556 * lookup into such maps. They always contain a single map value hence unique
10557 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10559 * So, in case of global variables, they use array maps with max_entries = 1,
10560 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10561 * into the same map value as max_entries is 1, as described above).
10563 * In case of inner map lookups, the inner map pointer has same map_ptr as the
10564 * outer map pointer (in verifier context), but each lookup into an inner map
10565 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10566 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10567 * will get different reg->id assigned to each lookup, hence different
10570 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10571 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10572 * returned from bpf_obj_new. Each allocation receives a new reg->id.
10574 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10579 switch ((int)reg->type) {
10580 case PTR_TO_MAP_VALUE:
10581 ptr = reg->map_ptr;
10583 case PTR_TO_BTF_ID | MEM_ALLOC:
10587 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10592 if (!env->cur_state->active_lock.ptr)
10594 if (env->cur_state->active_lock.ptr != ptr ||
10595 env->cur_state->active_lock.id != id) {
10596 verbose(env, "held lock and object are not in the same allocation\n");
10602 static bool is_bpf_list_api_kfunc(u32 btf_id)
10604 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10605 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10606 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10607 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10610 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10612 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10613 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10614 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10617 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10619 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10620 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10623 static bool is_callback_calling_kfunc(u32 btf_id)
10625 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10628 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10630 return is_bpf_rbtree_api_kfunc(btf_id);
10633 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10634 enum btf_field_type head_field_type,
10639 switch (head_field_type) {
10640 case BPF_LIST_HEAD:
10641 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10644 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10647 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10648 btf_field_type_name(head_field_type));
10653 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10654 btf_field_type_name(head_field_type));
10658 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10659 enum btf_field_type node_field_type,
10664 switch (node_field_type) {
10665 case BPF_LIST_NODE:
10666 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10667 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10670 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10671 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10674 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10675 btf_field_type_name(node_field_type));
10680 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10681 btf_field_type_name(node_field_type));
10686 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10687 struct bpf_reg_state *reg, u32 regno,
10688 struct bpf_kfunc_call_arg_meta *meta,
10689 enum btf_field_type head_field_type,
10690 struct btf_field **head_field)
10692 const char *head_type_name;
10693 struct btf_field *field;
10694 struct btf_record *rec;
10697 if (meta->btf != btf_vmlinux) {
10698 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10702 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10705 head_type_name = btf_field_type_name(head_field_type);
10706 if (!tnum_is_const(reg->var_off)) {
10708 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10709 regno, head_type_name);
10713 rec = reg_btf_record(reg);
10714 head_off = reg->off + reg->var_off.value;
10715 field = btf_record_find(rec, head_off, head_field_type);
10717 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10721 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10722 if (check_reg_allocation_locked(env, reg)) {
10723 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10724 rec->spin_lock_off, head_type_name);
10729 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10732 *head_field = field;
10736 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10737 struct bpf_reg_state *reg, u32 regno,
10738 struct bpf_kfunc_call_arg_meta *meta)
10740 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10741 &meta->arg_list_head.field);
10744 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10745 struct bpf_reg_state *reg, u32 regno,
10746 struct bpf_kfunc_call_arg_meta *meta)
10748 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10749 &meta->arg_rbtree_root.field);
10753 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10754 struct bpf_reg_state *reg, u32 regno,
10755 struct bpf_kfunc_call_arg_meta *meta,
10756 enum btf_field_type head_field_type,
10757 enum btf_field_type node_field_type,
10758 struct btf_field **node_field)
10760 const char *node_type_name;
10761 const struct btf_type *et, *t;
10762 struct btf_field *field;
10765 if (meta->btf != btf_vmlinux) {
10766 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10770 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10773 node_type_name = btf_field_type_name(node_field_type);
10774 if (!tnum_is_const(reg->var_off)) {
10776 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10777 regno, node_type_name);
10781 node_off = reg->off + reg->var_off.value;
10782 field = reg_find_field_offset(reg, node_off, node_field_type);
10783 if (!field || field->offset != node_off) {
10784 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10788 field = *node_field;
10790 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10791 t = btf_type_by_id(reg->btf, reg->btf_id);
10792 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10793 field->graph_root.value_btf_id, true)) {
10794 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10795 "in struct %s, but arg is at offset=%d in struct %s\n",
10796 btf_field_type_name(head_field_type),
10797 btf_field_type_name(node_field_type),
10798 field->graph_root.node_offset,
10799 btf_name_by_offset(field->graph_root.btf, et->name_off),
10800 node_off, btf_name_by_offset(reg->btf, t->name_off));
10803 meta->arg_btf = reg->btf;
10804 meta->arg_btf_id = reg->btf_id;
10806 if (node_off != field->graph_root.node_offset) {
10807 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10808 node_off, btf_field_type_name(node_field_type),
10809 field->graph_root.node_offset,
10810 btf_name_by_offset(field->graph_root.btf, et->name_off));
10817 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10818 struct bpf_reg_state *reg, u32 regno,
10819 struct bpf_kfunc_call_arg_meta *meta)
10821 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10822 BPF_LIST_HEAD, BPF_LIST_NODE,
10823 &meta->arg_list_head.field);
10826 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10827 struct bpf_reg_state *reg, u32 regno,
10828 struct bpf_kfunc_call_arg_meta *meta)
10830 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10831 BPF_RB_ROOT, BPF_RB_NODE,
10832 &meta->arg_rbtree_root.field);
10835 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10838 const char *func_name = meta->func_name, *ref_tname;
10839 const struct btf *btf = meta->btf;
10840 const struct btf_param *args;
10841 struct btf_record *rec;
10845 args = (const struct btf_param *)(meta->func_proto + 1);
10846 nargs = btf_type_vlen(meta->func_proto);
10847 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10848 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10849 MAX_BPF_FUNC_REG_ARGS);
10853 /* Check that BTF function arguments match actual types that the
10856 for (i = 0; i < nargs; i++) {
10857 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
10858 const struct btf_type *t, *ref_t, *resolve_ret;
10859 enum bpf_arg_type arg_type = ARG_DONTCARE;
10860 u32 regno = i + 1, ref_id, type_size;
10861 bool is_ret_buf_sz = false;
10864 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10866 if (is_kfunc_arg_ignore(btf, &args[i]))
10869 if (btf_type_is_scalar(t)) {
10870 if (reg->type != SCALAR_VALUE) {
10871 verbose(env, "R%d is not a scalar\n", regno);
10875 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10876 if (meta->arg_constant.found) {
10877 verbose(env, "verifier internal error: only one constant argument permitted\n");
10880 if (!tnum_is_const(reg->var_off)) {
10881 verbose(env, "R%d must be a known constant\n", regno);
10884 ret = mark_chain_precision(env, regno);
10887 meta->arg_constant.found = true;
10888 meta->arg_constant.value = reg->var_off.value;
10889 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10890 meta->r0_rdonly = true;
10891 is_ret_buf_sz = true;
10892 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10893 is_ret_buf_sz = true;
10896 if (is_ret_buf_sz) {
10897 if (meta->r0_size) {
10898 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10902 if (!tnum_is_const(reg->var_off)) {
10903 verbose(env, "R%d is not a const\n", regno);
10907 meta->r0_size = reg->var_off.value;
10908 ret = mark_chain_precision(env, regno);
10915 if (!btf_type_is_ptr(t)) {
10916 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10920 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10921 (register_is_null(reg) || type_may_be_null(reg->type))) {
10922 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10926 if (reg->ref_obj_id) {
10927 if (is_kfunc_release(meta) && meta->ref_obj_id) {
10928 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10929 regno, reg->ref_obj_id,
10933 meta->ref_obj_id = reg->ref_obj_id;
10934 if (is_kfunc_release(meta))
10935 meta->release_regno = regno;
10938 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10939 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10941 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10942 if (kf_arg_type < 0)
10943 return kf_arg_type;
10945 switch (kf_arg_type) {
10946 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10947 case KF_ARG_PTR_TO_BTF_ID:
10948 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10951 if (!is_trusted_reg(reg)) {
10952 if (!is_kfunc_rcu(meta)) {
10953 verbose(env, "R%d must be referenced or trusted\n", regno);
10956 if (!is_rcu_reg(reg)) {
10957 verbose(env, "R%d must be a rcu pointer\n", regno);
10963 case KF_ARG_PTR_TO_CTX:
10964 /* Trusted arguments have the same offset checks as release arguments */
10965 arg_type |= OBJ_RELEASE;
10967 case KF_ARG_PTR_TO_DYNPTR:
10968 case KF_ARG_PTR_TO_ITER:
10969 case KF_ARG_PTR_TO_LIST_HEAD:
10970 case KF_ARG_PTR_TO_LIST_NODE:
10971 case KF_ARG_PTR_TO_RB_ROOT:
10972 case KF_ARG_PTR_TO_RB_NODE:
10973 case KF_ARG_PTR_TO_MEM:
10974 case KF_ARG_PTR_TO_MEM_SIZE:
10975 case KF_ARG_PTR_TO_CALLBACK:
10976 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10977 /* Trusted by default */
10984 if (is_kfunc_release(meta) && reg->ref_obj_id)
10985 arg_type |= OBJ_RELEASE;
10986 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10990 switch (kf_arg_type) {
10991 case KF_ARG_PTR_TO_CTX:
10992 if (reg->type != PTR_TO_CTX) {
10993 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10997 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10998 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11001 meta->ret_btf_id = ret;
11004 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11005 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11006 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11009 if (!reg->ref_obj_id) {
11010 verbose(env, "allocated object must be referenced\n");
11013 if (meta->btf == btf_vmlinux &&
11014 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11015 meta->arg_btf = reg->btf;
11016 meta->arg_btf_id = reg->btf_id;
11019 case KF_ARG_PTR_TO_DYNPTR:
11021 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11022 int clone_ref_obj_id = 0;
11024 if (reg->type != PTR_TO_STACK &&
11025 reg->type != CONST_PTR_TO_DYNPTR) {
11026 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11030 if (reg->type == CONST_PTR_TO_DYNPTR)
11031 dynptr_arg_type |= MEM_RDONLY;
11033 if (is_kfunc_arg_uninit(btf, &args[i]))
11034 dynptr_arg_type |= MEM_UNINIT;
11036 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11037 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11038 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11039 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11040 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11041 (dynptr_arg_type & MEM_UNINIT)) {
11042 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11044 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11045 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11049 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11050 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11051 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11052 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11057 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11061 if (!(dynptr_arg_type & MEM_UNINIT)) {
11062 int id = dynptr_id(env, reg);
11065 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11068 meta->initialized_dynptr.id = id;
11069 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11070 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11075 case KF_ARG_PTR_TO_ITER:
11076 ret = process_iter_arg(env, regno, insn_idx, meta);
11080 case KF_ARG_PTR_TO_LIST_HEAD:
11081 if (reg->type != PTR_TO_MAP_VALUE &&
11082 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11083 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11086 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11087 verbose(env, "allocated object must be referenced\n");
11090 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11094 case KF_ARG_PTR_TO_RB_ROOT:
11095 if (reg->type != PTR_TO_MAP_VALUE &&
11096 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11097 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11100 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11101 verbose(env, "allocated object must be referenced\n");
11104 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11108 case KF_ARG_PTR_TO_LIST_NODE:
11109 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11110 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11113 if (!reg->ref_obj_id) {
11114 verbose(env, "allocated object must be referenced\n");
11117 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11121 case KF_ARG_PTR_TO_RB_NODE:
11122 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11123 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11124 verbose(env, "rbtree_remove node input must be non-owning ref\n");
11127 if (in_rbtree_lock_required_cb(env)) {
11128 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11132 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11133 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11136 if (!reg->ref_obj_id) {
11137 verbose(env, "allocated object must be referenced\n");
11142 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11146 case KF_ARG_PTR_TO_BTF_ID:
11147 /* Only base_type is checked, further checks are done here */
11148 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11149 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11150 !reg2btf_ids[base_type(reg->type)]) {
11151 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11152 verbose(env, "expected %s or socket\n",
11153 reg_type_str(env, base_type(reg->type) |
11154 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11157 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11161 case KF_ARG_PTR_TO_MEM:
11162 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11163 if (IS_ERR(resolve_ret)) {
11164 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11165 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11168 ret = check_mem_reg(env, reg, regno, type_size);
11172 case KF_ARG_PTR_TO_MEM_SIZE:
11174 struct bpf_reg_state *buff_reg = ®s[regno];
11175 const struct btf_param *buff_arg = &args[i];
11176 struct bpf_reg_state *size_reg = ®s[regno + 1];
11177 const struct btf_param *size_arg = &args[i + 1];
11179 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11180 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11182 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11187 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11188 if (meta->arg_constant.found) {
11189 verbose(env, "verifier internal error: only one constant argument permitted\n");
11192 if (!tnum_is_const(size_reg->var_off)) {
11193 verbose(env, "R%d must be a known constant\n", regno + 1);
11196 meta->arg_constant.found = true;
11197 meta->arg_constant.value = size_reg->var_off.value;
11200 /* Skip next '__sz' or '__szk' argument */
11204 case KF_ARG_PTR_TO_CALLBACK:
11205 meta->subprogno = reg->subprogno;
11207 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11208 if (!type_is_ptr_alloc_obj(reg->type)) {
11209 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11212 if (!type_is_non_owning_ref(reg->type))
11213 meta->arg_owning_ref = true;
11215 rec = reg_btf_record(reg);
11217 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11221 if (rec->refcount_off < 0) {
11222 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11225 if (rec->refcount_off >= 0) {
11226 verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
11229 meta->arg_btf = reg->btf;
11230 meta->arg_btf_id = reg->btf_id;
11235 if (is_kfunc_release(meta) && !meta->release_regno) {
11236 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11244 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11245 struct bpf_insn *insn,
11246 struct bpf_kfunc_call_arg_meta *meta,
11247 const char **kfunc_name)
11249 const struct btf_type *func, *func_proto;
11250 u32 func_id, *kfunc_flags;
11251 const char *func_name;
11252 struct btf *desc_btf;
11255 *kfunc_name = NULL;
11260 desc_btf = find_kfunc_desc_btf(env, insn->off);
11261 if (IS_ERR(desc_btf))
11262 return PTR_ERR(desc_btf);
11264 func_id = insn->imm;
11265 func = btf_type_by_id(desc_btf, func_id);
11266 func_name = btf_name_by_offset(desc_btf, func->name_off);
11268 *kfunc_name = func_name;
11269 func_proto = btf_type_by_id(desc_btf, func->type);
11271 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11272 if (!kfunc_flags) {
11276 memset(meta, 0, sizeof(*meta));
11277 meta->btf = desc_btf;
11278 meta->func_id = func_id;
11279 meta->kfunc_flags = *kfunc_flags;
11280 meta->func_proto = func_proto;
11281 meta->func_name = func_name;
11286 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11289 const struct btf_type *t, *ptr_type;
11290 u32 i, nargs, ptr_type_id, release_ref_obj_id;
11291 struct bpf_reg_state *regs = cur_regs(env);
11292 const char *func_name, *ptr_type_name;
11293 bool sleepable, rcu_lock, rcu_unlock;
11294 struct bpf_kfunc_call_arg_meta meta;
11295 struct bpf_insn_aux_data *insn_aux;
11296 int err, insn_idx = *insn_idx_p;
11297 const struct btf_param *args;
11298 const struct btf_type *ret_t;
11299 struct btf *desc_btf;
11301 /* skip for now, but return error when we find this in fixup_kfunc_call */
11305 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11306 if (err == -EACCES && func_name)
11307 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11310 desc_btf = meta.btf;
11311 insn_aux = &env->insn_aux_data[insn_idx];
11313 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11315 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11316 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11320 sleepable = is_kfunc_sleepable(&meta);
11321 if (sleepable && !env->prog->aux->sleepable) {
11322 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11326 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11327 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11329 if (env->cur_state->active_rcu_lock) {
11330 struct bpf_func_state *state;
11331 struct bpf_reg_state *reg;
11334 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11336 } else if (rcu_unlock) {
11337 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11338 if (reg->type & MEM_RCU) {
11339 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11340 reg->type |= PTR_UNTRUSTED;
11343 env->cur_state->active_rcu_lock = false;
11344 } else if (sleepable) {
11345 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11348 } else if (rcu_lock) {
11349 env->cur_state->active_rcu_lock = true;
11350 } else if (rcu_unlock) {
11351 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11355 /* Check the arguments */
11356 err = check_kfunc_args(env, &meta, insn_idx);
11359 /* In case of release function, we get register number of refcounted
11360 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11362 if (meta.release_regno) {
11363 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11365 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11366 func_name, meta.func_id);
11371 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11372 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11373 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11374 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11375 insn_aux->insert_off = regs[BPF_REG_2].off;
11376 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11377 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11379 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11380 func_name, meta.func_id);
11384 err = release_reference(env, release_ref_obj_id);
11386 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11387 func_name, meta.func_id);
11392 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11393 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11394 set_rbtree_add_callback_state);
11396 verbose(env, "kfunc %s#%d failed callback verification\n",
11397 func_name, meta.func_id);
11402 for (i = 0; i < CALLER_SAVED_REGS; i++)
11403 mark_reg_not_init(env, regs, caller_saved[i]);
11405 /* Check return type */
11406 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11408 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11409 /* Only exception is bpf_obj_new_impl */
11410 if (meta.btf != btf_vmlinux ||
11411 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11412 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11413 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11418 if (btf_type_is_scalar(t)) {
11419 mark_reg_unknown(env, regs, BPF_REG_0);
11420 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11421 } else if (btf_type_is_ptr(t)) {
11422 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11424 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11425 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11426 struct btf *ret_btf;
11429 if (unlikely(!bpf_global_ma_set))
11432 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11433 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11437 ret_btf = env->prog->aux->btf;
11438 ret_btf_id = meta.arg_constant.value;
11440 /* This may be NULL due to user not supplying a BTF */
11442 verbose(env, "bpf_obj_new requires prog BTF\n");
11446 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11447 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11448 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11452 mark_reg_known_zero(env, regs, BPF_REG_0);
11453 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11454 regs[BPF_REG_0].btf = ret_btf;
11455 regs[BPF_REG_0].btf_id = ret_btf_id;
11457 insn_aux->obj_new_size = ret_t->size;
11458 insn_aux->kptr_struct_meta =
11459 btf_find_struct_meta(ret_btf, ret_btf_id);
11460 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11461 mark_reg_known_zero(env, regs, BPF_REG_0);
11462 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11463 regs[BPF_REG_0].btf = meta.arg_btf;
11464 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11466 insn_aux->kptr_struct_meta =
11467 btf_find_struct_meta(meta.arg_btf,
11469 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11470 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11471 struct btf_field *field = meta.arg_list_head.field;
11473 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11474 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11475 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11476 struct btf_field *field = meta.arg_rbtree_root.field;
11478 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11479 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11480 mark_reg_known_zero(env, regs, BPF_REG_0);
11481 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11482 regs[BPF_REG_0].btf = desc_btf;
11483 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11484 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11485 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11486 if (!ret_t || !btf_type_is_struct(ret_t)) {
11488 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11492 mark_reg_known_zero(env, regs, BPF_REG_0);
11493 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11494 regs[BPF_REG_0].btf = desc_btf;
11495 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11496 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11497 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11498 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11500 mark_reg_known_zero(env, regs, BPF_REG_0);
11502 if (!meta.arg_constant.found) {
11503 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11507 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11509 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11510 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11512 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11513 regs[BPF_REG_0].type |= MEM_RDONLY;
11515 /* this will set env->seen_direct_write to true */
11516 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11517 verbose(env, "the prog does not allow writes to packet data\n");
11522 if (!meta.initialized_dynptr.id) {
11523 verbose(env, "verifier internal error: no dynptr id\n");
11526 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11528 /* we don't need to set BPF_REG_0's ref obj id
11529 * because packet slices are not refcounted (see
11530 * dynptr_type_refcounted)
11533 verbose(env, "kernel function %s unhandled dynamic return type\n",
11537 } else if (!__btf_type_is_struct(ptr_type)) {
11538 if (!meta.r0_size) {
11541 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11543 meta.r0_rdonly = true;
11546 if (!meta.r0_size) {
11547 ptr_type_name = btf_name_by_offset(desc_btf,
11548 ptr_type->name_off);
11550 "kernel function %s returns pointer type %s %s is not supported\n",
11552 btf_type_str(ptr_type),
11557 mark_reg_known_zero(env, regs, BPF_REG_0);
11558 regs[BPF_REG_0].type = PTR_TO_MEM;
11559 regs[BPF_REG_0].mem_size = meta.r0_size;
11561 if (meta.r0_rdonly)
11562 regs[BPF_REG_0].type |= MEM_RDONLY;
11564 /* Ensures we don't access the memory after a release_reference() */
11565 if (meta.ref_obj_id)
11566 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11568 mark_reg_known_zero(env, regs, BPF_REG_0);
11569 regs[BPF_REG_0].btf = desc_btf;
11570 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11571 regs[BPF_REG_0].btf_id = ptr_type_id;
11574 if (is_kfunc_ret_null(&meta)) {
11575 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11576 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11577 regs[BPF_REG_0].id = ++env->id_gen;
11579 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11580 if (is_kfunc_acquire(&meta)) {
11581 int id = acquire_reference_state(env, insn_idx);
11585 if (is_kfunc_ret_null(&meta))
11586 regs[BPF_REG_0].id = id;
11587 regs[BPF_REG_0].ref_obj_id = id;
11588 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11589 ref_set_non_owning(env, ®s[BPF_REG_0]);
11592 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
11593 regs[BPF_REG_0].id = ++env->id_gen;
11594 } else if (btf_type_is_void(t)) {
11595 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11596 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11597 insn_aux->kptr_struct_meta =
11598 btf_find_struct_meta(meta.arg_btf,
11604 nargs = btf_type_vlen(meta.func_proto);
11605 args = (const struct btf_param *)(meta.func_proto + 1);
11606 for (i = 0; i < nargs; i++) {
11609 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11610 if (btf_type_is_ptr(t))
11611 mark_btf_func_reg_size(env, regno, sizeof(void *));
11613 /* scalar. ensured by btf_check_kfunc_arg_match() */
11614 mark_btf_func_reg_size(env, regno, t->size);
11617 if (is_iter_next_kfunc(&meta)) {
11618 err = process_iter_next_call(env, insn_idx, &meta);
11626 static bool signed_add_overflows(s64 a, s64 b)
11628 /* Do the add in u64, where overflow is well-defined */
11629 s64 res = (s64)((u64)a + (u64)b);
11636 static bool signed_add32_overflows(s32 a, s32 b)
11638 /* Do the add in u32, where overflow is well-defined */
11639 s32 res = (s32)((u32)a + (u32)b);
11646 static bool signed_sub_overflows(s64 a, s64 b)
11648 /* Do the sub in u64, where overflow is well-defined */
11649 s64 res = (s64)((u64)a - (u64)b);
11656 static bool signed_sub32_overflows(s32 a, s32 b)
11658 /* Do the sub in u32, where overflow is well-defined */
11659 s32 res = (s32)((u32)a - (u32)b);
11666 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11667 const struct bpf_reg_state *reg,
11668 enum bpf_reg_type type)
11670 bool known = tnum_is_const(reg->var_off);
11671 s64 val = reg->var_off.value;
11672 s64 smin = reg->smin_value;
11674 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11675 verbose(env, "math between %s pointer and %lld is not allowed\n",
11676 reg_type_str(env, type), val);
11680 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11681 verbose(env, "%s pointer offset %d is not allowed\n",
11682 reg_type_str(env, type), reg->off);
11686 if (smin == S64_MIN) {
11687 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11688 reg_type_str(env, type));
11692 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11693 verbose(env, "value %lld makes %s pointer be out of bounds\n",
11694 smin, reg_type_str(env, type));
11702 REASON_BOUNDS = -1,
11709 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11710 u32 *alu_limit, bool mask_to_left)
11712 u32 max = 0, ptr_limit = 0;
11714 switch (ptr_reg->type) {
11716 /* Offset 0 is out-of-bounds, but acceptable start for the
11717 * left direction, see BPF_REG_FP. Also, unknown scalar
11718 * offset where we would need to deal with min/max bounds is
11719 * currently prohibited for unprivileged.
11721 max = MAX_BPF_STACK + mask_to_left;
11722 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11724 case PTR_TO_MAP_VALUE:
11725 max = ptr_reg->map_ptr->value_size;
11726 ptr_limit = (mask_to_left ?
11727 ptr_reg->smin_value :
11728 ptr_reg->umax_value) + ptr_reg->off;
11731 return REASON_TYPE;
11734 if (ptr_limit >= max)
11735 return REASON_LIMIT;
11736 *alu_limit = ptr_limit;
11740 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11741 const struct bpf_insn *insn)
11743 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11746 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11747 u32 alu_state, u32 alu_limit)
11749 /* If we arrived here from different branches with different
11750 * state or limits to sanitize, then this won't work.
11752 if (aux->alu_state &&
11753 (aux->alu_state != alu_state ||
11754 aux->alu_limit != alu_limit))
11755 return REASON_PATHS;
11757 /* Corresponding fixup done in do_misc_fixups(). */
11758 aux->alu_state = alu_state;
11759 aux->alu_limit = alu_limit;
11763 static int sanitize_val_alu(struct bpf_verifier_env *env,
11764 struct bpf_insn *insn)
11766 struct bpf_insn_aux_data *aux = cur_aux(env);
11768 if (can_skip_alu_sanitation(env, insn))
11771 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11774 static bool sanitize_needed(u8 opcode)
11776 return opcode == BPF_ADD || opcode == BPF_SUB;
11779 struct bpf_sanitize_info {
11780 struct bpf_insn_aux_data aux;
11784 static struct bpf_verifier_state *
11785 sanitize_speculative_path(struct bpf_verifier_env *env,
11786 const struct bpf_insn *insn,
11787 u32 next_idx, u32 curr_idx)
11789 struct bpf_verifier_state *branch;
11790 struct bpf_reg_state *regs;
11792 branch = push_stack(env, next_idx, curr_idx, true);
11793 if (branch && insn) {
11794 regs = branch->frame[branch->curframe]->regs;
11795 if (BPF_SRC(insn->code) == BPF_K) {
11796 mark_reg_unknown(env, regs, insn->dst_reg);
11797 } else if (BPF_SRC(insn->code) == BPF_X) {
11798 mark_reg_unknown(env, regs, insn->dst_reg);
11799 mark_reg_unknown(env, regs, insn->src_reg);
11805 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11806 struct bpf_insn *insn,
11807 const struct bpf_reg_state *ptr_reg,
11808 const struct bpf_reg_state *off_reg,
11809 struct bpf_reg_state *dst_reg,
11810 struct bpf_sanitize_info *info,
11811 const bool commit_window)
11813 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11814 struct bpf_verifier_state *vstate = env->cur_state;
11815 bool off_is_imm = tnum_is_const(off_reg->var_off);
11816 bool off_is_neg = off_reg->smin_value < 0;
11817 bool ptr_is_dst_reg = ptr_reg == dst_reg;
11818 u8 opcode = BPF_OP(insn->code);
11819 u32 alu_state, alu_limit;
11820 struct bpf_reg_state tmp;
11824 if (can_skip_alu_sanitation(env, insn))
11827 /* We already marked aux for masking from non-speculative
11828 * paths, thus we got here in the first place. We only care
11829 * to explore bad access from here.
11831 if (vstate->speculative)
11834 if (!commit_window) {
11835 if (!tnum_is_const(off_reg->var_off) &&
11836 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11837 return REASON_BOUNDS;
11839 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
11840 (opcode == BPF_SUB && !off_is_neg);
11843 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11847 if (commit_window) {
11848 /* In commit phase we narrow the masking window based on
11849 * the observed pointer move after the simulated operation.
11851 alu_state = info->aux.alu_state;
11852 alu_limit = abs(info->aux.alu_limit - alu_limit);
11854 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11855 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11856 alu_state |= ptr_is_dst_reg ?
11857 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11859 /* Limit pruning on unknown scalars to enable deep search for
11860 * potential masking differences from other program paths.
11863 env->explore_alu_limits = true;
11866 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11870 /* If we're in commit phase, we're done here given we already
11871 * pushed the truncated dst_reg into the speculative verification
11874 * Also, when register is a known constant, we rewrite register-based
11875 * operation to immediate-based, and thus do not need masking (and as
11876 * a consequence, do not need to simulate the zero-truncation either).
11878 if (commit_window || off_is_imm)
11881 /* Simulate and find potential out-of-bounds access under
11882 * speculative execution from truncation as a result of
11883 * masking when off was not within expected range. If off
11884 * sits in dst, then we temporarily need to move ptr there
11885 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11886 * for cases where we use K-based arithmetic in one direction
11887 * and truncated reg-based in the other in order to explore
11890 if (!ptr_is_dst_reg) {
11892 copy_register_state(dst_reg, ptr_reg);
11894 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11896 if (!ptr_is_dst_reg && ret)
11898 return !ret ? REASON_STACK : 0;
11901 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11903 struct bpf_verifier_state *vstate = env->cur_state;
11905 /* If we simulate paths under speculation, we don't update the
11906 * insn as 'seen' such that when we verify unreachable paths in
11907 * the non-speculative domain, sanitize_dead_code() can still
11908 * rewrite/sanitize them.
11910 if (!vstate->speculative)
11911 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11914 static int sanitize_err(struct bpf_verifier_env *env,
11915 const struct bpf_insn *insn, int reason,
11916 const struct bpf_reg_state *off_reg,
11917 const struct bpf_reg_state *dst_reg)
11919 static const char *err = "pointer arithmetic with it prohibited for !root";
11920 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11921 u32 dst = insn->dst_reg, src = insn->src_reg;
11924 case REASON_BOUNDS:
11925 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11926 off_reg == dst_reg ? dst : src, err);
11929 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11930 off_reg == dst_reg ? src : dst, err);
11933 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11937 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11941 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11945 verbose(env, "verifier internal error: unknown reason (%d)\n",
11953 /* check that stack access falls within stack limits and that 'reg' doesn't
11954 * have a variable offset.
11956 * Variable offset is prohibited for unprivileged mode for simplicity since it
11957 * requires corresponding support in Spectre masking for stack ALU. See also
11958 * retrieve_ptr_limit().
11961 * 'off' includes 'reg->off'.
11963 static int check_stack_access_for_ptr_arithmetic(
11964 struct bpf_verifier_env *env,
11966 const struct bpf_reg_state *reg,
11969 if (!tnum_is_const(reg->var_off)) {
11972 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11973 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11974 regno, tn_buf, off);
11978 if (off >= 0 || off < -MAX_BPF_STACK) {
11979 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11980 "prohibited for !root; off=%d\n", regno, off);
11987 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11988 const struct bpf_insn *insn,
11989 const struct bpf_reg_state *dst_reg)
11991 u32 dst = insn->dst_reg;
11993 /* For unprivileged we require that resulting offset must be in bounds
11994 * in order to be able to sanitize access later on.
11996 if (env->bypass_spec_v1)
11999 switch (dst_reg->type) {
12001 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12002 dst_reg->off + dst_reg->var_off.value))
12005 case PTR_TO_MAP_VALUE:
12006 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12007 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12008 "prohibited for !root\n", dst);
12019 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12020 * Caller should also handle BPF_MOV case separately.
12021 * If we return -EACCES, caller may want to try again treating pointer as a
12022 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
12024 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12025 struct bpf_insn *insn,
12026 const struct bpf_reg_state *ptr_reg,
12027 const struct bpf_reg_state *off_reg)
12029 struct bpf_verifier_state *vstate = env->cur_state;
12030 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12031 struct bpf_reg_state *regs = state->regs, *dst_reg;
12032 bool known = tnum_is_const(off_reg->var_off);
12033 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12034 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12035 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12036 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12037 struct bpf_sanitize_info info = {};
12038 u8 opcode = BPF_OP(insn->code);
12039 u32 dst = insn->dst_reg;
12042 dst_reg = ®s[dst];
12044 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12045 smin_val > smax_val || umin_val > umax_val) {
12046 /* Taint dst register if offset had invalid bounds derived from
12047 * e.g. dead branches.
12049 __mark_reg_unknown(env, dst_reg);
12053 if (BPF_CLASS(insn->code) != BPF_ALU64) {
12054 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12055 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12056 __mark_reg_unknown(env, dst_reg);
12061 "R%d 32-bit pointer arithmetic prohibited\n",
12066 if (ptr_reg->type & PTR_MAYBE_NULL) {
12067 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12068 dst, reg_type_str(env, ptr_reg->type));
12072 switch (base_type(ptr_reg->type)) {
12073 case CONST_PTR_TO_MAP:
12074 /* smin_val represents the known value */
12075 if (known && smin_val == 0 && opcode == BPF_ADD)
12078 case PTR_TO_PACKET_END:
12079 case PTR_TO_SOCKET:
12080 case PTR_TO_SOCK_COMMON:
12081 case PTR_TO_TCP_SOCK:
12082 case PTR_TO_XDP_SOCK:
12083 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12084 dst, reg_type_str(env, ptr_reg->type));
12090 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12091 * The id may be overwritten later if we create a new variable offset.
12093 dst_reg->type = ptr_reg->type;
12094 dst_reg->id = ptr_reg->id;
12096 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12097 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12100 /* pointer types do not carry 32-bit bounds at the moment. */
12101 __mark_reg32_unbounded(dst_reg);
12103 if (sanitize_needed(opcode)) {
12104 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12107 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12112 /* We can take a fixed offset as long as it doesn't overflow
12113 * the s32 'off' field
12115 if (known && (ptr_reg->off + smin_val ==
12116 (s64)(s32)(ptr_reg->off + smin_val))) {
12117 /* pointer += K. Accumulate it into fixed offset */
12118 dst_reg->smin_value = smin_ptr;
12119 dst_reg->smax_value = smax_ptr;
12120 dst_reg->umin_value = umin_ptr;
12121 dst_reg->umax_value = umax_ptr;
12122 dst_reg->var_off = ptr_reg->var_off;
12123 dst_reg->off = ptr_reg->off + smin_val;
12124 dst_reg->raw = ptr_reg->raw;
12127 /* A new variable offset is created. Note that off_reg->off
12128 * == 0, since it's a scalar.
12129 * dst_reg gets the pointer type and since some positive
12130 * integer value was added to the pointer, give it a new 'id'
12131 * if it's a PTR_TO_PACKET.
12132 * this creates a new 'base' pointer, off_reg (variable) gets
12133 * added into the variable offset, and we copy the fixed offset
12136 if (signed_add_overflows(smin_ptr, smin_val) ||
12137 signed_add_overflows(smax_ptr, smax_val)) {
12138 dst_reg->smin_value = S64_MIN;
12139 dst_reg->smax_value = S64_MAX;
12141 dst_reg->smin_value = smin_ptr + smin_val;
12142 dst_reg->smax_value = smax_ptr + smax_val;
12144 if (umin_ptr + umin_val < umin_ptr ||
12145 umax_ptr + umax_val < umax_ptr) {
12146 dst_reg->umin_value = 0;
12147 dst_reg->umax_value = U64_MAX;
12149 dst_reg->umin_value = umin_ptr + umin_val;
12150 dst_reg->umax_value = umax_ptr + umax_val;
12152 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12153 dst_reg->off = ptr_reg->off;
12154 dst_reg->raw = ptr_reg->raw;
12155 if (reg_is_pkt_pointer(ptr_reg)) {
12156 dst_reg->id = ++env->id_gen;
12157 /* something was added to pkt_ptr, set range to zero */
12158 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12162 if (dst_reg == off_reg) {
12163 /* scalar -= pointer. Creates an unknown scalar */
12164 verbose(env, "R%d tried to subtract pointer from scalar\n",
12168 /* We don't allow subtraction from FP, because (according to
12169 * test_verifier.c test "invalid fp arithmetic", JITs might not
12170 * be able to deal with it.
12172 if (ptr_reg->type == PTR_TO_STACK) {
12173 verbose(env, "R%d subtraction from stack pointer prohibited\n",
12177 if (known && (ptr_reg->off - smin_val ==
12178 (s64)(s32)(ptr_reg->off - smin_val))) {
12179 /* pointer -= K. Subtract it from fixed offset */
12180 dst_reg->smin_value = smin_ptr;
12181 dst_reg->smax_value = smax_ptr;
12182 dst_reg->umin_value = umin_ptr;
12183 dst_reg->umax_value = umax_ptr;
12184 dst_reg->var_off = ptr_reg->var_off;
12185 dst_reg->id = ptr_reg->id;
12186 dst_reg->off = ptr_reg->off - smin_val;
12187 dst_reg->raw = ptr_reg->raw;
12190 /* A new variable offset is created. If the subtrahend is known
12191 * nonnegative, then any reg->range we had before is still good.
12193 if (signed_sub_overflows(smin_ptr, smax_val) ||
12194 signed_sub_overflows(smax_ptr, smin_val)) {
12195 /* Overflow possible, we know nothing */
12196 dst_reg->smin_value = S64_MIN;
12197 dst_reg->smax_value = S64_MAX;
12199 dst_reg->smin_value = smin_ptr - smax_val;
12200 dst_reg->smax_value = smax_ptr - smin_val;
12202 if (umin_ptr < umax_val) {
12203 /* Overflow possible, we know nothing */
12204 dst_reg->umin_value = 0;
12205 dst_reg->umax_value = U64_MAX;
12207 /* Cannot overflow (as long as bounds are consistent) */
12208 dst_reg->umin_value = umin_ptr - umax_val;
12209 dst_reg->umax_value = umax_ptr - umin_val;
12211 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12212 dst_reg->off = ptr_reg->off;
12213 dst_reg->raw = ptr_reg->raw;
12214 if (reg_is_pkt_pointer(ptr_reg)) {
12215 dst_reg->id = ++env->id_gen;
12216 /* something was added to pkt_ptr, set range to zero */
12218 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12224 /* bitwise ops on pointers are troublesome, prohibit. */
12225 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12226 dst, bpf_alu_string[opcode >> 4]);
12229 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12230 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12231 dst, bpf_alu_string[opcode >> 4]);
12235 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12237 reg_bounds_sync(dst_reg);
12238 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12240 if (sanitize_needed(opcode)) {
12241 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12244 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12250 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12251 struct bpf_reg_state *src_reg)
12253 s32 smin_val = src_reg->s32_min_value;
12254 s32 smax_val = src_reg->s32_max_value;
12255 u32 umin_val = src_reg->u32_min_value;
12256 u32 umax_val = src_reg->u32_max_value;
12258 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12259 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12260 dst_reg->s32_min_value = S32_MIN;
12261 dst_reg->s32_max_value = S32_MAX;
12263 dst_reg->s32_min_value += smin_val;
12264 dst_reg->s32_max_value += smax_val;
12266 if (dst_reg->u32_min_value + umin_val < umin_val ||
12267 dst_reg->u32_max_value + umax_val < umax_val) {
12268 dst_reg->u32_min_value = 0;
12269 dst_reg->u32_max_value = U32_MAX;
12271 dst_reg->u32_min_value += umin_val;
12272 dst_reg->u32_max_value += umax_val;
12276 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12277 struct bpf_reg_state *src_reg)
12279 s64 smin_val = src_reg->smin_value;
12280 s64 smax_val = src_reg->smax_value;
12281 u64 umin_val = src_reg->umin_value;
12282 u64 umax_val = src_reg->umax_value;
12284 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12285 signed_add_overflows(dst_reg->smax_value, smax_val)) {
12286 dst_reg->smin_value = S64_MIN;
12287 dst_reg->smax_value = S64_MAX;
12289 dst_reg->smin_value += smin_val;
12290 dst_reg->smax_value += smax_val;
12292 if (dst_reg->umin_value + umin_val < umin_val ||
12293 dst_reg->umax_value + umax_val < umax_val) {
12294 dst_reg->umin_value = 0;
12295 dst_reg->umax_value = U64_MAX;
12297 dst_reg->umin_value += umin_val;
12298 dst_reg->umax_value += umax_val;
12302 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12303 struct bpf_reg_state *src_reg)
12305 s32 smin_val = src_reg->s32_min_value;
12306 s32 smax_val = src_reg->s32_max_value;
12307 u32 umin_val = src_reg->u32_min_value;
12308 u32 umax_val = src_reg->u32_max_value;
12310 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12311 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12312 /* Overflow possible, we know nothing */
12313 dst_reg->s32_min_value = S32_MIN;
12314 dst_reg->s32_max_value = S32_MAX;
12316 dst_reg->s32_min_value -= smax_val;
12317 dst_reg->s32_max_value -= smin_val;
12319 if (dst_reg->u32_min_value < umax_val) {
12320 /* Overflow possible, we know nothing */
12321 dst_reg->u32_min_value = 0;
12322 dst_reg->u32_max_value = U32_MAX;
12324 /* Cannot overflow (as long as bounds are consistent) */
12325 dst_reg->u32_min_value -= umax_val;
12326 dst_reg->u32_max_value -= umin_val;
12330 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12331 struct bpf_reg_state *src_reg)
12333 s64 smin_val = src_reg->smin_value;
12334 s64 smax_val = src_reg->smax_value;
12335 u64 umin_val = src_reg->umin_value;
12336 u64 umax_val = src_reg->umax_value;
12338 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12339 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12340 /* Overflow possible, we know nothing */
12341 dst_reg->smin_value = S64_MIN;
12342 dst_reg->smax_value = S64_MAX;
12344 dst_reg->smin_value -= smax_val;
12345 dst_reg->smax_value -= smin_val;
12347 if (dst_reg->umin_value < umax_val) {
12348 /* Overflow possible, we know nothing */
12349 dst_reg->umin_value = 0;
12350 dst_reg->umax_value = U64_MAX;
12352 /* Cannot overflow (as long as bounds are consistent) */
12353 dst_reg->umin_value -= umax_val;
12354 dst_reg->umax_value -= umin_val;
12358 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12359 struct bpf_reg_state *src_reg)
12361 s32 smin_val = src_reg->s32_min_value;
12362 u32 umin_val = src_reg->u32_min_value;
12363 u32 umax_val = src_reg->u32_max_value;
12365 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12366 /* Ain't nobody got time to multiply that sign */
12367 __mark_reg32_unbounded(dst_reg);
12370 /* Both values are positive, so we can work with unsigned and
12371 * copy the result to signed (unless it exceeds S32_MAX).
12373 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12374 /* Potential overflow, we know nothing */
12375 __mark_reg32_unbounded(dst_reg);
12378 dst_reg->u32_min_value *= umin_val;
12379 dst_reg->u32_max_value *= umax_val;
12380 if (dst_reg->u32_max_value > S32_MAX) {
12381 /* Overflow possible, we know nothing */
12382 dst_reg->s32_min_value = S32_MIN;
12383 dst_reg->s32_max_value = S32_MAX;
12385 dst_reg->s32_min_value = dst_reg->u32_min_value;
12386 dst_reg->s32_max_value = dst_reg->u32_max_value;
12390 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12391 struct bpf_reg_state *src_reg)
12393 s64 smin_val = src_reg->smin_value;
12394 u64 umin_val = src_reg->umin_value;
12395 u64 umax_val = src_reg->umax_value;
12397 if (smin_val < 0 || dst_reg->smin_value < 0) {
12398 /* Ain't nobody got time to multiply that sign */
12399 __mark_reg64_unbounded(dst_reg);
12402 /* Both values are positive, so we can work with unsigned and
12403 * copy the result to signed (unless it exceeds S64_MAX).
12405 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12406 /* Potential overflow, we know nothing */
12407 __mark_reg64_unbounded(dst_reg);
12410 dst_reg->umin_value *= umin_val;
12411 dst_reg->umax_value *= umax_val;
12412 if (dst_reg->umax_value > S64_MAX) {
12413 /* Overflow possible, we know nothing */
12414 dst_reg->smin_value = S64_MIN;
12415 dst_reg->smax_value = S64_MAX;
12417 dst_reg->smin_value = dst_reg->umin_value;
12418 dst_reg->smax_value = dst_reg->umax_value;
12422 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12423 struct bpf_reg_state *src_reg)
12425 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12426 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12427 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12428 s32 smin_val = src_reg->s32_min_value;
12429 u32 umax_val = src_reg->u32_max_value;
12431 if (src_known && dst_known) {
12432 __mark_reg32_known(dst_reg, var32_off.value);
12436 /* We get our minimum from the var_off, since that's inherently
12437 * bitwise. Our maximum is the minimum of the operands' maxima.
12439 dst_reg->u32_min_value = var32_off.value;
12440 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12441 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12442 /* Lose signed bounds when ANDing negative numbers,
12443 * ain't nobody got time for that.
12445 dst_reg->s32_min_value = S32_MIN;
12446 dst_reg->s32_max_value = S32_MAX;
12448 /* ANDing two positives gives a positive, so safe to
12449 * cast result into s64.
12451 dst_reg->s32_min_value = dst_reg->u32_min_value;
12452 dst_reg->s32_max_value = dst_reg->u32_max_value;
12456 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12457 struct bpf_reg_state *src_reg)
12459 bool src_known = tnum_is_const(src_reg->var_off);
12460 bool dst_known = tnum_is_const(dst_reg->var_off);
12461 s64 smin_val = src_reg->smin_value;
12462 u64 umax_val = src_reg->umax_value;
12464 if (src_known && dst_known) {
12465 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12469 /* We get our minimum from the var_off, since that's inherently
12470 * bitwise. Our maximum is the minimum of the operands' maxima.
12472 dst_reg->umin_value = dst_reg->var_off.value;
12473 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12474 if (dst_reg->smin_value < 0 || smin_val < 0) {
12475 /* Lose signed bounds when ANDing negative numbers,
12476 * ain't nobody got time for that.
12478 dst_reg->smin_value = S64_MIN;
12479 dst_reg->smax_value = S64_MAX;
12481 /* ANDing two positives gives a positive, so safe to
12482 * cast result into s64.
12484 dst_reg->smin_value = dst_reg->umin_value;
12485 dst_reg->smax_value = dst_reg->umax_value;
12487 /* We may learn something more from the var_off */
12488 __update_reg_bounds(dst_reg);
12491 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12492 struct bpf_reg_state *src_reg)
12494 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12495 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12496 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12497 s32 smin_val = src_reg->s32_min_value;
12498 u32 umin_val = src_reg->u32_min_value;
12500 if (src_known && dst_known) {
12501 __mark_reg32_known(dst_reg, var32_off.value);
12505 /* We get our maximum from the var_off, and our minimum is the
12506 * maximum of the operands' minima
12508 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12509 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12510 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12511 /* Lose signed bounds when ORing negative numbers,
12512 * ain't nobody got time for that.
12514 dst_reg->s32_min_value = S32_MIN;
12515 dst_reg->s32_max_value = S32_MAX;
12517 /* ORing two positives gives a positive, so safe to
12518 * cast result into s64.
12520 dst_reg->s32_min_value = dst_reg->u32_min_value;
12521 dst_reg->s32_max_value = dst_reg->u32_max_value;
12525 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12526 struct bpf_reg_state *src_reg)
12528 bool src_known = tnum_is_const(src_reg->var_off);
12529 bool dst_known = tnum_is_const(dst_reg->var_off);
12530 s64 smin_val = src_reg->smin_value;
12531 u64 umin_val = src_reg->umin_value;
12533 if (src_known && dst_known) {
12534 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12538 /* We get our maximum from the var_off, and our minimum is the
12539 * maximum of the operands' minima
12541 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12542 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12543 if (dst_reg->smin_value < 0 || smin_val < 0) {
12544 /* Lose signed bounds when ORing negative numbers,
12545 * ain't nobody got time for that.
12547 dst_reg->smin_value = S64_MIN;
12548 dst_reg->smax_value = S64_MAX;
12550 /* ORing two positives gives a positive, so safe to
12551 * cast result into s64.
12553 dst_reg->smin_value = dst_reg->umin_value;
12554 dst_reg->smax_value = dst_reg->umax_value;
12556 /* We may learn something more from the var_off */
12557 __update_reg_bounds(dst_reg);
12560 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12561 struct bpf_reg_state *src_reg)
12563 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12564 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12565 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12566 s32 smin_val = src_reg->s32_min_value;
12568 if (src_known && dst_known) {
12569 __mark_reg32_known(dst_reg, var32_off.value);
12573 /* We get both minimum and maximum from the var32_off. */
12574 dst_reg->u32_min_value = var32_off.value;
12575 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12577 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12578 /* XORing two positive sign numbers gives a positive,
12579 * so safe to cast u32 result into s32.
12581 dst_reg->s32_min_value = dst_reg->u32_min_value;
12582 dst_reg->s32_max_value = dst_reg->u32_max_value;
12584 dst_reg->s32_min_value = S32_MIN;
12585 dst_reg->s32_max_value = S32_MAX;
12589 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12590 struct bpf_reg_state *src_reg)
12592 bool src_known = tnum_is_const(src_reg->var_off);
12593 bool dst_known = tnum_is_const(dst_reg->var_off);
12594 s64 smin_val = src_reg->smin_value;
12596 if (src_known && dst_known) {
12597 /* dst_reg->var_off.value has been updated earlier */
12598 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12602 /* We get both minimum and maximum from the var_off. */
12603 dst_reg->umin_value = dst_reg->var_off.value;
12604 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12606 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12607 /* XORing two positive sign numbers gives a positive,
12608 * so safe to cast u64 result into s64.
12610 dst_reg->smin_value = dst_reg->umin_value;
12611 dst_reg->smax_value = dst_reg->umax_value;
12613 dst_reg->smin_value = S64_MIN;
12614 dst_reg->smax_value = S64_MAX;
12617 __update_reg_bounds(dst_reg);
12620 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12621 u64 umin_val, u64 umax_val)
12623 /* We lose all sign bit information (except what we can pick
12626 dst_reg->s32_min_value = S32_MIN;
12627 dst_reg->s32_max_value = S32_MAX;
12628 /* If we might shift our top bit out, then we know nothing */
12629 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12630 dst_reg->u32_min_value = 0;
12631 dst_reg->u32_max_value = U32_MAX;
12633 dst_reg->u32_min_value <<= umin_val;
12634 dst_reg->u32_max_value <<= umax_val;
12638 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12639 struct bpf_reg_state *src_reg)
12641 u32 umax_val = src_reg->u32_max_value;
12642 u32 umin_val = src_reg->u32_min_value;
12643 /* u32 alu operation will zext upper bits */
12644 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12646 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12647 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12648 /* Not required but being careful mark reg64 bounds as unknown so
12649 * that we are forced to pick them up from tnum and zext later and
12650 * if some path skips this step we are still safe.
12652 __mark_reg64_unbounded(dst_reg);
12653 __update_reg32_bounds(dst_reg);
12656 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12657 u64 umin_val, u64 umax_val)
12659 /* Special case <<32 because it is a common compiler pattern to sign
12660 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12661 * positive we know this shift will also be positive so we can track
12662 * bounds correctly. Otherwise we lose all sign bit information except
12663 * what we can pick up from var_off. Perhaps we can generalize this
12664 * later to shifts of any length.
12666 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12667 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12669 dst_reg->smax_value = S64_MAX;
12671 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12672 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12674 dst_reg->smin_value = S64_MIN;
12676 /* If we might shift our top bit out, then we know nothing */
12677 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12678 dst_reg->umin_value = 0;
12679 dst_reg->umax_value = U64_MAX;
12681 dst_reg->umin_value <<= umin_val;
12682 dst_reg->umax_value <<= umax_val;
12686 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12687 struct bpf_reg_state *src_reg)
12689 u64 umax_val = src_reg->umax_value;
12690 u64 umin_val = src_reg->umin_value;
12692 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
12693 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12694 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12696 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12697 /* We may learn something more from the var_off */
12698 __update_reg_bounds(dst_reg);
12701 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12702 struct bpf_reg_state *src_reg)
12704 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12705 u32 umax_val = src_reg->u32_max_value;
12706 u32 umin_val = src_reg->u32_min_value;
12708 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12709 * be negative, then either:
12710 * 1) src_reg might be zero, so the sign bit of the result is
12711 * unknown, so we lose our signed bounds
12712 * 2) it's known negative, thus the unsigned bounds capture the
12714 * 3) the signed bounds cross zero, so they tell us nothing
12716 * If the value in dst_reg is known nonnegative, then again the
12717 * unsigned bounds capture the signed bounds.
12718 * Thus, in all cases it suffices to blow away our signed bounds
12719 * and rely on inferring new ones from the unsigned bounds and
12720 * var_off of the result.
12722 dst_reg->s32_min_value = S32_MIN;
12723 dst_reg->s32_max_value = S32_MAX;
12725 dst_reg->var_off = tnum_rshift(subreg, umin_val);
12726 dst_reg->u32_min_value >>= umax_val;
12727 dst_reg->u32_max_value >>= umin_val;
12729 __mark_reg64_unbounded(dst_reg);
12730 __update_reg32_bounds(dst_reg);
12733 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12734 struct bpf_reg_state *src_reg)
12736 u64 umax_val = src_reg->umax_value;
12737 u64 umin_val = src_reg->umin_value;
12739 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12740 * be negative, then either:
12741 * 1) src_reg might be zero, so the sign bit of the result is
12742 * unknown, so we lose our signed bounds
12743 * 2) it's known negative, thus the unsigned bounds capture the
12745 * 3) the signed bounds cross zero, so they tell us nothing
12747 * If the value in dst_reg is known nonnegative, then again the
12748 * unsigned bounds capture the signed bounds.
12749 * Thus, in all cases it suffices to blow away our signed bounds
12750 * and rely on inferring new ones from the unsigned bounds and
12751 * var_off of the result.
12753 dst_reg->smin_value = S64_MIN;
12754 dst_reg->smax_value = S64_MAX;
12755 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12756 dst_reg->umin_value >>= umax_val;
12757 dst_reg->umax_value >>= umin_val;
12759 /* Its not easy to operate on alu32 bounds here because it depends
12760 * on bits being shifted in. Take easy way out and mark unbounded
12761 * so we can recalculate later from tnum.
12763 __mark_reg32_unbounded(dst_reg);
12764 __update_reg_bounds(dst_reg);
12767 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12768 struct bpf_reg_state *src_reg)
12770 u64 umin_val = src_reg->u32_min_value;
12772 /* Upon reaching here, src_known is true and
12773 * umax_val is equal to umin_val.
12775 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12776 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12778 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12780 /* blow away the dst_reg umin_value/umax_value and rely on
12781 * dst_reg var_off to refine the result.
12783 dst_reg->u32_min_value = 0;
12784 dst_reg->u32_max_value = U32_MAX;
12786 __mark_reg64_unbounded(dst_reg);
12787 __update_reg32_bounds(dst_reg);
12790 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12791 struct bpf_reg_state *src_reg)
12793 u64 umin_val = src_reg->umin_value;
12795 /* Upon reaching here, src_known is true and umax_val is equal
12798 dst_reg->smin_value >>= umin_val;
12799 dst_reg->smax_value >>= umin_val;
12801 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12803 /* blow away the dst_reg umin_value/umax_value and rely on
12804 * dst_reg var_off to refine the result.
12806 dst_reg->umin_value = 0;
12807 dst_reg->umax_value = U64_MAX;
12809 /* Its not easy to operate on alu32 bounds here because it depends
12810 * on bits being shifted in from upper 32-bits. Take easy way out
12811 * and mark unbounded so we can recalculate later from tnum.
12813 __mark_reg32_unbounded(dst_reg);
12814 __update_reg_bounds(dst_reg);
12817 /* WARNING: This function does calculations on 64-bit values, but the actual
12818 * execution may occur on 32-bit values. Therefore, things like bitshifts
12819 * need extra checks in the 32-bit case.
12821 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12822 struct bpf_insn *insn,
12823 struct bpf_reg_state *dst_reg,
12824 struct bpf_reg_state src_reg)
12826 struct bpf_reg_state *regs = cur_regs(env);
12827 u8 opcode = BPF_OP(insn->code);
12829 s64 smin_val, smax_val;
12830 u64 umin_val, umax_val;
12831 s32 s32_min_val, s32_max_val;
12832 u32 u32_min_val, u32_max_val;
12833 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12834 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12837 smin_val = src_reg.smin_value;
12838 smax_val = src_reg.smax_value;
12839 umin_val = src_reg.umin_value;
12840 umax_val = src_reg.umax_value;
12842 s32_min_val = src_reg.s32_min_value;
12843 s32_max_val = src_reg.s32_max_value;
12844 u32_min_val = src_reg.u32_min_value;
12845 u32_max_val = src_reg.u32_max_value;
12848 src_known = tnum_subreg_is_const(src_reg.var_off);
12850 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12851 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12852 /* Taint dst register if offset had invalid bounds
12853 * derived from e.g. dead branches.
12855 __mark_reg_unknown(env, dst_reg);
12859 src_known = tnum_is_const(src_reg.var_off);
12861 (smin_val != smax_val || umin_val != umax_val)) ||
12862 smin_val > smax_val || umin_val > umax_val) {
12863 /* Taint dst register if offset had invalid bounds
12864 * derived from e.g. dead branches.
12866 __mark_reg_unknown(env, dst_reg);
12872 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12873 __mark_reg_unknown(env, dst_reg);
12877 if (sanitize_needed(opcode)) {
12878 ret = sanitize_val_alu(env, insn);
12880 return sanitize_err(env, insn, ret, NULL, NULL);
12883 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12884 * There are two classes of instructions: The first class we track both
12885 * alu32 and alu64 sign/unsigned bounds independently this provides the
12886 * greatest amount of precision when alu operations are mixed with jmp32
12887 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12888 * and BPF_OR. This is possible because these ops have fairly easy to
12889 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12890 * See alu32 verifier tests for examples. The second class of
12891 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12892 * with regards to tracking sign/unsigned bounds because the bits may
12893 * cross subreg boundaries in the alu64 case. When this happens we mark
12894 * the reg unbounded in the subreg bound space and use the resulting
12895 * tnum to calculate an approximation of the sign/unsigned bounds.
12899 scalar32_min_max_add(dst_reg, &src_reg);
12900 scalar_min_max_add(dst_reg, &src_reg);
12901 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12904 scalar32_min_max_sub(dst_reg, &src_reg);
12905 scalar_min_max_sub(dst_reg, &src_reg);
12906 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12909 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12910 scalar32_min_max_mul(dst_reg, &src_reg);
12911 scalar_min_max_mul(dst_reg, &src_reg);
12914 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12915 scalar32_min_max_and(dst_reg, &src_reg);
12916 scalar_min_max_and(dst_reg, &src_reg);
12919 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12920 scalar32_min_max_or(dst_reg, &src_reg);
12921 scalar_min_max_or(dst_reg, &src_reg);
12924 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12925 scalar32_min_max_xor(dst_reg, &src_reg);
12926 scalar_min_max_xor(dst_reg, &src_reg);
12929 if (umax_val >= insn_bitness) {
12930 /* Shifts greater than 31 or 63 are undefined.
12931 * This includes shifts by a negative number.
12933 mark_reg_unknown(env, regs, insn->dst_reg);
12937 scalar32_min_max_lsh(dst_reg, &src_reg);
12939 scalar_min_max_lsh(dst_reg, &src_reg);
12942 if (umax_val >= insn_bitness) {
12943 /* Shifts greater than 31 or 63 are undefined.
12944 * This includes shifts by a negative number.
12946 mark_reg_unknown(env, regs, insn->dst_reg);
12950 scalar32_min_max_rsh(dst_reg, &src_reg);
12952 scalar_min_max_rsh(dst_reg, &src_reg);
12955 if (umax_val >= insn_bitness) {
12956 /* Shifts greater than 31 or 63 are undefined.
12957 * This includes shifts by a negative number.
12959 mark_reg_unknown(env, regs, insn->dst_reg);
12963 scalar32_min_max_arsh(dst_reg, &src_reg);
12965 scalar_min_max_arsh(dst_reg, &src_reg);
12968 mark_reg_unknown(env, regs, insn->dst_reg);
12972 /* ALU32 ops are zero extended into 64bit register */
12974 zext_32_to_64(dst_reg);
12975 reg_bounds_sync(dst_reg);
12979 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12982 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12983 struct bpf_insn *insn)
12985 struct bpf_verifier_state *vstate = env->cur_state;
12986 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12987 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12988 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12989 u8 opcode = BPF_OP(insn->code);
12992 dst_reg = ®s[insn->dst_reg];
12994 if (dst_reg->type != SCALAR_VALUE)
12997 /* Make sure ID is cleared otherwise dst_reg min/max could be
12998 * incorrectly propagated into other registers by find_equal_scalars()
13001 if (BPF_SRC(insn->code) == BPF_X) {
13002 src_reg = ®s[insn->src_reg];
13003 if (src_reg->type != SCALAR_VALUE) {
13004 if (dst_reg->type != SCALAR_VALUE) {
13005 /* Combining two pointers by any ALU op yields
13006 * an arbitrary scalar. Disallow all math except
13007 * pointer subtraction
13009 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13010 mark_reg_unknown(env, regs, insn->dst_reg);
13013 verbose(env, "R%d pointer %s pointer prohibited\n",
13015 bpf_alu_string[opcode >> 4]);
13018 /* scalar += pointer
13019 * This is legal, but we have to reverse our
13020 * src/dest handling in computing the range
13022 err = mark_chain_precision(env, insn->dst_reg);
13025 return adjust_ptr_min_max_vals(env, insn,
13028 } else if (ptr_reg) {
13029 /* pointer += scalar */
13030 err = mark_chain_precision(env, insn->src_reg);
13033 return adjust_ptr_min_max_vals(env, insn,
13035 } else if (dst_reg->precise) {
13036 /* if dst_reg is precise, src_reg should be precise as well */
13037 err = mark_chain_precision(env, insn->src_reg);
13042 /* Pretend the src is a reg with a known value, since we only
13043 * need to be able to read from this state.
13045 off_reg.type = SCALAR_VALUE;
13046 __mark_reg_known(&off_reg, insn->imm);
13047 src_reg = &off_reg;
13048 if (ptr_reg) /* pointer += K */
13049 return adjust_ptr_min_max_vals(env, insn,
13053 /* Got here implies adding two SCALAR_VALUEs */
13054 if (WARN_ON_ONCE(ptr_reg)) {
13055 print_verifier_state(env, state, true);
13056 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13059 if (WARN_ON(!src_reg)) {
13060 print_verifier_state(env, state, true);
13061 verbose(env, "verifier internal error: no src_reg\n");
13064 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13067 /* check validity of 32-bit and 64-bit arithmetic operations */
13068 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13070 struct bpf_reg_state *regs = cur_regs(env);
13071 u8 opcode = BPF_OP(insn->code);
13074 if (opcode == BPF_END || opcode == BPF_NEG) {
13075 if (opcode == BPF_NEG) {
13076 if (BPF_SRC(insn->code) != BPF_K ||
13077 insn->src_reg != BPF_REG_0 ||
13078 insn->off != 0 || insn->imm != 0) {
13079 verbose(env, "BPF_NEG uses reserved fields\n");
13083 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13084 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13085 (BPF_CLASS(insn->code) == BPF_ALU64 &&
13086 BPF_SRC(insn->code) != BPF_TO_LE)) {
13087 verbose(env, "BPF_END uses reserved fields\n");
13092 /* check src operand */
13093 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13097 if (is_pointer_value(env, insn->dst_reg)) {
13098 verbose(env, "R%d pointer arithmetic prohibited\n",
13103 /* check dest operand */
13104 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13108 } else if (opcode == BPF_MOV) {
13110 if (BPF_SRC(insn->code) == BPF_X) {
13111 if (insn->imm != 0) {
13112 verbose(env, "BPF_MOV uses reserved fields\n");
13116 if (BPF_CLASS(insn->code) == BPF_ALU) {
13117 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13118 verbose(env, "BPF_MOV uses reserved fields\n");
13122 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13124 verbose(env, "BPF_MOV uses reserved fields\n");
13129 /* check src operand */
13130 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13134 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13135 verbose(env, "BPF_MOV uses reserved fields\n");
13140 /* check dest operand, mark as required later */
13141 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13145 if (BPF_SRC(insn->code) == BPF_X) {
13146 struct bpf_reg_state *src_reg = regs + insn->src_reg;
13147 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13148 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13149 !tnum_is_const(src_reg->var_off);
13151 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13152 if (insn->off == 0) {
13154 * copy register state to dest reg
13157 /* Assign src and dst registers the same ID
13158 * that will be used by find_equal_scalars()
13159 * to propagate min/max range.
13161 src_reg->id = ++env->id_gen;
13162 copy_register_state(dst_reg, src_reg);
13163 dst_reg->live |= REG_LIVE_WRITTEN;
13164 dst_reg->subreg_def = DEF_NOT_SUBREG;
13166 /* case: R1 = (s8, s16 s32)R2 */
13169 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13170 if (no_sext && need_id)
13171 src_reg->id = ++env->id_gen;
13172 copy_register_state(dst_reg, src_reg);
13175 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13176 dst_reg->live |= REG_LIVE_WRITTEN;
13177 dst_reg->subreg_def = DEF_NOT_SUBREG;
13180 /* R1 = (u32) R2 */
13181 if (is_pointer_value(env, insn->src_reg)) {
13183 "R%d partial copy of pointer\n",
13186 } else if (src_reg->type == SCALAR_VALUE) {
13187 if (insn->off == 0) {
13188 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13190 if (is_src_reg_u32 && need_id)
13191 src_reg->id = ++env->id_gen;
13192 copy_register_state(dst_reg, src_reg);
13193 /* Make sure ID is cleared if src_reg is not in u32
13194 * range otherwise dst_reg min/max could be incorrectly
13195 * propagated into src_reg by find_equal_scalars()
13197 if (!is_src_reg_u32)
13199 dst_reg->live |= REG_LIVE_WRITTEN;
13200 dst_reg->subreg_def = env->insn_idx + 1;
13202 /* case: W1 = (s8, s16)W2 */
13203 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13205 if (no_sext && need_id)
13206 src_reg->id = ++env->id_gen;
13207 copy_register_state(dst_reg, src_reg);
13210 dst_reg->live |= REG_LIVE_WRITTEN;
13211 dst_reg->subreg_def = env->insn_idx + 1;
13212 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13215 mark_reg_unknown(env, regs,
13218 zext_32_to_64(dst_reg);
13219 reg_bounds_sync(dst_reg);
13223 * remember the value we stored into this reg
13225 /* clear any state __mark_reg_known doesn't set */
13226 mark_reg_unknown(env, regs, insn->dst_reg);
13227 regs[insn->dst_reg].type = SCALAR_VALUE;
13228 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13229 __mark_reg_known(regs + insn->dst_reg,
13232 __mark_reg_known(regs + insn->dst_reg,
13237 } else if (opcode > BPF_END) {
13238 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13241 } else { /* all other ALU ops: and, sub, xor, add, ... */
13243 if (BPF_SRC(insn->code) == BPF_X) {
13244 if (insn->imm != 0 || insn->off > 1 ||
13245 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13246 verbose(env, "BPF_ALU uses reserved fields\n");
13249 /* check src1 operand */
13250 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13254 if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13255 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13256 verbose(env, "BPF_ALU uses reserved fields\n");
13261 /* check src2 operand */
13262 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13266 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13267 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13268 verbose(env, "div by zero\n");
13272 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13273 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13274 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13276 if (insn->imm < 0 || insn->imm >= size) {
13277 verbose(env, "invalid shift %d\n", insn->imm);
13282 /* check dest operand */
13283 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13287 return adjust_reg_min_max_vals(env, insn);
13293 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13294 struct bpf_reg_state *dst_reg,
13295 enum bpf_reg_type type,
13296 bool range_right_open)
13298 struct bpf_func_state *state;
13299 struct bpf_reg_state *reg;
13302 if (dst_reg->off < 0 ||
13303 (dst_reg->off == 0 && range_right_open))
13304 /* This doesn't give us any range */
13307 if (dst_reg->umax_value > MAX_PACKET_OFF ||
13308 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13309 /* Risk of overflow. For instance, ptr + (1<<63) may be less
13310 * than pkt_end, but that's because it's also less than pkt.
13314 new_range = dst_reg->off;
13315 if (range_right_open)
13318 /* Examples for register markings:
13320 * pkt_data in dst register:
13324 * if (r2 > pkt_end) goto <handle exception>
13329 * if (r2 < pkt_end) goto <access okay>
13330 * <handle exception>
13333 * r2 == dst_reg, pkt_end == src_reg
13334 * r2=pkt(id=n,off=8,r=0)
13335 * r3=pkt(id=n,off=0,r=0)
13337 * pkt_data in src register:
13341 * if (pkt_end >= r2) goto <access okay>
13342 * <handle exception>
13346 * if (pkt_end <= r2) goto <handle exception>
13350 * pkt_end == dst_reg, r2 == src_reg
13351 * r2=pkt(id=n,off=8,r=0)
13352 * r3=pkt(id=n,off=0,r=0)
13354 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13355 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13356 * and [r3, r3 + 8-1) respectively is safe to access depending on
13360 /* If our ids match, then we must have the same max_value. And we
13361 * don't care about the other reg's fixed offset, since if it's too big
13362 * the range won't allow anything.
13363 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13365 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13366 if (reg->type == type && reg->id == dst_reg->id)
13367 /* keep the maximum range already checked */
13368 reg->range = max(reg->range, new_range);
13372 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13374 struct tnum subreg = tnum_subreg(reg->var_off);
13375 s32 sval = (s32)val;
13379 if (tnum_is_const(subreg))
13380 return !!tnum_equals_const(subreg, val);
13381 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13385 if (tnum_is_const(subreg))
13386 return !tnum_equals_const(subreg, val);
13387 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13391 if ((~subreg.mask & subreg.value) & val)
13393 if (!((subreg.mask | subreg.value) & val))
13397 if (reg->u32_min_value > val)
13399 else if (reg->u32_max_value <= val)
13403 if (reg->s32_min_value > sval)
13405 else if (reg->s32_max_value <= sval)
13409 if (reg->u32_max_value < val)
13411 else if (reg->u32_min_value >= val)
13415 if (reg->s32_max_value < sval)
13417 else if (reg->s32_min_value >= sval)
13421 if (reg->u32_min_value >= val)
13423 else if (reg->u32_max_value < val)
13427 if (reg->s32_min_value >= sval)
13429 else if (reg->s32_max_value < sval)
13433 if (reg->u32_max_value <= val)
13435 else if (reg->u32_min_value > val)
13439 if (reg->s32_max_value <= sval)
13441 else if (reg->s32_min_value > sval)
13450 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13452 s64 sval = (s64)val;
13456 if (tnum_is_const(reg->var_off))
13457 return !!tnum_equals_const(reg->var_off, val);
13458 else if (val < reg->umin_value || val > reg->umax_value)
13462 if (tnum_is_const(reg->var_off))
13463 return !tnum_equals_const(reg->var_off, val);
13464 else if (val < reg->umin_value || val > reg->umax_value)
13468 if ((~reg->var_off.mask & reg->var_off.value) & val)
13470 if (!((reg->var_off.mask | reg->var_off.value) & val))
13474 if (reg->umin_value > val)
13476 else if (reg->umax_value <= val)
13480 if (reg->smin_value > sval)
13482 else if (reg->smax_value <= sval)
13486 if (reg->umax_value < val)
13488 else if (reg->umin_value >= val)
13492 if (reg->smax_value < sval)
13494 else if (reg->smin_value >= sval)
13498 if (reg->umin_value >= val)
13500 else if (reg->umax_value < val)
13504 if (reg->smin_value >= sval)
13506 else if (reg->smax_value < sval)
13510 if (reg->umax_value <= val)
13512 else if (reg->umin_value > val)
13516 if (reg->smax_value <= sval)
13518 else if (reg->smin_value > sval)
13526 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13528 * 1 - branch will be taken and "goto target" will be executed
13529 * 0 - branch will not be taken and fall-through to next insn
13530 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13533 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13536 if (__is_pointer_value(false, reg)) {
13537 if (!reg_not_null(reg))
13540 /* If pointer is valid tests against zero will fail so we can
13541 * use this to direct branch taken.
13557 return is_branch32_taken(reg, val, opcode);
13558 return is_branch64_taken(reg, val, opcode);
13561 static int flip_opcode(u32 opcode)
13563 /* How can we transform "a <op> b" into "b <op> a"? */
13564 static const u8 opcode_flip[16] = {
13565 /* these stay the same */
13566 [BPF_JEQ >> 4] = BPF_JEQ,
13567 [BPF_JNE >> 4] = BPF_JNE,
13568 [BPF_JSET >> 4] = BPF_JSET,
13569 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13570 [BPF_JGE >> 4] = BPF_JLE,
13571 [BPF_JGT >> 4] = BPF_JLT,
13572 [BPF_JLE >> 4] = BPF_JGE,
13573 [BPF_JLT >> 4] = BPF_JGT,
13574 [BPF_JSGE >> 4] = BPF_JSLE,
13575 [BPF_JSGT >> 4] = BPF_JSLT,
13576 [BPF_JSLE >> 4] = BPF_JSGE,
13577 [BPF_JSLT >> 4] = BPF_JSGT
13579 return opcode_flip[opcode >> 4];
13582 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13583 struct bpf_reg_state *src_reg,
13586 struct bpf_reg_state *pkt;
13588 if (src_reg->type == PTR_TO_PACKET_END) {
13590 } else if (dst_reg->type == PTR_TO_PACKET_END) {
13592 opcode = flip_opcode(opcode);
13597 if (pkt->range >= 0)
13602 /* pkt <= pkt_end */
13605 /* pkt > pkt_end */
13606 if (pkt->range == BEYOND_PKT_END)
13607 /* pkt has at last one extra byte beyond pkt_end */
13608 return opcode == BPF_JGT;
13611 /* pkt < pkt_end */
13614 /* pkt >= pkt_end */
13615 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13616 return opcode == BPF_JGE;
13622 /* Adjusts the register min/max values in the case that the dst_reg is the
13623 * variable register that we are working on, and src_reg is a constant or we're
13624 * simply doing a BPF_K check.
13625 * In JEQ/JNE cases we also adjust the var_off values.
13627 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13628 struct bpf_reg_state *false_reg,
13629 u64 val, u32 val32,
13630 u8 opcode, bool is_jmp32)
13632 struct tnum false_32off = tnum_subreg(false_reg->var_off);
13633 struct tnum false_64off = false_reg->var_off;
13634 struct tnum true_32off = tnum_subreg(true_reg->var_off);
13635 struct tnum true_64off = true_reg->var_off;
13636 s64 sval = (s64)val;
13637 s32 sval32 = (s32)val32;
13639 /* If the dst_reg is a pointer, we can't learn anything about its
13640 * variable offset from the compare (unless src_reg were a pointer into
13641 * the same object, but we don't bother with that.
13642 * Since false_reg and true_reg have the same type by construction, we
13643 * only need to check one of them for pointerness.
13645 if (__is_pointer_value(false, false_reg))
13649 /* JEQ/JNE comparison doesn't change the register equivalence.
13652 * if (r1 == 42) goto label;
13654 * label: // here both r1 and r2 are known to be 42.
13656 * Hence when marking register as known preserve it's ID.
13660 __mark_reg32_known(true_reg, val32);
13661 true_32off = tnum_subreg(true_reg->var_off);
13663 ___mark_reg_known(true_reg, val);
13664 true_64off = true_reg->var_off;
13669 __mark_reg32_known(false_reg, val32);
13670 false_32off = tnum_subreg(false_reg->var_off);
13672 ___mark_reg_known(false_reg, val);
13673 false_64off = false_reg->var_off;
13678 false_32off = tnum_and(false_32off, tnum_const(~val32));
13679 if (is_power_of_2(val32))
13680 true_32off = tnum_or(true_32off,
13681 tnum_const(val32));
13683 false_64off = tnum_and(false_64off, tnum_const(~val));
13684 if (is_power_of_2(val))
13685 true_64off = tnum_or(true_64off,
13693 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
13694 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13696 false_reg->u32_max_value = min(false_reg->u32_max_value,
13698 true_reg->u32_min_value = max(true_reg->u32_min_value,
13701 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
13702 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13704 false_reg->umax_value = min(false_reg->umax_value, false_umax);
13705 true_reg->umin_value = max(true_reg->umin_value, true_umin);
13713 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
13714 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13716 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13717 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13719 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
13720 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13722 false_reg->smax_value = min(false_reg->smax_value, false_smax);
13723 true_reg->smin_value = max(true_reg->smin_value, true_smin);
13731 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
13732 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13734 false_reg->u32_min_value = max(false_reg->u32_min_value,
13736 true_reg->u32_max_value = min(true_reg->u32_max_value,
13739 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
13740 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13742 false_reg->umin_value = max(false_reg->umin_value, false_umin);
13743 true_reg->umax_value = min(true_reg->umax_value, true_umax);
13751 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
13752 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13754 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13755 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13757 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
13758 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13760 false_reg->smin_value = max(false_reg->smin_value, false_smin);
13761 true_reg->smax_value = min(true_reg->smax_value, true_smax);
13770 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13771 tnum_subreg(false_32off));
13772 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13773 tnum_subreg(true_32off));
13774 __reg_combine_32_into_64(false_reg);
13775 __reg_combine_32_into_64(true_reg);
13777 false_reg->var_off = false_64off;
13778 true_reg->var_off = true_64off;
13779 __reg_combine_64_into_32(false_reg);
13780 __reg_combine_64_into_32(true_reg);
13784 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13785 * the variable reg.
13787 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13788 struct bpf_reg_state *false_reg,
13789 u64 val, u32 val32,
13790 u8 opcode, bool is_jmp32)
13792 opcode = flip_opcode(opcode);
13793 /* This uses zero as "not present in table"; luckily the zero opcode,
13794 * BPF_JA, can't get here.
13797 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13800 /* Regs are known to be equal, so intersect their min/max/var_off */
13801 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13802 struct bpf_reg_state *dst_reg)
13804 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13805 dst_reg->umin_value);
13806 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13807 dst_reg->umax_value);
13808 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13809 dst_reg->smin_value);
13810 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13811 dst_reg->smax_value);
13812 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13814 reg_bounds_sync(src_reg);
13815 reg_bounds_sync(dst_reg);
13818 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13819 struct bpf_reg_state *true_dst,
13820 struct bpf_reg_state *false_src,
13821 struct bpf_reg_state *false_dst,
13826 __reg_combine_min_max(true_src, true_dst);
13829 __reg_combine_min_max(false_src, false_dst);
13834 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13835 struct bpf_reg_state *reg, u32 id,
13838 if (type_may_be_null(reg->type) && reg->id == id &&
13839 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13840 /* Old offset (both fixed and variable parts) should have been
13841 * known-zero, because we don't allow pointer arithmetic on
13842 * pointers that might be NULL. If we see this happening, don't
13843 * convert the register.
13845 * But in some cases, some helpers that return local kptrs
13846 * advance offset for the returned pointer. In those cases, it
13847 * is fine to expect to see reg->off.
13849 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13851 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13852 WARN_ON_ONCE(reg->off))
13856 reg->type = SCALAR_VALUE;
13857 /* We don't need id and ref_obj_id from this point
13858 * onwards anymore, thus we should better reset it,
13859 * so that state pruning has chances to take effect.
13862 reg->ref_obj_id = 0;
13867 mark_ptr_not_null_reg(reg);
13869 if (!reg_may_point_to_spin_lock(reg)) {
13870 /* For not-NULL ptr, reg->ref_obj_id will be reset
13871 * in release_reference().
13873 * reg->id is still used by spin_lock ptr. Other
13874 * than spin_lock ptr type, reg->id can be reset.
13881 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13882 * be folded together at some point.
13884 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13887 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13888 struct bpf_reg_state *regs = state->regs, *reg;
13889 u32 ref_obj_id = regs[regno].ref_obj_id;
13890 u32 id = regs[regno].id;
13892 if (ref_obj_id && ref_obj_id == id && is_null)
13893 /* regs[regno] is in the " == NULL" branch.
13894 * No one could have freed the reference state before
13895 * doing the NULL check.
13897 WARN_ON_ONCE(release_reference_state(state, id));
13899 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13900 mark_ptr_or_null_reg(state, reg, id, is_null);
13904 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13905 struct bpf_reg_state *dst_reg,
13906 struct bpf_reg_state *src_reg,
13907 struct bpf_verifier_state *this_branch,
13908 struct bpf_verifier_state *other_branch)
13910 if (BPF_SRC(insn->code) != BPF_X)
13913 /* Pointers are always 64-bit. */
13914 if (BPF_CLASS(insn->code) == BPF_JMP32)
13917 switch (BPF_OP(insn->code)) {
13919 if ((dst_reg->type == PTR_TO_PACKET &&
13920 src_reg->type == PTR_TO_PACKET_END) ||
13921 (dst_reg->type == PTR_TO_PACKET_META &&
13922 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13923 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13924 find_good_pkt_pointers(this_branch, dst_reg,
13925 dst_reg->type, false);
13926 mark_pkt_end(other_branch, insn->dst_reg, true);
13927 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13928 src_reg->type == PTR_TO_PACKET) ||
13929 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13930 src_reg->type == PTR_TO_PACKET_META)) {
13931 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13932 find_good_pkt_pointers(other_branch, src_reg,
13933 src_reg->type, true);
13934 mark_pkt_end(this_branch, insn->src_reg, false);
13940 if ((dst_reg->type == PTR_TO_PACKET &&
13941 src_reg->type == PTR_TO_PACKET_END) ||
13942 (dst_reg->type == PTR_TO_PACKET_META &&
13943 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13944 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13945 find_good_pkt_pointers(other_branch, dst_reg,
13946 dst_reg->type, true);
13947 mark_pkt_end(this_branch, insn->dst_reg, false);
13948 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13949 src_reg->type == PTR_TO_PACKET) ||
13950 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13951 src_reg->type == PTR_TO_PACKET_META)) {
13952 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13953 find_good_pkt_pointers(this_branch, src_reg,
13954 src_reg->type, false);
13955 mark_pkt_end(other_branch, insn->src_reg, true);
13961 if ((dst_reg->type == PTR_TO_PACKET &&
13962 src_reg->type == PTR_TO_PACKET_END) ||
13963 (dst_reg->type == PTR_TO_PACKET_META &&
13964 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13965 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13966 find_good_pkt_pointers(this_branch, dst_reg,
13967 dst_reg->type, true);
13968 mark_pkt_end(other_branch, insn->dst_reg, false);
13969 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13970 src_reg->type == PTR_TO_PACKET) ||
13971 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13972 src_reg->type == PTR_TO_PACKET_META)) {
13973 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13974 find_good_pkt_pointers(other_branch, src_reg,
13975 src_reg->type, false);
13976 mark_pkt_end(this_branch, insn->src_reg, true);
13982 if ((dst_reg->type == PTR_TO_PACKET &&
13983 src_reg->type == PTR_TO_PACKET_END) ||
13984 (dst_reg->type == PTR_TO_PACKET_META &&
13985 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13986 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13987 find_good_pkt_pointers(other_branch, dst_reg,
13988 dst_reg->type, false);
13989 mark_pkt_end(this_branch, insn->dst_reg, true);
13990 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13991 src_reg->type == PTR_TO_PACKET) ||
13992 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13993 src_reg->type == PTR_TO_PACKET_META)) {
13994 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13995 find_good_pkt_pointers(this_branch, src_reg,
13996 src_reg->type, true);
13997 mark_pkt_end(other_branch, insn->src_reg, false);
14009 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14010 struct bpf_reg_state *known_reg)
14012 struct bpf_func_state *state;
14013 struct bpf_reg_state *reg;
14015 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14016 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14017 copy_register_state(reg, known_reg);
14021 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14022 struct bpf_insn *insn, int *insn_idx)
14024 struct bpf_verifier_state *this_branch = env->cur_state;
14025 struct bpf_verifier_state *other_branch;
14026 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14027 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14028 struct bpf_reg_state *eq_branch_regs;
14029 u8 opcode = BPF_OP(insn->code);
14034 /* Only conditional jumps are expected to reach here. */
14035 if (opcode == BPF_JA || opcode > BPF_JSLE) {
14036 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14040 if (BPF_SRC(insn->code) == BPF_X) {
14041 if (insn->imm != 0) {
14042 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14046 /* check src1 operand */
14047 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14051 if (is_pointer_value(env, insn->src_reg)) {
14052 verbose(env, "R%d pointer comparison prohibited\n",
14056 src_reg = ®s[insn->src_reg];
14058 if (insn->src_reg != BPF_REG_0) {
14059 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14064 /* check src2 operand */
14065 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14069 dst_reg = ®s[insn->dst_reg];
14070 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14072 if (BPF_SRC(insn->code) == BPF_K) {
14073 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14074 } else if (src_reg->type == SCALAR_VALUE &&
14075 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14076 pred = is_branch_taken(dst_reg,
14077 tnum_subreg(src_reg->var_off).value,
14080 } else if (src_reg->type == SCALAR_VALUE &&
14081 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14082 pred = is_branch_taken(dst_reg,
14083 src_reg->var_off.value,
14086 } else if (dst_reg->type == SCALAR_VALUE &&
14087 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14088 pred = is_branch_taken(src_reg,
14089 tnum_subreg(dst_reg->var_off).value,
14090 flip_opcode(opcode),
14092 } else if (dst_reg->type == SCALAR_VALUE &&
14093 !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14094 pred = is_branch_taken(src_reg,
14095 dst_reg->var_off.value,
14096 flip_opcode(opcode),
14098 } else if (reg_is_pkt_pointer_any(dst_reg) &&
14099 reg_is_pkt_pointer_any(src_reg) &&
14101 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14105 /* If we get here with a dst_reg pointer type it is because
14106 * above is_branch_taken() special cased the 0 comparison.
14108 if (!__is_pointer_value(false, dst_reg))
14109 err = mark_chain_precision(env, insn->dst_reg);
14110 if (BPF_SRC(insn->code) == BPF_X && !err &&
14111 !__is_pointer_value(false, src_reg))
14112 err = mark_chain_precision(env, insn->src_reg);
14118 /* Only follow the goto, ignore fall-through. If needed, push
14119 * the fall-through branch for simulation under speculative
14122 if (!env->bypass_spec_v1 &&
14123 !sanitize_speculative_path(env, insn, *insn_idx + 1,
14126 *insn_idx += insn->off;
14128 } else if (pred == 0) {
14129 /* Only follow the fall-through branch, since that's where the
14130 * program will go. If needed, push the goto branch for
14131 * simulation under speculative execution.
14133 if (!env->bypass_spec_v1 &&
14134 !sanitize_speculative_path(env, insn,
14135 *insn_idx + insn->off + 1,
14141 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14145 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14147 /* detect if we are comparing against a constant value so we can adjust
14148 * our min/max values for our dst register.
14149 * this is only legit if both are scalars (or pointers to the same
14150 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14151 * because otherwise the different base pointers mean the offsets aren't
14154 if (BPF_SRC(insn->code) == BPF_X) {
14155 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
14157 if (dst_reg->type == SCALAR_VALUE &&
14158 src_reg->type == SCALAR_VALUE) {
14159 if (tnum_is_const(src_reg->var_off) ||
14161 tnum_is_const(tnum_subreg(src_reg->var_off))))
14162 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14164 src_reg->var_off.value,
14165 tnum_subreg(src_reg->var_off).value,
14167 else if (tnum_is_const(dst_reg->var_off) ||
14169 tnum_is_const(tnum_subreg(dst_reg->var_off))))
14170 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14172 dst_reg->var_off.value,
14173 tnum_subreg(dst_reg->var_off).value,
14175 else if (!is_jmp32 &&
14176 (opcode == BPF_JEQ || opcode == BPF_JNE))
14177 /* Comparing for equality, we can combine knowledge */
14178 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14179 &other_branch_regs[insn->dst_reg],
14180 src_reg, dst_reg, opcode);
14182 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14183 find_equal_scalars(this_branch, src_reg);
14184 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14188 } else if (dst_reg->type == SCALAR_VALUE) {
14189 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14190 dst_reg, insn->imm, (u32)insn->imm,
14194 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14195 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14196 find_equal_scalars(this_branch, dst_reg);
14197 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14200 /* if one pointer register is compared to another pointer
14201 * register check if PTR_MAYBE_NULL could be lifted.
14202 * E.g. register A - maybe null
14203 * register B - not null
14204 * for JNE A, B, ... - A is not null in the false branch;
14205 * for JEQ A, B, ... - A is not null in the true branch.
14207 * Since PTR_TO_BTF_ID points to a kernel struct that does
14208 * not need to be null checked by the BPF program, i.e.,
14209 * could be null even without PTR_MAYBE_NULL marking, so
14210 * only propagate nullness when neither reg is that type.
14212 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14213 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14214 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14215 base_type(src_reg->type) != PTR_TO_BTF_ID &&
14216 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14217 eq_branch_regs = NULL;
14220 eq_branch_regs = other_branch_regs;
14223 eq_branch_regs = regs;
14229 if (eq_branch_regs) {
14230 if (type_may_be_null(src_reg->type))
14231 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14233 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14237 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14238 * NOTE: these optimizations below are related with pointer comparison
14239 * which will never be JMP32.
14241 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14242 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14243 type_may_be_null(dst_reg->type)) {
14244 /* Mark all identical registers in each branch as either
14245 * safe or unknown depending R == 0 or R != 0 conditional.
14247 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14248 opcode == BPF_JNE);
14249 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14250 opcode == BPF_JEQ);
14251 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
14252 this_branch, other_branch) &&
14253 is_pointer_value(env, insn->dst_reg)) {
14254 verbose(env, "R%d pointer comparison prohibited\n",
14258 if (env->log.level & BPF_LOG_LEVEL)
14259 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14263 /* verify BPF_LD_IMM64 instruction */
14264 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14266 struct bpf_insn_aux_data *aux = cur_aux(env);
14267 struct bpf_reg_state *regs = cur_regs(env);
14268 struct bpf_reg_state *dst_reg;
14269 struct bpf_map *map;
14272 if (BPF_SIZE(insn->code) != BPF_DW) {
14273 verbose(env, "invalid BPF_LD_IMM insn\n");
14276 if (insn->off != 0) {
14277 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14281 err = check_reg_arg(env, insn->dst_reg, DST_OP);
14285 dst_reg = ®s[insn->dst_reg];
14286 if (insn->src_reg == 0) {
14287 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14289 dst_reg->type = SCALAR_VALUE;
14290 __mark_reg_known(®s[insn->dst_reg], imm);
14294 /* All special src_reg cases are listed below. From this point onwards
14295 * we either succeed and assign a corresponding dst_reg->type after
14296 * zeroing the offset, or fail and reject the program.
14298 mark_reg_known_zero(env, regs, insn->dst_reg);
14300 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14301 dst_reg->type = aux->btf_var.reg_type;
14302 switch (base_type(dst_reg->type)) {
14304 dst_reg->mem_size = aux->btf_var.mem_size;
14306 case PTR_TO_BTF_ID:
14307 dst_reg->btf = aux->btf_var.btf;
14308 dst_reg->btf_id = aux->btf_var.btf_id;
14311 verbose(env, "bpf verifier is misconfigured\n");
14317 if (insn->src_reg == BPF_PSEUDO_FUNC) {
14318 struct bpf_prog_aux *aux = env->prog->aux;
14319 u32 subprogno = find_subprog(env,
14320 env->insn_idx + insn->imm + 1);
14322 if (!aux->func_info) {
14323 verbose(env, "missing btf func_info\n");
14326 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14327 verbose(env, "callback function not static\n");
14331 dst_reg->type = PTR_TO_FUNC;
14332 dst_reg->subprogno = subprogno;
14336 map = env->used_maps[aux->map_index];
14337 dst_reg->map_ptr = map;
14339 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14340 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14341 dst_reg->type = PTR_TO_MAP_VALUE;
14342 dst_reg->off = aux->map_off;
14343 WARN_ON_ONCE(map->max_entries != 1);
14344 /* We want reg->id to be same (0) as map_value is not distinct */
14345 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14346 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14347 dst_reg->type = CONST_PTR_TO_MAP;
14349 verbose(env, "bpf verifier is misconfigured\n");
14356 static bool may_access_skb(enum bpf_prog_type type)
14359 case BPF_PROG_TYPE_SOCKET_FILTER:
14360 case BPF_PROG_TYPE_SCHED_CLS:
14361 case BPF_PROG_TYPE_SCHED_ACT:
14368 /* verify safety of LD_ABS|LD_IND instructions:
14369 * - they can only appear in the programs where ctx == skb
14370 * - since they are wrappers of function calls, they scratch R1-R5 registers,
14371 * preserve R6-R9, and store return value into R0
14374 * ctx == skb == R6 == CTX
14377 * SRC == any register
14378 * IMM == 32-bit immediate
14381 * R0 - 8/16/32-bit skb data converted to cpu endianness
14383 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14385 struct bpf_reg_state *regs = cur_regs(env);
14386 static const int ctx_reg = BPF_REG_6;
14387 u8 mode = BPF_MODE(insn->code);
14390 if (!may_access_skb(resolve_prog_type(env->prog))) {
14391 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14395 if (!env->ops->gen_ld_abs) {
14396 verbose(env, "bpf verifier is misconfigured\n");
14400 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14401 BPF_SIZE(insn->code) == BPF_DW ||
14402 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14403 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14407 /* check whether implicit source operand (register R6) is readable */
14408 err = check_reg_arg(env, ctx_reg, SRC_OP);
14412 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14413 * gen_ld_abs() may terminate the program at runtime, leading to
14416 err = check_reference_leak(env);
14418 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14422 if (env->cur_state->active_lock.ptr) {
14423 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14427 if (env->cur_state->active_rcu_lock) {
14428 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14432 if (regs[ctx_reg].type != PTR_TO_CTX) {
14434 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14438 if (mode == BPF_IND) {
14439 /* check explicit source operand */
14440 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14445 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
14449 /* reset caller saved regs to unreadable */
14450 for (i = 0; i < CALLER_SAVED_REGS; i++) {
14451 mark_reg_not_init(env, regs, caller_saved[i]);
14452 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14455 /* mark destination R0 register as readable, since it contains
14456 * the value fetched from the packet.
14457 * Already marked as written above.
14459 mark_reg_unknown(env, regs, BPF_REG_0);
14460 /* ld_abs load up to 32-bit skb data. */
14461 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14465 static int check_return_code(struct bpf_verifier_env *env)
14467 struct tnum enforce_attach_type_range = tnum_unknown;
14468 const struct bpf_prog *prog = env->prog;
14469 struct bpf_reg_state *reg;
14470 struct tnum range = tnum_range(0, 1);
14471 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14473 struct bpf_func_state *frame = env->cur_state->frame[0];
14474 const bool is_subprog = frame->subprogno;
14476 /* LSM and struct_ops func-ptr's return type could be "void" */
14478 switch (prog_type) {
14479 case BPF_PROG_TYPE_LSM:
14480 if (prog->expected_attach_type == BPF_LSM_CGROUP)
14481 /* See below, can be 0 or 0-1 depending on hook. */
14484 case BPF_PROG_TYPE_STRUCT_OPS:
14485 if (!prog->aux->attach_func_proto->type)
14493 /* eBPF calling convention is such that R0 is used
14494 * to return the value from eBPF program.
14495 * Make sure that it's readable at this time
14496 * of bpf_exit, which means that program wrote
14497 * something into it earlier
14499 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14503 if (is_pointer_value(env, BPF_REG_0)) {
14504 verbose(env, "R0 leaks addr as return value\n");
14508 reg = cur_regs(env) + BPF_REG_0;
14510 if (frame->in_async_callback_fn) {
14511 /* enforce return zero from async callbacks like timer */
14512 if (reg->type != SCALAR_VALUE) {
14513 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14514 reg_type_str(env, reg->type));
14518 if (!tnum_in(tnum_const(0), reg->var_off)) {
14519 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14526 if (reg->type != SCALAR_VALUE) {
14527 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14528 reg_type_str(env, reg->type));
14534 switch (prog_type) {
14535 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14536 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14537 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14538 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14539 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14540 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14541 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14542 range = tnum_range(1, 1);
14543 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14544 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14545 range = tnum_range(0, 3);
14547 case BPF_PROG_TYPE_CGROUP_SKB:
14548 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14549 range = tnum_range(0, 3);
14550 enforce_attach_type_range = tnum_range(2, 3);
14553 case BPF_PROG_TYPE_CGROUP_SOCK:
14554 case BPF_PROG_TYPE_SOCK_OPS:
14555 case BPF_PROG_TYPE_CGROUP_DEVICE:
14556 case BPF_PROG_TYPE_CGROUP_SYSCTL:
14557 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14559 case BPF_PROG_TYPE_RAW_TRACEPOINT:
14560 if (!env->prog->aux->attach_btf_id)
14562 range = tnum_const(0);
14564 case BPF_PROG_TYPE_TRACING:
14565 switch (env->prog->expected_attach_type) {
14566 case BPF_TRACE_FENTRY:
14567 case BPF_TRACE_FEXIT:
14568 range = tnum_const(0);
14570 case BPF_TRACE_RAW_TP:
14571 case BPF_MODIFY_RETURN:
14573 case BPF_TRACE_ITER:
14579 case BPF_PROG_TYPE_SK_LOOKUP:
14580 range = tnum_range(SK_DROP, SK_PASS);
14583 case BPF_PROG_TYPE_LSM:
14584 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14585 /* Regular BPF_PROG_TYPE_LSM programs can return
14590 if (!env->prog->aux->attach_func_proto->type) {
14591 /* Make sure programs that attach to void
14592 * hooks don't try to modify return value.
14594 range = tnum_range(1, 1);
14598 case BPF_PROG_TYPE_NETFILTER:
14599 range = tnum_range(NF_DROP, NF_ACCEPT);
14601 case BPF_PROG_TYPE_EXT:
14602 /* freplace program can return anything as its return value
14603 * depends on the to-be-replaced kernel func or bpf program.
14609 if (reg->type != SCALAR_VALUE) {
14610 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14611 reg_type_str(env, reg->type));
14615 if (!tnum_in(range, reg->var_off)) {
14616 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14617 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14618 prog_type == BPF_PROG_TYPE_LSM &&
14619 !prog->aux->attach_func_proto->type)
14620 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14624 if (!tnum_is_unknown(enforce_attach_type_range) &&
14625 tnum_in(enforce_attach_type_range, reg->var_off))
14626 env->prog->enforce_expected_attach_type = 1;
14630 /* non-recursive DFS pseudo code
14631 * 1 procedure DFS-iterative(G,v):
14632 * 2 label v as discovered
14633 * 3 let S be a stack
14635 * 5 while S is not empty
14637 * 7 if t is what we're looking for:
14639 * 9 for all edges e in G.adjacentEdges(t) do
14640 * 10 if edge e is already labelled
14641 * 11 continue with the next edge
14642 * 12 w <- G.adjacentVertex(t,e)
14643 * 13 if vertex w is not discovered and not explored
14644 * 14 label e as tree-edge
14645 * 15 label w as discovered
14648 * 18 else if vertex w is discovered
14649 * 19 label e as back-edge
14651 * 21 // vertex w is explored
14652 * 22 label e as forward- or cross-edge
14653 * 23 label t as explored
14657 * 0x10 - discovered
14658 * 0x11 - discovered and fall-through edge labelled
14659 * 0x12 - discovered and fall-through and branch edges labelled
14670 static u32 state_htab_size(struct bpf_verifier_env *env)
14672 return env->prog->len;
14675 static struct bpf_verifier_state_list **explored_state(
14676 struct bpf_verifier_env *env,
14679 struct bpf_verifier_state *cur = env->cur_state;
14680 struct bpf_func_state *state = cur->frame[cur->curframe];
14682 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14685 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14687 env->insn_aux_data[idx].prune_point = true;
14690 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14692 return env->insn_aux_data[insn_idx].prune_point;
14695 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14697 env->insn_aux_data[idx].force_checkpoint = true;
14700 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14702 return env->insn_aux_data[insn_idx].force_checkpoint;
14707 DONE_EXPLORING = 0,
14708 KEEP_EXPLORING = 1,
14711 /* t, w, e - match pseudo-code above:
14712 * t - index of current instruction
14713 * w - next instruction
14716 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14719 int *insn_stack = env->cfg.insn_stack;
14720 int *insn_state = env->cfg.insn_state;
14722 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14723 return DONE_EXPLORING;
14725 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14726 return DONE_EXPLORING;
14728 if (w < 0 || w >= env->prog->len) {
14729 verbose_linfo(env, t, "%d: ", t);
14730 verbose(env, "jump out of range from insn %d to %d\n", t, w);
14735 /* mark branch target for state pruning */
14736 mark_prune_point(env, w);
14737 mark_jmp_point(env, w);
14740 if (insn_state[w] == 0) {
14742 insn_state[t] = DISCOVERED | e;
14743 insn_state[w] = DISCOVERED;
14744 if (env->cfg.cur_stack >= env->prog->len)
14746 insn_stack[env->cfg.cur_stack++] = w;
14747 return KEEP_EXPLORING;
14748 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14749 if (loop_ok && env->bpf_capable)
14750 return DONE_EXPLORING;
14751 verbose_linfo(env, t, "%d: ", t);
14752 verbose_linfo(env, w, "%d: ", w);
14753 verbose(env, "back-edge from insn %d to %d\n", t, w);
14755 } else if (insn_state[w] == EXPLORED) {
14756 /* forward- or cross-edge */
14757 insn_state[t] = DISCOVERED | e;
14759 verbose(env, "insn state internal bug\n");
14762 return DONE_EXPLORING;
14765 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14766 struct bpf_verifier_env *env,
14771 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14775 mark_prune_point(env, t + 1);
14776 /* when we exit from subprog, we need to record non-linear history */
14777 mark_jmp_point(env, t + 1);
14779 if (visit_callee) {
14780 mark_prune_point(env, t);
14781 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14782 /* It's ok to allow recursion from CFG point of
14783 * view. __check_func_call() will do the actual
14786 bpf_pseudo_func(insns + t));
14791 /* Visits the instruction at index t and returns one of the following:
14792 * < 0 - an error occurred
14793 * DONE_EXPLORING - the instruction was fully explored
14794 * KEEP_EXPLORING - there is still work to be done before it is fully explored
14796 static int visit_insn(int t, struct bpf_verifier_env *env)
14798 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14801 if (bpf_pseudo_func(insn))
14802 return visit_func_call_insn(t, insns, env, true);
14804 /* All non-branch instructions have a single fall-through edge. */
14805 if (BPF_CLASS(insn->code) != BPF_JMP &&
14806 BPF_CLASS(insn->code) != BPF_JMP32)
14807 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14809 switch (BPF_OP(insn->code)) {
14811 return DONE_EXPLORING;
14814 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14815 /* Mark this call insn as a prune point to trigger
14816 * is_state_visited() check before call itself is
14817 * processed by __check_func_call(). Otherwise new
14818 * async state will be pushed for further exploration.
14820 mark_prune_point(env, t);
14821 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14822 struct bpf_kfunc_call_arg_meta meta;
14824 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14825 if (ret == 0 && is_iter_next_kfunc(&meta)) {
14826 mark_prune_point(env, t);
14827 /* Checking and saving state checkpoints at iter_next() call
14828 * is crucial for fast convergence of open-coded iterator loop
14829 * logic, so we need to force it. If we don't do that,
14830 * is_state_visited() might skip saving a checkpoint, causing
14831 * unnecessarily long sequence of not checkpointed
14832 * instructions and jumps, leading to exhaustion of jump
14833 * history buffer, and potentially other undesired outcomes.
14834 * It is expected that with correct open-coded iterators
14835 * convergence will happen quickly, so we don't run a risk of
14836 * exhausting memory.
14838 mark_force_checkpoint(env, t);
14841 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14844 if (BPF_SRC(insn->code) != BPF_K)
14847 if (BPF_CLASS(insn->code) == BPF_JMP)
14852 /* unconditional jump with single edge */
14853 ret = push_insn(t, t + off + 1, FALLTHROUGH, env,
14858 mark_prune_point(env, t + off + 1);
14859 mark_jmp_point(env, t + off + 1);
14864 /* conditional jump with two edges */
14865 mark_prune_point(env, t);
14867 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14871 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14875 /* non-recursive depth-first-search to detect loops in BPF program
14876 * loop == back-edge in directed graph
14878 static int check_cfg(struct bpf_verifier_env *env)
14880 int insn_cnt = env->prog->len;
14881 int *insn_stack, *insn_state;
14885 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14889 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14891 kvfree(insn_state);
14895 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14896 insn_stack[0] = 0; /* 0 is the first instruction */
14897 env->cfg.cur_stack = 1;
14899 while (env->cfg.cur_stack > 0) {
14900 int t = insn_stack[env->cfg.cur_stack - 1];
14902 ret = visit_insn(t, env);
14904 case DONE_EXPLORING:
14905 insn_state[t] = EXPLORED;
14906 env->cfg.cur_stack--;
14908 case KEEP_EXPLORING:
14912 verbose(env, "visit_insn internal bug\n");
14919 if (env->cfg.cur_stack < 0) {
14920 verbose(env, "pop stack internal bug\n");
14925 for (i = 0; i < insn_cnt; i++) {
14926 if (insn_state[i] != EXPLORED) {
14927 verbose(env, "unreachable insn %d\n", i);
14932 ret = 0; /* cfg looks good */
14935 kvfree(insn_state);
14936 kvfree(insn_stack);
14937 env->cfg.insn_state = env->cfg.insn_stack = NULL;
14941 static int check_abnormal_return(struct bpf_verifier_env *env)
14945 for (i = 1; i < env->subprog_cnt; i++) {
14946 if (env->subprog_info[i].has_ld_abs) {
14947 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14950 if (env->subprog_info[i].has_tail_call) {
14951 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14958 /* The minimum supported BTF func info size */
14959 #define MIN_BPF_FUNCINFO_SIZE 8
14960 #define MAX_FUNCINFO_REC_SIZE 252
14962 static int check_btf_func(struct bpf_verifier_env *env,
14963 const union bpf_attr *attr,
14966 const struct btf_type *type, *func_proto, *ret_type;
14967 u32 i, nfuncs, urec_size, min_size;
14968 u32 krec_size = sizeof(struct bpf_func_info);
14969 struct bpf_func_info *krecord;
14970 struct bpf_func_info_aux *info_aux = NULL;
14971 struct bpf_prog *prog;
14972 const struct btf *btf;
14974 u32 prev_offset = 0;
14975 bool scalar_return;
14978 nfuncs = attr->func_info_cnt;
14980 if (check_abnormal_return(env))
14985 if (nfuncs != env->subprog_cnt) {
14986 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14990 urec_size = attr->func_info_rec_size;
14991 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14992 urec_size > MAX_FUNCINFO_REC_SIZE ||
14993 urec_size % sizeof(u32)) {
14994 verbose(env, "invalid func info rec size %u\n", urec_size);
14999 btf = prog->aux->btf;
15001 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15002 min_size = min_t(u32, krec_size, urec_size);
15004 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15007 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15011 for (i = 0; i < nfuncs; i++) {
15012 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15014 if (ret == -E2BIG) {
15015 verbose(env, "nonzero tailing record in func info");
15016 /* set the size kernel expects so loader can zero
15017 * out the rest of the record.
15019 if (copy_to_bpfptr_offset(uattr,
15020 offsetof(union bpf_attr, func_info_rec_size),
15021 &min_size, sizeof(min_size)))
15027 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15032 /* check insn_off */
15035 if (krecord[i].insn_off) {
15037 "nonzero insn_off %u for the first func info record",
15038 krecord[i].insn_off);
15041 } else if (krecord[i].insn_off <= prev_offset) {
15043 "same or smaller insn offset (%u) than previous func info record (%u)",
15044 krecord[i].insn_off, prev_offset);
15048 if (env->subprog_info[i].start != krecord[i].insn_off) {
15049 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15053 /* check type_id */
15054 type = btf_type_by_id(btf, krecord[i].type_id);
15055 if (!type || !btf_type_is_func(type)) {
15056 verbose(env, "invalid type id %d in func info",
15057 krecord[i].type_id);
15060 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15062 func_proto = btf_type_by_id(btf, type->type);
15063 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15064 /* btf_func_check() already verified it during BTF load */
15066 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15068 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15069 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15070 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15073 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15074 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15078 prev_offset = krecord[i].insn_off;
15079 bpfptr_add(&urecord, urec_size);
15082 prog->aux->func_info = krecord;
15083 prog->aux->func_info_cnt = nfuncs;
15084 prog->aux->func_info_aux = info_aux;
15093 static void adjust_btf_func(struct bpf_verifier_env *env)
15095 struct bpf_prog_aux *aux = env->prog->aux;
15098 if (!aux->func_info)
15101 for (i = 0; i < env->subprog_cnt; i++)
15102 aux->func_info[i].insn_off = env->subprog_info[i].start;
15105 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
15106 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
15108 static int check_btf_line(struct bpf_verifier_env *env,
15109 const union bpf_attr *attr,
15112 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15113 struct bpf_subprog_info *sub;
15114 struct bpf_line_info *linfo;
15115 struct bpf_prog *prog;
15116 const struct btf *btf;
15120 nr_linfo = attr->line_info_cnt;
15123 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15126 rec_size = attr->line_info_rec_size;
15127 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15128 rec_size > MAX_LINEINFO_REC_SIZE ||
15129 rec_size & (sizeof(u32) - 1))
15132 /* Need to zero it in case the userspace may
15133 * pass in a smaller bpf_line_info object.
15135 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15136 GFP_KERNEL | __GFP_NOWARN);
15141 btf = prog->aux->btf;
15144 sub = env->subprog_info;
15145 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15146 expected_size = sizeof(struct bpf_line_info);
15147 ncopy = min_t(u32, expected_size, rec_size);
15148 for (i = 0; i < nr_linfo; i++) {
15149 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15151 if (err == -E2BIG) {
15152 verbose(env, "nonzero tailing record in line_info");
15153 if (copy_to_bpfptr_offset(uattr,
15154 offsetof(union bpf_attr, line_info_rec_size),
15155 &expected_size, sizeof(expected_size)))
15161 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15167 * Check insn_off to ensure
15168 * 1) strictly increasing AND
15169 * 2) bounded by prog->len
15171 * The linfo[0].insn_off == 0 check logically falls into
15172 * the later "missing bpf_line_info for func..." case
15173 * because the first linfo[0].insn_off must be the
15174 * first sub also and the first sub must have
15175 * subprog_info[0].start == 0.
15177 if ((i && linfo[i].insn_off <= prev_offset) ||
15178 linfo[i].insn_off >= prog->len) {
15179 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15180 i, linfo[i].insn_off, prev_offset,
15186 if (!prog->insnsi[linfo[i].insn_off].code) {
15188 "Invalid insn code at line_info[%u].insn_off\n",
15194 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15195 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15196 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15201 if (s != env->subprog_cnt) {
15202 if (linfo[i].insn_off == sub[s].start) {
15203 sub[s].linfo_idx = i;
15205 } else if (sub[s].start < linfo[i].insn_off) {
15206 verbose(env, "missing bpf_line_info for func#%u\n", s);
15212 prev_offset = linfo[i].insn_off;
15213 bpfptr_add(&ulinfo, rec_size);
15216 if (s != env->subprog_cnt) {
15217 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15218 env->subprog_cnt - s, s);
15223 prog->aux->linfo = linfo;
15224 prog->aux->nr_linfo = nr_linfo;
15233 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
15234 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
15236 static int check_core_relo(struct bpf_verifier_env *env,
15237 const union bpf_attr *attr,
15240 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15241 struct bpf_core_relo core_relo = {};
15242 struct bpf_prog *prog = env->prog;
15243 const struct btf *btf = prog->aux->btf;
15244 struct bpf_core_ctx ctx = {
15248 bpfptr_t u_core_relo;
15251 nr_core_relo = attr->core_relo_cnt;
15254 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15257 rec_size = attr->core_relo_rec_size;
15258 if (rec_size < MIN_CORE_RELO_SIZE ||
15259 rec_size > MAX_CORE_RELO_SIZE ||
15260 rec_size % sizeof(u32))
15263 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15264 expected_size = sizeof(struct bpf_core_relo);
15265 ncopy = min_t(u32, expected_size, rec_size);
15267 /* Unlike func_info and line_info, copy and apply each CO-RE
15268 * relocation record one at a time.
15270 for (i = 0; i < nr_core_relo; i++) {
15271 /* future proofing when sizeof(bpf_core_relo) changes */
15272 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15274 if (err == -E2BIG) {
15275 verbose(env, "nonzero tailing record in core_relo");
15276 if (copy_to_bpfptr_offset(uattr,
15277 offsetof(union bpf_attr, core_relo_rec_size),
15278 &expected_size, sizeof(expected_size)))
15284 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15289 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15290 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15291 i, core_relo.insn_off, prog->len);
15296 err = bpf_core_apply(&ctx, &core_relo, i,
15297 &prog->insnsi[core_relo.insn_off / 8]);
15300 bpfptr_add(&u_core_relo, rec_size);
15305 static int check_btf_info(struct bpf_verifier_env *env,
15306 const union bpf_attr *attr,
15312 if (!attr->func_info_cnt && !attr->line_info_cnt) {
15313 if (check_abnormal_return(env))
15318 btf = btf_get_by_fd(attr->prog_btf_fd);
15320 return PTR_ERR(btf);
15321 if (btf_is_kernel(btf)) {
15325 env->prog->aux->btf = btf;
15327 err = check_btf_func(env, attr, uattr);
15331 err = check_btf_line(env, attr, uattr);
15335 err = check_core_relo(env, attr, uattr);
15342 /* check %cur's range satisfies %old's */
15343 static bool range_within(struct bpf_reg_state *old,
15344 struct bpf_reg_state *cur)
15346 return old->umin_value <= cur->umin_value &&
15347 old->umax_value >= cur->umax_value &&
15348 old->smin_value <= cur->smin_value &&
15349 old->smax_value >= cur->smax_value &&
15350 old->u32_min_value <= cur->u32_min_value &&
15351 old->u32_max_value >= cur->u32_max_value &&
15352 old->s32_min_value <= cur->s32_min_value &&
15353 old->s32_max_value >= cur->s32_max_value;
15356 /* If in the old state two registers had the same id, then they need to have
15357 * the same id in the new state as well. But that id could be different from
15358 * the old state, so we need to track the mapping from old to new ids.
15359 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15360 * regs with old id 5 must also have new id 9 for the new state to be safe. But
15361 * regs with a different old id could still have new id 9, we don't care about
15363 * So we look through our idmap to see if this old id has been seen before. If
15364 * so, we require the new id to match; otherwise, we add the id pair to the map.
15366 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15368 struct bpf_id_pair *map = idmap->map;
15371 /* either both IDs should be set or both should be zero */
15372 if (!!old_id != !!cur_id)
15375 if (old_id == 0) /* cur_id == 0 as well */
15378 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15380 /* Reached an empty slot; haven't seen this id before */
15381 map[i].old = old_id;
15382 map[i].cur = cur_id;
15385 if (map[i].old == old_id)
15386 return map[i].cur == cur_id;
15387 if (map[i].cur == cur_id)
15390 /* We ran out of idmap slots, which should be impossible */
15395 /* Similar to check_ids(), but allocate a unique temporary ID
15396 * for 'old_id' or 'cur_id' of zero.
15397 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15399 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15401 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15402 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15404 return check_ids(old_id, cur_id, idmap);
15407 static void clean_func_state(struct bpf_verifier_env *env,
15408 struct bpf_func_state *st)
15410 enum bpf_reg_liveness live;
15413 for (i = 0; i < BPF_REG_FP; i++) {
15414 live = st->regs[i].live;
15415 /* liveness must not touch this register anymore */
15416 st->regs[i].live |= REG_LIVE_DONE;
15417 if (!(live & REG_LIVE_READ))
15418 /* since the register is unused, clear its state
15419 * to make further comparison simpler
15421 __mark_reg_not_init(env, &st->regs[i]);
15424 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15425 live = st->stack[i].spilled_ptr.live;
15426 /* liveness must not touch this stack slot anymore */
15427 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15428 if (!(live & REG_LIVE_READ)) {
15429 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15430 for (j = 0; j < BPF_REG_SIZE; j++)
15431 st->stack[i].slot_type[j] = STACK_INVALID;
15436 static void clean_verifier_state(struct bpf_verifier_env *env,
15437 struct bpf_verifier_state *st)
15441 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15442 /* all regs in this state in all frames were already marked */
15445 for (i = 0; i <= st->curframe; i++)
15446 clean_func_state(env, st->frame[i]);
15449 /* the parentage chains form a tree.
15450 * the verifier states are added to state lists at given insn and
15451 * pushed into state stack for future exploration.
15452 * when the verifier reaches bpf_exit insn some of the verifer states
15453 * stored in the state lists have their final liveness state already,
15454 * but a lot of states will get revised from liveness point of view when
15455 * the verifier explores other branches.
15458 * 2: if r1 == 100 goto pc+1
15461 * when the verifier reaches exit insn the register r0 in the state list of
15462 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15463 * of insn 2 and goes exploring further. At the insn 4 it will walk the
15464 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15466 * Since the verifier pushes the branch states as it sees them while exploring
15467 * the program the condition of walking the branch instruction for the second
15468 * time means that all states below this branch were already explored and
15469 * their final liveness marks are already propagated.
15470 * Hence when the verifier completes the search of state list in is_state_visited()
15471 * we can call this clean_live_states() function to mark all liveness states
15472 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15473 * will not be used.
15474 * This function also clears the registers and stack for states that !READ
15475 * to simplify state merging.
15477 * Important note here that walking the same branch instruction in the callee
15478 * doesn't meant that the states are DONE. The verifier has to compare
15481 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15482 struct bpf_verifier_state *cur)
15484 struct bpf_verifier_state_list *sl;
15487 sl = *explored_state(env, insn);
15489 if (sl->state.branches)
15491 if (sl->state.insn_idx != insn ||
15492 sl->state.curframe != cur->curframe)
15494 for (i = 0; i <= cur->curframe; i++)
15495 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15497 clean_verifier_state(env, &sl->state);
15503 static bool regs_exact(const struct bpf_reg_state *rold,
15504 const struct bpf_reg_state *rcur,
15505 struct bpf_idmap *idmap)
15507 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15508 check_ids(rold->id, rcur->id, idmap) &&
15509 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15512 /* Returns true if (rold safe implies rcur safe) */
15513 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15514 struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15516 if (!(rold->live & REG_LIVE_READ))
15517 /* explored state didn't use this */
15519 if (rold->type == NOT_INIT)
15520 /* explored state can't have used this */
15522 if (rcur->type == NOT_INIT)
15525 /* Enforce that register types have to match exactly, including their
15526 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15529 * One can make a point that using a pointer register as unbounded
15530 * SCALAR would be technically acceptable, but this could lead to
15531 * pointer leaks because scalars are allowed to leak while pointers
15532 * are not. We could make this safe in special cases if root is
15533 * calling us, but it's probably not worth the hassle.
15535 * Also, register types that are *not* MAYBE_NULL could technically be
15536 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15537 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15538 * to the same map).
15539 * However, if the old MAYBE_NULL register then got NULL checked,
15540 * doing so could have affected others with the same id, and we can't
15541 * check for that because we lost the id when we converted to
15542 * a non-MAYBE_NULL variant.
15543 * So, as a general rule we don't allow mixing MAYBE_NULL and
15544 * non-MAYBE_NULL registers as well.
15546 if (rold->type != rcur->type)
15549 switch (base_type(rold->type)) {
15551 if (env->explore_alu_limits) {
15552 /* explore_alu_limits disables tnum_in() and range_within()
15553 * logic and requires everything to be strict
15555 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15556 check_scalar_ids(rold->id, rcur->id, idmap);
15558 if (!rold->precise)
15560 /* Why check_ids() for scalar registers?
15562 * Consider the following BPF code:
15563 * 1: r6 = ... unbound scalar, ID=a ...
15564 * 2: r7 = ... unbound scalar, ID=b ...
15565 * 3: if (r6 > r7) goto +1
15567 * 5: if (r6 > X) goto ...
15568 * 6: ... memory operation using r7 ...
15570 * First verification path is [1-6]:
15571 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15572 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15573 * r7 <= X, because r6 and r7 share same id.
15574 * Next verification path is [1-4, 6].
15576 * Instruction (6) would be reached in two states:
15577 * I. r6{.id=b}, r7{.id=b} via path 1-6;
15578 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15580 * Use check_ids() to distinguish these states.
15582 * Also verify that new value satisfies old value range knowledge.
15584 return range_within(rold, rcur) &&
15585 tnum_in(rold->var_off, rcur->var_off) &&
15586 check_scalar_ids(rold->id, rcur->id, idmap);
15587 case PTR_TO_MAP_KEY:
15588 case PTR_TO_MAP_VALUE:
15591 case PTR_TO_TP_BUFFER:
15592 /* If the new min/max/var_off satisfy the old ones and
15593 * everything else matches, we are OK.
15595 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15596 range_within(rold, rcur) &&
15597 tnum_in(rold->var_off, rcur->var_off) &&
15598 check_ids(rold->id, rcur->id, idmap) &&
15599 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15600 case PTR_TO_PACKET_META:
15601 case PTR_TO_PACKET:
15602 /* We must have at least as much range as the old ptr
15603 * did, so that any accesses which were safe before are
15604 * still safe. This is true even if old range < old off,
15605 * since someone could have accessed through (ptr - k), or
15606 * even done ptr -= k in a register, to get a safe access.
15608 if (rold->range > rcur->range)
15610 /* If the offsets don't match, we can't trust our alignment;
15611 * nor can we be sure that we won't fall out of range.
15613 if (rold->off != rcur->off)
15615 /* id relations must be preserved */
15616 if (!check_ids(rold->id, rcur->id, idmap))
15618 /* new val must satisfy old val knowledge */
15619 return range_within(rold, rcur) &&
15620 tnum_in(rold->var_off, rcur->var_off);
15622 /* two stack pointers are equal only if they're pointing to
15623 * the same stack frame, since fp-8 in foo != fp-8 in bar
15625 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15627 return regs_exact(rold, rcur, idmap);
15631 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15632 struct bpf_func_state *cur, struct bpf_idmap *idmap)
15636 /* walk slots of the explored stack and ignore any additional
15637 * slots in the current stack, since explored(safe) state
15640 for (i = 0; i < old->allocated_stack; i++) {
15641 struct bpf_reg_state *old_reg, *cur_reg;
15643 spi = i / BPF_REG_SIZE;
15645 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15646 i += BPF_REG_SIZE - 1;
15647 /* explored state didn't use this */
15651 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15654 if (env->allow_uninit_stack &&
15655 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15658 /* explored stack has more populated slots than current stack
15659 * and these slots were used
15661 if (i >= cur->allocated_stack)
15664 /* if old state was safe with misc data in the stack
15665 * it will be safe with zero-initialized stack.
15666 * The opposite is not true
15668 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15669 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15671 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15672 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15673 /* Ex: old explored (safe) state has STACK_SPILL in
15674 * this stack slot, but current has STACK_MISC ->
15675 * this verifier states are not equivalent,
15676 * return false to continue verification of this path
15679 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15681 /* Both old and cur are having same slot_type */
15682 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15684 /* when explored and current stack slot are both storing
15685 * spilled registers, check that stored pointers types
15686 * are the same as well.
15687 * Ex: explored safe path could have stored
15688 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15689 * but current path has stored:
15690 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15691 * such verifier states are not equivalent.
15692 * return false to continue verification of this path
15694 if (!regsafe(env, &old->stack[spi].spilled_ptr,
15695 &cur->stack[spi].spilled_ptr, idmap))
15699 old_reg = &old->stack[spi].spilled_ptr;
15700 cur_reg = &cur->stack[spi].spilled_ptr;
15701 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15702 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15703 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15707 old_reg = &old->stack[spi].spilled_ptr;
15708 cur_reg = &cur->stack[spi].spilled_ptr;
15709 /* iter.depth is not compared between states as it
15710 * doesn't matter for correctness and would otherwise
15711 * prevent convergence; we maintain it only to prevent
15712 * infinite loop check triggering, see
15713 * iter_active_depths_differ()
15715 if (old_reg->iter.btf != cur_reg->iter.btf ||
15716 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15717 old_reg->iter.state != cur_reg->iter.state ||
15718 /* ignore {old_reg,cur_reg}->iter.depth, see above */
15719 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15724 case STACK_INVALID:
15726 /* Ensure that new unhandled slot types return false by default */
15734 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15735 struct bpf_idmap *idmap)
15739 if (old->acquired_refs != cur->acquired_refs)
15742 for (i = 0; i < old->acquired_refs; i++) {
15743 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15750 /* compare two verifier states
15752 * all states stored in state_list are known to be valid, since
15753 * verifier reached 'bpf_exit' instruction through them
15755 * this function is called when verifier exploring different branches of
15756 * execution popped from the state stack. If it sees an old state that has
15757 * more strict register state and more strict stack state then this execution
15758 * branch doesn't need to be explored further, since verifier already
15759 * concluded that more strict state leads to valid finish.
15761 * Therefore two states are equivalent if register state is more conservative
15762 * and explored stack state is more conservative than the current one.
15765 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15766 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15768 * In other words if current stack state (one being explored) has more
15769 * valid slots than old one that already passed validation, it means
15770 * the verifier can stop exploring and conclude that current state is valid too
15772 * Similarly with registers. If explored state has register type as invalid
15773 * whereas register type in current state is meaningful, it means that
15774 * the current state will reach 'bpf_exit' instruction safely
15776 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15777 struct bpf_func_state *cur)
15781 for (i = 0; i < MAX_BPF_REG; i++)
15782 if (!regsafe(env, &old->regs[i], &cur->regs[i],
15783 &env->idmap_scratch))
15786 if (!stacksafe(env, old, cur, &env->idmap_scratch))
15789 if (!refsafe(old, cur, &env->idmap_scratch))
15795 static bool states_equal(struct bpf_verifier_env *env,
15796 struct bpf_verifier_state *old,
15797 struct bpf_verifier_state *cur)
15801 if (old->curframe != cur->curframe)
15804 env->idmap_scratch.tmp_id_gen = env->id_gen;
15805 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15807 /* Verification state from speculative execution simulation
15808 * must never prune a non-speculative execution one.
15810 if (old->speculative && !cur->speculative)
15813 if (old->active_lock.ptr != cur->active_lock.ptr)
15816 /* Old and cur active_lock's have to be either both present
15819 if (!!old->active_lock.id != !!cur->active_lock.id)
15822 if (old->active_lock.id &&
15823 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15826 if (old->active_rcu_lock != cur->active_rcu_lock)
15829 /* for states to be equal callsites have to be the same
15830 * and all frame states need to be equivalent
15832 for (i = 0; i <= old->curframe; i++) {
15833 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15835 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15841 /* Return 0 if no propagation happened. Return negative error code if error
15842 * happened. Otherwise, return the propagated bit.
15844 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15845 struct bpf_reg_state *reg,
15846 struct bpf_reg_state *parent_reg)
15848 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15849 u8 flag = reg->live & REG_LIVE_READ;
15852 /* When comes here, read flags of PARENT_REG or REG could be any of
15853 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15854 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15856 if (parent_flag == REG_LIVE_READ64 ||
15857 /* Or if there is no read flag from REG. */
15859 /* Or if the read flag from REG is the same as PARENT_REG. */
15860 parent_flag == flag)
15863 err = mark_reg_read(env, reg, parent_reg, flag);
15870 /* A write screens off any subsequent reads; but write marks come from the
15871 * straight-line code between a state and its parent. When we arrive at an
15872 * equivalent state (jump target or such) we didn't arrive by the straight-line
15873 * code, so read marks in the state must propagate to the parent regardless
15874 * of the state's write marks. That's what 'parent == state->parent' comparison
15875 * in mark_reg_read() is for.
15877 static int propagate_liveness(struct bpf_verifier_env *env,
15878 const struct bpf_verifier_state *vstate,
15879 struct bpf_verifier_state *vparent)
15881 struct bpf_reg_state *state_reg, *parent_reg;
15882 struct bpf_func_state *state, *parent;
15883 int i, frame, err = 0;
15885 if (vparent->curframe != vstate->curframe) {
15886 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15887 vparent->curframe, vstate->curframe);
15890 /* Propagate read liveness of registers... */
15891 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15892 for (frame = 0; frame <= vstate->curframe; frame++) {
15893 parent = vparent->frame[frame];
15894 state = vstate->frame[frame];
15895 parent_reg = parent->regs;
15896 state_reg = state->regs;
15897 /* We don't need to worry about FP liveness, it's read-only */
15898 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15899 err = propagate_liveness_reg(env, &state_reg[i],
15903 if (err == REG_LIVE_READ64)
15904 mark_insn_zext(env, &parent_reg[i]);
15907 /* Propagate stack slots. */
15908 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15909 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15910 parent_reg = &parent->stack[i].spilled_ptr;
15911 state_reg = &state->stack[i].spilled_ptr;
15912 err = propagate_liveness_reg(env, state_reg,
15921 /* find precise scalars in the previous equivalent state and
15922 * propagate them into the current state
15924 static int propagate_precision(struct bpf_verifier_env *env,
15925 const struct bpf_verifier_state *old)
15927 struct bpf_reg_state *state_reg;
15928 struct bpf_func_state *state;
15929 int i, err = 0, fr;
15932 for (fr = old->curframe; fr >= 0; fr--) {
15933 state = old->frame[fr];
15934 state_reg = state->regs;
15936 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15937 if (state_reg->type != SCALAR_VALUE ||
15938 !state_reg->precise ||
15939 !(state_reg->live & REG_LIVE_READ))
15941 if (env->log.level & BPF_LOG_LEVEL2) {
15943 verbose(env, "frame %d: propagating r%d", fr, i);
15945 verbose(env, ",r%d", i);
15947 bt_set_frame_reg(&env->bt, fr, i);
15951 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15952 if (!is_spilled_reg(&state->stack[i]))
15954 state_reg = &state->stack[i].spilled_ptr;
15955 if (state_reg->type != SCALAR_VALUE ||
15956 !state_reg->precise ||
15957 !(state_reg->live & REG_LIVE_READ))
15959 if (env->log.level & BPF_LOG_LEVEL2) {
15961 verbose(env, "frame %d: propagating fp%d",
15962 fr, (-i - 1) * BPF_REG_SIZE);
15964 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15966 bt_set_frame_slot(&env->bt, fr, i);
15970 verbose(env, "\n");
15973 err = mark_chain_precision_batch(env);
15980 static bool states_maybe_looping(struct bpf_verifier_state *old,
15981 struct bpf_verifier_state *cur)
15983 struct bpf_func_state *fold, *fcur;
15984 int i, fr = cur->curframe;
15986 if (old->curframe != fr)
15989 fold = old->frame[fr];
15990 fcur = cur->frame[fr];
15991 for (i = 0; i < MAX_BPF_REG; i++)
15992 if (memcmp(&fold->regs[i], &fcur->regs[i],
15993 offsetof(struct bpf_reg_state, parent)))
15998 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16000 return env->insn_aux_data[insn_idx].is_iter_next;
16003 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16004 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16005 * states to match, which otherwise would look like an infinite loop. So while
16006 * iter_next() calls are taken care of, we still need to be careful and
16007 * prevent erroneous and too eager declaration of "ininite loop", when
16008 * iterators are involved.
16010 * Here's a situation in pseudo-BPF assembly form:
16012 * 0: again: ; set up iter_next() call args
16013 * 1: r1 = &it ; <CHECKPOINT HERE>
16014 * 2: call bpf_iter_num_next ; this is iter_next() call
16015 * 3: if r0 == 0 goto done
16016 * 4: ... something useful here ...
16017 * 5: goto again ; another iteration
16020 * 8: call bpf_iter_num_destroy ; clean up iter state
16023 * This is a typical loop. Let's assume that we have a prune point at 1:,
16024 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16025 * again`, assuming other heuristics don't get in a way).
16027 * When we first time come to 1:, let's say we have some state X. We proceed
16028 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16029 * Now we come back to validate that forked ACTIVE state. We proceed through
16030 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16031 * are converging. But the problem is that we don't know that yet, as this
16032 * convergence has to happen at iter_next() call site only. So if nothing is
16033 * done, at 1: verifier will use bounded loop logic and declare infinite
16034 * looping (and would be *technically* correct, if not for iterator's
16035 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16036 * don't want that. So what we do in process_iter_next_call() when we go on
16037 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16038 * a different iteration. So when we suspect an infinite loop, we additionally
16039 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16040 * pretend we are not looping and wait for next iter_next() call.
16042 * This only applies to ACTIVE state. In DRAINED state we don't expect to
16043 * loop, because that would actually mean infinite loop, as DRAINED state is
16044 * "sticky", and so we'll keep returning into the same instruction with the
16045 * same state (at least in one of possible code paths).
16047 * This approach allows to keep infinite loop heuristic even in the face of
16048 * active iterator. E.g., C snippet below is and will be detected as
16049 * inifintely looping:
16051 * struct bpf_iter_num it;
16054 * bpf_iter_num_new(&it, 0, 10);
16055 * while ((p = bpf_iter_num_next(&t))) {
16057 * while (x--) {} // <<-- infinite loop here
16061 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16063 struct bpf_reg_state *slot, *cur_slot;
16064 struct bpf_func_state *state;
16067 for (fr = old->curframe; fr >= 0; fr--) {
16068 state = old->frame[fr];
16069 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16070 if (state->stack[i].slot_type[0] != STACK_ITER)
16073 slot = &state->stack[i].spilled_ptr;
16074 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16077 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16078 if (cur_slot->iter.depth != slot->iter.depth)
16085 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16087 struct bpf_verifier_state_list *new_sl;
16088 struct bpf_verifier_state_list *sl, **pprev;
16089 struct bpf_verifier_state *cur = env->cur_state, *new;
16090 int i, j, err, states_cnt = 0;
16091 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16092 bool add_new_state = force_new_state;
16094 /* bpf progs typically have pruning point every 4 instructions
16095 * http://vger.kernel.org/bpfconf2019.html#session-1
16096 * Do not add new state for future pruning if the verifier hasn't seen
16097 * at least 2 jumps and at least 8 instructions.
16098 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16099 * In tests that amounts to up to 50% reduction into total verifier
16100 * memory consumption and 20% verifier time speedup.
16102 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16103 env->insn_processed - env->prev_insn_processed >= 8)
16104 add_new_state = true;
16106 pprev = explored_state(env, insn_idx);
16109 clean_live_states(env, insn_idx, cur);
16113 if (sl->state.insn_idx != insn_idx)
16116 if (sl->state.branches) {
16117 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16119 if (frame->in_async_callback_fn &&
16120 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16121 /* Different async_entry_cnt means that the verifier is
16122 * processing another entry into async callback.
16123 * Seeing the same state is not an indication of infinite
16124 * loop or infinite recursion.
16125 * But finding the same state doesn't mean that it's safe
16126 * to stop processing the current state. The previous state
16127 * hasn't yet reached bpf_exit, since state.branches > 0.
16128 * Checking in_async_callback_fn alone is not enough either.
16129 * Since the verifier still needs to catch infinite loops
16130 * inside async callbacks.
16132 goto skip_inf_loop_check;
16134 /* BPF open-coded iterators loop detection is special.
16135 * states_maybe_looping() logic is too simplistic in detecting
16136 * states that *might* be equivalent, because it doesn't know
16137 * about ID remapping, so don't even perform it.
16138 * See process_iter_next_call() and iter_active_depths_differ()
16139 * for overview of the logic. When current and one of parent
16140 * states are detected as equivalent, it's a good thing: we prove
16141 * convergence and can stop simulating further iterations.
16142 * It's safe to assume that iterator loop will finish, taking into
16143 * account iter_next() contract of eventually returning
16144 * sticky NULL result.
16146 if (is_iter_next_insn(env, insn_idx)) {
16147 if (states_equal(env, &sl->state, cur)) {
16148 struct bpf_func_state *cur_frame;
16149 struct bpf_reg_state *iter_state, *iter_reg;
16152 cur_frame = cur->frame[cur->curframe];
16153 /* btf_check_iter_kfuncs() enforces that
16154 * iter state pointer is always the first arg
16156 iter_reg = &cur_frame->regs[BPF_REG_1];
16157 /* current state is valid due to states_equal(),
16158 * so we can assume valid iter and reg state,
16159 * no need for extra (re-)validations
16161 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16162 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16163 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
16166 goto skip_inf_loop_check;
16168 /* attempt to detect infinite loop to avoid unnecessary doomed work */
16169 if (states_maybe_looping(&sl->state, cur) &&
16170 states_equal(env, &sl->state, cur) &&
16171 !iter_active_depths_differ(&sl->state, cur)) {
16172 verbose_linfo(env, insn_idx, "; ");
16173 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16176 /* if the verifier is processing a loop, avoid adding new state
16177 * too often, since different loop iterations have distinct
16178 * states and may not help future pruning.
16179 * This threshold shouldn't be too low to make sure that
16180 * a loop with large bound will be rejected quickly.
16181 * The most abusive loop will be:
16183 * if r1 < 1000000 goto pc-2
16184 * 1M insn_procssed limit / 100 == 10k peak states.
16185 * This threshold shouldn't be too high either, since states
16186 * at the end of the loop are likely to be useful in pruning.
16188 skip_inf_loop_check:
16189 if (!force_new_state &&
16190 env->jmps_processed - env->prev_jmps_processed < 20 &&
16191 env->insn_processed - env->prev_insn_processed < 100)
16192 add_new_state = false;
16195 if (states_equal(env, &sl->state, cur)) {
16198 /* reached equivalent register/stack state,
16199 * prune the search.
16200 * Registers read by the continuation are read by us.
16201 * If we have any write marks in env->cur_state, they
16202 * will prevent corresponding reads in the continuation
16203 * from reaching our parent (an explored_state). Our
16204 * own state will get the read marks recorded, but
16205 * they'll be immediately forgotten as we're pruning
16206 * this state and will pop a new one.
16208 err = propagate_liveness(env, &sl->state, cur);
16210 /* if previous state reached the exit with precision and
16211 * current state is equivalent to it (except precsion marks)
16212 * the precision needs to be propagated back in
16213 * the current state.
16215 err = err ? : push_jmp_history(env, cur);
16216 err = err ? : propagate_precision(env, &sl->state);
16222 /* when new state is not going to be added do not increase miss count.
16223 * Otherwise several loop iterations will remove the state
16224 * recorded earlier. The goal of these heuristics is to have
16225 * states from some iterations of the loop (some in the beginning
16226 * and some at the end) to help pruning.
16230 /* heuristic to determine whether this state is beneficial
16231 * to keep checking from state equivalence point of view.
16232 * Higher numbers increase max_states_per_insn and verification time,
16233 * but do not meaningfully decrease insn_processed.
16235 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16236 /* the state is unlikely to be useful. Remove it to
16237 * speed up verification
16240 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16241 u32 br = sl->state.branches;
16244 "BUG live_done but branches_to_explore %d\n",
16246 free_verifier_state(&sl->state, false);
16248 env->peak_states--;
16250 /* cannot free this state, since parentage chain may
16251 * walk it later. Add it for free_list instead to
16252 * be freed at the end of verification
16254 sl->next = env->free_list;
16255 env->free_list = sl;
16265 if (env->max_states_per_insn < states_cnt)
16266 env->max_states_per_insn = states_cnt;
16268 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16271 if (!add_new_state)
16274 /* There were no equivalent states, remember the current one.
16275 * Technically the current state is not proven to be safe yet,
16276 * but it will either reach outer most bpf_exit (which means it's safe)
16277 * or it will be rejected. When there are no loops the verifier won't be
16278 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16279 * again on the way to bpf_exit.
16280 * When looping the sl->state.branches will be > 0 and this state
16281 * will not be considered for equivalence until branches == 0.
16283 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16286 env->total_states++;
16287 env->peak_states++;
16288 env->prev_jmps_processed = env->jmps_processed;
16289 env->prev_insn_processed = env->insn_processed;
16291 /* forget precise markings we inherited, see __mark_chain_precision */
16292 if (env->bpf_capable)
16293 mark_all_scalars_imprecise(env, cur);
16295 /* add new state to the head of linked list */
16296 new = &new_sl->state;
16297 err = copy_verifier_state(new, cur);
16299 free_verifier_state(new, false);
16303 new->insn_idx = insn_idx;
16304 WARN_ONCE(new->branches != 1,
16305 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16308 cur->first_insn_idx = insn_idx;
16309 clear_jmp_history(cur);
16310 new_sl->next = *explored_state(env, insn_idx);
16311 *explored_state(env, insn_idx) = new_sl;
16312 /* connect new state to parentage chain. Current frame needs all
16313 * registers connected. Only r6 - r9 of the callers are alive (pushed
16314 * to the stack implicitly by JITs) so in callers' frames connect just
16315 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16316 * the state of the call instruction (with WRITTEN set), and r0 comes
16317 * from callee with its full parentage chain, anyway.
16319 /* clear write marks in current state: the writes we did are not writes
16320 * our child did, so they don't screen off its reads from us.
16321 * (There are no read marks in current state, because reads always mark
16322 * their parent and current state never has children yet. Only
16323 * explored_states can get read marks.)
16325 for (j = 0; j <= cur->curframe; j++) {
16326 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16327 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16328 for (i = 0; i < BPF_REG_FP; i++)
16329 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16332 /* all stack frames are accessible from callee, clear them all */
16333 for (j = 0; j <= cur->curframe; j++) {
16334 struct bpf_func_state *frame = cur->frame[j];
16335 struct bpf_func_state *newframe = new->frame[j];
16337 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16338 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16339 frame->stack[i].spilled_ptr.parent =
16340 &newframe->stack[i].spilled_ptr;
16346 /* Return true if it's OK to have the same insn return a different type. */
16347 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16349 switch (base_type(type)) {
16351 case PTR_TO_SOCKET:
16352 case PTR_TO_SOCK_COMMON:
16353 case PTR_TO_TCP_SOCK:
16354 case PTR_TO_XDP_SOCK:
16355 case PTR_TO_BTF_ID:
16362 /* If an instruction was previously used with particular pointer types, then we
16363 * need to be careful to avoid cases such as the below, where it may be ok
16364 * for one branch accessing the pointer, but not ok for the other branch:
16369 * R1 = some_other_valid_ptr;
16372 * R2 = *(u32 *)(R1 + 0);
16374 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16376 return src != prev && (!reg_type_mismatch_ok(src) ||
16377 !reg_type_mismatch_ok(prev));
16380 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16381 bool allow_trust_missmatch)
16383 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16385 if (*prev_type == NOT_INIT) {
16386 /* Saw a valid insn
16387 * dst_reg = *(u32 *)(src_reg + off)
16388 * save type to validate intersecting paths
16391 } else if (reg_type_mismatch(type, *prev_type)) {
16392 /* Abuser program is trying to use the same insn
16393 * dst_reg = *(u32*) (src_reg + off)
16394 * with different pointer types:
16395 * src_reg == ctx in one branch and
16396 * src_reg == stack|map in some other branch.
16399 if (allow_trust_missmatch &&
16400 base_type(type) == PTR_TO_BTF_ID &&
16401 base_type(*prev_type) == PTR_TO_BTF_ID) {
16403 * Have to support a use case when one path through
16404 * the program yields TRUSTED pointer while another
16405 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16406 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16408 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16410 verbose(env, "same insn cannot be used with different pointers\n");
16418 static int do_check(struct bpf_verifier_env *env)
16420 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16421 struct bpf_verifier_state *state = env->cur_state;
16422 struct bpf_insn *insns = env->prog->insnsi;
16423 struct bpf_reg_state *regs;
16424 int insn_cnt = env->prog->len;
16425 bool do_print_state = false;
16426 int prev_insn_idx = -1;
16429 struct bpf_insn *insn;
16433 env->prev_insn_idx = prev_insn_idx;
16434 if (env->insn_idx >= insn_cnt) {
16435 verbose(env, "invalid insn idx %d insn_cnt %d\n",
16436 env->insn_idx, insn_cnt);
16440 insn = &insns[env->insn_idx];
16441 class = BPF_CLASS(insn->code);
16443 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16445 "BPF program is too large. Processed %d insn\n",
16446 env->insn_processed);
16450 state->last_insn_idx = env->prev_insn_idx;
16452 if (is_prune_point(env, env->insn_idx)) {
16453 err = is_state_visited(env, env->insn_idx);
16457 /* found equivalent state, can prune the search */
16458 if (env->log.level & BPF_LOG_LEVEL) {
16459 if (do_print_state)
16460 verbose(env, "\nfrom %d to %d%s: safe\n",
16461 env->prev_insn_idx, env->insn_idx,
16462 env->cur_state->speculative ?
16463 " (speculative execution)" : "");
16465 verbose(env, "%d: safe\n", env->insn_idx);
16467 goto process_bpf_exit;
16471 if (is_jmp_point(env, env->insn_idx)) {
16472 err = push_jmp_history(env, state);
16477 if (signal_pending(current))
16480 if (need_resched())
16483 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16484 verbose(env, "\nfrom %d to %d%s:",
16485 env->prev_insn_idx, env->insn_idx,
16486 env->cur_state->speculative ?
16487 " (speculative execution)" : "");
16488 print_verifier_state(env, state->frame[state->curframe], true);
16489 do_print_state = false;
16492 if (env->log.level & BPF_LOG_LEVEL) {
16493 const struct bpf_insn_cbs cbs = {
16494 .cb_call = disasm_kfunc_name,
16495 .cb_print = verbose,
16496 .private_data = env,
16499 if (verifier_state_scratched(env))
16500 print_insn_state(env, state->frame[state->curframe]);
16502 verbose_linfo(env, env->insn_idx, "; ");
16503 env->prev_log_pos = env->log.end_pos;
16504 verbose(env, "%d: ", env->insn_idx);
16505 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16506 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16507 env->prev_log_pos = env->log.end_pos;
16510 if (bpf_prog_is_offloaded(env->prog->aux)) {
16511 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16512 env->prev_insn_idx);
16517 regs = cur_regs(env);
16518 sanitize_mark_insn_seen(env);
16519 prev_insn_idx = env->insn_idx;
16521 if (class == BPF_ALU || class == BPF_ALU64) {
16522 err = check_alu_op(env, insn);
16526 } else if (class == BPF_LDX) {
16527 enum bpf_reg_type src_reg_type;
16529 /* check for reserved fields is already done */
16531 /* check src operand */
16532 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16536 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16540 src_reg_type = regs[insn->src_reg].type;
16542 /* check that memory (src_reg + off) is readable,
16543 * the state of dst_reg will be updated by this func
16545 err = check_mem_access(env, env->insn_idx, insn->src_reg,
16546 insn->off, BPF_SIZE(insn->code),
16547 BPF_READ, insn->dst_reg, false,
16548 BPF_MODE(insn->code) == BPF_MEMSX);
16552 err = save_aux_ptr_type(env, src_reg_type, true);
16555 } else if (class == BPF_STX) {
16556 enum bpf_reg_type dst_reg_type;
16558 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16559 err = check_atomic(env, env->insn_idx, insn);
16566 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16567 verbose(env, "BPF_STX uses reserved fields\n");
16571 /* check src1 operand */
16572 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16575 /* check src2 operand */
16576 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16580 dst_reg_type = regs[insn->dst_reg].type;
16582 /* check that memory (dst_reg + off) is writeable */
16583 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16584 insn->off, BPF_SIZE(insn->code),
16585 BPF_WRITE, insn->src_reg, false, false);
16589 err = save_aux_ptr_type(env, dst_reg_type, false);
16592 } else if (class == BPF_ST) {
16593 enum bpf_reg_type dst_reg_type;
16595 if (BPF_MODE(insn->code) != BPF_MEM ||
16596 insn->src_reg != BPF_REG_0) {
16597 verbose(env, "BPF_ST uses reserved fields\n");
16600 /* check src operand */
16601 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16605 dst_reg_type = regs[insn->dst_reg].type;
16607 /* check that memory (dst_reg + off) is writeable */
16608 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16609 insn->off, BPF_SIZE(insn->code),
16610 BPF_WRITE, -1, false, false);
16614 err = save_aux_ptr_type(env, dst_reg_type, false);
16617 } else if (class == BPF_JMP || class == BPF_JMP32) {
16618 u8 opcode = BPF_OP(insn->code);
16620 env->jmps_processed++;
16621 if (opcode == BPF_CALL) {
16622 if (BPF_SRC(insn->code) != BPF_K ||
16623 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16624 && insn->off != 0) ||
16625 (insn->src_reg != BPF_REG_0 &&
16626 insn->src_reg != BPF_PSEUDO_CALL &&
16627 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16628 insn->dst_reg != BPF_REG_0 ||
16629 class == BPF_JMP32) {
16630 verbose(env, "BPF_CALL uses reserved fields\n");
16634 if (env->cur_state->active_lock.ptr) {
16635 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16636 (insn->src_reg == BPF_PSEUDO_CALL) ||
16637 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16638 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16639 verbose(env, "function calls are not allowed while holding a lock\n");
16643 if (insn->src_reg == BPF_PSEUDO_CALL)
16644 err = check_func_call(env, insn, &env->insn_idx);
16645 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16646 err = check_kfunc_call(env, insn, &env->insn_idx);
16648 err = check_helper_call(env, insn, &env->insn_idx);
16652 mark_reg_scratched(env, BPF_REG_0);
16653 } else if (opcode == BPF_JA) {
16654 if (BPF_SRC(insn->code) != BPF_K ||
16655 insn->src_reg != BPF_REG_0 ||
16656 insn->dst_reg != BPF_REG_0 ||
16657 (class == BPF_JMP && insn->imm != 0) ||
16658 (class == BPF_JMP32 && insn->off != 0)) {
16659 verbose(env, "BPF_JA uses reserved fields\n");
16663 if (class == BPF_JMP)
16664 env->insn_idx += insn->off + 1;
16666 env->insn_idx += insn->imm + 1;
16669 } else if (opcode == BPF_EXIT) {
16670 if (BPF_SRC(insn->code) != BPF_K ||
16672 insn->src_reg != BPF_REG_0 ||
16673 insn->dst_reg != BPF_REG_0 ||
16674 class == BPF_JMP32) {
16675 verbose(env, "BPF_EXIT uses reserved fields\n");
16679 if (env->cur_state->active_lock.ptr &&
16680 !in_rbtree_lock_required_cb(env)) {
16681 verbose(env, "bpf_spin_unlock is missing\n");
16685 if (env->cur_state->active_rcu_lock) {
16686 verbose(env, "bpf_rcu_read_unlock is missing\n");
16690 /* We must do check_reference_leak here before
16691 * prepare_func_exit to handle the case when
16692 * state->curframe > 0, it may be a callback
16693 * function, for which reference_state must
16694 * match caller reference state when it exits.
16696 err = check_reference_leak(env);
16700 if (state->curframe) {
16701 /* exit from nested function */
16702 err = prepare_func_exit(env, &env->insn_idx);
16705 do_print_state = true;
16709 err = check_return_code(env);
16713 mark_verifier_state_scratched(env);
16714 update_branch_counts(env, env->cur_state);
16715 err = pop_stack(env, &prev_insn_idx,
16716 &env->insn_idx, pop_log);
16718 if (err != -ENOENT)
16722 do_print_state = true;
16726 err = check_cond_jmp_op(env, insn, &env->insn_idx);
16730 } else if (class == BPF_LD) {
16731 u8 mode = BPF_MODE(insn->code);
16733 if (mode == BPF_ABS || mode == BPF_IND) {
16734 err = check_ld_abs(env, insn);
16738 } else if (mode == BPF_IMM) {
16739 err = check_ld_imm(env, insn);
16744 sanitize_mark_insn_seen(env);
16746 verbose(env, "invalid BPF_LD mode\n");
16750 verbose(env, "unknown insn class %d\n", class);
16760 static int find_btf_percpu_datasec(struct btf *btf)
16762 const struct btf_type *t;
16767 * Both vmlinux and module each have their own ".data..percpu"
16768 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16769 * types to look at only module's own BTF types.
16771 n = btf_nr_types(btf);
16772 if (btf_is_module(btf))
16773 i = btf_nr_types(btf_vmlinux);
16777 for(; i < n; i++) {
16778 t = btf_type_by_id(btf, i);
16779 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16782 tname = btf_name_by_offset(btf, t->name_off);
16783 if (!strcmp(tname, ".data..percpu"))
16790 /* replace pseudo btf_id with kernel symbol address */
16791 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16792 struct bpf_insn *insn,
16793 struct bpf_insn_aux_data *aux)
16795 const struct btf_var_secinfo *vsi;
16796 const struct btf_type *datasec;
16797 struct btf_mod_pair *btf_mod;
16798 const struct btf_type *t;
16799 const char *sym_name;
16800 bool percpu = false;
16801 u32 type, id = insn->imm;
16805 int i, btf_fd, err;
16807 btf_fd = insn[1].imm;
16809 btf = btf_get_by_fd(btf_fd);
16811 verbose(env, "invalid module BTF object FD specified.\n");
16815 if (!btf_vmlinux) {
16816 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16823 t = btf_type_by_id(btf, id);
16825 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16830 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16831 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16836 sym_name = btf_name_by_offset(btf, t->name_off);
16837 addr = kallsyms_lookup_name(sym_name);
16839 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16844 insn[0].imm = (u32)addr;
16845 insn[1].imm = addr >> 32;
16847 if (btf_type_is_func(t)) {
16848 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16849 aux->btf_var.mem_size = 0;
16853 datasec_id = find_btf_percpu_datasec(btf);
16854 if (datasec_id > 0) {
16855 datasec = btf_type_by_id(btf, datasec_id);
16856 for_each_vsi(i, datasec, vsi) {
16857 if (vsi->type == id) {
16865 t = btf_type_skip_modifiers(btf, type, NULL);
16867 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16868 aux->btf_var.btf = btf;
16869 aux->btf_var.btf_id = type;
16870 } else if (!btf_type_is_struct(t)) {
16871 const struct btf_type *ret;
16875 /* resolve the type size of ksym. */
16876 ret = btf_resolve_size(btf, t, &tsize);
16878 tname = btf_name_by_offset(btf, t->name_off);
16879 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16880 tname, PTR_ERR(ret));
16884 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16885 aux->btf_var.mem_size = tsize;
16887 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16888 aux->btf_var.btf = btf;
16889 aux->btf_var.btf_id = type;
16892 /* check whether we recorded this BTF (and maybe module) already */
16893 for (i = 0; i < env->used_btf_cnt; i++) {
16894 if (env->used_btfs[i].btf == btf) {
16900 if (env->used_btf_cnt >= MAX_USED_BTFS) {
16905 btf_mod = &env->used_btfs[env->used_btf_cnt];
16906 btf_mod->btf = btf;
16907 btf_mod->module = NULL;
16909 /* if we reference variables from kernel module, bump its refcount */
16910 if (btf_is_module(btf)) {
16911 btf_mod->module = btf_try_get_module(btf);
16912 if (!btf_mod->module) {
16918 env->used_btf_cnt++;
16926 static bool is_tracing_prog_type(enum bpf_prog_type type)
16929 case BPF_PROG_TYPE_KPROBE:
16930 case BPF_PROG_TYPE_TRACEPOINT:
16931 case BPF_PROG_TYPE_PERF_EVENT:
16932 case BPF_PROG_TYPE_RAW_TRACEPOINT:
16933 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16940 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16941 struct bpf_map *map,
16942 struct bpf_prog *prog)
16945 enum bpf_prog_type prog_type = resolve_prog_type(prog);
16947 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16948 btf_record_has_field(map->record, BPF_RB_ROOT)) {
16949 if (is_tracing_prog_type(prog_type)) {
16950 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16955 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16956 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16957 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16961 if (is_tracing_prog_type(prog_type)) {
16962 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16966 if (prog->aux->sleepable) {
16967 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16972 if (btf_record_has_field(map->record, BPF_TIMER)) {
16973 if (is_tracing_prog_type(prog_type)) {
16974 verbose(env, "tracing progs cannot use bpf_timer yet\n");
16979 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16980 !bpf_offload_prog_map_match(prog, map)) {
16981 verbose(env, "offload device mismatch between prog and map\n");
16985 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16986 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16990 if (prog->aux->sleepable)
16991 switch (map->map_type) {
16992 case BPF_MAP_TYPE_HASH:
16993 case BPF_MAP_TYPE_LRU_HASH:
16994 case BPF_MAP_TYPE_ARRAY:
16995 case BPF_MAP_TYPE_PERCPU_HASH:
16996 case BPF_MAP_TYPE_PERCPU_ARRAY:
16997 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16998 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16999 case BPF_MAP_TYPE_HASH_OF_MAPS:
17000 case BPF_MAP_TYPE_RINGBUF:
17001 case BPF_MAP_TYPE_USER_RINGBUF:
17002 case BPF_MAP_TYPE_INODE_STORAGE:
17003 case BPF_MAP_TYPE_SK_STORAGE:
17004 case BPF_MAP_TYPE_TASK_STORAGE:
17005 case BPF_MAP_TYPE_CGRP_STORAGE:
17009 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17016 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17018 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17019 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17022 /* find and rewrite pseudo imm in ld_imm64 instructions:
17024 * 1. if it accesses map FD, replace it with actual map pointer.
17025 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17027 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17029 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17031 struct bpf_insn *insn = env->prog->insnsi;
17032 int insn_cnt = env->prog->len;
17035 err = bpf_prog_calc_tag(env->prog);
17039 for (i = 0; i < insn_cnt; i++, insn++) {
17040 if (BPF_CLASS(insn->code) == BPF_LDX &&
17041 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17043 verbose(env, "BPF_LDX uses reserved fields\n");
17047 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17048 struct bpf_insn_aux_data *aux;
17049 struct bpf_map *map;
17054 if (i == insn_cnt - 1 || insn[1].code != 0 ||
17055 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17056 insn[1].off != 0) {
17057 verbose(env, "invalid bpf_ld_imm64 insn\n");
17061 if (insn[0].src_reg == 0)
17062 /* valid generic load 64-bit imm */
17065 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17066 aux = &env->insn_aux_data[i];
17067 err = check_pseudo_btf_id(env, insn, aux);
17073 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17074 aux = &env->insn_aux_data[i];
17075 aux->ptr_type = PTR_TO_FUNC;
17079 /* In final convert_pseudo_ld_imm64() step, this is
17080 * converted into regular 64-bit imm load insn.
17082 switch (insn[0].src_reg) {
17083 case BPF_PSEUDO_MAP_VALUE:
17084 case BPF_PSEUDO_MAP_IDX_VALUE:
17086 case BPF_PSEUDO_MAP_FD:
17087 case BPF_PSEUDO_MAP_IDX:
17088 if (insn[1].imm == 0)
17092 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17096 switch (insn[0].src_reg) {
17097 case BPF_PSEUDO_MAP_IDX_VALUE:
17098 case BPF_PSEUDO_MAP_IDX:
17099 if (bpfptr_is_null(env->fd_array)) {
17100 verbose(env, "fd_idx without fd_array is invalid\n");
17103 if (copy_from_bpfptr_offset(&fd, env->fd_array,
17104 insn[0].imm * sizeof(fd),
17114 map = __bpf_map_get(f);
17116 verbose(env, "fd %d is not pointing to valid bpf_map\n",
17118 return PTR_ERR(map);
17121 err = check_map_prog_compatibility(env, map, env->prog);
17127 aux = &env->insn_aux_data[i];
17128 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17129 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17130 addr = (unsigned long)map;
17132 u32 off = insn[1].imm;
17134 if (off >= BPF_MAX_VAR_OFF) {
17135 verbose(env, "direct value offset of %u is not allowed\n", off);
17140 if (!map->ops->map_direct_value_addr) {
17141 verbose(env, "no direct value access support for this map type\n");
17146 err = map->ops->map_direct_value_addr(map, &addr, off);
17148 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17149 map->value_size, off);
17154 aux->map_off = off;
17158 insn[0].imm = (u32)addr;
17159 insn[1].imm = addr >> 32;
17161 /* check whether we recorded this map already */
17162 for (j = 0; j < env->used_map_cnt; j++) {
17163 if (env->used_maps[j] == map) {
17164 aux->map_index = j;
17170 if (env->used_map_cnt >= MAX_USED_MAPS) {
17175 /* hold the map. If the program is rejected by verifier,
17176 * the map will be released by release_maps() or it
17177 * will be used by the valid program until it's unloaded
17178 * and all maps are released in free_used_maps()
17182 aux->map_index = env->used_map_cnt;
17183 env->used_maps[env->used_map_cnt++] = map;
17185 if (bpf_map_is_cgroup_storage(map) &&
17186 bpf_cgroup_storage_assign(env->prog->aux, map)) {
17187 verbose(env, "only one cgroup storage of each type is allowed\n");
17199 /* Basic sanity check before we invest more work here. */
17200 if (!bpf_opcode_in_insntable(insn->code)) {
17201 verbose(env, "unknown opcode %02x\n", insn->code);
17206 /* now all pseudo BPF_LD_IMM64 instructions load valid
17207 * 'struct bpf_map *' into a register instead of user map_fd.
17208 * These pointers will be used later by verifier to validate map access.
17213 /* drop refcnt of maps used by the rejected program */
17214 static void release_maps(struct bpf_verifier_env *env)
17216 __bpf_free_used_maps(env->prog->aux, env->used_maps,
17217 env->used_map_cnt);
17220 /* drop refcnt of maps used by the rejected program */
17221 static void release_btfs(struct bpf_verifier_env *env)
17223 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17224 env->used_btf_cnt);
17227 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17228 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17230 struct bpf_insn *insn = env->prog->insnsi;
17231 int insn_cnt = env->prog->len;
17234 for (i = 0; i < insn_cnt; i++, insn++) {
17235 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17237 if (insn->src_reg == BPF_PSEUDO_FUNC)
17243 /* single env->prog->insni[off] instruction was replaced with the range
17244 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
17245 * [0, off) and [off, end) to new locations, so the patched range stays zero
17247 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17248 struct bpf_insn_aux_data *new_data,
17249 struct bpf_prog *new_prog, u32 off, u32 cnt)
17251 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17252 struct bpf_insn *insn = new_prog->insnsi;
17253 u32 old_seen = old_data[off].seen;
17257 /* aux info at OFF always needs adjustment, no matter fast path
17258 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17259 * original insn at old prog.
17261 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17265 prog_len = new_prog->len;
17267 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17268 memcpy(new_data + off + cnt - 1, old_data + off,
17269 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17270 for (i = off; i < off + cnt - 1; i++) {
17271 /* Expand insni[off]'s seen count to the patched range. */
17272 new_data[i].seen = old_seen;
17273 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17275 env->insn_aux_data = new_data;
17279 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17285 /* NOTE: fake 'exit' subprog should be updated as well. */
17286 for (i = 0; i <= env->subprog_cnt; i++) {
17287 if (env->subprog_info[i].start <= off)
17289 env->subprog_info[i].start += len - 1;
17293 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17295 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17296 int i, sz = prog->aux->size_poke_tab;
17297 struct bpf_jit_poke_descriptor *desc;
17299 for (i = 0; i < sz; i++) {
17301 if (desc->insn_idx <= off)
17303 desc->insn_idx += len - 1;
17307 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17308 const struct bpf_insn *patch, u32 len)
17310 struct bpf_prog *new_prog;
17311 struct bpf_insn_aux_data *new_data = NULL;
17314 new_data = vzalloc(array_size(env->prog->len + len - 1,
17315 sizeof(struct bpf_insn_aux_data)));
17320 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17321 if (IS_ERR(new_prog)) {
17322 if (PTR_ERR(new_prog) == -ERANGE)
17324 "insn %d cannot be patched due to 16-bit range\n",
17325 env->insn_aux_data[off].orig_idx);
17329 adjust_insn_aux_data(env, new_data, new_prog, off, len);
17330 adjust_subprog_starts(env, off, len);
17331 adjust_poke_descs(new_prog, off, len);
17335 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17340 /* find first prog starting at or after off (first to remove) */
17341 for (i = 0; i < env->subprog_cnt; i++)
17342 if (env->subprog_info[i].start >= off)
17344 /* find first prog starting at or after off + cnt (first to stay) */
17345 for (j = i; j < env->subprog_cnt; j++)
17346 if (env->subprog_info[j].start >= off + cnt)
17348 /* if j doesn't start exactly at off + cnt, we are just removing
17349 * the front of previous prog
17351 if (env->subprog_info[j].start != off + cnt)
17355 struct bpf_prog_aux *aux = env->prog->aux;
17358 /* move fake 'exit' subprog as well */
17359 move = env->subprog_cnt + 1 - j;
17361 memmove(env->subprog_info + i,
17362 env->subprog_info + j,
17363 sizeof(*env->subprog_info) * move);
17364 env->subprog_cnt -= j - i;
17366 /* remove func_info */
17367 if (aux->func_info) {
17368 move = aux->func_info_cnt - j;
17370 memmove(aux->func_info + i,
17371 aux->func_info + j,
17372 sizeof(*aux->func_info) * move);
17373 aux->func_info_cnt -= j - i;
17374 /* func_info->insn_off is set after all code rewrites,
17375 * in adjust_btf_func() - no need to adjust
17379 /* convert i from "first prog to remove" to "first to adjust" */
17380 if (env->subprog_info[i].start == off)
17384 /* update fake 'exit' subprog as well */
17385 for (; i <= env->subprog_cnt; i++)
17386 env->subprog_info[i].start -= cnt;
17391 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17394 struct bpf_prog *prog = env->prog;
17395 u32 i, l_off, l_cnt, nr_linfo;
17396 struct bpf_line_info *linfo;
17398 nr_linfo = prog->aux->nr_linfo;
17402 linfo = prog->aux->linfo;
17404 /* find first line info to remove, count lines to be removed */
17405 for (i = 0; i < nr_linfo; i++)
17406 if (linfo[i].insn_off >= off)
17411 for (; i < nr_linfo; i++)
17412 if (linfo[i].insn_off < off + cnt)
17417 /* First live insn doesn't match first live linfo, it needs to "inherit"
17418 * last removed linfo. prog is already modified, so prog->len == off
17419 * means no live instructions after (tail of the program was removed).
17421 if (prog->len != off && l_cnt &&
17422 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17424 linfo[--i].insn_off = off + cnt;
17427 /* remove the line info which refer to the removed instructions */
17429 memmove(linfo + l_off, linfo + i,
17430 sizeof(*linfo) * (nr_linfo - i));
17432 prog->aux->nr_linfo -= l_cnt;
17433 nr_linfo = prog->aux->nr_linfo;
17436 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17437 for (i = l_off; i < nr_linfo; i++)
17438 linfo[i].insn_off -= cnt;
17440 /* fix up all subprogs (incl. 'exit') which start >= off */
17441 for (i = 0; i <= env->subprog_cnt; i++)
17442 if (env->subprog_info[i].linfo_idx > l_off) {
17443 /* program may have started in the removed region but
17444 * may not be fully removed
17446 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17447 env->subprog_info[i].linfo_idx -= l_cnt;
17449 env->subprog_info[i].linfo_idx = l_off;
17455 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17457 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17458 unsigned int orig_prog_len = env->prog->len;
17461 if (bpf_prog_is_offloaded(env->prog->aux))
17462 bpf_prog_offload_remove_insns(env, off, cnt);
17464 err = bpf_remove_insns(env->prog, off, cnt);
17468 err = adjust_subprog_starts_after_remove(env, off, cnt);
17472 err = bpf_adj_linfo_after_remove(env, off, cnt);
17476 memmove(aux_data + off, aux_data + off + cnt,
17477 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17482 /* The verifier does more data flow analysis than llvm and will not
17483 * explore branches that are dead at run time. Malicious programs can
17484 * have dead code too. Therefore replace all dead at-run-time code
17487 * Just nops are not optimal, e.g. if they would sit at the end of the
17488 * program and through another bug we would manage to jump there, then
17489 * we'd execute beyond program memory otherwise. Returning exception
17490 * code also wouldn't work since we can have subprogs where the dead
17491 * code could be located.
17493 static void sanitize_dead_code(struct bpf_verifier_env *env)
17495 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17496 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17497 struct bpf_insn *insn = env->prog->insnsi;
17498 const int insn_cnt = env->prog->len;
17501 for (i = 0; i < insn_cnt; i++) {
17502 if (aux_data[i].seen)
17504 memcpy(insn + i, &trap, sizeof(trap));
17505 aux_data[i].zext_dst = false;
17509 static bool insn_is_cond_jump(u8 code)
17514 if (BPF_CLASS(code) == BPF_JMP32)
17515 return op != BPF_JA;
17517 if (BPF_CLASS(code) != BPF_JMP)
17520 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17523 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17525 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17526 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17527 struct bpf_insn *insn = env->prog->insnsi;
17528 const int insn_cnt = env->prog->len;
17531 for (i = 0; i < insn_cnt; i++, insn++) {
17532 if (!insn_is_cond_jump(insn->code))
17535 if (!aux_data[i + 1].seen)
17536 ja.off = insn->off;
17537 else if (!aux_data[i + 1 + insn->off].seen)
17542 if (bpf_prog_is_offloaded(env->prog->aux))
17543 bpf_prog_offload_replace_insn(env, i, &ja);
17545 memcpy(insn, &ja, sizeof(ja));
17549 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17551 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17552 int insn_cnt = env->prog->len;
17555 for (i = 0; i < insn_cnt; i++) {
17559 while (i + j < insn_cnt && !aux_data[i + j].seen)
17564 err = verifier_remove_insns(env, i, j);
17567 insn_cnt = env->prog->len;
17573 static int opt_remove_nops(struct bpf_verifier_env *env)
17575 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17576 struct bpf_insn *insn = env->prog->insnsi;
17577 int insn_cnt = env->prog->len;
17580 for (i = 0; i < insn_cnt; i++) {
17581 if (memcmp(&insn[i], &ja, sizeof(ja)))
17584 err = verifier_remove_insns(env, i, 1);
17594 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17595 const union bpf_attr *attr)
17597 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17598 struct bpf_insn_aux_data *aux = env->insn_aux_data;
17599 int i, patch_len, delta = 0, len = env->prog->len;
17600 struct bpf_insn *insns = env->prog->insnsi;
17601 struct bpf_prog *new_prog;
17604 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17605 zext_patch[1] = BPF_ZEXT_REG(0);
17606 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17607 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17608 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17609 for (i = 0; i < len; i++) {
17610 int adj_idx = i + delta;
17611 struct bpf_insn insn;
17614 insn = insns[adj_idx];
17615 load_reg = insn_def_regno(&insn);
17616 if (!aux[adj_idx].zext_dst) {
17624 class = BPF_CLASS(code);
17625 if (load_reg == -1)
17628 /* NOTE: arg "reg" (the fourth one) is only used for
17629 * BPF_STX + SRC_OP, so it is safe to pass NULL
17632 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17633 if (class == BPF_LD &&
17634 BPF_MODE(code) == BPF_IMM)
17639 /* ctx load could be transformed into wider load. */
17640 if (class == BPF_LDX &&
17641 aux[adj_idx].ptr_type == PTR_TO_CTX)
17644 imm_rnd = get_random_u32();
17645 rnd_hi32_patch[0] = insn;
17646 rnd_hi32_patch[1].imm = imm_rnd;
17647 rnd_hi32_patch[3].dst_reg = load_reg;
17648 patch = rnd_hi32_patch;
17650 goto apply_patch_buffer;
17653 /* Add in an zero-extend instruction if a) the JIT has requested
17654 * it or b) it's a CMPXCHG.
17656 * The latter is because: BPF_CMPXCHG always loads a value into
17657 * R0, therefore always zero-extends. However some archs'
17658 * equivalent instruction only does this load when the
17659 * comparison is successful. This detail of CMPXCHG is
17660 * orthogonal to the general zero-extension behaviour of the
17661 * CPU, so it's treated independently of bpf_jit_needs_zext.
17663 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17666 /* Zero-extension is done by the caller. */
17667 if (bpf_pseudo_kfunc_call(&insn))
17670 if (WARN_ON(load_reg == -1)) {
17671 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17675 zext_patch[0] = insn;
17676 zext_patch[1].dst_reg = load_reg;
17677 zext_patch[1].src_reg = load_reg;
17678 patch = zext_patch;
17680 apply_patch_buffer:
17681 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17684 env->prog = new_prog;
17685 insns = new_prog->insnsi;
17686 aux = env->insn_aux_data;
17687 delta += patch_len - 1;
17693 /* convert load instructions that access fields of a context type into a
17694 * sequence of instructions that access fields of the underlying structure:
17695 * struct __sk_buff -> struct sk_buff
17696 * struct bpf_sock_ops -> struct sock
17698 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17700 const struct bpf_verifier_ops *ops = env->ops;
17701 int i, cnt, size, ctx_field_size, delta = 0;
17702 const int insn_cnt = env->prog->len;
17703 struct bpf_insn insn_buf[16], *insn;
17704 u32 target_size, size_default, off;
17705 struct bpf_prog *new_prog;
17706 enum bpf_access_type type;
17707 bool is_narrower_load;
17709 if (ops->gen_prologue || env->seen_direct_write) {
17710 if (!ops->gen_prologue) {
17711 verbose(env, "bpf verifier is misconfigured\n");
17714 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17716 if (cnt >= ARRAY_SIZE(insn_buf)) {
17717 verbose(env, "bpf verifier is misconfigured\n");
17720 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17724 env->prog = new_prog;
17729 if (bpf_prog_is_offloaded(env->prog->aux))
17732 insn = env->prog->insnsi + delta;
17734 for (i = 0; i < insn_cnt; i++, insn++) {
17735 bpf_convert_ctx_access_t convert_ctx_access;
17738 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17739 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17740 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17741 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
17742 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
17743 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
17744 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
17746 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17747 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17748 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17749 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17750 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17751 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17752 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17753 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17759 if (type == BPF_WRITE &&
17760 env->insn_aux_data[i + delta].sanitize_stack_spill) {
17761 struct bpf_insn patch[] = {
17766 cnt = ARRAY_SIZE(patch);
17767 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17772 env->prog = new_prog;
17773 insn = new_prog->insnsi + i + delta;
17777 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17779 if (!ops->convert_ctx_access)
17781 convert_ctx_access = ops->convert_ctx_access;
17783 case PTR_TO_SOCKET:
17784 case PTR_TO_SOCK_COMMON:
17785 convert_ctx_access = bpf_sock_convert_ctx_access;
17787 case PTR_TO_TCP_SOCK:
17788 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17790 case PTR_TO_XDP_SOCK:
17791 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17793 case PTR_TO_BTF_ID:
17794 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17795 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17796 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17797 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17798 * any faults for loads into such types. BPF_WRITE is disallowed
17801 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17802 if (type == BPF_READ) {
17803 if (BPF_MODE(insn->code) == BPF_MEM)
17804 insn->code = BPF_LDX | BPF_PROBE_MEM |
17805 BPF_SIZE((insn)->code);
17807 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
17808 BPF_SIZE((insn)->code);
17809 env->prog->aux->num_exentries++;
17816 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17817 size = BPF_LDST_BYTES(insn);
17818 mode = BPF_MODE(insn->code);
17820 /* If the read access is a narrower load of the field,
17821 * convert to a 4/8-byte load, to minimum program type specific
17822 * convert_ctx_access changes. If conversion is successful,
17823 * we will apply proper mask to the result.
17825 is_narrower_load = size < ctx_field_size;
17826 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17828 if (is_narrower_load) {
17831 if (type == BPF_WRITE) {
17832 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17837 if (ctx_field_size == 4)
17839 else if (ctx_field_size == 8)
17840 size_code = BPF_DW;
17842 insn->off = off & ~(size_default - 1);
17843 insn->code = BPF_LDX | BPF_MEM | size_code;
17847 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17849 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17850 (ctx_field_size && !target_size)) {
17851 verbose(env, "bpf verifier is misconfigured\n");
17855 if (is_narrower_load && size < target_size) {
17856 u8 shift = bpf_ctx_narrow_access_offset(
17857 off, size, size_default) * 8;
17858 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17859 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17862 if (ctx_field_size <= 4) {
17864 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17867 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17868 (1 << size * 8) - 1);
17871 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17874 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17875 (1ULL << size * 8) - 1);
17878 if (mode == BPF_MEMSX)
17879 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
17880 insn->dst_reg, insn->dst_reg,
17883 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17889 /* keep walking new program and skip insns we just inserted */
17890 env->prog = new_prog;
17891 insn = new_prog->insnsi + i + delta;
17897 static int jit_subprogs(struct bpf_verifier_env *env)
17899 struct bpf_prog *prog = env->prog, **func, *tmp;
17900 int i, j, subprog_start, subprog_end = 0, len, subprog;
17901 struct bpf_map *map_ptr;
17902 struct bpf_insn *insn;
17903 void *old_bpf_func;
17904 int err, num_exentries;
17906 if (env->subprog_cnt <= 1)
17909 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17910 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17913 /* Upon error here we cannot fall back to interpreter but
17914 * need a hard reject of the program. Thus -EFAULT is
17915 * propagated in any case.
17917 subprog = find_subprog(env, i + insn->imm + 1);
17919 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17920 i + insn->imm + 1);
17923 /* temporarily remember subprog id inside insn instead of
17924 * aux_data, since next loop will split up all insns into funcs
17926 insn->off = subprog;
17927 /* remember original imm in case JIT fails and fallback
17928 * to interpreter will be needed
17930 env->insn_aux_data[i].call_imm = insn->imm;
17931 /* point imm to __bpf_call_base+1 from JITs point of view */
17933 if (bpf_pseudo_func(insn))
17934 /* jit (e.g. x86_64) may emit fewer instructions
17935 * if it learns a u32 imm is the same as a u64 imm.
17936 * Force a non zero here.
17941 err = bpf_prog_alloc_jited_linfo(prog);
17943 goto out_undo_insn;
17946 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17948 goto out_undo_insn;
17950 for (i = 0; i < env->subprog_cnt; i++) {
17951 subprog_start = subprog_end;
17952 subprog_end = env->subprog_info[i + 1].start;
17954 len = subprog_end - subprog_start;
17955 /* bpf_prog_run() doesn't call subprogs directly,
17956 * hence main prog stats include the runtime of subprogs.
17957 * subprogs don't have IDs and not reachable via prog_get_next_id
17958 * func[i]->stats will never be accessed and stays NULL
17960 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17963 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17964 len * sizeof(struct bpf_insn));
17965 func[i]->type = prog->type;
17966 func[i]->len = len;
17967 if (bpf_prog_calc_tag(func[i]))
17969 func[i]->is_func = 1;
17970 func[i]->aux->func_idx = i;
17971 /* Below members will be freed only at prog->aux */
17972 func[i]->aux->btf = prog->aux->btf;
17973 func[i]->aux->func_info = prog->aux->func_info;
17974 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17975 func[i]->aux->poke_tab = prog->aux->poke_tab;
17976 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17978 for (j = 0; j < prog->aux->size_poke_tab; j++) {
17979 struct bpf_jit_poke_descriptor *poke;
17981 poke = &prog->aux->poke_tab[j];
17982 if (poke->insn_idx < subprog_end &&
17983 poke->insn_idx >= subprog_start)
17984 poke->aux = func[i]->aux;
17987 func[i]->aux->name[0] = 'F';
17988 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17989 func[i]->jit_requested = 1;
17990 func[i]->blinding_requested = prog->blinding_requested;
17991 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17992 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17993 func[i]->aux->linfo = prog->aux->linfo;
17994 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17995 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17996 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17998 insn = func[i]->insnsi;
17999 for (j = 0; j < func[i]->len; j++, insn++) {
18000 if (BPF_CLASS(insn->code) == BPF_LDX &&
18001 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18002 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18005 func[i]->aux->num_exentries = num_exentries;
18006 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18007 func[i] = bpf_int_jit_compile(func[i]);
18008 if (!func[i]->jited) {
18015 /* at this point all bpf functions were successfully JITed
18016 * now populate all bpf_calls with correct addresses and
18017 * run last pass of JIT
18019 for (i = 0; i < env->subprog_cnt; i++) {
18020 insn = func[i]->insnsi;
18021 for (j = 0; j < func[i]->len; j++, insn++) {
18022 if (bpf_pseudo_func(insn)) {
18023 subprog = insn->off;
18024 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18025 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18028 if (!bpf_pseudo_call(insn))
18030 subprog = insn->off;
18031 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18034 /* we use the aux data to keep a list of the start addresses
18035 * of the JITed images for each function in the program
18037 * for some architectures, such as powerpc64, the imm field
18038 * might not be large enough to hold the offset of the start
18039 * address of the callee's JITed image from __bpf_call_base
18041 * in such cases, we can lookup the start address of a callee
18042 * by using its subprog id, available from the off field of
18043 * the call instruction, as an index for this list
18045 func[i]->aux->func = func;
18046 func[i]->aux->func_cnt = env->subprog_cnt;
18048 for (i = 0; i < env->subprog_cnt; i++) {
18049 old_bpf_func = func[i]->bpf_func;
18050 tmp = bpf_int_jit_compile(func[i]);
18051 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18052 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18059 /* finally lock prog and jit images for all functions and
18060 * populate kallsysm. Begin at the first subprogram, since
18061 * bpf_prog_load will add the kallsyms for the main program.
18063 for (i = 1; i < env->subprog_cnt; i++) {
18064 bpf_prog_lock_ro(func[i]);
18065 bpf_prog_kallsyms_add(func[i]);
18068 /* Last step: make now unused interpreter insns from main
18069 * prog consistent for later dump requests, so they can
18070 * later look the same as if they were interpreted only.
18072 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18073 if (bpf_pseudo_func(insn)) {
18074 insn[0].imm = env->insn_aux_data[i].call_imm;
18075 insn[1].imm = insn->off;
18079 if (!bpf_pseudo_call(insn))
18081 insn->off = env->insn_aux_data[i].call_imm;
18082 subprog = find_subprog(env, i + insn->off + 1);
18083 insn->imm = subprog;
18087 prog->bpf_func = func[0]->bpf_func;
18088 prog->jited_len = func[0]->jited_len;
18089 prog->aux->extable = func[0]->aux->extable;
18090 prog->aux->num_exentries = func[0]->aux->num_exentries;
18091 prog->aux->func = func;
18092 prog->aux->func_cnt = env->subprog_cnt;
18093 bpf_prog_jit_attempt_done(prog);
18096 /* We failed JIT'ing, so at this point we need to unregister poke
18097 * descriptors from subprogs, so that kernel is not attempting to
18098 * patch it anymore as we're freeing the subprog JIT memory.
18100 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18101 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18102 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18104 /* At this point we're guaranteed that poke descriptors are not
18105 * live anymore. We can just unlink its descriptor table as it's
18106 * released with the main prog.
18108 for (i = 0; i < env->subprog_cnt; i++) {
18111 func[i]->aux->poke_tab = NULL;
18112 bpf_jit_free(func[i]);
18116 /* cleanup main prog to be interpreted */
18117 prog->jit_requested = 0;
18118 prog->blinding_requested = 0;
18119 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18120 if (!bpf_pseudo_call(insn))
18123 insn->imm = env->insn_aux_data[i].call_imm;
18125 bpf_prog_jit_attempt_done(prog);
18129 static int fixup_call_args(struct bpf_verifier_env *env)
18131 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18132 struct bpf_prog *prog = env->prog;
18133 struct bpf_insn *insn = prog->insnsi;
18134 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18139 if (env->prog->jit_requested &&
18140 !bpf_prog_is_offloaded(env->prog->aux)) {
18141 err = jit_subprogs(env);
18144 if (err == -EFAULT)
18147 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18148 if (has_kfunc_call) {
18149 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18152 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18153 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18154 * have to be rejected, since interpreter doesn't support them yet.
18156 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18159 for (i = 0; i < prog->len; i++, insn++) {
18160 if (bpf_pseudo_func(insn)) {
18161 /* When JIT fails the progs with callback calls
18162 * have to be rejected, since interpreter doesn't support them yet.
18164 verbose(env, "callbacks are not allowed in non-JITed programs\n");
18168 if (!bpf_pseudo_call(insn))
18170 depth = get_callee_stack_depth(env, insn, i);
18173 bpf_patch_call_args(insn, depth);
18180 /* replace a generic kfunc with a specialized version if necessary */
18181 static void specialize_kfunc(struct bpf_verifier_env *env,
18182 u32 func_id, u16 offset, unsigned long *addr)
18184 struct bpf_prog *prog = env->prog;
18185 bool seen_direct_write;
18189 if (bpf_dev_bound_kfunc_id(func_id)) {
18190 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18192 *addr = (unsigned long)xdp_kfunc;
18195 /* fallback to default kfunc when not supported by netdev */
18201 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18202 seen_direct_write = env->seen_direct_write;
18203 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18206 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18208 /* restore env->seen_direct_write to its original value, since
18209 * may_access_direct_pkt_data mutates it
18211 env->seen_direct_write = seen_direct_write;
18215 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18216 u16 struct_meta_reg,
18217 u16 node_offset_reg,
18218 struct bpf_insn *insn,
18219 struct bpf_insn *insn_buf,
18222 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18223 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18225 insn_buf[0] = addr[0];
18226 insn_buf[1] = addr[1];
18227 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18228 insn_buf[3] = *insn;
18232 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18233 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18235 const struct bpf_kfunc_desc *desc;
18238 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18244 /* insn->imm has the btf func_id. Replace it with an offset relative to
18245 * __bpf_call_base, unless the JIT needs to call functions that are
18246 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18248 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18250 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18255 if (!bpf_jit_supports_far_kfunc_call())
18256 insn->imm = BPF_CALL_IMM(desc->addr);
18259 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18260 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18261 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18262 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18264 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18265 insn_buf[1] = addr[0];
18266 insn_buf[2] = addr[1];
18267 insn_buf[3] = *insn;
18269 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18270 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18271 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18272 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18274 insn_buf[0] = addr[0];
18275 insn_buf[1] = addr[1];
18276 insn_buf[2] = *insn;
18278 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18279 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18280 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18281 int struct_meta_reg = BPF_REG_3;
18282 int node_offset_reg = BPF_REG_4;
18284 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18285 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18286 struct_meta_reg = BPF_REG_4;
18287 node_offset_reg = BPF_REG_5;
18290 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18291 node_offset_reg, insn, insn_buf, cnt);
18292 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18293 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18294 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18300 /* Do various post-verification rewrites in a single program pass.
18301 * These rewrites simplify JIT and interpreter implementations.
18303 static int do_misc_fixups(struct bpf_verifier_env *env)
18305 struct bpf_prog *prog = env->prog;
18306 enum bpf_attach_type eatype = prog->expected_attach_type;
18307 enum bpf_prog_type prog_type = resolve_prog_type(prog);
18308 struct bpf_insn *insn = prog->insnsi;
18309 const struct bpf_func_proto *fn;
18310 const int insn_cnt = prog->len;
18311 const struct bpf_map_ops *ops;
18312 struct bpf_insn_aux_data *aux;
18313 struct bpf_insn insn_buf[16];
18314 struct bpf_prog *new_prog;
18315 struct bpf_map *map_ptr;
18316 int i, ret, cnt, delta = 0;
18318 for (i = 0; i < insn_cnt; i++, insn++) {
18319 /* Make divide-by-zero exceptions impossible. */
18320 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18321 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18322 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18323 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18324 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18325 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18326 struct bpf_insn *patchlet;
18327 struct bpf_insn chk_and_div[] = {
18328 /* [R,W]x div 0 -> 0 */
18329 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18330 BPF_JNE | BPF_K, insn->src_reg,
18332 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18333 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18336 struct bpf_insn chk_and_mod[] = {
18337 /* [R,W]x mod 0 -> [R,W]x */
18338 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18339 BPF_JEQ | BPF_K, insn->src_reg,
18340 0, 1 + (is64 ? 0 : 1), 0),
18342 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18343 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18346 patchlet = isdiv ? chk_and_div : chk_and_mod;
18347 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18348 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18350 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18355 env->prog = prog = new_prog;
18356 insn = new_prog->insnsi + i + delta;
18360 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18361 if (BPF_CLASS(insn->code) == BPF_LD &&
18362 (BPF_MODE(insn->code) == BPF_ABS ||
18363 BPF_MODE(insn->code) == BPF_IND)) {
18364 cnt = env->ops->gen_ld_abs(insn, insn_buf);
18365 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18366 verbose(env, "bpf verifier is misconfigured\n");
18370 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18375 env->prog = prog = new_prog;
18376 insn = new_prog->insnsi + i + delta;
18380 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18381 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18382 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18383 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18384 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18385 struct bpf_insn *patch = &insn_buf[0];
18386 bool issrc, isneg, isimm;
18389 aux = &env->insn_aux_data[i + delta];
18390 if (!aux->alu_state ||
18391 aux->alu_state == BPF_ALU_NON_POINTER)
18394 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18395 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18396 BPF_ALU_SANITIZE_SRC;
18397 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18399 off_reg = issrc ? insn->src_reg : insn->dst_reg;
18401 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18404 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18405 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18406 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18407 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18408 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18409 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18410 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18413 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18414 insn->src_reg = BPF_REG_AX;
18416 insn->code = insn->code == code_add ?
18417 code_sub : code_add;
18419 if (issrc && isneg && !isimm)
18420 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18421 cnt = patch - insn_buf;
18423 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18428 env->prog = prog = new_prog;
18429 insn = new_prog->insnsi + i + delta;
18433 if (insn->code != (BPF_JMP | BPF_CALL))
18435 if (insn->src_reg == BPF_PSEUDO_CALL)
18437 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18438 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18444 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18449 env->prog = prog = new_prog;
18450 insn = new_prog->insnsi + i + delta;
18454 if (insn->imm == BPF_FUNC_get_route_realm)
18455 prog->dst_needed = 1;
18456 if (insn->imm == BPF_FUNC_get_prandom_u32)
18457 bpf_user_rnd_init_once();
18458 if (insn->imm == BPF_FUNC_override_return)
18459 prog->kprobe_override = 1;
18460 if (insn->imm == BPF_FUNC_tail_call) {
18461 /* If we tail call into other programs, we
18462 * cannot make any assumptions since they can
18463 * be replaced dynamically during runtime in
18464 * the program array.
18466 prog->cb_access = 1;
18467 if (!allow_tail_call_in_subprogs(env))
18468 prog->aux->stack_depth = MAX_BPF_STACK;
18469 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18471 /* mark bpf_tail_call as different opcode to avoid
18472 * conditional branch in the interpreter for every normal
18473 * call and to prevent accidental JITing by JIT compiler
18474 * that doesn't support bpf_tail_call yet
18477 insn->code = BPF_JMP | BPF_TAIL_CALL;
18479 aux = &env->insn_aux_data[i + delta];
18480 if (env->bpf_capable && !prog->blinding_requested &&
18481 prog->jit_requested &&
18482 !bpf_map_key_poisoned(aux) &&
18483 !bpf_map_ptr_poisoned(aux) &&
18484 !bpf_map_ptr_unpriv(aux)) {
18485 struct bpf_jit_poke_descriptor desc = {
18486 .reason = BPF_POKE_REASON_TAIL_CALL,
18487 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18488 .tail_call.key = bpf_map_key_immediate(aux),
18489 .insn_idx = i + delta,
18492 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18494 verbose(env, "adding tail call poke descriptor failed\n");
18498 insn->imm = ret + 1;
18502 if (!bpf_map_ptr_unpriv(aux))
18505 /* instead of changing every JIT dealing with tail_call
18506 * emit two extra insns:
18507 * if (index >= max_entries) goto out;
18508 * index &= array->index_mask;
18509 * to avoid out-of-bounds cpu speculation
18511 if (bpf_map_ptr_poisoned(aux)) {
18512 verbose(env, "tail_call abusing map_ptr\n");
18516 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18517 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18518 map_ptr->max_entries, 2);
18519 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18520 container_of(map_ptr,
18523 insn_buf[2] = *insn;
18525 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18530 env->prog = prog = new_prog;
18531 insn = new_prog->insnsi + i + delta;
18535 if (insn->imm == BPF_FUNC_timer_set_callback) {
18536 /* The verifier will process callback_fn as many times as necessary
18537 * with different maps and the register states prepared by
18538 * set_timer_callback_state will be accurate.
18540 * The following use case is valid:
18541 * map1 is shared by prog1, prog2, prog3.
18542 * prog1 calls bpf_timer_init for some map1 elements
18543 * prog2 calls bpf_timer_set_callback for some map1 elements.
18544 * Those that were not bpf_timer_init-ed will return -EINVAL.
18545 * prog3 calls bpf_timer_start for some map1 elements.
18546 * Those that were not both bpf_timer_init-ed and
18547 * bpf_timer_set_callback-ed will return -EINVAL.
18549 struct bpf_insn ld_addrs[2] = {
18550 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18553 insn_buf[0] = ld_addrs[0];
18554 insn_buf[1] = ld_addrs[1];
18555 insn_buf[2] = *insn;
18558 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18563 env->prog = prog = new_prog;
18564 insn = new_prog->insnsi + i + delta;
18565 goto patch_call_imm;
18568 if (is_storage_get_function(insn->imm)) {
18569 if (!env->prog->aux->sleepable ||
18570 env->insn_aux_data[i + delta].storage_get_func_atomic)
18571 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18573 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18574 insn_buf[1] = *insn;
18577 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18582 env->prog = prog = new_prog;
18583 insn = new_prog->insnsi + i + delta;
18584 goto patch_call_imm;
18587 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18588 * and other inlining handlers are currently limited to 64 bit
18591 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18592 (insn->imm == BPF_FUNC_map_lookup_elem ||
18593 insn->imm == BPF_FUNC_map_update_elem ||
18594 insn->imm == BPF_FUNC_map_delete_elem ||
18595 insn->imm == BPF_FUNC_map_push_elem ||
18596 insn->imm == BPF_FUNC_map_pop_elem ||
18597 insn->imm == BPF_FUNC_map_peek_elem ||
18598 insn->imm == BPF_FUNC_redirect_map ||
18599 insn->imm == BPF_FUNC_for_each_map_elem ||
18600 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18601 aux = &env->insn_aux_data[i + delta];
18602 if (bpf_map_ptr_poisoned(aux))
18603 goto patch_call_imm;
18605 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18606 ops = map_ptr->ops;
18607 if (insn->imm == BPF_FUNC_map_lookup_elem &&
18608 ops->map_gen_lookup) {
18609 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18610 if (cnt == -EOPNOTSUPP)
18611 goto patch_map_ops_generic;
18612 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18613 verbose(env, "bpf verifier is misconfigured\n");
18617 new_prog = bpf_patch_insn_data(env, i + delta,
18623 env->prog = prog = new_prog;
18624 insn = new_prog->insnsi + i + delta;
18628 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18629 (void *(*)(struct bpf_map *map, void *key))NULL));
18630 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18631 (long (*)(struct bpf_map *map, void *key))NULL));
18632 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18633 (long (*)(struct bpf_map *map, void *key, void *value,
18635 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18636 (long (*)(struct bpf_map *map, void *value,
18638 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18639 (long (*)(struct bpf_map *map, void *value))NULL));
18640 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18641 (long (*)(struct bpf_map *map, void *value))NULL));
18642 BUILD_BUG_ON(!__same_type(ops->map_redirect,
18643 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18644 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18645 (long (*)(struct bpf_map *map,
18646 bpf_callback_t callback_fn,
18647 void *callback_ctx,
18649 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18650 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18652 patch_map_ops_generic:
18653 switch (insn->imm) {
18654 case BPF_FUNC_map_lookup_elem:
18655 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18657 case BPF_FUNC_map_update_elem:
18658 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18660 case BPF_FUNC_map_delete_elem:
18661 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18663 case BPF_FUNC_map_push_elem:
18664 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18666 case BPF_FUNC_map_pop_elem:
18667 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18669 case BPF_FUNC_map_peek_elem:
18670 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18672 case BPF_FUNC_redirect_map:
18673 insn->imm = BPF_CALL_IMM(ops->map_redirect);
18675 case BPF_FUNC_for_each_map_elem:
18676 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18678 case BPF_FUNC_map_lookup_percpu_elem:
18679 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18683 goto patch_call_imm;
18686 /* Implement bpf_jiffies64 inline. */
18687 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18688 insn->imm == BPF_FUNC_jiffies64) {
18689 struct bpf_insn ld_jiffies_addr[2] = {
18690 BPF_LD_IMM64(BPF_REG_0,
18691 (unsigned long)&jiffies),
18694 insn_buf[0] = ld_jiffies_addr[0];
18695 insn_buf[1] = ld_jiffies_addr[1];
18696 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18700 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18706 env->prog = prog = new_prog;
18707 insn = new_prog->insnsi + i + delta;
18711 /* Implement bpf_get_func_arg inline. */
18712 if (prog_type == BPF_PROG_TYPE_TRACING &&
18713 insn->imm == BPF_FUNC_get_func_arg) {
18714 /* Load nr_args from ctx - 8 */
18715 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18716 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18717 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18718 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18719 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18720 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18721 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18722 insn_buf[7] = BPF_JMP_A(1);
18723 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18726 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18731 env->prog = prog = new_prog;
18732 insn = new_prog->insnsi + i + delta;
18736 /* Implement bpf_get_func_ret inline. */
18737 if (prog_type == BPF_PROG_TYPE_TRACING &&
18738 insn->imm == BPF_FUNC_get_func_ret) {
18739 if (eatype == BPF_TRACE_FEXIT ||
18740 eatype == BPF_MODIFY_RETURN) {
18741 /* Load nr_args from ctx - 8 */
18742 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18743 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18744 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18745 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18746 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18747 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18750 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18754 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18759 env->prog = prog = new_prog;
18760 insn = new_prog->insnsi + i + delta;
18764 /* Implement get_func_arg_cnt inline. */
18765 if (prog_type == BPF_PROG_TYPE_TRACING &&
18766 insn->imm == BPF_FUNC_get_func_arg_cnt) {
18767 /* Load nr_args from ctx - 8 */
18768 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18770 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18774 env->prog = prog = new_prog;
18775 insn = new_prog->insnsi + i + delta;
18779 /* Implement bpf_get_func_ip inline. */
18780 if (prog_type == BPF_PROG_TYPE_TRACING &&
18781 insn->imm == BPF_FUNC_get_func_ip) {
18782 /* Load IP address from ctx - 16 */
18783 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18785 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18789 env->prog = prog = new_prog;
18790 insn = new_prog->insnsi + i + delta;
18795 fn = env->ops->get_func_proto(insn->imm, env->prog);
18796 /* all functions that have prototype and verifier allowed
18797 * programs to call them, must be real in-kernel functions
18801 "kernel subsystem misconfigured func %s#%d\n",
18802 func_id_name(insn->imm), insn->imm);
18805 insn->imm = fn->func - __bpf_call_base;
18808 /* Since poke tab is now finalized, publish aux to tracker. */
18809 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18810 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18811 if (!map_ptr->ops->map_poke_track ||
18812 !map_ptr->ops->map_poke_untrack ||
18813 !map_ptr->ops->map_poke_run) {
18814 verbose(env, "bpf verifier is misconfigured\n");
18818 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18820 verbose(env, "tracking tail call prog failed\n");
18825 sort_kfunc_descs_by_imm_off(env->prog);
18830 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18833 u32 callback_subprogno,
18836 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18837 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18838 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18839 int reg_loop_max = BPF_REG_6;
18840 int reg_loop_cnt = BPF_REG_7;
18841 int reg_loop_ctx = BPF_REG_8;
18843 struct bpf_prog *new_prog;
18844 u32 callback_start;
18845 u32 call_insn_offset;
18846 s32 callback_offset;
18848 /* This represents an inlined version of bpf_iter.c:bpf_loop,
18849 * be careful to modify this code in sync.
18851 struct bpf_insn insn_buf[] = {
18852 /* Return error and jump to the end of the patch if
18853 * expected number of iterations is too big.
18855 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18856 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18857 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18858 /* spill R6, R7, R8 to use these as loop vars */
18859 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18860 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18861 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18862 /* initialize loop vars */
18863 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18864 BPF_MOV32_IMM(reg_loop_cnt, 0),
18865 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18867 * if reg_loop_cnt >= reg_loop_max skip the loop body
18869 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18871 * correct callback offset would be set after patching
18873 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18874 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18876 /* increment loop counter */
18877 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18878 /* jump to loop header if callback returned 0 */
18879 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18880 /* return value of bpf_loop,
18881 * set R0 to the number of iterations
18883 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18884 /* restore original values of R6, R7, R8 */
18885 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18886 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18887 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18890 *cnt = ARRAY_SIZE(insn_buf);
18891 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18895 /* callback start is known only after patching */
18896 callback_start = env->subprog_info[callback_subprogno].start;
18897 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18898 call_insn_offset = position + 12;
18899 callback_offset = callback_start - call_insn_offset - 1;
18900 new_prog->insnsi[call_insn_offset].imm = callback_offset;
18905 static bool is_bpf_loop_call(struct bpf_insn *insn)
18907 return insn->code == (BPF_JMP | BPF_CALL) &&
18908 insn->src_reg == 0 &&
18909 insn->imm == BPF_FUNC_loop;
18912 /* For all sub-programs in the program (including main) check
18913 * insn_aux_data to see if there are bpf_loop calls that require
18914 * inlining. If such calls are found the calls are replaced with a
18915 * sequence of instructions produced by `inline_bpf_loop` function and
18916 * subprog stack_depth is increased by the size of 3 registers.
18917 * This stack space is used to spill values of the R6, R7, R8. These
18918 * registers are used to store the loop bound, counter and context
18921 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18923 struct bpf_subprog_info *subprogs = env->subprog_info;
18924 int i, cur_subprog = 0, cnt, delta = 0;
18925 struct bpf_insn *insn = env->prog->insnsi;
18926 int insn_cnt = env->prog->len;
18927 u16 stack_depth = subprogs[cur_subprog].stack_depth;
18928 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18929 u16 stack_depth_extra = 0;
18931 for (i = 0; i < insn_cnt; i++, insn++) {
18932 struct bpf_loop_inline_state *inline_state =
18933 &env->insn_aux_data[i + delta].loop_inline_state;
18935 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18936 struct bpf_prog *new_prog;
18938 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18939 new_prog = inline_bpf_loop(env,
18941 -(stack_depth + stack_depth_extra),
18942 inline_state->callback_subprogno,
18948 env->prog = new_prog;
18949 insn = new_prog->insnsi + i + delta;
18952 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18953 subprogs[cur_subprog].stack_depth += stack_depth_extra;
18955 stack_depth = subprogs[cur_subprog].stack_depth;
18956 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18957 stack_depth_extra = 0;
18961 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18966 static void free_states(struct bpf_verifier_env *env)
18968 struct bpf_verifier_state_list *sl, *sln;
18971 sl = env->free_list;
18974 free_verifier_state(&sl->state, false);
18978 env->free_list = NULL;
18980 if (!env->explored_states)
18983 for (i = 0; i < state_htab_size(env); i++) {
18984 sl = env->explored_states[i];
18988 free_verifier_state(&sl->state, false);
18992 env->explored_states[i] = NULL;
18996 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18998 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18999 struct bpf_verifier_state *state;
19000 struct bpf_reg_state *regs;
19003 env->prev_linfo = NULL;
19006 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19009 state->curframe = 0;
19010 state->speculative = false;
19011 state->branches = 1;
19012 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19013 if (!state->frame[0]) {
19017 env->cur_state = state;
19018 init_func_state(env, state->frame[0],
19019 BPF_MAIN_FUNC /* callsite */,
19022 state->first_insn_idx = env->subprog_info[subprog].start;
19023 state->last_insn_idx = -1;
19025 regs = state->frame[state->curframe]->regs;
19026 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19027 ret = btf_prepare_func_args(env, subprog, regs);
19030 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19031 if (regs[i].type == PTR_TO_CTX)
19032 mark_reg_known_zero(env, regs, i);
19033 else if (regs[i].type == SCALAR_VALUE)
19034 mark_reg_unknown(env, regs, i);
19035 else if (base_type(regs[i].type) == PTR_TO_MEM) {
19036 const u32 mem_size = regs[i].mem_size;
19038 mark_reg_known_zero(env, regs, i);
19039 regs[i].mem_size = mem_size;
19040 regs[i].id = ++env->id_gen;
19044 /* 1st arg to a function */
19045 regs[BPF_REG_1].type = PTR_TO_CTX;
19046 mark_reg_known_zero(env, regs, BPF_REG_1);
19047 ret = btf_check_subprog_arg_match(env, subprog, regs);
19048 if (ret == -EFAULT)
19049 /* unlikely verifier bug. abort.
19050 * ret == 0 and ret < 0 are sadly acceptable for
19051 * main() function due to backward compatibility.
19052 * Like socket filter program may be written as:
19053 * int bpf_prog(struct pt_regs *ctx)
19054 * and never dereference that ctx in the program.
19055 * 'struct pt_regs' is a type mismatch for socket
19056 * filter that should be using 'struct __sk_buff'.
19061 ret = do_check(env);
19063 /* check for NULL is necessary, since cur_state can be freed inside
19064 * do_check() under memory pressure.
19066 if (env->cur_state) {
19067 free_verifier_state(env->cur_state, true);
19068 env->cur_state = NULL;
19070 while (!pop_stack(env, NULL, NULL, false));
19071 if (!ret && pop_log)
19072 bpf_vlog_reset(&env->log, 0);
19077 /* Verify all global functions in a BPF program one by one based on their BTF.
19078 * All global functions must pass verification. Otherwise the whole program is rejected.
19089 * foo() will be verified first for R1=any_scalar_value. During verification it
19090 * will be assumed that bar() already verified successfully and call to bar()
19091 * from foo() will be checked for type match only. Later bar() will be verified
19092 * independently to check that it's safe for R1=any_scalar_value.
19094 static int do_check_subprogs(struct bpf_verifier_env *env)
19096 struct bpf_prog_aux *aux = env->prog->aux;
19099 if (!aux->func_info)
19102 for (i = 1; i < env->subprog_cnt; i++) {
19103 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19105 env->insn_idx = env->subprog_info[i].start;
19106 WARN_ON_ONCE(env->insn_idx == 0);
19107 ret = do_check_common(env, i);
19110 } else if (env->log.level & BPF_LOG_LEVEL) {
19112 "Func#%d is safe for any args that match its prototype\n",
19119 static int do_check_main(struct bpf_verifier_env *env)
19124 ret = do_check_common(env, 0);
19126 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19131 static void print_verification_stats(struct bpf_verifier_env *env)
19135 if (env->log.level & BPF_LOG_STATS) {
19136 verbose(env, "verification time %lld usec\n",
19137 div_u64(env->verification_time, 1000));
19138 verbose(env, "stack depth ");
19139 for (i = 0; i < env->subprog_cnt; i++) {
19140 u32 depth = env->subprog_info[i].stack_depth;
19142 verbose(env, "%d", depth);
19143 if (i + 1 < env->subprog_cnt)
19146 verbose(env, "\n");
19148 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19149 "total_states %d peak_states %d mark_read %d\n",
19150 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19151 env->max_states_per_insn, env->total_states,
19152 env->peak_states, env->longest_mark_read_walk);
19155 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19157 const struct btf_type *t, *func_proto;
19158 const struct bpf_struct_ops *st_ops;
19159 const struct btf_member *member;
19160 struct bpf_prog *prog = env->prog;
19161 u32 btf_id, member_idx;
19164 if (!prog->gpl_compatible) {
19165 verbose(env, "struct ops programs must have a GPL compatible license\n");
19169 btf_id = prog->aux->attach_btf_id;
19170 st_ops = bpf_struct_ops_find(btf_id);
19172 verbose(env, "attach_btf_id %u is not a supported struct\n",
19178 member_idx = prog->expected_attach_type;
19179 if (member_idx >= btf_type_vlen(t)) {
19180 verbose(env, "attach to invalid member idx %u of struct %s\n",
19181 member_idx, st_ops->name);
19185 member = &btf_type_member(t)[member_idx];
19186 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19187 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19190 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19191 mname, member_idx, st_ops->name);
19195 if (st_ops->check_member) {
19196 int err = st_ops->check_member(t, member, prog);
19199 verbose(env, "attach to unsupported member %s of struct %s\n",
19200 mname, st_ops->name);
19205 prog->aux->attach_func_proto = func_proto;
19206 prog->aux->attach_func_name = mname;
19207 env->ops = st_ops->verifier_ops;
19211 #define SECURITY_PREFIX "security_"
19213 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19215 if (within_error_injection_list(addr) ||
19216 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19222 /* list of non-sleepable functions that are otherwise on
19223 * ALLOW_ERROR_INJECTION list
19225 BTF_SET_START(btf_non_sleepable_error_inject)
19226 /* Three functions below can be called from sleepable and non-sleepable context.
19227 * Assume non-sleepable from bpf safety point of view.
19229 BTF_ID(func, __filemap_add_folio)
19230 BTF_ID(func, should_fail_alloc_page)
19231 BTF_ID(func, should_failslab)
19232 BTF_SET_END(btf_non_sleepable_error_inject)
19234 static int check_non_sleepable_error_inject(u32 btf_id)
19236 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19239 int bpf_check_attach_target(struct bpf_verifier_log *log,
19240 const struct bpf_prog *prog,
19241 const struct bpf_prog *tgt_prog,
19243 struct bpf_attach_target_info *tgt_info)
19245 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19246 const char prefix[] = "btf_trace_";
19247 int ret = 0, subprog = -1, i;
19248 const struct btf_type *t;
19249 bool conservative = true;
19253 struct module *mod = NULL;
19256 bpf_log(log, "Tracing programs must provide btf_id\n");
19259 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19262 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19265 t = btf_type_by_id(btf, btf_id);
19267 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19270 tname = btf_name_by_offset(btf, t->name_off);
19272 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19276 struct bpf_prog_aux *aux = tgt_prog->aux;
19278 if (bpf_prog_is_dev_bound(prog->aux) &&
19279 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19280 bpf_log(log, "Target program bound device mismatch");
19284 for (i = 0; i < aux->func_info_cnt; i++)
19285 if (aux->func_info[i].type_id == btf_id) {
19289 if (subprog == -1) {
19290 bpf_log(log, "Subprog %s doesn't exist\n", tname);
19293 conservative = aux->func_info_aux[subprog].unreliable;
19294 if (prog_extension) {
19295 if (conservative) {
19297 "Cannot replace static functions\n");
19300 if (!prog->jit_requested) {
19302 "Extension programs should be JITed\n");
19306 if (!tgt_prog->jited) {
19307 bpf_log(log, "Can attach to only JITed progs\n");
19310 if (tgt_prog->type == prog->type) {
19311 /* Cannot fentry/fexit another fentry/fexit program.
19312 * Cannot attach program extension to another extension.
19313 * It's ok to attach fentry/fexit to extension program.
19315 bpf_log(log, "Cannot recursively attach\n");
19318 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19320 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19321 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19322 /* Program extensions can extend all program types
19323 * except fentry/fexit. The reason is the following.
19324 * The fentry/fexit programs are used for performance
19325 * analysis, stats and can be attached to any program
19326 * type except themselves. When extension program is
19327 * replacing XDP function it is necessary to allow
19328 * performance analysis of all functions. Both original
19329 * XDP program and its program extension. Hence
19330 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19331 * allowed. If extending of fentry/fexit was allowed it
19332 * would be possible to create long call chain
19333 * fentry->extension->fentry->extension beyond
19334 * reasonable stack size. Hence extending fentry is not
19337 bpf_log(log, "Cannot extend fentry/fexit\n");
19341 if (prog_extension) {
19342 bpf_log(log, "Cannot replace kernel functions\n");
19347 switch (prog->expected_attach_type) {
19348 case BPF_TRACE_RAW_TP:
19351 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19354 if (!btf_type_is_typedef(t)) {
19355 bpf_log(log, "attach_btf_id %u is not a typedef\n",
19359 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19360 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19364 tname += sizeof(prefix) - 1;
19365 t = btf_type_by_id(btf, t->type);
19366 if (!btf_type_is_ptr(t))
19367 /* should never happen in valid vmlinux build */
19369 t = btf_type_by_id(btf, t->type);
19370 if (!btf_type_is_func_proto(t))
19371 /* should never happen in valid vmlinux build */
19375 case BPF_TRACE_ITER:
19376 if (!btf_type_is_func(t)) {
19377 bpf_log(log, "attach_btf_id %u is not a function\n",
19381 t = btf_type_by_id(btf, t->type);
19382 if (!btf_type_is_func_proto(t))
19384 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19389 if (!prog_extension)
19392 case BPF_MODIFY_RETURN:
19394 case BPF_LSM_CGROUP:
19395 case BPF_TRACE_FENTRY:
19396 case BPF_TRACE_FEXIT:
19397 if (!btf_type_is_func(t)) {
19398 bpf_log(log, "attach_btf_id %u is not a function\n",
19402 if (prog_extension &&
19403 btf_check_type_match(log, prog, btf, t))
19405 t = btf_type_by_id(btf, t->type);
19406 if (!btf_type_is_func_proto(t))
19409 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19410 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19411 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19414 if (tgt_prog && conservative)
19417 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19423 addr = (long) tgt_prog->bpf_func;
19425 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19427 if (btf_is_module(btf)) {
19428 mod = btf_try_get_module(btf);
19430 addr = find_kallsyms_symbol_value(mod, tname);
19434 addr = kallsyms_lookup_name(tname);
19439 "The address of function %s cannot be found\n",
19445 if (prog->aux->sleepable) {
19447 switch (prog->type) {
19448 case BPF_PROG_TYPE_TRACING:
19450 /* fentry/fexit/fmod_ret progs can be sleepable if they are
19451 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19453 if (!check_non_sleepable_error_inject(btf_id) &&
19454 within_error_injection_list(addr))
19456 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19457 * in the fmodret id set with the KF_SLEEPABLE flag.
19460 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19463 if (flags && (*flags & KF_SLEEPABLE))
19467 case BPF_PROG_TYPE_LSM:
19468 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19469 * Only some of them are sleepable.
19471 if (bpf_lsm_is_sleepable_hook(btf_id))
19479 bpf_log(log, "%s is not sleepable\n", tname);
19482 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19485 bpf_log(log, "can't modify return codes of BPF programs\n");
19489 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19490 !check_attach_modify_return(addr, tname))
19494 bpf_log(log, "%s() is not modifiable\n", tname);
19501 tgt_info->tgt_addr = addr;
19502 tgt_info->tgt_name = tname;
19503 tgt_info->tgt_type = t;
19504 tgt_info->tgt_mod = mod;
19508 BTF_SET_START(btf_id_deny)
19511 BTF_ID(func, migrate_disable)
19512 BTF_ID(func, migrate_enable)
19514 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19515 BTF_ID(func, rcu_read_unlock_strict)
19517 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19518 BTF_ID(func, preempt_count_add)
19519 BTF_ID(func, preempt_count_sub)
19521 #ifdef CONFIG_PREEMPT_RCU
19522 BTF_ID(func, __rcu_read_lock)
19523 BTF_ID(func, __rcu_read_unlock)
19525 BTF_SET_END(btf_id_deny)
19527 static bool can_be_sleepable(struct bpf_prog *prog)
19529 if (prog->type == BPF_PROG_TYPE_TRACING) {
19530 switch (prog->expected_attach_type) {
19531 case BPF_TRACE_FENTRY:
19532 case BPF_TRACE_FEXIT:
19533 case BPF_MODIFY_RETURN:
19534 case BPF_TRACE_ITER:
19540 return prog->type == BPF_PROG_TYPE_LSM ||
19541 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19542 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19545 static int check_attach_btf_id(struct bpf_verifier_env *env)
19547 struct bpf_prog *prog = env->prog;
19548 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19549 struct bpf_attach_target_info tgt_info = {};
19550 u32 btf_id = prog->aux->attach_btf_id;
19551 struct bpf_trampoline *tr;
19555 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19556 if (prog->aux->sleepable)
19557 /* attach_btf_id checked to be zero already */
19559 verbose(env, "Syscall programs can only be sleepable\n");
19563 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19564 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19568 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19569 return check_struct_ops_btf_id(env);
19571 if (prog->type != BPF_PROG_TYPE_TRACING &&
19572 prog->type != BPF_PROG_TYPE_LSM &&
19573 prog->type != BPF_PROG_TYPE_EXT)
19576 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19580 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19581 /* to make freplace equivalent to their targets, they need to
19582 * inherit env->ops and expected_attach_type for the rest of the
19585 env->ops = bpf_verifier_ops[tgt_prog->type];
19586 prog->expected_attach_type = tgt_prog->expected_attach_type;
19589 /* store info about the attachment target that will be used later */
19590 prog->aux->attach_func_proto = tgt_info.tgt_type;
19591 prog->aux->attach_func_name = tgt_info.tgt_name;
19592 prog->aux->mod = tgt_info.tgt_mod;
19595 prog->aux->saved_dst_prog_type = tgt_prog->type;
19596 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19599 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19600 prog->aux->attach_btf_trace = true;
19602 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19603 if (!bpf_iter_prog_supported(prog))
19608 if (prog->type == BPF_PROG_TYPE_LSM) {
19609 ret = bpf_lsm_verify_prog(&env->log, prog);
19612 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
19613 btf_id_set_contains(&btf_id_deny, btf_id)) {
19617 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19618 tr = bpf_trampoline_get(key, &tgt_info);
19622 prog->aux->dst_trampoline = tr;
19626 struct btf *bpf_get_btf_vmlinux(void)
19628 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19629 mutex_lock(&bpf_verifier_lock);
19631 btf_vmlinux = btf_parse_vmlinux();
19632 mutex_unlock(&bpf_verifier_lock);
19634 return btf_vmlinux;
19637 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19639 u64 start_time = ktime_get_ns();
19640 struct bpf_verifier_env *env;
19641 int i, len, ret = -EINVAL, err;
19645 /* no program is valid */
19646 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19649 /* 'struct bpf_verifier_env' can be global, but since it's not small,
19650 * allocate/free it every time bpf_check() is called
19652 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19658 len = (*prog)->len;
19659 env->insn_aux_data =
19660 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19662 if (!env->insn_aux_data)
19664 for (i = 0; i < len; i++)
19665 env->insn_aux_data[i].orig_idx = i;
19667 env->ops = bpf_verifier_ops[env->prog->type];
19668 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19669 is_priv = bpf_capable();
19671 bpf_get_btf_vmlinux();
19673 /* grab the mutex to protect few globals used by verifier */
19675 mutex_lock(&bpf_verifier_lock);
19677 /* user could have requested verbose verifier output
19678 * and supplied buffer to store the verification trace
19680 ret = bpf_vlog_init(&env->log, attr->log_level,
19681 (char __user *) (unsigned long) attr->log_buf,
19686 mark_verifier_state_clean(env);
19688 if (IS_ERR(btf_vmlinux)) {
19689 /* Either gcc or pahole or kernel are broken. */
19690 verbose(env, "in-kernel BTF is malformed\n");
19691 ret = PTR_ERR(btf_vmlinux);
19692 goto skip_full_check;
19695 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19696 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19697 env->strict_alignment = true;
19698 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19699 env->strict_alignment = false;
19701 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19702 env->allow_uninit_stack = bpf_allow_uninit_stack();
19703 env->bypass_spec_v1 = bpf_bypass_spec_v1();
19704 env->bypass_spec_v4 = bpf_bypass_spec_v4();
19705 env->bpf_capable = bpf_capable();
19708 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19710 env->explored_states = kvcalloc(state_htab_size(env),
19711 sizeof(struct bpf_verifier_state_list *),
19714 if (!env->explored_states)
19715 goto skip_full_check;
19717 ret = add_subprog_and_kfunc(env);
19719 goto skip_full_check;
19721 ret = check_subprogs(env);
19723 goto skip_full_check;
19725 ret = check_btf_info(env, attr, uattr);
19727 goto skip_full_check;
19729 ret = check_attach_btf_id(env);
19731 goto skip_full_check;
19733 ret = resolve_pseudo_ldimm64(env);
19735 goto skip_full_check;
19737 if (bpf_prog_is_offloaded(env->prog->aux)) {
19738 ret = bpf_prog_offload_verifier_prep(env->prog);
19740 goto skip_full_check;
19743 ret = check_cfg(env);
19745 goto skip_full_check;
19747 ret = do_check_subprogs(env);
19748 ret = ret ?: do_check_main(env);
19750 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19751 ret = bpf_prog_offload_finalize(env);
19754 kvfree(env->explored_states);
19757 ret = check_max_stack_depth(env);
19759 /* instruction rewrites happen after this point */
19761 ret = optimize_bpf_loop(env);
19765 opt_hard_wire_dead_code_branches(env);
19767 ret = opt_remove_dead_code(env);
19769 ret = opt_remove_nops(env);
19772 sanitize_dead_code(env);
19776 /* program is valid, convert *(u32*)(ctx + off) accesses */
19777 ret = convert_ctx_accesses(env);
19780 ret = do_misc_fixups(env);
19782 /* do 32-bit optimization after insn patching has done so those patched
19783 * insns could be handled correctly.
19785 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19786 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19787 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19792 ret = fixup_call_args(env);
19794 env->verification_time = ktime_get_ns() - start_time;
19795 print_verification_stats(env);
19796 env->prog->aux->verified_insns = env->insn_processed;
19798 /* preserve original error even if log finalization is successful */
19799 err = bpf_vlog_finalize(&env->log, &log_true_size);
19803 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19804 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19805 &log_true_size, sizeof(log_true_size))) {
19807 goto err_release_maps;
19811 goto err_release_maps;
19813 if (env->used_map_cnt) {
19814 /* if program passed verifier, update used_maps in bpf_prog_info */
19815 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19816 sizeof(env->used_maps[0]),
19819 if (!env->prog->aux->used_maps) {
19821 goto err_release_maps;
19824 memcpy(env->prog->aux->used_maps, env->used_maps,
19825 sizeof(env->used_maps[0]) * env->used_map_cnt);
19826 env->prog->aux->used_map_cnt = env->used_map_cnt;
19828 if (env->used_btf_cnt) {
19829 /* if program passed verifier, update used_btfs in bpf_prog_aux */
19830 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19831 sizeof(env->used_btfs[0]),
19833 if (!env->prog->aux->used_btfs) {
19835 goto err_release_maps;
19838 memcpy(env->prog->aux->used_btfs, env->used_btfs,
19839 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19840 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19842 if (env->used_map_cnt || env->used_btf_cnt) {
19843 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
19844 * bpf_ld_imm64 instructions
19846 convert_pseudo_ld_imm64(env);
19849 adjust_btf_func(env);
19852 if (!env->prog->aux->used_maps)
19853 /* if we didn't copy map pointers into bpf_prog_info, release
19854 * them now. Otherwise free_used_maps() will release them.
19857 if (!env->prog->aux->used_btfs)
19860 /* extension progs temporarily inherit the attach_type of their targets
19861 for verification purposes, so set it back to zero before returning
19863 if (env->prog->type == BPF_PROG_TYPE_EXT)
19864 env->prog->expected_attach_type = 0;
19869 mutex_unlock(&bpf_verifier_lock);
19870 vfree(env->insn_aux_data);