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>
33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
35 [_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #define BPF_LINK_TYPE(_id, _name)
38 #include <linux/bpf_types.h>
44 /* bpf_check() is a static code analyzer that walks eBPF program
45 * instruction by instruction and updates register/stack state.
46 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
48 * The first pass is depth-first-search to check that the program is a DAG.
49 * It rejects the following programs:
50 * - larger than BPF_MAXINSNS insns
51 * - if loop is present (detected via back-edge)
52 * - unreachable insns exist (shouldn't be a forest. program = one function)
53 * - out of bounds or malformed jumps
54 * The second pass is all possible path descent from the 1st insn.
55 * Since it's analyzing all paths through the program, the length of the
56 * analysis is limited to 64k insn, which may be hit even if total number of
57 * insn is less then 4K, but there are too many branches that change stack/regs.
58 * Number of 'branches to be analyzed' is limited to 1k
60 * On entry to each instruction, each register has a type, and the instruction
61 * changes the types of the registers depending on instruction semantics.
62 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
65 * All registers are 64-bit.
66 * R0 - return register
67 * R1-R5 argument passing registers
68 * R6-R9 callee saved registers
69 * R10 - frame pointer read-only
71 * At the start of BPF program the register R1 contains a pointer to bpf_context
72 * and has type PTR_TO_CTX.
74 * Verifier tracks arithmetic operations on pointers in case:
75 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
76 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
77 * 1st insn copies R10 (which has FRAME_PTR) type into R1
78 * and 2nd arithmetic instruction is pattern matched to recognize
79 * that it wants to construct a pointer to some element within stack.
80 * So after 2nd insn, the register R1 has type PTR_TO_STACK
81 * (and -20 constant is saved for further stack bounds checking).
82 * Meaning that this reg is a pointer to stack plus known immediate constant.
84 * Most of the time the registers have SCALAR_VALUE type, which
85 * means the register has some value, but it's not a valid pointer.
86 * (like pointer plus pointer becomes SCALAR_VALUE type)
88 * When verifier sees load or store instructions the type of base register
89 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
90 * four pointer types recognized by check_mem_access() function.
92 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
93 * and the range of [ptr, ptr + map's value_size) is accessible.
95 * registers used to pass values to function calls are checked against
96 * function argument constraints.
98 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
99 * It means that the register type passed to this function must be
100 * PTR_TO_STACK and it will be used inside the function as
101 * 'pointer to map element key'
103 * For example the argument constraints for bpf_map_lookup_elem():
104 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
105 * .arg1_type = ARG_CONST_MAP_PTR,
106 * .arg2_type = ARG_PTR_TO_MAP_KEY,
108 * ret_type says that this function returns 'pointer to map elem value or null'
109 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
110 * 2nd argument should be a pointer to stack, which will be used inside
111 * the helper function as a pointer to map element key.
113 * On the kernel side the helper function looks like:
114 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
116 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
117 * void *key = (void *) (unsigned long) r2;
120 * here kernel can access 'key' and 'map' pointers safely, knowing that
121 * [key, key + map->key_size) bytes are valid and were initialized on
122 * the stack of eBPF program.
125 * Corresponding eBPF program may look like:
126 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
127 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
128 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
129 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
130 * here verifier looks at prototype of map_lookup_elem() and sees:
131 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
132 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
134 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
135 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
136 * and were initialized prior to this call.
137 * If it's ok, then verifier allows this BPF_CALL insn and looks at
138 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
139 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
140 * returns either pointer to map value or NULL.
142 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
143 * insn, the register holding that pointer in the true branch changes state to
144 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
145 * branch. See check_cond_jmp_op().
147 * After the call R0 is set to return type of the function and registers R1-R5
148 * are set to NOT_INIT to indicate that they are no longer readable.
150 * The following reference types represent a potential reference to a kernel
151 * resource which, after first being allocated, must be checked and freed by
153 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
155 * When the verifier sees a helper call return a reference type, it allocates a
156 * pointer id for the reference and stores it in the current function state.
157 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
158 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
159 * passes through a NULL-check conditional. For the branch wherein the state is
160 * changed to CONST_IMM, the verifier releases the reference.
162 * For each helper function that allocates a reference, such as
163 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
164 * bpf_sk_release(). When a reference type passes into the release function,
165 * the verifier also releases the reference. If any unchecked or unreleased
166 * reference remains at the end of the program, the verifier rejects it.
169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
170 struct bpf_verifier_stack_elem {
171 /* verifer state is 'st'
172 * before processing instruction 'insn_idx'
173 * and after processing instruction 'prev_insn_idx'
175 struct bpf_verifier_state st;
178 struct bpf_verifier_stack_elem *next;
179 /* length of verifier log at the time this state was pushed on stack */
183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
184 #define BPF_COMPLEXITY_LIMIT_STATES 64
186 #define BPF_MAP_KEY_POISON (1ULL << 63)
187 #define BPF_MAP_KEY_SEEN (1ULL << 62)
189 #define BPF_MAP_PTR_UNPRIV 1UL
190 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
191 POISON_POINTER_DELTA))
192 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
198 static int ref_set_non_owning(struct bpf_verifier_env *env,
199 struct bpf_reg_state *reg);
200 static void specialize_kfunc(struct bpf_verifier_env *env,
201 u32 func_id, u16 offset, unsigned long *addr);
202 static bool is_trusted_reg(const struct bpf_reg_state *reg);
204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
206 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
211 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
215 const struct bpf_map *map, bool unpriv)
217 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
218 unpriv |= bpf_map_ptr_unpriv(aux);
219 aux->map_ptr_state = (unsigned long)map |
220 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
225 return aux->map_key_state & BPF_MAP_KEY_POISON;
228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
230 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
235 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
240 bool poisoned = bpf_map_key_poisoned(aux);
242 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
243 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
246 static bool bpf_helper_call(const struct bpf_insn *insn)
248 return insn->code == (BPF_JMP | BPF_CALL) &&
252 static bool bpf_pseudo_call(const struct bpf_insn *insn)
254 return insn->code == (BPF_JMP | BPF_CALL) &&
255 insn->src_reg == BPF_PSEUDO_CALL;
258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
260 return insn->code == (BPF_JMP | BPF_CALL) &&
261 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
264 struct bpf_call_arg_meta {
265 struct bpf_map *map_ptr;
282 struct btf_field *kptr_field;
285 struct bpf_kfunc_call_arg_meta {
290 const struct btf_type *func_proto;
291 const char *func_name;
304 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
305 * generally to pass info about user-defined local kptr types to later
307 * bpf_obj_drop/bpf_percpu_obj_drop
308 * Record the local kptr type to be drop'd
309 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
310 * Record the local kptr type to be refcount_incr'd and use
311 * arg_owning_ref to determine whether refcount_acquire should be
319 struct btf_field *field;
322 struct btf_field *field;
325 enum bpf_dynptr_type type;
328 } initialized_dynptr;
336 struct btf *btf_vmlinux;
338 static DEFINE_MUTEX(bpf_verifier_lock);
340 static const struct bpf_line_info *
341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
343 const struct bpf_line_info *linfo;
344 const struct bpf_prog *prog;
348 nr_linfo = prog->aux->nr_linfo;
350 if (!nr_linfo || insn_off >= prog->len)
353 linfo = prog->aux->linfo;
354 for (i = 1; i < nr_linfo; i++)
355 if (insn_off < linfo[i].insn_off)
358 return &linfo[i - 1];
361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
363 struct bpf_verifier_env *env = private_data;
366 if (!bpf_verifier_log_needed(&env->log))
370 bpf_verifier_vlog(&env->log, fmt, args);
374 static const char *ltrim(const char *s)
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
384 const char *prefix_fmt, ...)
386 const struct bpf_line_info *linfo;
388 if (!bpf_verifier_log_needed(&env->log))
391 linfo = find_linfo(env, insn_off);
392 if (!linfo || linfo == env->prev_linfo)
398 va_start(args, prefix_fmt);
399 bpf_verifier_vlog(&env->log, prefix_fmt, args);
404 ltrim(btf_name_by_offset(env->prog->aux->btf,
407 env->prev_linfo = linfo;
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411 struct bpf_reg_state *reg,
412 struct tnum *range, const char *ctx,
413 const char *reg_name)
417 verbose(env, "At %s the register %s ", ctx, reg_name);
418 if (!tnum_is_unknown(reg->var_off)) {
419 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420 verbose(env, "has value %s", tn_buf);
422 verbose(env, "has unknown scalar value");
424 tnum_strn(tn_buf, sizeof(tn_buf), *range);
425 verbose(env, " should have been in %s\n", tn_buf);
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
430 type = base_type(type);
431 return type == PTR_TO_PACKET ||
432 type == PTR_TO_PACKET_META;
435 static bool type_is_sk_pointer(enum bpf_reg_type type)
437 return type == PTR_TO_SOCKET ||
438 type == PTR_TO_SOCK_COMMON ||
439 type == PTR_TO_TCP_SOCK ||
440 type == PTR_TO_XDP_SOCK;
443 static bool type_may_be_null(u32 type)
445 return type & PTR_MAYBE_NULL;
448 static bool reg_not_null(const struct bpf_reg_state *reg)
450 enum bpf_reg_type type;
453 if (type_may_be_null(type))
456 type = base_type(type);
457 return type == PTR_TO_SOCKET ||
458 type == PTR_TO_TCP_SOCK ||
459 type == PTR_TO_MAP_VALUE ||
460 type == PTR_TO_MAP_KEY ||
461 type == PTR_TO_SOCK_COMMON ||
462 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
466 static bool type_is_ptr_alloc_obj(u32 type)
468 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
471 static bool type_is_non_owning_ref(u32 type)
473 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
478 struct btf_record *rec = NULL;
479 struct btf_struct_meta *meta;
481 if (reg->type == PTR_TO_MAP_VALUE) {
482 rec = reg->map_ptr->record;
483 } else if (type_is_ptr_alloc_obj(reg->type)) {
484 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
493 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
495 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
500 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
503 static bool type_is_rdonly_mem(u32 type)
505 return type & MEM_RDONLY;
508 static bool is_acquire_function(enum bpf_func_id func_id,
509 const struct bpf_map *map)
511 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
513 if (func_id == BPF_FUNC_sk_lookup_tcp ||
514 func_id == BPF_FUNC_sk_lookup_udp ||
515 func_id == BPF_FUNC_skc_lookup_tcp ||
516 func_id == BPF_FUNC_ringbuf_reserve ||
517 func_id == BPF_FUNC_kptr_xchg)
520 if (func_id == BPF_FUNC_map_lookup_elem &&
521 (map_type == BPF_MAP_TYPE_SOCKMAP ||
522 map_type == BPF_MAP_TYPE_SOCKHASH))
528 static bool is_ptr_cast_function(enum bpf_func_id func_id)
530 return func_id == BPF_FUNC_tcp_sock ||
531 func_id == BPF_FUNC_sk_fullsock ||
532 func_id == BPF_FUNC_skc_to_tcp_sock ||
533 func_id == BPF_FUNC_skc_to_tcp6_sock ||
534 func_id == BPF_FUNC_skc_to_udp6_sock ||
535 func_id == BPF_FUNC_skc_to_mptcp_sock ||
536 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537 func_id == BPF_FUNC_skc_to_tcp_request_sock;
540 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
542 return func_id == BPF_FUNC_dynptr_data;
545 static bool is_callback_calling_kfunc(u32 btf_id);
546 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
548 static bool is_callback_calling_function(enum bpf_func_id func_id)
550 return func_id == BPF_FUNC_for_each_map_elem ||
551 func_id == BPF_FUNC_timer_set_callback ||
552 func_id == BPF_FUNC_find_vma ||
553 func_id == BPF_FUNC_loop ||
554 func_id == BPF_FUNC_user_ringbuf_drain;
557 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
559 return func_id == BPF_FUNC_timer_set_callback;
562 static bool is_storage_get_function(enum bpf_func_id func_id)
564 return func_id == BPF_FUNC_sk_storage_get ||
565 func_id == BPF_FUNC_inode_storage_get ||
566 func_id == BPF_FUNC_task_storage_get ||
567 func_id == BPF_FUNC_cgrp_storage_get;
570 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
571 const struct bpf_map *map)
573 int ref_obj_uses = 0;
575 if (is_ptr_cast_function(func_id))
577 if (is_acquire_function(func_id, map))
579 if (is_dynptr_ref_function(func_id))
582 return ref_obj_uses > 1;
585 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
587 return BPF_CLASS(insn->code) == BPF_STX &&
588 BPF_MODE(insn->code) == BPF_ATOMIC &&
589 insn->imm == BPF_CMPXCHG;
592 /* string representation of 'enum bpf_reg_type'
594 * Note that reg_type_str() can not appear more than once in a single verbose()
597 static const char *reg_type_str(struct bpf_verifier_env *env,
598 enum bpf_reg_type type)
600 char postfix[16] = {0}, prefix[64] = {0};
601 static const char * const str[] = {
603 [SCALAR_VALUE] = "scalar",
604 [PTR_TO_CTX] = "ctx",
605 [CONST_PTR_TO_MAP] = "map_ptr",
606 [PTR_TO_MAP_VALUE] = "map_value",
607 [PTR_TO_STACK] = "fp",
608 [PTR_TO_PACKET] = "pkt",
609 [PTR_TO_PACKET_META] = "pkt_meta",
610 [PTR_TO_PACKET_END] = "pkt_end",
611 [PTR_TO_FLOW_KEYS] = "flow_keys",
612 [PTR_TO_SOCKET] = "sock",
613 [PTR_TO_SOCK_COMMON] = "sock_common",
614 [PTR_TO_TCP_SOCK] = "tcp_sock",
615 [PTR_TO_TP_BUFFER] = "tp_buffer",
616 [PTR_TO_XDP_SOCK] = "xdp_sock",
617 [PTR_TO_BTF_ID] = "ptr_",
618 [PTR_TO_MEM] = "mem",
619 [PTR_TO_BUF] = "buf",
620 [PTR_TO_FUNC] = "func",
621 [PTR_TO_MAP_KEY] = "map_key",
622 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr",
625 if (type & PTR_MAYBE_NULL) {
626 if (base_type(type) == PTR_TO_BTF_ID)
627 strncpy(postfix, "or_null_", 16);
629 strncpy(postfix, "_or_null", 16);
632 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
633 type & MEM_RDONLY ? "rdonly_" : "",
634 type & MEM_RINGBUF ? "ringbuf_" : "",
635 type & MEM_USER ? "user_" : "",
636 type & MEM_PERCPU ? "percpu_" : "",
637 type & MEM_RCU ? "rcu_" : "",
638 type & PTR_UNTRUSTED ? "untrusted_" : "",
639 type & PTR_TRUSTED ? "trusted_" : ""
642 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
643 prefix, str[base_type(type)], postfix);
644 return env->tmp_str_buf;
647 static char slot_type_char[] = {
648 [STACK_INVALID] = '?',
652 [STACK_DYNPTR] = 'd',
656 static void print_liveness(struct bpf_verifier_env *env,
657 enum bpf_reg_liveness live)
659 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
661 if (live & REG_LIVE_READ)
663 if (live & REG_LIVE_WRITTEN)
665 if (live & REG_LIVE_DONE)
669 static int __get_spi(s32 off)
671 return (-off - 1) / BPF_REG_SIZE;
674 static struct bpf_func_state *func(struct bpf_verifier_env *env,
675 const struct bpf_reg_state *reg)
677 struct bpf_verifier_state *cur = env->cur_state;
679 return cur->frame[reg->frameno];
682 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
684 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
686 /* We need to check that slots between [spi - nr_slots + 1, spi] are
687 * within [0, allocated_stack).
689 * Please note that the spi grows downwards. For example, a dynptr
690 * takes the size of two stack slots; the first slot will be at
691 * spi and the second slot will be at spi - 1.
693 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
696 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
697 const char *obj_kind, int nr_slots)
701 if (!tnum_is_const(reg->var_off)) {
702 verbose(env, "%s has to be at a constant offset\n", obj_kind);
706 off = reg->off + reg->var_off.value;
707 if (off % BPF_REG_SIZE) {
708 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
712 spi = __get_spi(off);
713 if (spi + 1 < nr_slots) {
714 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
718 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
723 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
725 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
728 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
730 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
733 static const char *btf_type_name(const struct btf *btf, u32 id)
735 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
738 static const char *dynptr_type_str(enum bpf_dynptr_type type)
741 case BPF_DYNPTR_TYPE_LOCAL:
743 case BPF_DYNPTR_TYPE_RINGBUF:
745 case BPF_DYNPTR_TYPE_SKB:
747 case BPF_DYNPTR_TYPE_XDP:
749 case BPF_DYNPTR_TYPE_INVALID:
752 WARN_ONCE(1, "unknown dynptr type %d\n", type);
757 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
759 if (!btf || btf_id == 0)
762 /* we already validated that type is valid and has conforming name */
763 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
766 static const char *iter_state_str(enum bpf_iter_state state)
769 case BPF_ITER_STATE_ACTIVE:
771 case BPF_ITER_STATE_DRAINED:
773 case BPF_ITER_STATE_INVALID:
776 WARN_ONCE(1, "unknown iter state %d\n", state);
781 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
783 env->scratched_regs |= 1U << regno;
786 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
788 env->scratched_stack_slots |= 1ULL << spi;
791 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
793 return (env->scratched_regs >> regno) & 1;
796 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
798 return (env->scratched_stack_slots >> regno) & 1;
801 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
803 return env->scratched_regs || env->scratched_stack_slots;
806 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
808 env->scratched_regs = 0U;
809 env->scratched_stack_slots = 0ULL;
812 /* Used for printing the entire verifier state. */
813 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
815 env->scratched_regs = ~0U;
816 env->scratched_stack_slots = ~0ULL;
819 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
821 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
822 case DYNPTR_TYPE_LOCAL:
823 return BPF_DYNPTR_TYPE_LOCAL;
824 case DYNPTR_TYPE_RINGBUF:
825 return BPF_DYNPTR_TYPE_RINGBUF;
826 case DYNPTR_TYPE_SKB:
827 return BPF_DYNPTR_TYPE_SKB;
828 case DYNPTR_TYPE_XDP:
829 return BPF_DYNPTR_TYPE_XDP;
831 return BPF_DYNPTR_TYPE_INVALID;
835 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
838 case BPF_DYNPTR_TYPE_LOCAL:
839 return DYNPTR_TYPE_LOCAL;
840 case BPF_DYNPTR_TYPE_RINGBUF:
841 return DYNPTR_TYPE_RINGBUF;
842 case BPF_DYNPTR_TYPE_SKB:
843 return DYNPTR_TYPE_SKB;
844 case BPF_DYNPTR_TYPE_XDP:
845 return DYNPTR_TYPE_XDP;
851 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
853 return type == BPF_DYNPTR_TYPE_RINGBUF;
856 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
857 enum bpf_dynptr_type type,
858 bool first_slot, int dynptr_id);
860 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
861 struct bpf_reg_state *reg);
863 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
864 struct bpf_reg_state *sreg1,
865 struct bpf_reg_state *sreg2,
866 enum bpf_dynptr_type type)
868 int id = ++env->id_gen;
870 __mark_dynptr_reg(sreg1, type, true, id);
871 __mark_dynptr_reg(sreg2, type, false, id);
874 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
875 struct bpf_reg_state *reg,
876 enum bpf_dynptr_type type)
878 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
881 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
882 struct bpf_func_state *state, int spi);
884 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
885 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
887 struct bpf_func_state *state = func(env, reg);
888 enum bpf_dynptr_type type;
891 spi = dynptr_get_spi(env, reg);
895 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
896 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
897 * to ensure that for the following example:
900 * So marking spi = 2 should lead to destruction of both d1 and d2. In
901 * case they do belong to same dynptr, second call won't see slot_type
902 * as STACK_DYNPTR and will simply skip destruction.
904 err = destroy_if_dynptr_stack_slot(env, state, spi);
907 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
911 for (i = 0; i < BPF_REG_SIZE; i++) {
912 state->stack[spi].slot_type[i] = STACK_DYNPTR;
913 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
916 type = arg_to_dynptr_type(arg_type);
917 if (type == BPF_DYNPTR_TYPE_INVALID)
920 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
921 &state->stack[spi - 1].spilled_ptr, type);
923 if (dynptr_type_refcounted(type)) {
924 /* The id is used to track proper releasing */
927 if (clone_ref_obj_id)
928 id = clone_ref_obj_id;
930 id = acquire_reference_state(env, insn_idx);
935 state->stack[spi].spilled_ptr.ref_obj_id = id;
936 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
939 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
940 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
945 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
949 for (i = 0; i < BPF_REG_SIZE; i++) {
950 state->stack[spi].slot_type[i] = STACK_INVALID;
951 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
954 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
955 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
957 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
959 * While we don't allow reading STACK_INVALID, it is still possible to
960 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
961 * helpers or insns can do partial read of that part without failing,
962 * but check_stack_range_initialized, check_stack_read_var_off, and
963 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
964 * the slot conservatively. Hence we need to prevent those liveness
967 * This was not a problem before because STACK_INVALID is only set by
968 * default (where the default reg state has its reg->parent as NULL), or
969 * in clean_live_states after REG_LIVE_DONE (at which point
970 * mark_reg_read won't walk reg->parent chain), but not randomly during
971 * verifier state exploration (like we did above). Hence, for our case
972 * parentage chain will still be live (i.e. reg->parent may be
973 * non-NULL), while earlier reg->parent was NULL, so we need
974 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
975 * done later on reads or by mark_dynptr_read as well to unnecessary
976 * mark registers in verifier state.
978 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
979 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
982 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
984 struct bpf_func_state *state = func(env, reg);
985 int spi, ref_obj_id, i;
987 spi = dynptr_get_spi(env, reg);
991 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
992 invalidate_dynptr(env, state, spi);
996 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
998 /* If the dynptr has a ref_obj_id, then we need to invalidate
1001 * 1) Any dynptrs with a matching ref_obj_id (clones)
1002 * 2) Any slices derived from this dynptr.
1005 /* Invalidate any slices associated with this dynptr */
1006 WARN_ON_ONCE(release_reference(env, ref_obj_id));
1008 /* Invalidate any dynptr clones */
1009 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1010 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1013 /* it should always be the case that if the ref obj id
1014 * matches then the stack slot also belongs to a
1017 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1018 verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1021 if (state->stack[i].spilled_ptr.dynptr.first_slot)
1022 invalidate_dynptr(env, state, i);
1028 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1029 struct bpf_reg_state *reg);
1031 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1033 if (!env->allow_ptr_leaks)
1034 __mark_reg_not_init(env, reg);
1036 __mark_reg_unknown(env, reg);
1039 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1040 struct bpf_func_state *state, int spi)
1042 struct bpf_func_state *fstate;
1043 struct bpf_reg_state *dreg;
1046 /* We always ensure that STACK_DYNPTR is never set partially,
1047 * hence just checking for slot_type[0] is enough. This is
1048 * different for STACK_SPILL, where it may be only set for
1049 * 1 byte, so code has to use is_spilled_reg.
1051 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1054 /* Reposition spi to first slot */
1055 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1058 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1059 verbose(env, "cannot overwrite referenced dynptr\n");
1063 mark_stack_slot_scratched(env, spi);
1064 mark_stack_slot_scratched(env, spi - 1);
1066 /* Writing partially to one dynptr stack slot destroys both. */
1067 for (i = 0; i < BPF_REG_SIZE; i++) {
1068 state->stack[spi].slot_type[i] = STACK_INVALID;
1069 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1072 dynptr_id = state->stack[spi].spilled_ptr.id;
1073 /* Invalidate any slices associated with this dynptr */
1074 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1075 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1076 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1078 if (dreg->dynptr_id == dynptr_id)
1079 mark_reg_invalid(env, dreg);
1082 /* Do not release reference state, we are destroying dynptr on stack,
1083 * not using some helper to release it. Just reset register.
1085 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1086 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1088 /* Same reason as unmark_stack_slots_dynptr above */
1089 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1090 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1095 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1099 if (reg->type == CONST_PTR_TO_DYNPTR)
1102 spi = dynptr_get_spi(env, reg);
1104 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1105 * error because this just means the stack state hasn't been updated yet.
1106 * We will do check_mem_access to check and update stack bounds later.
1108 if (spi < 0 && spi != -ERANGE)
1111 /* We don't need to check if the stack slots are marked by previous
1112 * dynptr initializations because we allow overwriting existing unreferenced
1113 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1114 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1115 * touching are completely destructed before we reinitialize them for a new
1116 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1117 * instead of delaying it until the end where the user will get "Unreleased
1123 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1125 struct bpf_func_state *state = func(env, reg);
1128 /* This already represents first slot of initialized bpf_dynptr.
1130 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1131 * check_func_arg_reg_off's logic, so we don't need to check its
1132 * offset and alignment.
1134 if (reg->type == CONST_PTR_TO_DYNPTR)
1137 spi = dynptr_get_spi(env, reg);
1140 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1143 for (i = 0; i < BPF_REG_SIZE; i++) {
1144 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1145 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1152 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1153 enum bpf_arg_type arg_type)
1155 struct bpf_func_state *state = func(env, reg);
1156 enum bpf_dynptr_type dynptr_type;
1159 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1160 if (arg_type == ARG_PTR_TO_DYNPTR)
1163 dynptr_type = arg_to_dynptr_type(arg_type);
1164 if (reg->type == CONST_PTR_TO_DYNPTR) {
1165 return reg->dynptr.type == dynptr_type;
1167 spi = dynptr_get_spi(env, reg);
1170 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1174 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1176 static bool in_rcu_cs(struct bpf_verifier_env *env);
1178 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1180 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1181 struct bpf_kfunc_call_arg_meta *meta,
1182 struct bpf_reg_state *reg, int insn_idx,
1183 struct btf *btf, u32 btf_id, int nr_slots)
1185 struct bpf_func_state *state = func(env, reg);
1188 spi = iter_get_spi(env, reg, nr_slots);
1192 id = acquire_reference_state(env, insn_idx);
1196 for (i = 0; i < nr_slots; i++) {
1197 struct bpf_stack_state *slot = &state->stack[spi - i];
1198 struct bpf_reg_state *st = &slot->spilled_ptr;
1200 __mark_reg_known_zero(st);
1201 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1202 if (is_kfunc_rcu_protected(meta)) {
1204 st->type |= MEM_RCU;
1206 st->type |= PTR_UNTRUSTED;
1208 st->live |= REG_LIVE_WRITTEN;
1209 st->ref_obj_id = i == 0 ? id : 0;
1211 st->iter.btf_id = btf_id;
1212 st->iter.state = BPF_ITER_STATE_ACTIVE;
1215 for (j = 0; j < BPF_REG_SIZE; j++)
1216 slot->slot_type[j] = STACK_ITER;
1218 mark_stack_slot_scratched(env, spi - i);
1224 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1225 struct bpf_reg_state *reg, int nr_slots)
1227 struct bpf_func_state *state = func(env, reg);
1230 spi = iter_get_spi(env, reg, nr_slots);
1234 for (i = 0; i < nr_slots; i++) {
1235 struct bpf_stack_state *slot = &state->stack[spi - i];
1236 struct bpf_reg_state *st = &slot->spilled_ptr;
1239 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1241 __mark_reg_not_init(env, st);
1243 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1244 st->live |= REG_LIVE_WRITTEN;
1246 for (j = 0; j < BPF_REG_SIZE; j++)
1247 slot->slot_type[j] = STACK_INVALID;
1249 mark_stack_slot_scratched(env, spi - i);
1255 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1256 struct bpf_reg_state *reg, int nr_slots)
1258 struct bpf_func_state *state = func(env, reg);
1261 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1262 * will do check_mem_access to check and update stack bounds later, so
1263 * return true for that case.
1265 spi = iter_get_spi(env, reg, nr_slots);
1271 for (i = 0; i < nr_slots; i++) {
1272 struct bpf_stack_state *slot = &state->stack[spi - i];
1274 for (j = 0; j < BPF_REG_SIZE; j++)
1275 if (slot->slot_type[j] == STACK_ITER)
1282 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1283 struct btf *btf, u32 btf_id, int nr_slots)
1285 struct bpf_func_state *state = func(env, reg);
1288 spi = iter_get_spi(env, reg, nr_slots);
1292 for (i = 0; i < nr_slots; i++) {
1293 struct bpf_stack_state *slot = &state->stack[spi - i];
1294 struct bpf_reg_state *st = &slot->spilled_ptr;
1296 if (st->type & PTR_UNTRUSTED)
1298 /* only main (first) slot has ref_obj_id set */
1299 if (i == 0 && !st->ref_obj_id)
1301 if (i != 0 && st->ref_obj_id)
1303 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1306 for (j = 0; j < BPF_REG_SIZE; j++)
1307 if (slot->slot_type[j] != STACK_ITER)
1314 /* Check if given stack slot is "special":
1315 * - spilled register state (STACK_SPILL);
1316 * - dynptr state (STACK_DYNPTR);
1317 * - iter state (STACK_ITER).
1319 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1321 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1333 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1338 /* The reg state of a pointer or a bounded scalar was saved when
1339 * it was spilled to the stack.
1341 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1343 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1346 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1348 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1349 stack->spilled_ptr.type == SCALAR_VALUE;
1352 static void scrub_spilled_slot(u8 *stype)
1354 if (*stype != STACK_INVALID)
1355 *stype = STACK_MISC;
1358 static void print_scalar_ranges(struct bpf_verifier_env *env,
1359 const struct bpf_reg_state *reg,
1367 {"smin", reg->smin_value, reg->smin_value == S64_MIN},
1368 {"smax", reg->smax_value, reg->smax_value == S64_MAX},
1369 {"umin", reg->umin_value, reg->umin_value == 0},
1370 {"umax", reg->umax_value, reg->umax_value == U64_MAX},
1371 {"smin32", (s64)reg->s32_min_value, reg->s32_min_value == S32_MIN},
1372 {"smax32", (s64)reg->s32_max_value, reg->s32_max_value == S32_MAX},
1373 {"umin32", reg->u32_min_value, reg->u32_min_value == 0},
1374 {"umax32", reg->u32_max_value, reg->u32_max_value == U32_MAX},
1375 }, *m1, *m2, *mend = &minmaxs[ARRAY_SIZE(minmaxs)];
1378 for (m1 = &minmaxs[0]; m1 < mend; m1++) {
1382 neg1 = m1->name[0] == 's' && (s64)m1->val < 0;
1384 verbose(env, "%s%s=", *sep, m1->name);
1387 for (m2 = m1 + 2; m2 < mend; m2 += 2) {
1388 if (m2->omit || m2->val != m1->val)
1390 /* don't mix negatives with positives */
1391 neg2 = m2->name[0] == 's' && (s64)m2->val < 0;
1395 verbose(env, "%s=", m2->name);
1398 verbose(env, m1->name[0] == 's' ? "%lld" : "%llu", m1->val);
1402 static void print_verifier_state(struct bpf_verifier_env *env,
1403 const struct bpf_func_state *state,
1406 const struct bpf_reg_state *reg;
1407 enum bpf_reg_type t;
1411 verbose(env, " frame%d:", state->frameno);
1412 for (i = 0; i < MAX_BPF_REG; i++) {
1413 reg = &state->regs[i];
1417 if (!print_all && !reg_scratched(env, i))
1419 verbose(env, " R%d", i);
1420 print_liveness(env, reg->live);
1422 if (t == SCALAR_VALUE && reg->precise)
1424 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1425 tnum_is_const(reg->var_off)) {
1426 /* reg->off should be 0 for SCALAR_VALUE */
1427 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1428 verbose(env, "%lld", reg->var_off.value + reg->off);
1430 const char *sep = "";
1432 verbose(env, "%s", reg_type_str(env, t));
1433 if (base_type(t) == PTR_TO_BTF_ID)
1434 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1437 * _a stands for append, was shortened to avoid multiline statements below.
1438 * This macro is used to output a comma separated list of attributes.
1440 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1443 verbose_a("id=%d", reg->id);
1444 if (reg->ref_obj_id)
1445 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1446 if (type_is_non_owning_ref(reg->type))
1447 verbose_a("%s", "non_own_ref");
1448 if (t != SCALAR_VALUE)
1449 verbose_a("off=%d", reg->off);
1450 if (type_is_pkt_pointer(t))
1451 verbose_a("r=%d", reg->range);
1452 else if (base_type(t) == CONST_PTR_TO_MAP ||
1453 base_type(t) == PTR_TO_MAP_KEY ||
1454 base_type(t) == PTR_TO_MAP_VALUE)
1455 verbose_a("ks=%d,vs=%d",
1456 reg->map_ptr->key_size,
1457 reg->map_ptr->value_size);
1458 if (tnum_is_const(reg->var_off)) {
1459 /* Typically an immediate SCALAR_VALUE, but
1460 * could be a pointer whose offset is too big
1463 verbose_a("imm=%llx", reg->var_off.value);
1465 print_scalar_ranges(env, reg, &sep);
1466 if (!tnum_is_unknown(reg->var_off)) {
1469 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1470 verbose_a("var_off=%s", tn_buf);
1478 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1479 char types_buf[BPF_REG_SIZE + 1];
1483 for (j = 0; j < BPF_REG_SIZE; j++) {
1484 if (state->stack[i].slot_type[j] != STACK_INVALID)
1486 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1488 types_buf[BPF_REG_SIZE] = 0;
1491 if (!print_all && !stack_slot_scratched(env, i))
1493 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1495 reg = &state->stack[i].spilled_ptr;
1498 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1499 print_liveness(env, reg->live);
1500 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1501 if (t == SCALAR_VALUE && reg->precise)
1503 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1504 verbose(env, "%lld", reg->var_off.value + reg->off);
1507 i += BPF_DYNPTR_NR_SLOTS - 1;
1508 reg = &state->stack[i].spilled_ptr;
1510 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1511 print_liveness(env, reg->live);
1512 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1513 if (reg->ref_obj_id)
1514 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1517 /* only main slot has ref_obj_id set; skip others */
1518 reg = &state->stack[i].spilled_ptr;
1519 if (!reg->ref_obj_id)
1522 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1523 print_liveness(env, reg->live);
1524 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1525 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1526 reg->ref_obj_id, iter_state_str(reg->iter.state),
1532 reg = &state->stack[i].spilled_ptr;
1534 for (j = 0; j < BPF_REG_SIZE; j++)
1535 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1536 types_buf[BPF_REG_SIZE] = 0;
1538 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1539 print_liveness(env, reg->live);
1540 verbose(env, "=%s", types_buf);
1544 if (state->acquired_refs && state->refs[0].id) {
1545 verbose(env, " refs=%d", state->refs[0].id);
1546 for (i = 1; i < state->acquired_refs; i++)
1547 if (state->refs[i].id)
1548 verbose(env, ",%d", state->refs[i].id);
1550 if (state->in_callback_fn)
1551 verbose(env, " cb");
1552 if (state->in_async_callback_fn)
1553 verbose(env, " async_cb");
1556 mark_verifier_state_clean(env);
1559 static inline u32 vlog_alignment(u32 pos)
1561 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1562 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1565 static void print_insn_state(struct bpf_verifier_env *env,
1566 const struct bpf_func_state *state)
1568 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1569 /* remove new line character */
1570 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1571 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1573 verbose(env, "%d:", env->insn_idx);
1575 print_verifier_state(env, state, false);
1578 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1579 * small to hold src. This is different from krealloc since we don't want to preserve
1580 * the contents of dst.
1582 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1585 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1591 if (ZERO_OR_NULL_PTR(src))
1594 if (unlikely(check_mul_overflow(n, size, &bytes)))
1597 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1598 dst = krealloc(orig, alloc_bytes, flags);
1604 memcpy(dst, src, bytes);
1606 return dst ? dst : ZERO_SIZE_PTR;
1609 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1610 * small to hold new_n items. new items are zeroed out if the array grows.
1612 * Contrary to krealloc_array, does not free arr if new_n is zero.
1614 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1619 if (!new_n || old_n == new_n)
1622 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1623 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1631 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1634 return arr ? arr : ZERO_SIZE_PTR;
1637 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1639 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1640 sizeof(struct bpf_reference_state), GFP_KERNEL);
1644 dst->acquired_refs = src->acquired_refs;
1648 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1650 size_t n = src->allocated_stack / BPF_REG_SIZE;
1652 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1657 dst->allocated_stack = src->allocated_stack;
1661 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1663 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1664 sizeof(struct bpf_reference_state));
1668 state->acquired_refs = n;
1672 static int grow_stack_state(struct bpf_func_state *state, int size)
1674 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1679 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1683 state->allocated_stack = size;
1687 /* Acquire a pointer id from the env and update the state->refs to include
1688 * this new pointer reference.
1689 * On success, returns a valid pointer id to associate with the register
1690 * On failure, returns a negative errno.
1692 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1694 struct bpf_func_state *state = cur_func(env);
1695 int new_ofs = state->acquired_refs;
1698 err = resize_reference_state(state, state->acquired_refs + 1);
1702 state->refs[new_ofs].id = id;
1703 state->refs[new_ofs].insn_idx = insn_idx;
1704 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1709 /* release function corresponding to acquire_reference_state(). Idempotent. */
1710 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1714 last_idx = state->acquired_refs - 1;
1715 for (i = 0; i < state->acquired_refs; i++) {
1716 if (state->refs[i].id == ptr_id) {
1717 /* Cannot release caller references in callbacks */
1718 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1720 if (last_idx && i != last_idx)
1721 memcpy(&state->refs[i], &state->refs[last_idx],
1722 sizeof(*state->refs));
1723 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1724 state->acquired_refs--;
1731 static void free_func_state(struct bpf_func_state *state)
1736 kfree(state->stack);
1740 static void clear_jmp_history(struct bpf_verifier_state *state)
1742 kfree(state->jmp_history);
1743 state->jmp_history = NULL;
1744 state->jmp_history_cnt = 0;
1747 static void free_verifier_state(struct bpf_verifier_state *state,
1752 for (i = 0; i <= state->curframe; i++) {
1753 free_func_state(state->frame[i]);
1754 state->frame[i] = NULL;
1756 clear_jmp_history(state);
1761 /* copy verifier state from src to dst growing dst stack space
1762 * when necessary to accommodate larger src stack
1764 static int copy_func_state(struct bpf_func_state *dst,
1765 const struct bpf_func_state *src)
1769 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1770 err = copy_reference_state(dst, src);
1773 return copy_stack_state(dst, src);
1776 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1777 const struct bpf_verifier_state *src)
1779 struct bpf_func_state *dst;
1782 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1783 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1785 if (!dst_state->jmp_history)
1787 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1789 /* if dst has more stack frames then src frame, free them, this is also
1790 * necessary in case of exceptional exits using bpf_throw.
1792 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1793 free_func_state(dst_state->frame[i]);
1794 dst_state->frame[i] = NULL;
1796 dst_state->speculative = src->speculative;
1797 dst_state->active_rcu_lock = src->active_rcu_lock;
1798 dst_state->curframe = src->curframe;
1799 dst_state->active_lock.ptr = src->active_lock.ptr;
1800 dst_state->active_lock.id = src->active_lock.id;
1801 dst_state->branches = src->branches;
1802 dst_state->parent = src->parent;
1803 dst_state->first_insn_idx = src->first_insn_idx;
1804 dst_state->last_insn_idx = src->last_insn_idx;
1805 dst_state->dfs_depth = src->dfs_depth;
1806 dst_state->used_as_loop_entry = src->used_as_loop_entry;
1807 for (i = 0; i <= src->curframe; i++) {
1808 dst = dst_state->frame[i];
1810 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1813 dst_state->frame[i] = dst;
1815 err = copy_func_state(dst, src->frame[i]);
1822 static u32 state_htab_size(struct bpf_verifier_env *env)
1824 return env->prog->len;
1827 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1829 struct bpf_verifier_state *cur = env->cur_state;
1830 struct bpf_func_state *state = cur->frame[cur->curframe];
1832 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1835 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1839 if (a->curframe != b->curframe)
1842 for (fr = a->curframe; fr >= 0; fr--)
1843 if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1849 /* Open coded iterators allow back-edges in the state graph in order to
1850 * check unbounded loops that iterators.
1852 * In is_state_visited() it is necessary to know if explored states are
1853 * part of some loops in order to decide whether non-exact states
1854 * comparison could be used:
1855 * - non-exact states comparison establishes sub-state relation and uses
1856 * read and precision marks to do so, these marks are propagated from
1857 * children states and thus are not guaranteed to be final in a loop;
1858 * - exact states comparison just checks if current and explored states
1859 * are identical (and thus form a back-edge).
1861 * Paper "A New Algorithm for Identifying Loops in Decompilation"
1862 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1863 * algorithm for loop structure detection and gives an overview of
1864 * relevant terminology. It also has helpful illustrations.
1866 * [1] https://api.semanticscholar.org/CorpusID:15784067
1868 * We use a similar algorithm but because loop nested structure is
1869 * irrelevant for verifier ours is significantly simpler and resembles
1870 * strongly connected components algorithm from Sedgewick's textbook.
1872 * Define topmost loop entry as a first node of the loop traversed in a
1873 * depth first search starting from initial state. The goal of the loop
1874 * tracking algorithm is to associate topmost loop entries with states
1875 * derived from these entries.
1877 * For each step in the DFS states traversal algorithm needs to identify
1878 * the following situations:
1880 * initial initial initial
1883 * ... ... .---------> hdr
1886 * cur .-> succ | .------...
1889 * succ '-- cur | ... ...
1899 * (A) successor state of cur (B) successor state of cur or it's entry
1900 * not yet traversed are in current DFS path, thus cur and succ
1901 * are members of the same outermost loop
1909 * .------... .------...
1912 * .-> hdr ... ... ...
1915 * | succ <- cur succ <- cur
1922 * (C) successor state of cur is a part of some loop but this loop
1923 * does not include cur or successor state is not in a loop at all.
1925 * Algorithm could be described as the following python code:
1927 * traversed = set() # Set of traversed nodes
1928 * entries = {} # Mapping from node to loop entry
1929 * depths = {} # Depth level assigned to graph node
1930 * path = set() # Current DFS path
1932 * # Find outermost loop entry known for n
1933 * def get_loop_entry(n):
1934 * h = entries.get(n, None)
1935 * while h in entries and entries[h] != h:
1939 * # Update n's loop entry if h's outermost entry comes
1940 * # before n's outermost entry in current DFS path.
1941 * def update_loop_entry(n, h):
1942 * n1 = get_loop_entry(n) or n
1943 * h1 = get_loop_entry(h) or h
1944 * if h1 in path and depths[h1] <= depths[n1]:
1947 * def dfs(n, depth):
1951 * for succ in G.successors(n):
1952 * if succ not in traversed:
1953 * # Case A: explore succ and update cur's loop entry
1954 * # only if succ's entry is in current DFS path.
1955 * dfs(succ, depth + 1)
1956 * h = get_loop_entry(succ)
1957 * update_loop_entry(n, h)
1959 * # Case B or C depending on `h1 in path` check in update_loop_entry().
1960 * update_loop_entry(n, succ)
1963 * To adapt this algorithm for use with verifier:
1964 * - use st->branch == 0 as a signal that DFS of succ had been finished
1965 * and cur's loop entry has to be updated (case A), handle this in
1966 * update_branch_counts();
1967 * - use st->branch > 0 as a signal that st is in the current DFS path;
1968 * - handle cases B and C in is_state_visited();
1969 * - update topmost loop entry for intermediate states in get_loop_entry().
1971 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1973 struct bpf_verifier_state *topmost = st->loop_entry, *old;
1975 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1976 topmost = topmost->loop_entry;
1977 /* Update loop entries for intermediate states to avoid this
1978 * traversal in future get_loop_entry() calls.
1980 while (st && st->loop_entry != topmost) {
1981 old = st->loop_entry;
1982 st->loop_entry = topmost;
1988 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1990 struct bpf_verifier_state *cur1, *hdr1;
1992 cur1 = get_loop_entry(cur) ?: cur;
1993 hdr1 = get_loop_entry(hdr) ?: hdr;
1994 /* The head1->branches check decides between cases B and C in
1995 * comment for get_loop_entry(). If hdr1->branches == 0 then
1996 * head's topmost loop entry is not in current DFS path,
1997 * hence 'cur' and 'hdr' are not in the same loop and there is
1998 * no need to update cur->loop_entry.
2000 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
2001 cur->loop_entry = hdr;
2002 hdr->used_as_loop_entry = true;
2006 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2009 u32 br = --st->branches;
2011 /* br == 0 signals that DFS exploration for 'st' is finished,
2012 * thus it is necessary to update parent's loop entry if it
2013 * turned out that st is a part of some loop.
2014 * This is a part of 'case A' in get_loop_entry() comment.
2016 if (br == 0 && st->parent && st->loop_entry)
2017 update_loop_entry(st->parent, st->loop_entry);
2019 /* WARN_ON(br > 1) technically makes sense here,
2020 * but see comment in push_stack(), hence:
2022 WARN_ONCE((int)br < 0,
2023 "BUG update_branch_counts:branches_to_explore=%d\n",
2031 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2032 int *insn_idx, bool pop_log)
2034 struct bpf_verifier_state *cur = env->cur_state;
2035 struct bpf_verifier_stack_elem *elem, *head = env->head;
2038 if (env->head == NULL)
2042 err = copy_verifier_state(cur, &head->st);
2047 bpf_vlog_reset(&env->log, head->log_pos);
2049 *insn_idx = head->insn_idx;
2051 *prev_insn_idx = head->prev_insn_idx;
2053 free_verifier_state(&head->st, false);
2060 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2061 int insn_idx, int prev_insn_idx,
2064 struct bpf_verifier_state *cur = env->cur_state;
2065 struct bpf_verifier_stack_elem *elem;
2068 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2072 elem->insn_idx = insn_idx;
2073 elem->prev_insn_idx = prev_insn_idx;
2074 elem->next = env->head;
2075 elem->log_pos = env->log.end_pos;
2078 err = copy_verifier_state(&elem->st, cur);
2081 elem->st.speculative |= speculative;
2082 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2083 verbose(env, "The sequence of %d jumps is too complex.\n",
2087 if (elem->st.parent) {
2088 ++elem->st.parent->branches;
2089 /* WARN_ON(branches > 2) technically makes sense here,
2091 * 1. speculative states will bump 'branches' for non-branch
2093 * 2. is_state_visited() heuristics may decide not to create
2094 * a new state for a sequence of branches and all such current
2095 * and cloned states will be pointing to a single parent state
2096 * which might have large 'branches' count.
2101 free_verifier_state(env->cur_state, true);
2102 env->cur_state = NULL;
2103 /* pop all elements and return */
2104 while (!pop_stack(env, NULL, NULL, false));
2108 #define CALLER_SAVED_REGS 6
2109 static const int caller_saved[CALLER_SAVED_REGS] = {
2110 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2113 /* This helper doesn't clear reg->id */
2114 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2116 reg->var_off = tnum_const(imm);
2117 reg->smin_value = (s64)imm;
2118 reg->smax_value = (s64)imm;
2119 reg->umin_value = imm;
2120 reg->umax_value = imm;
2122 reg->s32_min_value = (s32)imm;
2123 reg->s32_max_value = (s32)imm;
2124 reg->u32_min_value = (u32)imm;
2125 reg->u32_max_value = (u32)imm;
2128 /* Mark the unknown part of a register (variable offset or scalar value) as
2129 * known to have the value @imm.
2131 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2133 /* Clear off and union(map_ptr, range) */
2134 memset(((u8 *)reg) + sizeof(reg->type), 0,
2135 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2137 reg->ref_obj_id = 0;
2138 ___mark_reg_known(reg, imm);
2141 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2143 reg->var_off = tnum_const_subreg(reg->var_off, imm);
2144 reg->s32_min_value = (s32)imm;
2145 reg->s32_max_value = (s32)imm;
2146 reg->u32_min_value = (u32)imm;
2147 reg->u32_max_value = (u32)imm;
2150 /* Mark the 'variable offset' part of a register as zero. This should be
2151 * used only on registers holding a pointer type.
2153 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2155 __mark_reg_known(reg, 0);
2158 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
2160 __mark_reg_known(reg, 0);
2161 reg->type = SCALAR_VALUE;
2164 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2165 struct bpf_reg_state *regs, u32 regno)
2167 if (WARN_ON(regno >= MAX_BPF_REG)) {
2168 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2169 /* Something bad happened, let's kill all regs */
2170 for (regno = 0; regno < MAX_BPF_REG; regno++)
2171 __mark_reg_not_init(env, regs + regno);
2174 __mark_reg_known_zero(regs + regno);
2177 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2178 bool first_slot, int dynptr_id)
2180 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2181 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2182 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2184 __mark_reg_known_zero(reg);
2185 reg->type = CONST_PTR_TO_DYNPTR;
2186 /* Give each dynptr a unique id to uniquely associate slices to it. */
2187 reg->id = dynptr_id;
2188 reg->dynptr.type = type;
2189 reg->dynptr.first_slot = first_slot;
2192 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2194 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2195 const struct bpf_map *map = reg->map_ptr;
2197 if (map->inner_map_meta) {
2198 reg->type = CONST_PTR_TO_MAP;
2199 reg->map_ptr = map->inner_map_meta;
2200 /* transfer reg's id which is unique for every map_lookup_elem
2201 * as UID of the inner map.
2203 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2204 reg->map_uid = reg->id;
2205 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2206 reg->type = PTR_TO_XDP_SOCK;
2207 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2208 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2209 reg->type = PTR_TO_SOCKET;
2211 reg->type = PTR_TO_MAP_VALUE;
2216 reg->type &= ~PTR_MAYBE_NULL;
2219 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2220 struct btf_field_graph_root *ds_head)
2222 __mark_reg_known_zero(®s[regno]);
2223 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2224 regs[regno].btf = ds_head->btf;
2225 regs[regno].btf_id = ds_head->value_btf_id;
2226 regs[regno].off = ds_head->node_offset;
2229 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2231 return type_is_pkt_pointer(reg->type);
2234 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2236 return reg_is_pkt_pointer(reg) ||
2237 reg->type == PTR_TO_PACKET_END;
2240 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2242 return base_type(reg->type) == PTR_TO_MEM &&
2243 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2246 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2247 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2248 enum bpf_reg_type which)
2250 /* The register can already have a range from prior markings.
2251 * This is fine as long as it hasn't been advanced from its
2254 return reg->type == which &&
2257 tnum_equals_const(reg->var_off, 0);
2260 /* Reset the min/max bounds of a register */
2261 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2263 reg->smin_value = S64_MIN;
2264 reg->smax_value = S64_MAX;
2265 reg->umin_value = 0;
2266 reg->umax_value = U64_MAX;
2268 reg->s32_min_value = S32_MIN;
2269 reg->s32_max_value = S32_MAX;
2270 reg->u32_min_value = 0;
2271 reg->u32_max_value = U32_MAX;
2274 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2276 reg->smin_value = S64_MIN;
2277 reg->smax_value = S64_MAX;
2278 reg->umin_value = 0;
2279 reg->umax_value = U64_MAX;
2282 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2284 reg->s32_min_value = S32_MIN;
2285 reg->s32_max_value = S32_MAX;
2286 reg->u32_min_value = 0;
2287 reg->u32_max_value = U32_MAX;
2290 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2292 struct tnum var32_off = tnum_subreg(reg->var_off);
2294 /* min signed is max(sign bit) | min(other bits) */
2295 reg->s32_min_value = max_t(s32, reg->s32_min_value,
2296 var32_off.value | (var32_off.mask & S32_MIN));
2297 /* max signed is min(sign bit) | max(other bits) */
2298 reg->s32_max_value = min_t(s32, reg->s32_max_value,
2299 var32_off.value | (var32_off.mask & S32_MAX));
2300 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2301 reg->u32_max_value = min(reg->u32_max_value,
2302 (u32)(var32_off.value | var32_off.mask));
2305 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2307 /* min signed is max(sign bit) | min(other bits) */
2308 reg->smin_value = max_t(s64, reg->smin_value,
2309 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2310 /* max signed is min(sign bit) | max(other bits) */
2311 reg->smax_value = min_t(s64, reg->smax_value,
2312 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2313 reg->umin_value = max(reg->umin_value, reg->var_off.value);
2314 reg->umax_value = min(reg->umax_value,
2315 reg->var_off.value | reg->var_off.mask);
2318 static void __update_reg_bounds(struct bpf_reg_state *reg)
2320 __update_reg32_bounds(reg);
2321 __update_reg64_bounds(reg);
2324 /* Uses signed min/max values to inform unsigned, and vice-versa */
2325 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2327 /* Learn sign from signed bounds.
2328 * If we cannot cross the sign boundary, then signed and unsigned bounds
2329 * are the same, so combine. This works even in the negative case, e.g.
2330 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2332 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2333 reg->s32_min_value = reg->u32_min_value =
2334 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2335 reg->s32_max_value = reg->u32_max_value =
2336 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2339 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2340 * boundary, so we must be careful.
2342 if ((s32)reg->u32_max_value >= 0) {
2343 /* Positive. We can't learn anything from the smin, but smax
2344 * is positive, hence safe.
2346 reg->s32_min_value = reg->u32_min_value;
2347 reg->s32_max_value = reg->u32_max_value =
2348 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2349 } else if ((s32)reg->u32_min_value < 0) {
2350 /* Negative. We can't learn anything from the smax, but smin
2351 * is negative, hence safe.
2353 reg->s32_min_value = reg->u32_min_value =
2354 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2355 reg->s32_max_value = reg->u32_max_value;
2359 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2361 /* Learn sign from signed bounds.
2362 * If we cannot cross the sign boundary, then signed and unsigned bounds
2363 * are the same, so combine. This works even in the negative case, e.g.
2364 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2366 if (reg->smin_value >= 0 || reg->smax_value < 0) {
2367 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2369 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2373 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2374 * boundary, so we must be careful.
2376 if ((s64)reg->umax_value >= 0) {
2377 /* Positive. We can't learn anything from the smin, but smax
2378 * is positive, hence safe.
2380 reg->smin_value = reg->umin_value;
2381 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2383 } else if ((s64)reg->umin_value < 0) {
2384 /* Negative. We can't learn anything from the smax, but smin
2385 * is negative, hence safe.
2387 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2389 reg->smax_value = reg->umax_value;
2393 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2395 __reg32_deduce_bounds(reg);
2396 __reg64_deduce_bounds(reg);
2399 /* Attempts to improve var_off based on unsigned min/max information */
2400 static void __reg_bound_offset(struct bpf_reg_state *reg)
2402 struct tnum var64_off = tnum_intersect(reg->var_off,
2403 tnum_range(reg->umin_value,
2405 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2406 tnum_range(reg->u32_min_value,
2407 reg->u32_max_value));
2409 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2412 static void reg_bounds_sync(struct bpf_reg_state *reg)
2414 /* We might have learned new bounds from the var_off. */
2415 __update_reg_bounds(reg);
2416 /* We might have learned something about the sign bit. */
2417 __reg_deduce_bounds(reg);
2418 /* We might have learned some bits from the bounds. */
2419 __reg_bound_offset(reg);
2420 /* Intersecting with the old var_off might have improved our bounds
2421 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2422 * then new var_off is (0; 0x7f...fc) which improves our umax.
2424 __update_reg_bounds(reg);
2427 static bool __reg32_bound_s64(s32 a)
2429 return a >= 0 && a <= S32_MAX;
2432 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2434 reg->umin_value = reg->u32_min_value;
2435 reg->umax_value = reg->u32_max_value;
2437 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2438 * be positive otherwise set to worse case bounds and refine later
2441 if (__reg32_bound_s64(reg->s32_min_value) &&
2442 __reg32_bound_s64(reg->s32_max_value)) {
2443 reg->smin_value = reg->s32_min_value;
2444 reg->smax_value = reg->s32_max_value;
2446 reg->smin_value = 0;
2447 reg->smax_value = U32_MAX;
2451 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2453 /* special case when 64-bit register has upper 32-bit register
2454 * zeroed. Typically happens after zext or <<32, >>32 sequence
2455 * allowing us to use 32-bit bounds directly,
2457 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2458 __reg_assign_32_into_64(reg);
2460 /* Otherwise the best we can do is push lower 32bit known and
2461 * unknown bits into register (var_off set from jmp logic)
2462 * then learn as much as possible from the 64-bit tnum
2463 * known and unknown bits. The previous smin/smax bounds are
2464 * invalid here because of jmp32 compare so mark them unknown
2465 * so they do not impact tnum bounds calculation.
2467 __mark_reg64_unbounded(reg);
2469 reg_bounds_sync(reg);
2472 static bool __reg64_bound_s32(s64 a)
2474 return a >= S32_MIN && a <= S32_MAX;
2477 static bool __reg64_bound_u32(u64 a)
2479 return a >= U32_MIN && a <= U32_MAX;
2482 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2484 __mark_reg32_unbounded(reg);
2485 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2486 reg->s32_min_value = (s32)reg->smin_value;
2487 reg->s32_max_value = (s32)reg->smax_value;
2489 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2490 reg->u32_min_value = (u32)reg->umin_value;
2491 reg->u32_max_value = (u32)reg->umax_value;
2493 reg_bounds_sync(reg);
2496 /* Mark a register as having a completely unknown (scalar) value. */
2497 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2498 struct bpf_reg_state *reg)
2501 * Clear type, off, and union(map_ptr, range) and
2502 * padding between 'type' and union
2504 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2505 reg->type = SCALAR_VALUE;
2507 reg->ref_obj_id = 0;
2508 reg->var_off = tnum_unknown;
2510 reg->precise = !env->bpf_capable;
2511 __mark_reg_unbounded(reg);
2514 static void mark_reg_unknown(struct bpf_verifier_env *env,
2515 struct bpf_reg_state *regs, u32 regno)
2517 if (WARN_ON(regno >= MAX_BPF_REG)) {
2518 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2519 /* Something bad happened, let's kill all regs except FP */
2520 for (regno = 0; regno < BPF_REG_FP; regno++)
2521 __mark_reg_not_init(env, regs + regno);
2524 __mark_reg_unknown(env, regs + regno);
2527 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2528 struct bpf_reg_state *reg)
2530 __mark_reg_unknown(env, reg);
2531 reg->type = NOT_INIT;
2534 static void mark_reg_not_init(struct bpf_verifier_env *env,
2535 struct bpf_reg_state *regs, u32 regno)
2537 if (WARN_ON(regno >= MAX_BPF_REG)) {
2538 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2539 /* Something bad happened, let's kill all regs except FP */
2540 for (regno = 0; regno < BPF_REG_FP; regno++)
2541 __mark_reg_not_init(env, regs + regno);
2544 __mark_reg_not_init(env, regs + regno);
2547 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2548 struct bpf_reg_state *regs, u32 regno,
2549 enum bpf_reg_type reg_type,
2550 struct btf *btf, u32 btf_id,
2551 enum bpf_type_flag flag)
2553 if (reg_type == SCALAR_VALUE) {
2554 mark_reg_unknown(env, regs, regno);
2557 mark_reg_known_zero(env, regs, regno);
2558 regs[regno].type = PTR_TO_BTF_ID | flag;
2559 regs[regno].btf = btf;
2560 regs[regno].btf_id = btf_id;
2563 #define DEF_NOT_SUBREG (0)
2564 static void init_reg_state(struct bpf_verifier_env *env,
2565 struct bpf_func_state *state)
2567 struct bpf_reg_state *regs = state->regs;
2570 for (i = 0; i < MAX_BPF_REG; i++) {
2571 mark_reg_not_init(env, regs, i);
2572 regs[i].live = REG_LIVE_NONE;
2573 regs[i].parent = NULL;
2574 regs[i].subreg_def = DEF_NOT_SUBREG;
2578 regs[BPF_REG_FP].type = PTR_TO_STACK;
2579 mark_reg_known_zero(env, regs, BPF_REG_FP);
2580 regs[BPF_REG_FP].frameno = state->frameno;
2583 #define BPF_MAIN_FUNC (-1)
2584 static void init_func_state(struct bpf_verifier_env *env,
2585 struct bpf_func_state *state,
2586 int callsite, int frameno, int subprogno)
2588 state->callsite = callsite;
2589 state->frameno = frameno;
2590 state->subprogno = subprogno;
2591 state->callback_ret_range = tnum_range(0, 0);
2592 init_reg_state(env, state);
2593 mark_verifier_state_scratched(env);
2596 /* Similar to push_stack(), but for async callbacks */
2597 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2598 int insn_idx, int prev_insn_idx,
2601 struct bpf_verifier_stack_elem *elem;
2602 struct bpf_func_state *frame;
2604 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2608 elem->insn_idx = insn_idx;
2609 elem->prev_insn_idx = prev_insn_idx;
2610 elem->next = env->head;
2611 elem->log_pos = env->log.end_pos;
2614 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2616 "The sequence of %d jumps is too complex for async cb.\n",
2620 /* Unlike push_stack() do not copy_verifier_state().
2621 * The caller state doesn't matter.
2622 * This is async callback. It starts in a fresh stack.
2623 * Initialize it similar to do_check_common().
2625 elem->st.branches = 1;
2626 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2629 init_func_state(env, frame,
2630 BPF_MAIN_FUNC /* callsite */,
2631 0 /* frameno within this callchain */,
2632 subprog /* subprog number within this prog */);
2633 elem->st.frame[0] = frame;
2636 free_verifier_state(env->cur_state, true);
2637 env->cur_state = NULL;
2638 /* pop all elements and return */
2639 while (!pop_stack(env, NULL, NULL, false));
2645 SRC_OP, /* register is used as source operand */
2646 DST_OP, /* register is used as destination operand */
2647 DST_OP_NO_MARK /* same as above, check only, don't mark */
2650 static int cmp_subprogs(const void *a, const void *b)
2652 return ((struct bpf_subprog_info *)a)->start -
2653 ((struct bpf_subprog_info *)b)->start;
2656 static int find_subprog(struct bpf_verifier_env *env, int off)
2658 struct bpf_subprog_info *p;
2660 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2661 sizeof(env->subprog_info[0]), cmp_subprogs);
2664 return p - env->subprog_info;
2668 static int add_subprog(struct bpf_verifier_env *env, int off)
2670 int insn_cnt = env->prog->len;
2673 if (off >= insn_cnt || off < 0) {
2674 verbose(env, "call to invalid destination\n");
2677 ret = find_subprog(env, off);
2680 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2681 verbose(env, "too many subprograms\n");
2684 /* determine subprog starts. The end is one before the next starts */
2685 env->subprog_info[env->subprog_cnt++].start = off;
2686 sort(env->subprog_info, env->subprog_cnt,
2687 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2688 return env->subprog_cnt - 1;
2691 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2693 struct bpf_prog_aux *aux = env->prog->aux;
2694 struct btf *btf = aux->btf;
2695 const struct btf_type *t;
2696 u32 main_btf_id, id;
2700 /* Non-zero func_info_cnt implies valid btf */
2701 if (!aux->func_info_cnt)
2703 main_btf_id = aux->func_info[0].type_id;
2705 t = btf_type_by_id(btf, main_btf_id);
2707 verbose(env, "invalid btf id for main subprog in func_info\n");
2711 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2713 ret = PTR_ERR(name);
2714 /* If there is no tag present, there is no exception callback */
2717 else if (ret == -EEXIST)
2718 verbose(env, "multiple exception callback tags for main subprog\n");
2722 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2724 verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2728 t = btf_type_by_id(btf, id);
2729 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2730 verbose(env, "exception callback '%s' must have global linkage\n", name);
2734 for (i = 0; i < aux->func_info_cnt; i++) {
2735 if (aux->func_info[i].type_id != id)
2737 ret = aux->func_info[i].insn_off;
2738 /* Further func_info and subprog checks will also happen
2739 * later, so assume this is the right insn_off for now.
2742 verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2747 verbose(env, "exception callback type id not found in func_info\n");
2753 #define MAX_KFUNC_DESCS 256
2754 #define MAX_KFUNC_BTFS 256
2756 struct bpf_kfunc_desc {
2757 struct btf_func_model func_model;
2764 struct bpf_kfunc_btf {
2766 struct module *module;
2770 struct bpf_kfunc_desc_tab {
2771 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2772 * verification. JITs do lookups by bpf_insn, where func_id may not be
2773 * available, therefore at the end of verification do_misc_fixups()
2774 * sorts this by imm and offset.
2776 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2780 struct bpf_kfunc_btf_tab {
2781 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2785 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2787 const struct bpf_kfunc_desc *d0 = a;
2788 const struct bpf_kfunc_desc *d1 = b;
2790 /* func_id is not greater than BTF_MAX_TYPE */
2791 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2794 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2796 const struct bpf_kfunc_btf *d0 = a;
2797 const struct bpf_kfunc_btf *d1 = b;
2799 return d0->offset - d1->offset;
2802 static const struct bpf_kfunc_desc *
2803 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2805 struct bpf_kfunc_desc desc = {
2809 struct bpf_kfunc_desc_tab *tab;
2811 tab = prog->aux->kfunc_tab;
2812 return bsearch(&desc, tab->descs, tab->nr_descs,
2813 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2816 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2817 u16 btf_fd_idx, u8 **func_addr)
2819 const struct bpf_kfunc_desc *desc;
2821 desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2825 *func_addr = (u8 *)desc->addr;
2829 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2832 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2833 struct bpf_kfunc_btf_tab *tab;
2834 struct bpf_kfunc_btf *b;
2839 tab = env->prog->aux->kfunc_btf_tab;
2840 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2841 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2843 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2844 verbose(env, "too many different module BTFs\n");
2845 return ERR_PTR(-E2BIG);
2848 if (bpfptr_is_null(env->fd_array)) {
2849 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2850 return ERR_PTR(-EPROTO);
2853 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2854 offset * sizeof(btf_fd),
2856 return ERR_PTR(-EFAULT);
2858 btf = btf_get_by_fd(btf_fd);
2860 verbose(env, "invalid module BTF fd specified\n");
2864 if (!btf_is_module(btf)) {
2865 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2867 return ERR_PTR(-EINVAL);
2870 mod = btf_try_get_module(btf);
2873 return ERR_PTR(-ENXIO);
2876 b = &tab->descs[tab->nr_descs++];
2881 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2882 kfunc_btf_cmp_by_off, NULL);
2887 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2892 while (tab->nr_descs--) {
2893 module_put(tab->descs[tab->nr_descs].module);
2894 btf_put(tab->descs[tab->nr_descs].btf);
2899 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2903 /* In the future, this can be allowed to increase limit
2904 * of fd index into fd_array, interpreted as u16.
2906 verbose(env, "negative offset disallowed for kernel module function call\n");
2907 return ERR_PTR(-EINVAL);
2910 return __find_kfunc_desc_btf(env, offset);
2912 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2915 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2917 const struct btf_type *func, *func_proto;
2918 struct bpf_kfunc_btf_tab *btf_tab;
2919 struct bpf_kfunc_desc_tab *tab;
2920 struct bpf_prog_aux *prog_aux;
2921 struct bpf_kfunc_desc *desc;
2922 const char *func_name;
2923 struct btf *desc_btf;
2924 unsigned long call_imm;
2928 prog_aux = env->prog->aux;
2929 tab = prog_aux->kfunc_tab;
2930 btf_tab = prog_aux->kfunc_btf_tab;
2933 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2937 if (!env->prog->jit_requested) {
2938 verbose(env, "JIT is required for calling kernel function\n");
2942 if (!bpf_jit_supports_kfunc_call()) {
2943 verbose(env, "JIT does not support calling kernel function\n");
2947 if (!env->prog->gpl_compatible) {
2948 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2952 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2955 prog_aux->kfunc_tab = tab;
2958 /* func_id == 0 is always invalid, but instead of returning an error, be
2959 * conservative and wait until the code elimination pass before returning
2960 * error, so that invalid calls that get pruned out can be in BPF programs
2961 * loaded from userspace. It is also required that offset be untouched
2964 if (!func_id && !offset)
2967 if (!btf_tab && offset) {
2968 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2971 prog_aux->kfunc_btf_tab = btf_tab;
2974 desc_btf = find_kfunc_desc_btf(env, offset);
2975 if (IS_ERR(desc_btf)) {
2976 verbose(env, "failed to find BTF for kernel function\n");
2977 return PTR_ERR(desc_btf);
2980 if (find_kfunc_desc(env->prog, func_id, offset))
2983 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2984 verbose(env, "too many different kernel function calls\n");
2988 func = btf_type_by_id(desc_btf, func_id);
2989 if (!func || !btf_type_is_func(func)) {
2990 verbose(env, "kernel btf_id %u is not a function\n",
2994 func_proto = btf_type_by_id(desc_btf, func->type);
2995 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2996 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
3001 func_name = btf_name_by_offset(desc_btf, func->name_off);
3002 addr = kallsyms_lookup_name(func_name);
3004 verbose(env, "cannot find address for kernel function %s\n",
3008 specialize_kfunc(env, func_id, offset, &addr);
3010 if (bpf_jit_supports_far_kfunc_call()) {
3013 call_imm = BPF_CALL_IMM(addr);
3014 /* Check whether the relative offset overflows desc->imm */
3015 if ((unsigned long)(s32)call_imm != call_imm) {
3016 verbose(env, "address of kernel function %s is out of range\n",
3022 if (bpf_dev_bound_kfunc_id(func_id)) {
3023 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3028 desc = &tab->descs[tab->nr_descs++];
3029 desc->func_id = func_id;
3030 desc->imm = call_imm;
3031 desc->offset = offset;
3033 err = btf_distill_func_proto(&env->log, desc_btf,
3034 func_proto, func_name,
3037 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3038 kfunc_desc_cmp_by_id_off, NULL);
3042 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3044 const struct bpf_kfunc_desc *d0 = a;
3045 const struct bpf_kfunc_desc *d1 = b;
3047 if (d0->imm != d1->imm)
3048 return d0->imm < d1->imm ? -1 : 1;
3049 if (d0->offset != d1->offset)
3050 return d0->offset < d1->offset ? -1 : 1;
3054 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
3056 struct bpf_kfunc_desc_tab *tab;
3058 tab = prog->aux->kfunc_tab;
3062 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3063 kfunc_desc_cmp_by_imm_off, NULL);
3066 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3068 return !!prog->aux->kfunc_tab;
3071 const struct btf_func_model *
3072 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3073 const struct bpf_insn *insn)
3075 const struct bpf_kfunc_desc desc = {
3077 .offset = insn->off,
3079 const struct bpf_kfunc_desc *res;
3080 struct bpf_kfunc_desc_tab *tab;
3082 tab = prog->aux->kfunc_tab;
3083 res = bsearch(&desc, tab->descs, tab->nr_descs,
3084 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3086 return res ? &res->func_model : NULL;
3089 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3091 struct bpf_subprog_info *subprog = env->subprog_info;
3092 int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3093 struct bpf_insn *insn = env->prog->insnsi;
3095 /* Add entry function. */
3096 ret = add_subprog(env, 0);
3100 for (i = 0; i < insn_cnt; i++, insn++) {
3101 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3102 !bpf_pseudo_kfunc_call(insn))
3105 if (!env->bpf_capable) {
3106 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3110 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3111 ret = add_subprog(env, i + insn->imm + 1);
3113 ret = add_kfunc_call(env, insn->imm, insn->off);
3119 ret = bpf_find_exception_callback_insn_off(env);
3124 /* If ex_cb_insn > 0, this means that the main program has a subprog
3125 * marked using BTF decl tag to serve as the exception callback.
3128 ret = add_subprog(env, ex_cb_insn);
3131 for (i = 1; i < env->subprog_cnt; i++) {
3132 if (env->subprog_info[i].start != ex_cb_insn)
3134 env->exception_callback_subprog = i;
3139 /* Add a fake 'exit' subprog which could simplify subprog iteration
3140 * logic. 'subprog_cnt' should not be increased.
3142 subprog[env->subprog_cnt].start = insn_cnt;
3144 if (env->log.level & BPF_LOG_LEVEL2)
3145 for (i = 0; i < env->subprog_cnt; i++)
3146 verbose(env, "func#%d @%d\n", i, subprog[i].start);
3151 static int check_subprogs(struct bpf_verifier_env *env)
3153 int i, subprog_start, subprog_end, off, cur_subprog = 0;
3154 struct bpf_subprog_info *subprog = env->subprog_info;
3155 struct bpf_insn *insn = env->prog->insnsi;
3156 int insn_cnt = env->prog->len;
3158 /* now check that all jumps are within the same subprog */
3159 subprog_start = subprog[cur_subprog].start;
3160 subprog_end = subprog[cur_subprog + 1].start;
3161 for (i = 0; i < insn_cnt; i++) {
3162 u8 code = insn[i].code;
3164 if (code == (BPF_JMP | BPF_CALL) &&
3165 insn[i].src_reg == 0 &&
3166 insn[i].imm == BPF_FUNC_tail_call)
3167 subprog[cur_subprog].has_tail_call = true;
3168 if (BPF_CLASS(code) == BPF_LD &&
3169 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3170 subprog[cur_subprog].has_ld_abs = true;
3171 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3173 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3175 if (code == (BPF_JMP32 | BPF_JA))
3176 off = i + insn[i].imm + 1;
3178 off = i + insn[i].off + 1;
3179 if (off < subprog_start || off >= subprog_end) {
3180 verbose(env, "jump out of range from insn %d to %d\n", i, off);
3184 if (i == subprog_end - 1) {
3185 /* to avoid fall-through from one subprog into another
3186 * the last insn of the subprog should be either exit
3187 * or unconditional jump back or bpf_throw call
3189 if (code != (BPF_JMP | BPF_EXIT) &&
3190 code != (BPF_JMP32 | BPF_JA) &&
3191 code != (BPF_JMP | BPF_JA)) {
3192 verbose(env, "last insn is not an exit or jmp\n");
3195 subprog_start = subprog_end;
3197 if (cur_subprog < env->subprog_cnt)
3198 subprog_end = subprog[cur_subprog + 1].start;
3204 /* Parentage chain of this register (or stack slot) should take care of all
3205 * issues like callee-saved registers, stack slot allocation time, etc.
3207 static int mark_reg_read(struct bpf_verifier_env *env,
3208 const struct bpf_reg_state *state,
3209 struct bpf_reg_state *parent, u8 flag)
3211 bool writes = parent == state->parent; /* Observe write marks */
3215 /* if read wasn't screened by an earlier write ... */
3216 if (writes && state->live & REG_LIVE_WRITTEN)
3218 if (parent->live & REG_LIVE_DONE) {
3219 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3220 reg_type_str(env, parent->type),
3221 parent->var_off.value, parent->off);
3224 /* The first condition is more likely to be true than the
3225 * second, checked it first.
3227 if ((parent->live & REG_LIVE_READ) == flag ||
3228 parent->live & REG_LIVE_READ64)
3229 /* The parentage chain never changes and
3230 * this parent was already marked as LIVE_READ.
3231 * There is no need to keep walking the chain again and
3232 * keep re-marking all parents as LIVE_READ.
3233 * This case happens when the same register is read
3234 * multiple times without writes into it in-between.
3235 * Also, if parent has the stronger REG_LIVE_READ64 set,
3236 * then no need to set the weak REG_LIVE_READ32.
3239 /* ... then we depend on parent's value */
3240 parent->live |= flag;
3241 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3242 if (flag == REG_LIVE_READ64)
3243 parent->live &= ~REG_LIVE_READ32;
3245 parent = state->parent;
3250 if (env->longest_mark_read_walk < cnt)
3251 env->longest_mark_read_walk = cnt;
3255 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3257 struct bpf_func_state *state = func(env, reg);
3260 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
3261 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3264 if (reg->type == CONST_PTR_TO_DYNPTR)
3266 spi = dynptr_get_spi(env, reg);
3269 /* Caller ensures dynptr is valid and initialized, which means spi is in
3270 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3273 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3274 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3277 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3278 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3281 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3282 int spi, int nr_slots)
3284 struct bpf_func_state *state = func(env, reg);
3287 for (i = 0; i < nr_slots; i++) {
3288 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3290 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3294 mark_stack_slot_scratched(env, spi - i);
3300 /* This function is supposed to be used by the following 32-bit optimization
3301 * code only. It returns TRUE if the source or destination register operates
3302 * on 64-bit, otherwise return FALSE.
3304 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3305 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3310 class = BPF_CLASS(code);
3312 if (class == BPF_JMP) {
3313 /* BPF_EXIT for "main" will reach here. Return TRUE
3318 if (op == BPF_CALL) {
3319 /* BPF to BPF call will reach here because of marking
3320 * caller saved clobber with DST_OP_NO_MARK for which we
3321 * don't care the register def because they are anyway
3322 * marked as NOT_INIT already.
3324 if (insn->src_reg == BPF_PSEUDO_CALL)
3326 /* Helper call will reach here because of arg type
3327 * check, conservatively return TRUE.
3336 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3339 if (class == BPF_ALU64 || class == BPF_JMP ||
3340 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3343 if (class == BPF_ALU || class == BPF_JMP32)
3346 if (class == BPF_LDX) {
3348 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3349 /* LDX source must be ptr. */
3353 if (class == BPF_STX) {
3354 /* BPF_STX (including atomic variants) has multiple source
3355 * operands, one of which is a ptr. Check whether the caller is
3358 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3360 return BPF_SIZE(code) == BPF_DW;
3363 if (class == BPF_LD) {
3364 u8 mode = BPF_MODE(code);
3367 if (mode == BPF_IMM)
3370 /* Both LD_IND and LD_ABS return 32-bit data. */
3374 /* Implicit ctx ptr. */
3375 if (regno == BPF_REG_6)
3378 /* Explicit source could be any width. */
3382 if (class == BPF_ST)
3383 /* The only source register for BPF_ST is a ptr. */
3386 /* Conservatively return true at default. */
3390 /* Return the regno defined by the insn, or -1. */
3391 static int insn_def_regno(const struct bpf_insn *insn)
3393 switch (BPF_CLASS(insn->code)) {
3399 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3400 (insn->imm & BPF_FETCH)) {
3401 if (insn->imm == BPF_CMPXCHG)
3404 return insn->src_reg;
3409 return insn->dst_reg;
3413 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3414 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3416 int dst_reg = insn_def_regno(insn);
3421 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3424 static void mark_insn_zext(struct bpf_verifier_env *env,
3425 struct bpf_reg_state *reg)
3427 s32 def_idx = reg->subreg_def;
3429 if (def_idx == DEF_NOT_SUBREG)
3432 env->insn_aux_data[def_idx - 1].zext_dst = true;
3433 /* The dst will be zero extended, so won't be sub-register anymore. */
3434 reg->subreg_def = DEF_NOT_SUBREG;
3437 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3438 enum reg_arg_type t)
3440 struct bpf_verifier_state *vstate = env->cur_state;
3441 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3442 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3443 struct bpf_reg_state *reg, *regs = state->regs;
3446 if (regno >= MAX_BPF_REG) {
3447 verbose(env, "R%d is invalid\n", regno);
3451 mark_reg_scratched(env, regno);
3454 rw64 = is_reg64(env, insn, regno, reg, t);
3456 /* check whether register used as source operand can be read */
3457 if (reg->type == NOT_INIT) {
3458 verbose(env, "R%d !read_ok\n", regno);
3461 /* We don't need to worry about FP liveness because it's read-only */
3462 if (regno == BPF_REG_FP)
3466 mark_insn_zext(env, reg);
3468 return mark_reg_read(env, reg, reg->parent,
3469 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3471 /* check whether register used as dest operand can be written to */
3472 if (regno == BPF_REG_FP) {
3473 verbose(env, "frame pointer is read only\n");
3476 reg->live |= REG_LIVE_WRITTEN;
3477 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3479 mark_reg_unknown(env, regs, regno);
3484 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3486 env->insn_aux_data[idx].jmp_point = true;
3489 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3491 return env->insn_aux_data[insn_idx].jmp_point;
3494 /* for any branch, call, exit record the history of jmps in the given state */
3495 static int push_jmp_history(struct bpf_verifier_env *env,
3496 struct bpf_verifier_state *cur)
3498 u32 cnt = cur->jmp_history_cnt;
3499 struct bpf_idx_pair *p;
3502 if (!is_jmp_point(env, env->insn_idx))
3506 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3507 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3510 p[cnt - 1].idx = env->insn_idx;
3511 p[cnt - 1].prev_idx = env->prev_insn_idx;
3512 cur->jmp_history = p;
3513 cur->jmp_history_cnt = cnt;
3517 /* Backtrack one insn at a time. If idx is not at the top of recorded
3518 * history then previous instruction came from straight line execution.
3520 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3525 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3526 i = st->jmp_history[cnt - 1].prev_idx;
3534 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3536 const struct btf_type *func;
3537 struct btf *desc_btf;
3539 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3542 desc_btf = find_kfunc_desc_btf(data, insn->off);
3543 if (IS_ERR(desc_btf))
3546 func = btf_type_by_id(desc_btf, insn->imm);
3547 return btf_name_by_offset(desc_btf, func->name_off);
3550 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3555 static inline void bt_reset(struct backtrack_state *bt)
3557 struct bpf_verifier_env *env = bt->env;
3559 memset(bt, 0, sizeof(*bt));
3563 static inline u32 bt_empty(struct backtrack_state *bt)
3568 for (i = 0; i <= bt->frame; i++)
3569 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3574 static inline int bt_subprog_enter(struct backtrack_state *bt)
3576 if (bt->frame == MAX_CALL_FRAMES - 1) {
3577 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3578 WARN_ONCE(1, "verifier backtracking bug");
3585 static inline int bt_subprog_exit(struct backtrack_state *bt)
3587 if (bt->frame == 0) {
3588 verbose(bt->env, "BUG subprog exit from frame 0\n");
3589 WARN_ONCE(1, "verifier backtracking bug");
3596 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3598 bt->reg_masks[frame] |= 1 << reg;
3601 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3603 bt->reg_masks[frame] &= ~(1 << reg);
3606 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3608 bt_set_frame_reg(bt, bt->frame, reg);
3611 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3613 bt_clear_frame_reg(bt, bt->frame, reg);
3616 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3618 bt->stack_masks[frame] |= 1ull << slot;
3621 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3623 bt->stack_masks[frame] &= ~(1ull << slot);
3626 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3628 bt_set_frame_slot(bt, bt->frame, slot);
3631 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3633 bt_clear_frame_slot(bt, bt->frame, slot);
3636 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3638 return bt->reg_masks[frame];
3641 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3643 return bt->reg_masks[bt->frame];
3646 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3648 return bt->stack_masks[frame];
3651 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3653 return bt->stack_masks[bt->frame];
3656 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3658 return bt->reg_masks[bt->frame] & (1 << reg);
3661 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3663 return bt->stack_masks[bt->frame] & (1ull << slot);
3666 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3667 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3669 DECLARE_BITMAP(mask, 64);
3675 bitmap_from_u64(mask, reg_mask);
3676 for_each_set_bit(i, mask, 32) {
3677 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3685 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3686 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3688 DECLARE_BITMAP(mask, 64);
3694 bitmap_from_u64(mask, stack_mask);
3695 for_each_set_bit(i, mask, 64) {
3696 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3705 /* For given verifier state backtrack_insn() is called from the last insn to
3706 * the first insn. Its purpose is to compute a bitmask of registers and
3707 * stack slots that needs precision in the parent verifier state.
3709 * @idx is an index of the instruction we are currently processing;
3710 * @subseq_idx is an index of the subsequent instruction that:
3711 * - *would be* executed next, if jump history is viewed in forward order;
3712 * - *was* processed previously during backtracking.
3714 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3715 struct backtrack_state *bt)
3717 const struct bpf_insn_cbs cbs = {
3718 .cb_call = disasm_kfunc_name,
3719 .cb_print = verbose,
3720 .private_data = env,
3722 struct bpf_insn *insn = env->prog->insnsi + idx;
3723 u8 class = BPF_CLASS(insn->code);
3724 u8 opcode = BPF_OP(insn->code);
3725 u8 mode = BPF_MODE(insn->code);
3726 u32 dreg = insn->dst_reg;
3727 u32 sreg = insn->src_reg;
3730 if (insn->code == 0)
3732 if (env->log.level & BPF_LOG_LEVEL2) {
3733 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3734 verbose(env, "mark_precise: frame%d: regs=%s ",
3735 bt->frame, env->tmp_str_buf);
3736 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3737 verbose(env, "stack=%s before ", env->tmp_str_buf);
3738 verbose(env, "%d: ", idx);
3739 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3742 if (class == BPF_ALU || class == BPF_ALU64) {
3743 if (!bt_is_reg_set(bt, dreg))
3745 if (opcode == BPF_MOV) {
3746 if (BPF_SRC(insn->code) == BPF_X) {
3747 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3748 * dreg needs precision after this insn
3749 * sreg needs precision before this insn
3751 bt_clear_reg(bt, dreg);
3752 bt_set_reg(bt, sreg);
3755 * dreg needs precision after this insn.
3756 * Corresponding register is already marked
3757 * as precise=true in this verifier state.
3758 * No further markings in parent are necessary
3760 bt_clear_reg(bt, dreg);
3763 if (BPF_SRC(insn->code) == BPF_X) {
3765 * both dreg and sreg need precision
3768 bt_set_reg(bt, sreg);
3770 * dreg still needs precision before this insn
3773 } else if (class == BPF_LDX) {
3774 if (!bt_is_reg_set(bt, dreg))
3776 bt_clear_reg(bt, dreg);
3778 /* scalars can only be spilled into stack w/o losing precision.
3779 * Load from any other memory can be zero extended.
3780 * The desire to keep that precision is already indicated
3781 * by 'precise' mark in corresponding register of this state.
3782 * No further tracking necessary.
3784 if (insn->src_reg != BPF_REG_FP)
3787 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3788 * that [fp - off] slot contains scalar that needs to be
3789 * tracked with precision
3791 spi = (-insn->off - 1) / BPF_REG_SIZE;
3793 verbose(env, "BUG spi %d\n", spi);
3794 WARN_ONCE(1, "verifier backtracking bug");
3797 bt_set_slot(bt, spi);
3798 } else if (class == BPF_STX || class == BPF_ST) {
3799 if (bt_is_reg_set(bt, dreg))
3800 /* stx & st shouldn't be using _scalar_ dst_reg
3801 * to access memory. It means backtracking
3802 * encountered a case of pointer subtraction.
3805 /* scalars can only be spilled into stack */
3806 if (insn->dst_reg != BPF_REG_FP)
3808 spi = (-insn->off - 1) / BPF_REG_SIZE;
3810 verbose(env, "BUG spi %d\n", spi);
3811 WARN_ONCE(1, "verifier backtracking bug");
3814 if (!bt_is_slot_set(bt, spi))
3816 bt_clear_slot(bt, spi);
3817 if (class == BPF_STX)
3818 bt_set_reg(bt, sreg);
3819 } else if (class == BPF_JMP || class == BPF_JMP32) {
3820 if (bpf_pseudo_call(insn)) {
3821 int subprog_insn_idx, subprog;
3823 subprog_insn_idx = idx + insn->imm + 1;
3824 subprog = find_subprog(env, subprog_insn_idx);
3828 if (subprog_is_global(env, subprog)) {
3829 /* check that jump history doesn't have any
3830 * extra instructions from subprog; the next
3831 * instruction after call to global subprog
3832 * should be literally next instruction in
3835 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3836 /* r1-r5 are invalidated after subprog call,
3837 * so for global func call it shouldn't be set
3840 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3841 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3842 WARN_ONCE(1, "verifier backtracking bug");
3845 /* global subprog always sets R0 */
3846 bt_clear_reg(bt, BPF_REG_0);
3849 /* static subprog call instruction, which
3850 * means that we are exiting current subprog,
3851 * so only r1-r5 could be still requested as
3852 * precise, r0 and r6-r10 or any stack slot in
3853 * the current frame should be zero by now
3855 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3856 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3857 WARN_ONCE(1, "verifier backtracking bug");
3860 /* we don't track register spills perfectly,
3861 * so fallback to force-precise instead of failing */
3862 if (bt_stack_mask(bt) != 0)
3864 /* propagate r1-r5 to the caller */
3865 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3866 if (bt_is_reg_set(bt, i)) {
3867 bt_clear_reg(bt, i);
3868 bt_set_frame_reg(bt, bt->frame - 1, i);
3871 if (bt_subprog_exit(bt))
3875 } else if ((bpf_helper_call(insn) &&
3876 is_callback_calling_function(insn->imm) &&
3877 !is_async_callback_calling_function(insn->imm)) ||
3878 (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3879 /* callback-calling helper or kfunc call, which means
3880 * we are exiting from subprog, but unlike the subprog
3881 * call handling above, we shouldn't propagate
3882 * precision of r1-r5 (if any requested), as they are
3883 * not actually arguments passed directly to callback
3886 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3887 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3888 WARN_ONCE(1, "verifier backtracking bug");
3891 if (bt_stack_mask(bt) != 0)
3893 /* clear r1-r5 in callback subprog's mask */
3894 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3895 bt_clear_reg(bt, i);
3896 if (bt_subprog_exit(bt))
3899 } else if (opcode == BPF_CALL) {
3900 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3901 * catch this error later. Make backtracking conservative
3904 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3906 /* regular helper call sets R0 */
3907 bt_clear_reg(bt, BPF_REG_0);
3908 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3909 /* if backtracing was looking for registers R1-R5
3910 * they should have been found already.
3912 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3913 WARN_ONCE(1, "verifier backtracking bug");
3916 } else if (opcode == BPF_EXIT) {
3919 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3920 /* if backtracing was looking for registers R1-R5
3921 * they should have been found already.
3923 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3924 WARN_ONCE(1, "verifier backtracking bug");
3928 /* BPF_EXIT in subprog or callback always returns
3929 * right after the call instruction, so by checking
3930 * whether the instruction at subseq_idx-1 is subprog
3931 * call or not we can distinguish actual exit from
3932 * *subprog* from exit from *callback*. In the former
3933 * case, we need to propagate r0 precision, if
3934 * necessary. In the former we never do that.
3936 r0_precise = subseq_idx - 1 >= 0 &&
3937 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3938 bt_is_reg_set(bt, BPF_REG_0);
3940 bt_clear_reg(bt, BPF_REG_0);
3941 if (bt_subprog_enter(bt))
3945 bt_set_reg(bt, BPF_REG_0);
3946 /* r6-r9 and stack slots will stay set in caller frame
3947 * bitmasks until we return back from callee(s)
3950 } else if (BPF_SRC(insn->code) == BPF_X) {
3951 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3954 * Both dreg and sreg need precision before
3955 * this insn. If only sreg was marked precise
3956 * before it would be equally necessary to
3957 * propagate it to dreg.
3959 bt_set_reg(bt, dreg);
3960 bt_set_reg(bt, sreg);
3961 /* else dreg <cond> K
3962 * Only dreg still needs precision before
3963 * this insn, so for the K-based conditional
3964 * there is nothing new to be marked.
3967 } else if (class == BPF_LD) {
3968 if (!bt_is_reg_set(bt, dreg))
3970 bt_clear_reg(bt, dreg);
3971 /* It's ld_imm64 or ld_abs or ld_ind.
3972 * For ld_imm64 no further tracking of precision
3973 * into parent is necessary
3975 if (mode == BPF_IND || mode == BPF_ABS)
3976 /* to be analyzed */
3982 /* the scalar precision tracking algorithm:
3983 * . at the start all registers have precise=false.
3984 * . scalar ranges are tracked as normal through alu and jmp insns.
3985 * . once precise value of the scalar register is used in:
3986 * . ptr + scalar alu
3987 * . if (scalar cond K|scalar)
3988 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3989 * backtrack through the verifier states and mark all registers and
3990 * stack slots with spilled constants that these scalar regisers
3991 * should be precise.
3992 * . during state pruning two registers (or spilled stack slots)
3993 * are equivalent if both are not precise.
3995 * Note the verifier cannot simply walk register parentage chain,
3996 * since many different registers and stack slots could have been
3997 * used to compute single precise scalar.
3999 * The approach of starting with precise=true for all registers and then
4000 * backtrack to mark a register as not precise when the verifier detects
4001 * that program doesn't care about specific value (e.g., when helper
4002 * takes register as ARG_ANYTHING parameter) is not safe.
4004 * It's ok to walk single parentage chain of the verifier states.
4005 * It's possible that this backtracking will go all the way till 1st insn.
4006 * All other branches will be explored for needing precision later.
4008 * The backtracking needs to deal with cases like:
4009 * 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)
4012 * if r5 > 0x79f goto pc+7
4013 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4016 * call bpf_perf_event_output#25
4017 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4021 * call foo // uses callee's r6 inside to compute r0
4025 * to track above reg_mask/stack_mask needs to be independent for each frame.
4027 * Also if parent's curframe > frame where backtracking started,
4028 * the verifier need to mark registers in both frames, otherwise callees
4029 * may incorrectly prune callers. This is similar to
4030 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4032 * For now backtracking falls back into conservative marking.
4034 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4035 struct bpf_verifier_state *st)
4037 struct bpf_func_state *func;
4038 struct bpf_reg_state *reg;
4041 if (env->log.level & BPF_LOG_LEVEL2) {
4042 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4046 /* big hammer: mark all scalars precise in this path.
4047 * pop_stack may still get !precise scalars.
4048 * We also skip current state and go straight to first parent state,
4049 * because precision markings in current non-checkpointed state are
4050 * not needed. See why in the comment in __mark_chain_precision below.
4052 for (st = st->parent; st; st = st->parent) {
4053 for (i = 0; i <= st->curframe; i++) {
4054 func = st->frame[i];
4055 for (j = 0; j < BPF_REG_FP; j++) {
4056 reg = &func->regs[j];
4057 if (reg->type != SCALAR_VALUE || reg->precise)
4059 reg->precise = true;
4060 if (env->log.level & BPF_LOG_LEVEL2) {
4061 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4065 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4066 if (!is_spilled_reg(&func->stack[j]))
4068 reg = &func->stack[j].spilled_ptr;
4069 if (reg->type != SCALAR_VALUE || reg->precise)
4071 reg->precise = true;
4072 if (env->log.level & BPF_LOG_LEVEL2) {
4073 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4081 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4083 struct bpf_func_state *func;
4084 struct bpf_reg_state *reg;
4087 for (i = 0; i <= st->curframe; i++) {
4088 func = st->frame[i];
4089 for (j = 0; j < BPF_REG_FP; j++) {
4090 reg = &func->regs[j];
4091 if (reg->type != SCALAR_VALUE)
4093 reg->precise = false;
4095 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4096 if (!is_spilled_reg(&func->stack[j]))
4098 reg = &func->stack[j].spilled_ptr;
4099 if (reg->type != SCALAR_VALUE)
4101 reg->precise = false;
4106 static bool idset_contains(struct bpf_idset *s, u32 id)
4110 for (i = 0; i < s->count; ++i)
4111 if (s->ids[i] == id)
4117 static int idset_push(struct bpf_idset *s, u32 id)
4119 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4121 s->ids[s->count++] = id;
4125 static void idset_reset(struct bpf_idset *s)
4130 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4131 * Mark all registers with these IDs as precise.
4133 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4135 struct bpf_idset *precise_ids = &env->idset_scratch;
4136 struct backtrack_state *bt = &env->bt;
4137 struct bpf_func_state *func;
4138 struct bpf_reg_state *reg;
4139 DECLARE_BITMAP(mask, 64);
4142 idset_reset(precise_ids);
4144 for (fr = bt->frame; fr >= 0; fr--) {
4145 func = st->frame[fr];
4147 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4148 for_each_set_bit(i, mask, 32) {
4149 reg = &func->regs[i];
4150 if (!reg->id || reg->type != SCALAR_VALUE)
4152 if (idset_push(precise_ids, reg->id))
4156 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4157 for_each_set_bit(i, mask, 64) {
4158 if (i >= func->allocated_stack / BPF_REG_SIZE)
4160 if (!is_spilled_scalar_reg(&func->stack[i]))
4162 reg = &func->stack[i].spilled_ptr;
4165 if (idset_push(precise_ids, reg->id))
4170 for (fr = 0; fr <= st->curframe; ++fr) {
4171 func = st->frame[fr];
4173 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4174 reg = &func->regs[i];
4177 if (!idset_contains(precise_ids, reg->id))
4179 bt_set_frame_reg(bt, fr, i);
4181 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4182 if (!is_spilled_scalar_reg(&func->stack[i]))
4184 reg = &func->stack[i].spilled_ptr;
4187 if (!idset_contains(precise_ids, reg->id))
4189 bt_set_frame_slot(bt, fr, i);
4197 * __mark_chain_precision() backtracks BPF program instruction sequence and
4198 * chain of verifier states making sure that register *regno* (if regno >= 0)
4199 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4200 * SCALARS, as well as any other registers and slots that contribute to
4201 * a tracked state of given registers/stack slots, depending on specific BPF
4202 * assembly instructions (see backtrack_insns() for exact instruction handling
4203 * logic). This backtracking relies on recorded jmp_history and is able to
4204 * traverse entire chain of parent states. This process ends only when all the
4205 * necessary registers/slots and their transitive dependencies are marked as
4208 * One important and subtle aspect is that precise marks *do not matter* in
4209 * the currently verified state (current state). It is important to understand
4210 * why this is the case.
4212 * First, note that current state is the state that is not yet "checkpointed",
4213 * i.e., it is not yet put into env->explored_states, and it has no children
4214 * states as well. It's ephemeral, and can end up either a) being discarded if
4215 * compatible explored state is found at some point or BPF_EXIT instruction is
4216 * reached or b) checkpointed and put into env->explored_states, branching out
4217 * into one or more children states.
4219 * In the former case, precise markings in current state are completely
4220 * ignored by state comparison code (see regsafe() for details). Only
4221 * checkpointed ("old") state precise markings are important, and if old
4222 * state's register/slot is precise, regsafe() assumes current state's
4223 * register/slot as precise and checks value ranges exactly and precisely. If
4224 * states turn out to be compatible, current state's necessary precise
4225 * markings and any required parent states' precise markings are enforced
4226 * after the fact with propagate_precision() logic, after the fact. But it's
4227 * important to realize that in this case, even after marking current state
4228 * registers/slots as precise, we immediately discard current state. So what
4229 * actually matters is any of the precise markings propagated into current
4230 * state's parent states, which are always checkpointed (due to b) case above).
4231 * As such, for scenario a) it doesn't matter if current state has precise
4232 * markings set or not.
4234 * Now, for the scenario b), checkpointing and forking into child(ren)
4235 * state(s). Note that before current state gets to checkpointing step, any
4236 * processed instruction always assumes precise SCALAR register/slot
4237 * knowledge: if precise value or range is useful to prune jump branch, BPF
4238 * verifier takes this opportunity enthusiastically. Similarly, when
4239 * register's value is used to calculate offset or memory address, exact
4240 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4241 * what we mentioned above about state comparison ignoring precise markings
4242 * during state comparison, BPF verifier ignores and also assumes precise
4243 * markings *at will* during instruction verification process. But as verifier
4244 * assumes precision, it also propagates any precision dependencies across
4245 * parent states, which are not yet finalized, so can be further restricted
4246 * based on new knowledge gained from restrictions enforced by their children
4247 * states. This is so that once those parent states are finalized, i.e., when
4248 * they have no more active children state, state comparison logic in
4249 * is_state_visited() would enforce strict and precise SCALAR ranges, if
4250 * required for correctness.
4252 * To build a bit more intuition, note also that once a state is checkpointed,
4253 * the path we took to get to that state is not important. This is crucial
4254 * property for state pruning. When state is checkpointed and finalized at
4255 * some instruction index, it can be correctly and safely used to "short
4256 * circuit" any *compatible* state that reaches exactly the same instruction
4257 * index. I.e., if we jumped to that instruction from a completely different
4258 * code path than original finalized state was derived from, it doesn't
4259 * matter, current state can be discarded because from that instruction
4260 * forward having a compatible state will ensure we will safely reach the
4261 * exit. States describe preconditions for further exploration, but completely
4262 * forget the history of how we got here.
4264 * This also means that even if we needed precise SCALAR range to get to
4265 * finalized state, but from that point forward *that same* SCALAR register is
4266 * never used in a precise context (i.e., it's precise value is not needed for
4267 * correctness), it's correct and safe to mark such register as "imprecise"
4268 * (i.e., precise marking set to false). This is what we rely on when we do
4269 * not set precise marking in current state. If no child state requires
4270 * precision for any given SCALAR register, it's safe to dictate that it can
4271 * be imprecise. If any child state does require this register to be precise,
4272 * we'll mark it precise later retroactively during precise markings
4273 * propagation from child state to parent states.
4275 * Skipping precise marking setting in current state is a mild version of
4276 * relying on the above observation. But we can utilize this property even
4277 * more aggressively by proactively forgetting any precise marking in the
4278 * current state (which we inherited from the parent state), right before we
4279 * checkpoint it and branch off into new child state. This is done by
4280 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4281 * finalized states which help in short circuiting more future states.
4283 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4285 struct backtrack_state *bt = &env->bt;
4286 struct bpf_verifier_state *st = env->cur_state;
4287 int first_idx = st->first_insn_idx;
4288 int last_idx = env->insn_idx;
4289 int subseq_idx = -1;
4290 struct bpf_func_state *func;
4291 struct bpf_reg_state *reg;
4292 bool skip_first = true;
4295 if (!env->bpf_capable)
4298 /* set frame number from which we are starting to backtrack */
4299 bt_init(bt, env->cur_state->curframe);
4301 /* Do sanity checks against current state of register and/or stack
4302 * slot, but don't set precise flag in current state, as precision
4303 * tracking in the current state is unnecessary.
4305 func = st->frame[bt->frame];
4307 reg = &func->regs[regno];
4308 if (reg->type != SCALAR_VALUE) {
4309 WARN_ONCE(1, "backtracing misuse");
4312 bt_set_reg(bt, regno);
4319 DECLARE_BITMAP(mask, 64);
4320 u32 history = st->jmp_history_cnt;
4322 if (env->log.level & BPF_LOG_LEVEL2) {
4323 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4324 bt->frame, last_idx, first_idx, subseq_idx);
4327 /* If some register with scalar ID is marked as precise,
4328 * make sure that all registers sharing this ID are also precise.
4329 * This is needed to estimate effect of find_equal_scalars().
4330 * Do this at the last instruction of each state,
4331 * bpf_reg_state::id fields are valid for these instructions.
4333 * Allows to track precision in situation like below:
4335 * r2 = unknown value
4339 * r1 = r2 // r1 and r2 now share the same ID
4341 * --- state #1 {r1.id = A, r2.id = A} ---
4343 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4345 * --- state #2 {r1.id = A, r2.id = A} ---
4347 * r3 += r1 // need to mark both r1 and r2
4349 if (mark_precise_scalar_ids(env, st))
4353 /* we are at the entry into subprog, which
4354 * is expected for global funcs, but only if
4355 * requested precise registers are R1-R5
4356 * (which are global func's input arguments)
4358 if (st->curframe == 0 &&
4359 st->frame[0]->subprogno > 0 &&
4360 st->frame[0]->callsite == BPF_MAIN_FUNC &&
4361 bt_stack_mask(bt) == 0 &&
4362 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4363 bitmap_from_u64(mask, bt_reg_mask(bt));
4364 for_each_set_bit(i, mask, 32) {
4365 reg = &st->frame[0]->regs[i];
4366 bt_clear_reg(bt, i);
4367 if (reg->type == SCALAR_VALUE)
4368 reg->precise = true;
4373 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4374 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4375 WARN_ONCE(1, "verifier backtracking bug");
4379 for (i = last_idx;;) {
4384 err = backtrack_insn(env, i, subseq_idx, bt);
4386 if (err == -ENOTSUPP) {
4387 mark_all_scalars_precise(env, env->cur_state);
4394 /* Found assignment(s) into tracked register in this state.
4395 * Since this state is already marked, just return.
4396 * Nothing to be tracked further in the parent state.
4402 i = get_prev_insn_idx(st, i, &history);
4403 if (i >= env->prog->len) {
4404 /* This can happen if backtracking reached insn 0
4405 * and there are still reg_mask or stack_mask
4407 * It means the backtracking missed the spot where
4408 * particular register was initialized with a constant.
4410 verbose(env, "BUG backtracking idx %d\n", i);
4411 WARN_ONCE(1, "verifier backtracking bug");
4419 for (fr = bt->frame; fr >= 0; fr--) {
4420 func = st->frame[fr];
4421 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4422 for_each_set_bit(i, mask, 32) {
4423 reg = &func->regs[i];
4424 if (reg->type != SCALAR_VALUE) {
4425 bt_clear_frame_reg(bt, fr, i);
4429 bt_clear_frame_reg(bt, fr, i);
4431 reg->precise = true;
4434 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4435 for_each_set_bit(i, mask, 64) {
4436 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4437 /* the sequence of instructions:
4439 * 3: (7b) *(u64 *)(r3 -8) = r0
4440 * 4: (79) r4 = *(u64 *)(r10 -8)
4441 * doesn't contain jmps. It's backtracked
4442 * as a single block.
4443 * During backtracking insn 3 is not recognized as
4444 * stack access, so at the end of backtracking
4445 * stack slot fp-8 is still marked in stack_mask.
4446 * However the parent state may not have accessed
4447 * fp-8 and it's "unallocated" stack space.
4448 * In such case fallback to conservative.
4450 mark_all_scalars_precise(env, env->cur_state);
4455 if (!is_spilled_scalar_reg(&func->stack[i])) {
4456 bt_clear_frame_slot(bt, fr, i);
4459 reg = &func->stack[i].spilled_ptr;
4461 bt_clear_frame_slot(bt, fr, i);
4463 reg->precise = true;
4465 if (env->log.level & BPF_LOG_LEVEL2) {
4466 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4467 bt_frame_reg_mask(bt, fr));
4468 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4469 fr, env->tmp_str_buf);
4470 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4471 bt_frame_stack_mask(bt, fr));
4472 verbose(env, "stack=%s: ", env->tmp_str_buf);
4473 print_verifier_state(env, func, true);
4480 subseq_idx = first_idx;
4481 last_idx = st->last_insn_idx;
4482 first_idx = st->first_insn_idx;
4485 /* if we still have requested precise regs or slots, we missed
4486 * something (e.g., stack access through non-r10 register), so
4487 * fallback to marking all precise
4489 if (!bt_empty(bt)) {
4490 mark_all_scalars_precise(env, env->cur_state);
4497 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4499 return __mark_chain_precision(env, regno);
4502 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4503 * desired reg and stack masks across all relevant frames
4505 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4507 return __mark_chain_precision(env, -1);
4510 static bool is_spillable_regtype(enum bpf_reg_type type)
4512 switch (base_type(type)) {
4513 case PTR_TO_MAP_VALUE:
4517 case PTR_TO_PACKET_META:
4518 case PTR_TO_PACKET_END:
4519 case PTR_TO_FLOW_KEYS:
4520 case CONST_PTR_TO_MAP:
4522 case PTR_TO_SOCK_COMMON:
4523 case PTR_TO_TCP_SOCK:
4524 case PTR_TO_XDP_SOCK:
4529 case PTR_TO_MAP_KEY:
4536 /* Does this register contain a constant zero? */
4537 static bool register_is_null(struct bpf_reg_state *reg)
4539 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4542 static bool register_is_const(struct bpf_reg_state *reg)
4544 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4547 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4549 return tnum_is_unknown(reg->var_off) &&
4550 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4551 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4552 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4553 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4556 static bool register_is_bounded(struct bpf_reg_state *reg)
4558 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4561 static bool __is_pointer_value(bool allow_ptr_leaks,
4562 const struct bpf_reg_state *reg)
4564 if (allow_ptr_leaks)
4567 return reg->type != SCALAR_VALUE;
4570 /* Copy src state preserving dst->parent and dst->live fields */
4571 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4573 struct bpf_reg_state *parent = dst->parent;
4574 enum bpf_reg_liveness live = dst->live;
4577 dst->parent = parent;
4581 static void save_register_state(struct bpf_func_state *state,
4582 int spi, struct bpf_reg_state *reg,
4587 copy_register_state(&state->stack[spi].spilled_ptr, reg);
4588 if (size == BPF_REG_SIZE)
4589 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4591 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4592 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4594 /* size < 8 bytes spill */
4596 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4599 static bool is_bpf_st_mem(struct bpf_insn *insn)
4601 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4604 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4605 * stack boundary and alignment are checked in check_mem_access()
4607 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4608 /* stack frame we're writing to */
4609 struct bpf_func_state *state,
4610 int off, int size, int value_regno,
4613 struct bpf_func_state *cur; /* state of the current function */
4614 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4615 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4616 struct bpf_reg_state *reg = NULL;
4617 u32 dst_reg = insn->dst_reg;
4619 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4622 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4623 * so it's aligned access and [off, off + size) are within stack limits
4625 if (!env->allow_ptr_leaks &&
4626 state->stack[spi].slot_type[0] == STACK_SPILL &&
4627 size != BPF_REG_SIZE) {
4628 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4632 cur = env->cur_state->frame[env->cur_state->curframe];
4633 if (value_regno >= 0)
4634 reg = &cur->regs[value_regno];
4635 if (!env->bypass_spec_v4) {
4636 bool sanitize = reg && is_spillable_regtype(reg->type);
4638 for (i = 0; i < size; i++) {
4639 u8 type = state->stack[spi].slot_type[i];
4641 if (type != STACK_MISC && type != STACK_ZERO) {
4648 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4651 err = destroy_if_dynptr_stack_slot(env, state, spi);
4655 mark_stack_slot_scratched(env, spi);
4656 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4657 !register_is_null(reg) && env->bpf_capable) {
4658 if (dst_reg != BPF_REG_FP) {
4659 /* The backtracking logic can only recognize explicit
4660 * stack slot address like [fp - 8]. Other spill of
4661 * scalar via different register has to be conservative.
4662 * Backtrack from here and mark all registers as precise
4663 * that contributed into 'reg' being a constant.
4665 err = mark_chain_precision(env, value_regno);
4669 save_register_state(state, spi, reg, size);
4670 /* Break the relation on a narrowing spill. */
4671 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4672 state->stack[spi].spilled_ptr.id = 0;
4673 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4674 insn->imm != 0 && env->bpf_capable) {
4675 struct bpf_reg_state fake_reg = {};
4677 __mark_reg_known(&fake_reg, (u32)insn->imm);
4678 fake_reg.type = SCALAR_VALUE;
4679 save_register_state(state, spi, &fake_reg, size);
4680 } else if (reg && is_spillable_regtype(reg->type)) {
4681 /* register containing pointer is being spilled into stack */
4682 if (size != BPF_REG_SIZE) {
4683 verbose_linfo(env, insn_idx, "; ");
4684 verbose(env, "invalid size of register spill\n");
4687 if (state != cur && reg->type == PTR_TO_STACK) {
4688 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4691 save_register_state(state, spi, reg, size);
4693 u8 type = STACK_MISC;
4695 /* regular write of data into stack destroys any spilled ptr */
4696 state->stack[spi].spilled_ptr.type = NOT_INIT;
4697 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4698 if (is_stack_slot_special(&state->stack[spi]))
4699 for (i = 0; i < BPF_REG_SIZE; i++)
4700 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4702 /* only mark the slot as written if all 8 bytes were written
4703 * otherwise read propagation may incorrectly stop too soon
4704 * when stack slots are partially written.
4705 * This heuristic means that read propagation will be
4706 * conservative, since it will add reg_live_read marks
4707 * to stack slots all the way to first state when programs
4708 * writes+reads less than 8 bytes
4710 if (size == BPF_REG_SIZE)
4711 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4713 /* when we zero initialize stack slots mark them as such */
4714 if ((reg && register_is_null(reg)) ||
4715 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4716 /* backtracking doesn't work for STACK_ZERO yet. */
4717 err = mark_chain_precision(env, value_regno);
4723 /* Mark slots affected by this stack write. */
4724 for (i = 0; i < size; i++)
4725 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4731 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4732 * known to contain a variable offset.
4733 * This function checks whether the write is permitted and conservatively
4734 * tracks the effects of the write, considering that each stack slot in the
4735 * dynamic range is potentially written to.
4737 * 'off' includes 'regno->off'.
4738 * 'value_regno' can be -1, meaning that an unknown value is being written to
4741 * Spilled pointers in range are not marked as written because we don't know
4742 * what's going to be actually written. This means that read propagation for
4743 * future reads cannot be terminated by this write.
4745 * For privileged programs, uninitialized stack slots are considered
4746 * initialized by this write (even though we don't know exactly what offsets
4747 * are going to be written to). The idea is that we don't want the verifier to
4748 * reject future reads that access slots written to through variable offsets.
4750 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4751 /* func where register points to */
4752 struct bpf_func_state *state,
4753 int ptr_regno, int off, int size,
4754 int value_regno, int insn_idx)
4756 struct bpf_func_state *cur; /* state of the current function */
4757 int min_off, max_off;
4759 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4760 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4761 bool writing_zero = false;
4762 /* set if the fact that we're writing a zero is used to let any
4763 * stack slots remain STACK_ZERO
4765 bool zero_used = false;
4767 cur = env->cur_state->frame[env->cur_state->curframe];
4768 ptr_reg = &cur->regs[ptr_regno];
4769 min_off = ptr_reg->smin_value + off;
4770 max_off = ptr_reg->smax_value + off + size;
4771 if (value_regno >= 0)
4772 value_reg = &cur->regs[value_regno];
4773 if ((value_reg && register_is_null(value_reg)) ||
4774 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4775 writing_zero = true;
4777 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4781 for (i = min_off; i < max_off; i++) {
4785 err = destroy_if_dynptr_stack_slot(env, state, spi);
4790 /* Variable offset writes destroy any spilled pointers in range. */
4791 for (i = min_off; i < max_off; i++) {
4792 u8 new_type, *stype;
4796 spi = slot / BPF_REG_SIZE;
4797 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4798 mark_stack_slot_scratched(env, spi);
4800 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4801 /* Reject the write if range we may write to has not
4802 * been initialized beforehand. If we didn't reject
4803 * here, the ptr status would be erased below (even
4804 * though not all slots are actually overwritten),
4805 * possibly opening the door to leaks.
4807 * We do however catch STACK_INVALID case below, and
4808 * only allow reading possibly uninitialized memory
4809 * later for CAP_PERFMON, as the write may not happen to
4812 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4817 /* Erase all spilled pointers. */
4818 state->stack[spi].spilled_ptr.type = NOT_INIT;
4820 /* Update the slot type. */
4821 new_type = STACK_MISC;
4822 if (writing_zero && *stype == STACK_ZERO) {
4823 new_type = STACK_ZERO;
4826 /* If the slot is STACK_INVALID, we check whether it's OK to
4827 * pretend that it will be initialized by this write. The slot
4828 * might not actually be written to, and so if we mark it as
4829 * initialized future reads might leak uninitialized memory.
4830 * For privileged programs, we will accept such reads to slots
4831 * that may or may not be written because, if we're reject
4832 * them, the error would be too confusing.
4834 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4835 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4842 /* backtracking doesn't work for STACK_ZERO yet. */
4843 err = mark_chain_precision(env, value_regno);
4850 /* When register 'dst_regno' is assigned some values from stack[min_off,
4851 * max_off), we set the register's type according to the types of the
4852 * respective stack slots. If all the stack values are known to be zeros, then
4853 * so is the destination reg. Otherwise, the register is considered to be
4854 * SCALAR. This function does not deal with register filling; the caller must
4855 * ensure that all spilled registers in the stack range have been marked as
4858 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4859 /* func where src register points to */
4860 struct bpf_func_state *ptr_state,
4861 int min_off, int max_off, int dst_regno)
4863 struct bpf_verifier_state *vstate = env->cur_state;
4864 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4869 for (i = min_off; i < max_off; i++) {
4871 spi = slot / BPF_REG_SIZE;
4872 mark_stack_slot_scratched(env, spi);
4873 stype = ptr_state->stack[spi].slot_type;
4874 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4878 if (zeros == max_off - min_off) {
4879 /* any access_size read into register is zero extended,
4880 * so the whole register == const_zero
4882 __mark_reg_const_zero(&state->regs[dst_regno]);
4883 /* backtracking doesn't support STACK_ZERO yet,
4884 * so mark it precise here, so that later
4885 * backtracking can stop here.
4886 * Backtracking may not need this if this register
4887 * doesn't participate in pointer adjustment.
4888 * Forward propagation of precise flag is not
4889 * necessary either. This mark is only to stop
4890 * backtracking. Any register that contributed
4891 * to const 0 was marked precise before spill.
4893 state->regs[dst_regno].precise = true;
4895 /* have read misc data from the stack */
4896 mark_reg_unknown(env, state->regs, dst_regno);
4898 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4901 /* Read the stack at 'off' and put the results into the register indicated by
4902 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4905 * 'dst_regno' can be -1, meaning that the read value is not going to a
4908 * The access is assumed to be within the current stack bounds.
4910 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4911 /* func where src register points to */
4912 struct bpf_func_state *reg_state,
4913 int off, int size, int dst_regno)
4915 struct bpf_verifier_state *vstate = env->cur_state;
4916 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4917 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4918 struct bpf_reg_state *reg;
4921 stype = reg_state->stack[spi].slot_type;
4922 reg = ®_state->stack[spi].spilled_ptr;
4924 mark_stack_slot_scratched(env, spi);
4926 if (is_spilled_reg(®_state->stack[spi])) {
4929 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4932 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4933 if (reg->type != SCALAR_VALUE) {
4934 verbose_linfo(env, env->insn_idx, "; ");
4935 verbose(env, "invalid size of register fill\n");
4939 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4943 if (!(off % BPF_REG_SIZE) && size == spill_size) {
4944 /* The earlier check_reg_arg() has decided the
4945 * subreg_def for this insn. Save it first.
4947 s32 subreg_def = state->regs[dst_regno].subreg_def;
4949 copy_register_state(&state->regs[dst_regno], reg);
4950 state->regs[dst_regno].subreg_def = subreg_def;
4952 for (i = 0; i < size; i++) {
4953 type = stype[(slot - i) % BPF_REG_SIZE];
4954 if (type == STACK_SPILL)
4956 if (type == STACK_MISC)
4958 if (type == STACK_INVALID && env->allow_uninit_stack)
4960 verbose(env, "invalid read from stack off %d+%d size %d\n",
4964 mark_reg_unknown(env, state->regs, dst_regno);
4966 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4970 if (dst_regno >= 0) {
4971 /* restore register state from stack */
4972 copy_register_state(&state->regs[dst_regno], reg);
4973 /* mark reg as written since spilled pointer state likely
4974 * has its liveness marks cleared by is_state_visited()
4975 * which resets stack/reg liveness for state transitions
4977 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4978 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4979 /* If dst_regno==-1, the caller is asking us whether
4980 * it is acceptable to use this value as a SCALAR_VALUE
4982 * We must not allow unprivileged callers to do that
4983 * with spilled pointers.
4985 verbose(env, "leaking pointer from stack off %d\n",
4989 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4991 for (i = 0; i < size; i++) {
4992 type = stype[(slot - i) % BPF_REG_SIZE];
4993 if (type == STACK_MISC)
4995 if (type == STACK_ZERO)
4997 if (type == STACK_INVALID && env->allow_uninit_stack)
4999 verbose(env, "invalid read from stack off %d+%d size %d\n",
5003 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5005 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5010 enum bpf_access_src {
5011 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
5012 ACCESS_HELPER = 2, /* the access is performed by a helper */
5015 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5016 int regno, int off, int access_size,
5017 bool zero_size_allowed,
5018 enum bpf_access_src type,
5019 struct bpf_call_arg_meta *meta);
5021 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5023 return cur_regs(env) + regno;
5026 /* Read the stack at 'ptr_regno + off' and put the result into the register
5028 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5029 * but not its variable offset.
5030 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5032 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5033 * filling registers (i.e. reads of spilled register cannot be detected when
5034 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5035 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5036 * offset; for a fixed offset check_stack_read_fixed_off should be used
5039 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5040 int ptr_regno, int off, int size, int dst_regno)
5042 /* The state of the source register. */
5043 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5044 struct bpf_func_state *ptr_state = func(env, reg);
5046 int min_off, max_off;
5048 /* Note that we pass a NULL meta, so raw access will not be permitted.
5050 err = check_stack_range_initialized(env, ptr_regno, off, size,
5051 false, ACCESS_DIRECT, NULL);
5055 min_off = reg->smin_value + off;
5056 max_off = reg->smax_value + off;
5057 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5061 /* check_stack_read dispatches to check_stack_read_fixed_off or
5062 * check_stack_read_var_off.
5064 * The caller must ensure that the offset falls within the allocated stack
5067 * 'dst_regno' is a register which will receive the value from the stack. It
5068 * can be -1, meaning that the read value is not going to a register.
5070 static int check_stack_read(struct bpf_verifier_env *env,
5071 int ptr_regno, int off, int size,
5074 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5075 struct bpf_func_state *state = func(env, reg);
5077 /* Some accesses are only permitted with a static offset. */
5078 bool var_off = !tnum_is_const(reg->var_off);
5080 /* The offset is required to be static when reads don't go to a
5081 * register, in order to not leak pointers (see
5082 * check_stack_read_fixed_off).
5084 if (dst_regno < 0 && var_off) {
5087 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5088 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5092 /* Variable offset is prohibited for unprivileged mode for simplicity
5093 * since it requires corresponding support in Spectre masking for stack
5094 * ALU. See also retrieve_ptr_limit(). The check in
5095 * check_stack_access_for_ptr_arithmetic() called by
5096 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5097 * with variable offsets, therefore no check is required here. Further,
5098 * just checking it here would be insufficient as speculative stack
5099 * writes could still lead to unsafe speculative behaviour.
5102 off += reg->var_off.value;
5103 err = check_stack_read_fixed_off(env, state, off, size,
5106 /* Variable offset stack reads need more conservative handling
5107 * than fixed offset ones. Note that dst_regno >= 0 on this
5110 err = check_stack_read_var_off(env, ptr_regno, off, size,
5117 /* check_stack_write dispatches to check_stack_write_fixed_off or
5118 * check_stack_write_var_off.
5120 * 'ptr_regno' is the register used as a pointer into the stack.
5121 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5122 * 'value_regno' is the register whose value we're writing to the stack. It can
5123 * be -1, meaning that we're not writing from a register.
5125 * The caller must ensure that the offset falls within the maximum stack size.
5127 static int check_stack_write(struct bpf_verifier_env *env,
5128 int ptr_regno, int off, int size,
5129 int value_regno, int insn_idx)
5131 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5132 struct bpf_func_state *state = func(env, reg);
5135 if (tnum_is_const(reg->var_off)) {
5136 off += reg->var_off.value;
5137 err = check_stack_write_fixed_off(env, state, off, size,
5138 value_regno, insn_idx);
5140 /* Variable offset stack reads need more conservative handling
5141 * than fixed offset ones.
5143 err = check_stack_write_var_off(env, state,
5144 ptr_regno, off, size,
5145 value_regno, insn_idx);
5150 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5151 int off, int size, enum bpf_access_type type)
5153 struct bpf_reg_state *regs = cur_regs(env);
5154 struct bpf_map *map = regs[regno].map_ptr;
5155 u32 cap = bpf_map_flags_to_cap(map);
5157 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5158 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5159 map->value_size, off, size);
5163 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5164 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5165 map->value_size, off, size);
5172 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5173 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5174 int off, int size, u32 mem_size,
5175 bool zero_size_allowed)
5177 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5178 struct bpf_reg_state *reg;
5180 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5183 reg = &cur_regs(env)[regno];
5184 switch (reg->type) {
5185 case PTR_TO_MAP_KEY:
5186 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5187 mem_size, off, size);
5189 case PTR_TO_MAP_VALUE:
5190 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5191 mem_size, off, size);
5194 case PTR_TO_PACKET_META:
5195 case PTR_TO_PACKET_END:
5196 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5197 off, size, regno, reg->id, off, mem_size);
5201 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5202 mem_size, off, size);
5208 /* check read/write into a memory region with possible variable offset */
5209 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5210 int off, int size, u32 mem_size,
5211 bool zero_size_allowed)
5213 struct bpf_verifier_state *vstate = env->cur_state;
5214 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5215 struct bpf_reg_state *reg = &state->regs[regno];
5218 /* We may have adjusted the register pointing to memory region, so we
5219 * need to try adding each of min_value and max_value to off
5220 * to make sure our theoretical access will be safe.
5222 * The minimum value is only important with signed
5223 * comparisons where we can't assume the floor of a
5224 * value is 0. If we are using signed variables for our
5225 * index'es we need to make sure that whatever we use
5226 * will have a set floor within our range.
5228 if (reg->smin_value < 0 &&
5229 (reg->smin_value == S64_MIN ||
5230 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5231 reg->smin_value + off < 0)) {
5232 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5236 err = __check_mem_access(env, regno, reg->smin_value + off, size,
5237 mem_size, zero_size_allowed);
5239 verbose(env, "R%d min value is outside of the allowed memory range\n",
5244 /* If we haven't set a max value then we need to bail since we can't be
5245 * sure we won't do bad things.
5246 * If reg->umax_value + off could overflow, treat that as unbounded too.
5248 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5249 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5253 err = __check_mem_access(env, regno, reg->umax_value + off, size,
5254 mem_size, zero_size_allowed);
5256 verbose(env, "R%d max value is outside of the allowed memory range\n",
5264 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5265 const struct bpf_reg_state *reg, int regno,
5268 /* Access to this pointer-typed register or passing it to a helper
5269 * is only allowed in its original, unmodified form.
5273 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5274 reg_type_str(env, reg->type), regno, reg->off);
5278 if (!fixed_off_ok && reg->off) {
5279 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5280 reg_type_str(env, reg->type), regno, reg->off);
5284 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5287 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5288 verbose(env, "variable %s access var_off=%s disallowed\n",
5289 reg_type_str(env, reg->type), tn_buf);
5296 int check_ptr_off_reg(struct bpf_verifier_env *env,
5297 const struct bpf_reg_state *reg, int regno)
5299 return __check_ptr_off_reg(env, reg, regno, false);
5302 static int map_kptr_match_type(struct bpf_verifier_env *env,
5303 struct btf_field *kptr_field,
5304 struct bpf_reg_state *reg, u32 regno)
5306 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5308 const char *reg_name = "";
5310 if (btf_is_kernel(reg->btf)) {
5311 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5313 /* Only unreferenced case accepts untrusted pointers */
5314 if (kptr_field->type == BPF_KPTR_UNREF)
5315 perm_flags |= PTR_UNTRUSTED;
5317 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5318 if (kptr_field->type == BPF_KPTR_PERCPU)
5319 perm_flags |= MEM_PERCPU;
5322 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5325 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5326 reg_name = btf_type_name(reg->btf, reg->btf_id);
5328 /* For ref_ptr case, release function check should ensure we get one
5329 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5330 * normal store of unreferenced kptr, we must ensure var_off is zero.
5331 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5332 * reg->off and reg->ref_obj_id are not needed here.
5334 if (__check_ptr_off_reg(env, reg, regno, true))
5337 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5338 * we also need to take into account the reg->off.
5340 * We want to support cases like:
5348 * v = func(); // PTR_TO_BTF_ID
5349 * val->foo = v; // reg->off is zero, btf and btf_id match type
5350 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5351 * // first member type of struct after comparison fails
5352 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5355 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5356 * is zero. We must also ensure that btf_struct_ids_match does not walk
5357 * the struct to match type against first member of struct, i.e. reject
5358 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5359 * strict mode to true for type match.
5361 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5362 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5363 kptr_field->type != BPF_KPTR_UNREF))
5367 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5368 reg_type_str(env, reg->type), reg_name);
5369 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5370 if (kptr_field->type == BPF_KPTR_UNREF)
5371 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5378 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5379 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5381 static bool in_rcu_cs(struct bpf_verifier_env *env)
5383 return env->cur_state->active_rcu_lock ||
5384 env->cur_state->active_lock.ptr ||
5385 !env->prog->aux->sleepable;
5388 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5389 BTF_SET_START(rcu_protected_types)
5390 BTF_ID(struct, prog_test_ref_kfunc)
5391 #ifdef CONFIG_CGROUPS
5392 BTF_ID(struct, cgroup)
5394 BTF_ID(struct, bpf_cpumask)
5395 BTF_ID(struct, task_struct)
5396 BTF_SET_END(rcu_protected_types)
5398 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5400 if (!btf_is_kernel(btf))
5402 return btf_id_set_contains(&rcu_protected_types, btf_id);
5405 static bool rcu_safe_kptr(const struct btf_field *field)
5407 const struct btf_field_kptr *kptr = &field->kptr;
5409 return field->type == BPF_KPTR_PERCPU ||
5410 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5413 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5415 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5416 if (kptr_field->type != BPF_KPTR_PERCPU)
5417 return PTR_MAYBE_NULL | MEM_RCU;
5418 return PTR_MAYBE_NULL | MEM_RCU | MEM_PERCPU;
5420 return PTR_MAYBE_NULL | PTR_UNTRUSTED;
5423 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5424 int value_regno, int insn_idx,
5425 struct btf_field *kptr_field)
5427 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5428 int class = BPF_CLASS(insn->code);
5429 struct bpf_reg_state *val_reg;
5431 /* Things we already checked for in check_map_access and caller:
5432 * - Reject cases where variable offset may touch kptr
5433 * - size of access (must be BPF_DW)
5434 * - tnum_is_const(reg->var_off)
5435 * - kptr_field->offset == off + reg->var_off.value
5437 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5438 if (BPF_MODE(insn->code) != BPF_MEM) {
5439 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5443 /* We only allow loading referenced kptr, since it will be marked as
5444 * untrusted, similar to unreferenced kptr.
5446 if (class != BPF_LDX &&
5447 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5448 verbose(env, "store to referenced kptr disallowed\n");
5452 if (class == BPF_LDX) {
5453 val_reg = reg_state(env, value_regno);
5454 /* We can simply mark the value_regno receiving the pointer
5455 * value from map as PTR_TO_BTF_ID, with the correct type.
5457 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5458 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5459 /* For mark_ptr_or_null_reg */
5460 val_reg->id = ++env->id_gen;
5461 } else if (class == BPF_STX) {
5462 val_reg = reg_state(env, value_regno);
5463 if (!register_is_null(val_reg) &&
5464 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5466 } else if (class == BPF_ST) {
5468 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5469 kptr_field->offset);
5473 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5479 /* check read/write into a map element with possible variable offset */
5480 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5481 int off, int size, bool zero_size_allowed,
5482 enum bpf_access_src src)
5484 struct bpf_verifier_state *vstate = env->cur_state;
5485 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5486 struct bpf_reg_state *reg = &state->regs[regno];
5487 struct bpf_map *map = reg->map_ptr;
5488 struct btf_record *rec;
5491 err = check_mem_region_access(env, regno, off, size, map->value_size,
5496 if (IS_ERR_OR_NULL(map->record))
5499 for (i = 0; i < rec->cnt; i++) {
5500 struct btf_field *field = &rec->fields[i];
5501 u32 p = field->offset;
5503 /* If any part of a field can be touched by load/store, reject
5504 * this program. To check that [x1, x2) overlaps with [y1, y2),
5505 * it is sufficient to check x1 < y2 && y1 < x2.
5507 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5508 p < reg->umax_value + off + size) {
5509 switch (field->type) {
5510 case BPF_KPTR_UNREF:
5512 case BPF_KPTR_PERCPU:
5513 if (src != ACCESS_DIRECT) {
5514 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5517 if (!tnum_is_const(reg->var_off)) {
5518 verbose(env, "kptr access cannot have variable offset\n");
5521 if (p != off + reg->var_off.value) {
5522 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5523 p, off + reg->var_off.value);
5526 if (size != bpf_size_to_bytes(BPF_DW)) {
5527 verbose(env, "kptr access size must be BPF_DW\n");
5532 verbose(env, "%s cannot be accessed directly by load/store\n",
5533 btf_field_type_name(field->type));
5541 #define MAX_PACKET_OFF 0xffff
5543 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5544 const struct bpf_call_arg_meta *meta,
5545 enum bpf_access_type t)
5547 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5549 switch (prog_type) {
5550 /* Program types only with direct read access go here! */
5551 case BPF_PROG_TYPE_LWT_IN:
5552 case BPF_PROG_TYPE_LWT_OUT:
5553 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5554 case BPF_PROG_TYPE_SK_REUSEPORT:
5555 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5556 case BPF_PROG_TYPE_CGROUP_SKB:
5561 /* Program types with direct read + write access go here! */
5562 case BPF_PROG_TYPE_SCHED_CLS:
5563 case BPF_PROG_TYPE_SCHED_ACT:
5564 case BPF_PROG_TYPE_XDP:
5565 case BPF_PROG_TYPE_LWT_XMIT:
5566 case BPF_PROG_TYPE_SK_SKB:
5567 case BPF_PROG_TYPE_SK_MSG:
5569 return meta->pkt_access;
5571 env->seen_direct_write = true;
5574 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5576 env->seen_direct_write = true;
5585 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5586 int size, bool zero_size_allowed)
5588 struct bpf_reg_state *regs = cur_regs(env);
5589 struct bpf_reg_state *reg = ®s[regno];
5592 /* We may have added a variable offset to the packet pointer; but any
5593 * reg->range we have comes after that. We are only checking the fixed
5597 /* We don't allow negative numbers, because we aren't tracking enough
5598 * detail to prove they're safe.
5600 if (reg->smin_value < 0) {
5601 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5606 err = reg->range < 0 ? -EINVAL :
5607 __check_mem_access(env, regno, off, size, reg->range,
5610 verbose(env, "R%d offset is outside of the packet\n", regno);
5614 /* __check_mem_access has made sure "off + size - 1" is within u16.
5615 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5616 * otherwise find_good_pkt_pointers would have refused to set range info
5617 * that __check_mem_access would have rejected this pkt access.
5618 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5620 env->prog->aux->max_pkt_offset =
5621 max_t(u32, env->prog->aux->max_pkt_offset,
5622 off + reg->umax_value + size - 1);
5627 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
5628 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5629 enum bpf_access_type t, enum bpf_reg_type *reg_type,
5630 struct btf **btf, u32 *btf_id)
5632 struct bpf_insn_access_aux info = {
5633 .reg_type = *reg_type,
5637 if (env->ops->is_valid_access &&
5638 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5639 /* A non zero info.ctx_field_size indicates that this field is a
5640 * candidate for later verifier transformation to load the whole
5641 * field and then apply a mask when accessed with a narrower
5642 * access than actual ctx access size. A zero info.ctx_field_size
5643 * will only allow for whole field access and rejects any other
5644 * type of narrower access.
5646 *reg_type = info.reg_type;
5648 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5650 *btf_id = info.btf_id;
5652 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5654 /* remember the offset of last byte accessed in ctx */
5655 if (env->prog->aux->max_ctx_offset < off + size)
5656 env->prog->aux->max_ctx_offset = off + size;
5660 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5664 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5667 if (size < 0 || off < 0 ||
5668 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5669 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5676 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5677 u32 regno, int off, int size,
5678 enum bpf_access_type t)
5680 struct bpf_reg_state *regs = cur_regs(env);
5681 struct bpf_reg_state *reg = ®s[regno];
5682 struct bpf_insn_access_aux info = {};
5685 if (reg->smin_value < 0) {
5686 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5691 switch (reg->type) {
5692 case PTR_TO_SOCK_COMMON:
5693 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5696 valid = bpf_sock_is_valid_access(off, size, t, &info);
5698 case PTR_TO_TCP_SOCK:
5699 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5701 case PTR_TO_XDP_SOCK:
5702 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5710 env->insn_aux_data[insn_idx].ctx_field_size =
5711 info.ctx_field_size;
5715 verbose(env, "R%d invalid %s access off=%d size=%d\n",
5716 regno, reg_type_str(env, reg->type), off, size);
5721 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5723 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5726 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5728 const struct bpf_reg_state *reg = reg_state(env, regno);
5730 return reg->type == PTR_TO_CTX;
5733 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5735 const struct bpf_reg_state *reg = reg_state(env, regno);
5737 return type_is_sk_pointer(reg->type);
5740 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5742 const struct bpf_reg_state *reg = reg_state(env, regno);
5744 return type_is_pkt_pointer(reg->type);
5747 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5749 const struct bpf_reg_state *reg = reg_state(env, regno);
5751 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5752 return reg->type == PTR_TO_FLOW_KEYS;
5755 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5757 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5758 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5759 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5761 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5764 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5766 /* A referenced register is always trusted. */
5767 if (reg->ref_obj_id)
5770 /* Types listed in the reg2btf_ids are always trusted */
5771 if (reg2btf_ids[base_type(reg->type)])
5774 /* If a register is not referenced, it is trusted if it has the
5775 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5776 * other type modifiers may be safe, but we elect to take an opt-in
5777 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5780 * Eventually, we should make PTR_TRUSTED the single source of truth
5781 * for whether a register is trusted.
5783 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5784 !bpf_type_has_unsafe_modifiers(reg->type);
5787 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5789 return reg->type & MEM_RCU;
5792 static void clear_trusted_flags(enum bpf_type_flag *flag)
5794 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5797 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5798 const struct bpf_reg_state *reg,
5799 int off, int size, bool strict)
5801 struct tnum reg_off;
5804 /* Byte size accesses are always allowed. */
5805 if (!strict || size == 1)
5808 /* For platforms that do not have a Kconfig enabling
5809 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5810 * NET_IP_ALIGN is universally set to '2'. And on platforms
5811 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5812 * to this code only in strict mode where we want to emulate
5813 * the NET_IP_ALIGN==2 checking. Therefore use an
5814 * unconditional IP align value of '2'.
5818 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5819 if (!tnum_is_aligned(reg_off, size)) {
5822 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5824 "misaligned packet access off %d+%s+%d+%d size %d\n",
5825 ip_align, tn_buf, reg->off, off, size);
5832 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5833 const struct bpf_reg_state *reg,
5834 const char *pointer_desc,
5835 int off, int size, bool strict)
5837 struct tnum reg_off;
5839 /* Byte size accesses are always allowed. */
5840 if (!strict || size == 1)
5843 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5844 if (!tnum_is_aligned(reg_off, size)) {
5847 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5848 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5849 pointer_desc, tn_buf, reg->off, off, size);
5856 static int check_ptr_alignment(struct bpf_verifier_env *env,
5857 const struct bpf_reg_state *reg, int off,
5858 int size, bool strict_alignment_once)
5860 bool strict = env->strict_alignment || strict_alignment_once;
5861 const char *pointer_desc = "";
5863 switch (reg->type) {
5865 case PTR_TO_PACKET_META:
5866 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5867 * right in front, treat it the very same way.
5869 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5870 case PTR_TO_FLOW_KEYS:
5871 pointer_desc = "flow keys ";
5873 case PTR_TO_MAP_KEY:
5874 pointer_desc = "key ";
5876 case PTR_TO_MAP_VALUE:
5877 pointer_desc = "value ";
5880 pointer_desc = "context ";
5883 pointer_desc = "stack ";
5884 /* The stack spill tracking logic in check_stack_write_fixed_off()
5885 * and check_stack_read_fixed_off() relies on stack accesses being
5891 pointer_desc = "sock ";
5893 case PTR_TO_SOCK_COMMON:
5894 pointer_desc = "sock_common ";
5896 case PTR_TO_TCP_SOCK:
5897 pointer_desc = "tcp_sock ";
5899 case PTR_TO_XDP_SOCK:
5900 pointer_desc = "xdp_sock ";
5905 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5909 static int update_stack_depth(struct bpf_verifier_env *env,
5910 const struct bpf_func_state *func,
5913 u16 stack = env->subprog_info[func->subprogno].stack_depth;
5918 /* update known max for given subprogram */
5919 env->subprog_info[func->subprogno].stack_depth = -off;
5923 /* starting from main bpf function walk all instructions of the function
5924 * and recursively walk all callees that given function can call.
5925 * Ignore jump and exit insns.
5926 * Since recursion is prevented by check_cfg() this algorithm
5927 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5929 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5931 struct bpf_subprog_info *subprog = env->subprog_info;
5932 struct bpf_insn *insn = env->prog->insnsi;
5933 int depth = 0, frame = 0, i, subprog_end;
5934 bool tail_call_reachable = false;
5935 int ret_insn[MAX_CALL_FRAMES];
5936 int ret_prog[MAX_CALL_FRAMES];
5939 i = subprog[idx].start;
5941 /* protect against potential stack overflow that might happen when
5942 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5943 * depth for such case down to 256 so that the worst case scenario
5944 * would result in 8k stack size (32 which is tailcall limit * 256 =
5947 * To get the idea what might happen, see an example:
5948 * func1 -> sub rsp, 128
5949 * subfunc1 -> sub rsp, 256
5950 * tailcall1 -> add rsp, 256
5951 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5952 * subfunc2 -> sub rsp, 64
5953 * subfunc22 -> sub rsp, 128
5954 * tailcall2 -> add rsp, 128
5955 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5957 * tailcall will unwind the current stack frame but it will not get rid
5958 * of caller's stack as shown on the example above.
5960 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5962 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5966 /* round up to 32-bytes, since this is granularity
5967 * of interpreter stack size
5969 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5970 if (depth > MAX_BPF_STACK) {
5971 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5976 subprog_end = subprog[idx + 1].start;
5977 for (; i < subprog_end; i++) {
5978 int next_insn, sidx;
5980 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5983 if (!is_bpf_throw_kfunc(insn + i))
5985 if (subprog[idx].is_cb)
5987 for (int c = 0; c < frame && !err; c++) {
5988 if (subprog[ret_prog[c]].is_cb) {
5996 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6001 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6003 /* remember insn and function to return to */
6004 ret_insn[frame] = i + 1;
6005 ret_prog[frame] = idx;
6007 /* find the callee */
6008 next_insn = i + insn[i].imm + 1;
6009 sidx = find_subprog(env, next_insn);
6011 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6015 if (subprog[sidx].is_async_cb) {
6016 if (subprog[sidx].has_tail_call) {
6017 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
6020 /* async callbacks don't increase bpf prog stack size unless called directly */
6021 if (!bpf_pseudo_call(insn + i))
6023 if (subprog[sidx].is_exception_cb) {
6024 verbose(env, "insn %d cannot call exception cb directly\n", i);
6031 if (subprog[idx].has_tail_call)
6032 tail_call_reachable = true;
6035 if (frame >= MAX_CALL_FRAMES) {
6036 verbose(env, "the call stack of %d frames is too deep !\n",
6042 /* if tail call got detected across bpf2bpf calls then mark each of the
6043 * currently present subprog frames as tail call reachable subprogs;
6044 * this info will be utilized by JIT so that we will be preserving the
6045 * tail call counter throughout bpf2bpf calls combined with tailcalls
6047 if (tail_call_reachable)
6048 for (j = 0; j < frame; j++) {
6049 if (subprog[ret_prog[j]].is_exception_cb) {
6050 verbose(env, "cannot tail call within exception cb\n");
6053 subprog[ret_prog[j]].tail_call_reachable = true;
6055 if (subprog[0].tail_call_reachable)
6056 env->prog->aux->tail_call_reachable = true;
6058 /* end of for() loop means the last insn of the 'subprog'
6059 * was reached. Doesn't matter whether it was JA or EXIT
6063 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
6065 i = ret_insn[frame];
6066 idx = ret_prog[frame];
6070 static int check_max_stack_depth(struct bpf_verifier_env *env)
6072 struct bpf_subprog_info *si = env->subprog_info;
6075 for (int i = 0; i < env->subprog_cnt; i++) {
6076 if (!i || si[i].is_async_cb) {
6077 ret = check_max_stack_depth_subprog(env, i);
6086 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6087 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6088 const struct bpf_insn *insn, int idx)
6090 int start = idx + insn->imm + 1, subprog;
6092 subprog = find_subprog(env, start);
6094 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6098 return env->subprog_info[subprog].stack_depth;
6102 static int __check_buffer_access(struct bpf_verifier_env *env,
6103 const char *buf_info,
6104 const struct bpf_reg_state *reg,
6105 int regno, int off, int size)
6109 "R%d invalid %s buffer access: off=%d, size=%d\n",
6110 regno, buf_info, off, size);
6113 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6116 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6118 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6119 regno, off, tn_buf);
6126 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6127 const struct bpf_reg_state *reg,
6128 int regno, int off, int size)
6132 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6136 if (off + size > env->prog->aux->max_tp_access)
6137 env->prog->aux->max_tp_access = off + size;
6142 static int check_buffer_access(struct bpf_verifier_env *env,
6143 const struct bpf_reg_state *reg,
6144 int regno, int off, int size,
6145 bool zero_size_allowed,
6148 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6151 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6155 if (off + size > *max_access)
6156 *max_access = off + size;
6161 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6162 static void zext_32_to_64(struct bpf_reg_state *reg)
6164 reg->var_off = tnum_subreg(reg->var_off);
6165 __reg_assign_32_into_64(reg);
6168 /* truncate register to smaller size (in bytes)
6169 * must be called with size < BPF_REG_SIZE
6171 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6175 /* clear high bits in bit representation */
6176 reg->var_off = tnum_cast(reg->var_off, size);
6178 /* fix arithmetic bounds */
6179 mask = ((u64)1 << (size * 8)) - 1;
6180 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6181 reg->umin_value &= mask;
6182 reg->umax_value &= mask;
6184 reg->umin_value = 0;
6185 reg->umax_value = mask;
6187 reg->smin_value = reg->umin_value;
6188 reg->smax_value = reg->umax_value;
6190 /* If size is smaller than 32bit register the 32bit register
6191 * values are also truncated so we push 64-bit bounds into
6192 * 32-bit bounds. Above were truncated < 32-bits already.
6196 __reg_combine_64_into_32(reg);
6199 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6202 reg->smin_value = reg->s32_min_value = S8_MIN;
6203 reg->smax_value = reg->s32_max_value = S8_MAX;
6204 } else if (size == 2) {
6205 reg->smin_value = reg->s32_min_value = S16_MIN;
6206 reg->smax_value = reg->s32_max_value = S16_MAX;
6209 reg->smin_value = reg->s32_min_value = S32_MIN;
6210 reg->smax_value = reg->s32_max_value = S32_MAX;
6212 reg->umin_value = reg->u32_min_value = 0;
6213 reg->umax_value = U64_MAX;
6214 reg->u32_max_value = U32_MAX;
6215 reg->var_off = tnum_unknown;
6218 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6220 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6221 u64 top_smax_value, top_smin_value;
6222 u64 num_bits = size * 8;
6224 if (tnum_is_const(reg->var_off)) {
6225 u64_cval = reg->var_off.value;
6227 reg->var_off = tnum_const((s8)u64_cval);
6229 reg->var_off = tnum_const((s16)u64_cval);
6232 reg->var_off = tnum_const((s32)u64_cval);
6234 u64_cval = reg->var_off.value;
6235 reg->smax_value = reg->smin_value = u64_cval;
6236 reg->umax_value = reg->umin_value = u64_cval;
6237 reg->s32_max_value = reg->s32_min_value = u64_cval;
6238 reg->u32_max_value = reg->u32_min_value = u64_cval;
6242 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6243 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6245 if (top_smax_value != top_smin_value)
6248 /* find the s64_min and s64_min after sign extension */
6250 init_s64_max = (s8)reg->smax_value;
6251 init_s64_min = (s8)reg->smin_value;
6252 } else if (size == 2) {
6253 init_s64_max = (s16)reg->smax_value;
6254 init_s64_min = (s16)reg->smin_value;
6256 init_s64_max = (s32)reg->smax_value;
6257 init_s64_min = (s32)reg->smin_value;
6260 s64_max = max(init_s64_max, init_s64_min);
6261 s64_min = min(init_s64_max, init_s64_min);
6263 /* both of s64_max/s64_min positive or negative */
6264 if ((s64_max >= 0) == (s64_min >= 0)) {
6265 reg->smin_value = reg->s32_min_value = s64_min;
6266 reg->smax_value = reg->s32_max_value = s64_max;
6267 reg->umin_value = reg->u32_min_value = s64_min;
6268 reg->umax_value = reg->u32_max_value = s64_max;
6269 reg->var_off = tnum_range(s64_min, s64_max);
6274 set_sext64_default_val(reg, size);
6277 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6280 reg->s32_min_value = S8_MIN;
6281 reg->s32_max_value = S8_MAX;
6284 reg->s32_min_value = S16_MIN;
6285 reg->s32_max_value = S16_MAX;
6287 reg->u32_min_value = 0;
6288 reg->u32_max_value = U32_MAX;
6291 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6293 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6294 u32 top_smax_value, top_smin_value;
6295 u32 num_bits = size * 8;
6297 if (tnum_is_const(reg->var_off)) {
6298 u32_val = reg->var_off.value;
6300 reg->var_off = tnum_const((s8)u32_val);
6302 reg->var_off = tnum_const((s16)u32_val);
6304 u32_val = reg->var_off.value;
6305 reg->s32_min_value = reg->s32_max_value = u32_val;
6306 reg->u32_min_value = reg->u32_max_value = u32_val;
6310 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6311 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6313 if (top_smax_value != top_smin_value)
6316 /* find the s32_min and s32_min after sign extension */
6318 init_s32_max = (s8)reg->s32_max_value;
6319 init_s32_min = (s8)reg->s32_min_value;
6322 init_s32_max = (s16)reg->s32_max_value;
6323 init_s32_min = (s16)reg->s32_min_value;
6325 s32_max = max(init_s32_max, init_s32_min);
6326 s32_min = min(init_s32_max, init_s32_min);
6328 if ((s32_min >= 0) == (s32_max >= 0)) {
6329 reg->s32_min_value = s32_min;
6330 reg->s32_max_value = s32_max;
6331 reg->u32_min_value = (u32)s32_min;
6332 reg->u32_max_value = (u32)s32_max;
6337 set_sext32_default_val(reg, size);
6340 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6342 /* A map is considered read-only if the following condition are true:
6344 * 1) BPF program side cannot change any of the map content. The
6345 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6346 * and was set at map creation time.
6347 * 2) The map value(s) have been initialized from user space by a
6348 * loader and then "frozen", such that no new map update/delete
6349 * operations from syscall side are possible for the rest of
6350 * the map's lifetime from that point onwards.
6351 * 3) Any parallel/pending map update/delete operations from syscall
6352 * side have been completed. Only after that point, it's safe to
6353 * assume that map value(s) are immutable.
6355 return (map->map_flags & BPF_F_RDONLY_PROG) &&
6356 READ_ONCE(map->frozen) &&
6357 !bpf_map_write_active(map);
6360 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6367 err = map->ops->map_direct_value_addr(map, &addr, off);
6370 ptr = (void *)(long)addr + off;
6374 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6377 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6380 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6391 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
6392 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6393 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
6396 * Allow list few fields as RCU trusted or full trusted.
6397 * This logic doesn't allow mix tagging and will be removed once GCC supports
6401 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6402 BTF_TYPE_SAFE_RCU(struct task_struct) {
6403 const cpumask_t *cpus_ptr;
6404 struct css_set __rcu *cgroups;
6405 struct task_struct __rcu *real_parent;
6406 struct task_struct *group_leader;
6409 BTF_TYPE_SAFE_RCU(struct cgroup) {
6410 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6411 struct kernfs_node *kn;
6414 BTF_TYPE_SAFE_RCU(struct css_set) {
6415 struct cgroup *dfl_cgrp;
6418 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6419 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6420 struct file __rcu *exe_file;
6423 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6424 * because bpf prog accessible sockets are SOCK_RCU_FREE.
6426 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6430 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6434 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6435 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6436 struct seq_file *seq;
6439 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6440 struct bpf_iter_meta *meta;
6441 struct task_struct *task;
6444 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6448 BTF_TYPE_SAFE_TRUSTED(struct file) {
6449 struct inode *f_inode;
6452 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6453 /* no negative dentry-s in places where bpf can see it */
6454 struct inode *d_inode;
6457 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6461 static bool type_is_rcu(struct bpf_verifier_env *env,
6462 struct bpf_reg_state *reg,
6463 const char *field_name, u32 btf_id)
6465 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6466 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6467 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6469 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6472 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6473 struct bpf_reg_state *reg,
6474 const char *field_name, u32 btf_id)
6476 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6477 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6478 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6480 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6483 static bool type_is_trusted(struct bpf_verifier_env *env,
6484 struct bpf_reg_state *reg,
6485 const char *field_name, u32 btf_id)
6487 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6488 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6489 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6490 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6491 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6492 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6494 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6497 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6498 struct bpf_reg_state *regs,
6499 int regno, int off, int size,
6500 enum bpf_access_type atype,
6503 struct bpf_reg_state *reg = regs + regno;
6504 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6505 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6506 const char *field_name = NULL;
6507 enum bpf_type_flag flag = 0;
6511 if (!env->allow_ptr_leaks) {
6513 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6517 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6519 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6525 "R%d is ptr_%s invalid negative access: off=%d\n",
6529 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6532 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6534 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6535 regno, tname, off, tn_buf);
6539 if (reg->type & MEM_USER) {
6541 "R%d is ptr_%s access user memory: off=%d\n",
6546 if (reg->type & MEM_PERCPU) {
6548 "R%d is ptr_%s access percpu memory: off=%d\n",
6553 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6554 if (!btf_is_kernel(reg->btf)) {
6555 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6558 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6560 /* Writes are permitted with default btf_struct_access for
6561 * program allocated objects (which always have ref_obj_id > 0),
6562 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6564 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6565 verbose(env, "only read is supported\n");
6569 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6570 !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6571 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6575 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6581 if (ret != PTR_TO_BTF_ID) {
6584 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6585 /* If this is an untrusted pointer, all pointers formed by walking it
6586 * also inherit the untrusted flag.
6588 flag = PTR_UNTRUSTED;
6590 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6591 /* By default any pointer obtained from walking a trusted pointer is no
6592 * longer trusted, unless the field being accessed has explicitly been
6593 * marked as inheriting its parent's state of trust (either full or RCU).
6595 * 'cgroups' pointer is untrusted if task->cgroups dereference
6596 * happened in a sleepable program outside of bpf_rcu_read_lock()
6597 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6598 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6600 * A regular RCU-protected pointer with __rcu tag can also be deemed
6601 * trusted if we are in an RCU CS. Such pointer can be NULL.
6603 if (type_is_trusted(env, reg, field_name, btf_id)) {
6604 flag |= PTR_TRUSTED;
6605 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6606 if (type_is_rcu(env, reg, field_name, btf_id)) {
6607 /* ignore __rcu tag and mark it MEM_RCU */
6609 } else if (flag & MEM_RCU ||
6610 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6611 /* __rcu tagged pointers can be NULL */
6612 flag |= MEM_RCU | PTR_MAYBE_NULL;
6614 /* We always trust them */
6615 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6616 flag & PTR_UNTRUSTED)
6617 flag &= ~PTR_UNTRUSTED;
6618 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6621 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6622 clear_trusted_flags(&flag);
6626 * If not in RCU CS or MEM_RCU pointer can be NULL then
6627 * aggressively mark as untrusted otherwise such
6628 * pointers will be plain PTR_TO_BTF_ID without flags
6629 * and will be allowed to be passed into helpers for
6632 flag = PTR_UNTRUSTED;
6635 /* Old compat. Deprecated */
6636 clear_trusted_flags(&flag);
6639 if (atype == BPF_READ && value_regno >= 0)
6640 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6645 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6646 struct bpf_reg_state *regs,
6647 int regno, int off, int size,
6648 enum bpf_access_type atype,
6651 struct bpf_reg_state *reg = regs + regno;
6652 struct bpf_map *map = reg->map_ptr;
6653 struct bpf_reg_state map_reg;
6654 enum bpf_type_flag flag = 0;
6655 const struct btf_type *t;
6661 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6665 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6666 verbose(env, "map_ptr access not supported for map type %d\n",
6671 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6672 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6674 if (!env->allow_ptr_leaks) {
6676 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6682 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6687 if (atype != BPF_READ) {
6688 verbose(env, "only read from %s is supported\n", tname);
6692 /* Simulate access to a PTR_TO_BTF_ID */
6693 memset(&map_reg, 0, sizeof(map_reg));
6694 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6695 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6699 if (value_regno >= 0)
6700 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6705 /* Check that the stack access at the given offset is within bounds. The
6706 * maximum valid offset is -1.
6708 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6709 * -state->allocated_stack for reads.
6711 static int check_stack_slot_within_bounds(int off,
6712 struct bpf_func_state *state,
6713 enum bpf_access_type t)
6718 min_valid_off = -MAX_BPF_STACK;
6720 min_valid_off = -state->allocated_stack;
6722 if (off < min_valid_off || off > -1)
6727 /* Check that the stack access at 'regno + off' falls within the maximum stack
6730 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6732 static int check_stack_access_within_bounds(
6733 struct bpf_verifier_env *env,
6734 int regno, int off, int access_size,
6735 enum bpf_access_src src, enum bpf_access_type type)
6737 struct bpf_reg_state *regs = cur_regs(env);
6738 struct bpf_reg_state *reg = regs + regno;
6739 struct bpf_func_state *state = func(env, reg);
6740 int min_off, max_off;
6744 if (src == ACCESS_HELPER)
6745 /* We don't know if helpers are reading or writing (or both). */
6746 err_extra = " indirect access to";
6747 else if (type == BPF_READ)
6748 err_extra = " read from";
6750 err_extra = " write to";
6752 if (tnum_is_const(reg->var_off)) {
6753 min_off = reg->var_off.value + off;
6754 if (access_size > 0)
6755 max_off = min_off + access_size - 1;
6759 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6760 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6761 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6765 min_off = reg->smin_value + off;
6766 if (access_size > 0)
6767 max_off = reg->smax_value + off + access_size - 1;
6772 err = check_stack_slot_within_bounds(min_off, state, type);
6774 err = check_stack_slot_within_bounds(max_off, state, type);
6777 if (tnum_is_const(reg->var_off)) {
6778 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6779 err_extra, regno, off, access_size);
6783 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6784 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6785 err_extra, regno, tn_buf, access_size);
6791 /* check whether memory at (regno + off) is accessible for t = (read | write)
6792 * if t==write, value_regno is a register which value is stored into memory
6793 * if t==read, value_regno is a register which will receive the value from memory
6794 * if t==write && value_regno==-1, some unknown value is stored into memory
6795 * if t==read && value_regno==-1, don't care what we read from memory
6797 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6798 int off, int bpf_size, enum bpf_access_type t,
6799 int value_regno, bool strict_alignment_once, bool is_ldsx)
6801 struct bpf_reg_state *regs = cur_regs(env);
6802 struct bpf_reg_state *reg = regs + regno;
6803 struct bpf_func_state *state;
6806 size = bpf_size_to_bytes(bpf_size);
6810 /* alignment checks will add in reg->off themselves */
6811 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6815 /* for access checks, reg->off is just part of off */
6818 if (reg->type == PTR_TO_MAP_KEY) {
6819 if (t == BPF_WRITE) {
6820 verbose(env, "write to change key R%d not allowed\n", regno);
6824 err = check_mem_region_access(env, regno, off, size,
6825 reg->map_ptr->key_size, false);
6828 if (value_regno >= 0)
6829 mark_reg_unknown(env, regs, value_regno);
6830 } else if (reg->type == PTR_TO_MAP_VALUE) {
6831 struct btf_field *kptr_field = NULL;
6833 if (t == BPF_WRITE && value_regno >= 0 &&
6834 is_pointer_value(env, value_regno)) {
6835 verbose(env, "R%d leaks addr into map\n", value_regno);
6838 err = check_map_access_type(env, regno, off, size, t);
6841 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6844 if (tnum_is_const(reg->var_off))
6845 kptr_field = btf_record_find(reg->map_ptr->record,
6846 off + reg->var_off.value, BPF_KPTR);
6848 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6849 } else if (t == BPF_READ && value_regno >= 0) {
6850 struct bpf_map *map = reg->map_ptr;
6852 /* if map is read-only, track its contents as scalars */
6853 if (tnum_is_const(reg->var_off) &&
6854 bpf_map_is_rdonly(map) &&
6855 map->ops->map_direct_value_addr) {
6856 int map_off = off + reg->var_off.value;
6859 err = bpf_map_direct_read(map, map_off, size,
6864 regs[value_regno].type = SCALAR_VALUE;
6865 __mark_reg_known(®s[value_regno], val);
6867 mark_reg_unknown(env, regs, value_regno);
6870 } else if (base_type(reg->type) == PTR_TO_MEM) {
6871 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6873 if (type_may_be_null(reg->type)) {
6874 verbose(env, "R%d invalid mem access '%s'\n", regno,
6875 reg_type_str(env, reg->type));
6879 if (t == BPF_WRITE && rdonly_mem) {
6880 verbose(env, "R%d cannot write into %s\n",
6881 regno, reg_type_str(env, reg->type));
6885 if (t == BPF_WRITE && value_regno >= 0 &&
6886 is_pointer_value(env, value_regno)) {
6887 verbose(env, "R%d leaks addr into mem\n", value_regno);
6891 err = check_mem_region_access(env, regno, off, size,
6892 reg->mem_size, false);
6893 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6894 mark_reg_unknown(env, regs, value_regno);
6895 } else if (reg->type == PTR_TO_CTX) {
6896 enum bpf_reg_type reg_type = SCALAR_VALUE;
6897 struct btf *btf = NULL;
6900 if (t == BPF_WRITE && value_regno >= 0 &&
6901 is_pointer_value(env, value_regno)) {
6902 verbose(env, "R%d leaks addr into ctx\n", value_regno);
6906 err = check_ptr_off_reg(env, reg, regno);
6910 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
6913 verbose_linfo(env, insn_idx, "; ");
6914 if (!err && t == BPF_READ && value_regno >= 0) {
6915 /* ctx access returns either a scalar, or a
6916 * PTR_TO_PACKET[_META,_END]. In the latter
6917 * case, we know the offset is zero.
6919 if (reg_type == SCALAR_VALUE) {
6920 mark_reg_unknown(env, regs, value_regno);
6922 mark_reg_known_zero(env, regs,
6924 if (type_may_be_null(reg_type))
6925 regs[value_regno].id = ++env->id_gen;
6926 /* A load of ctx field could have different
6927 * actual load size with the one encoded in the
6928 * insn. When the dst is PTR, it is for sure not
6931 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6932 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6933 regs[value_regno].btf = btf;
6934 regs[value_regno].btf_id = btf_id;
6937 regs[value_regno].type = reg_type;
6940 } else if (reg->type == PTR_TO_STACK) {
6941 /* Basic bounds checks. */
6942 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6946 state = func(env, reg);
6947 err = update_stack_depth(env, state, off);
6952 err = check_stack_read(env, regno, off, size,
6955 err = check_stack_write(env, regno, off, size,
6956 value_regno, insn_idx);
6957 } else if (reg_is_pkt_pointer(reg)) {
6958 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6959 verbose(env, "cannot write into packet\n");
6962 if (t == BPF_WRITE && value_regno >= 0 &&
6963 is_pointer_value(env, value_regno)) {
6964 verbose(env, "R%d leaks addr into packet\n",
6968 err = check_packet_access(env, regno, off, size, false);
6969 if (!err && t == BPF_READ && value_regno >= 0)
6970 mark_reg_unknown(env, regs, value_regno);
6971 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6972 if (t == BPF_WRITE && value_regno >= 0 &&
6973 is_pointer_value(env, value_regno)) {
6974 verbose(env, "R%d leaks addr into flow keys\n",
6979 err = check_flow_keys_access(env, off, size);
6980 if (!err && t == BPF_READ && value_regno >= 0)
6981 mark_reg_unknown(env, regs, value_regno);
6982 } else if (type_is_sk_pointer(reg->type)) {
6983 if (t == BPF_WRITE) {
6984 verbose(env, "R%d cannot write into %s\n",
6985 regno, reg_type_str(env, reg->type));
6988 err = check_sock_access(env, insn_idx, regno, off, size, t);
6989 if (!err && value_regno >= 0)
6990 mark_reg_unknown(env, regs, value_regno);
6991 } else if (reg->type == PTR_TO_TP_BUFFER) {
6992 err = check_tp_buffer_access(env, reg, regno, off, size);
6993 if (!err && t == BPF_READ && value_regno >= 0)
6994 mark_reg_unknown(env, regs, value_regno);
6995 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6996 !type_may_be_null(reg->type)) {
6997 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6999 } else if (reg->type == CONST_PTR_TO_MAP) {
7000 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7002 } else if (base_type(reg->type) == PTR_TO_BUF) {
7003 bool rdonly_mem = type_is_rdonly_mem(reg->type);
7007 if (t == BPF_WRITE) {
7008 verbose(env, "R%d cannot write into %s\n",
7009 regno, reg_type_str(env, reg->type));
7012 max_access = &env->prog->aux->max_rdonly_access;
7014 max_access = &env->prog->aux->max_rdwr_access;
7017 err = check_buffer_access(env, reg, regno, off, size, false,
7020 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7021 mark_reg_unknown(env, regs, value_regno);
7023 verbose(env, "R%d invalid mem access '%s'\n", regno,
7024 reg_type_str(env, reg->type));
7028 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7029 regs[value_regno].type == SCALAR_VALUE) {
7031 /* b/h/w load zero-extends, mark upper bits as known 0 */
7032 coerce_reg_to_size(®s[value_regno], size);
7034 coerce_reg_to_size_sx(®s[value_regno], size);
7039 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
7044 switch (insn->imm) {
7046 case BPF_ADD | BPF_FETCH:
7048 case BPF_AND | BPF_FETCH:
7050 case BPF_OR | BPF_FETCH:
7052 case BPF_XOR | BPF_FETCH:
7057 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
7061 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7062 verbose(env, "invalid atomic operand size\n");
7066 /* check src1 operand */
7067 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7071 /* check src2 operand */
7072 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7076 if (insn->imm == BPF_CMPXCHG) {
7077 /* Check comparison of R0 with memory location */
7078 const u32 aux_reg = BPF_REG_0;
7080 err = check_reg_arg(env, aux_reg, SRC_OP);
7084 if (is_pointer_value(env, aux_reg)) {
7085 verbose(env, "R%d leaks addr into mem\n", aux_reg);
7090 if (is_pointer_value(env, insn->src_reg)) {
7091 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7095 if (is_ctx_reg(env, insn->dst_reg) ||
7096 is_pkt_reg(env, insn->dst_reg) ||
7097 is_flow_key_reg(env, insn->dst_reg) ||
7098 is_sk_reg(env, insn->dst_reg)) {
7099 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7101 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7105 if (insn->imm & BPF_FETCH) {
7106 if (insn->imm == BPF_CMPXCHG)
7107 load_reg = BPF_REG_0;
7109 load_reg = insn->src_reg;
7111 /* check and record load of old value */
7112 err = check_reg_arg(env, load_reg, DST_OP);
7116 /* This instruction accesses a memory location but doesn't
7117 * actually load it into a register.
7122 /* Check whether we can read the memory, with second call for fetch
7123 * case to simulate the register fill.
7125 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7126 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7127 if (!err && load_reg >= 0)
7128 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7129 BPF_SIZE(insn->code), BPF_READ, load_reg,
7134 /* Check whether we can write into the same memory. */
7135 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7136 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7143 /* When register 'regno' is used to read the stack (either directly or through
7144 * a helper function) make sure that it's within stack boundary and, depending
7145 * on the access type, that all elements of the stack are initialized.
7147 * 'off' includes 'regno->off', but not its dynamic part (if any).
7149 * All registers that have been spilled on the stack in the slots within the
7150 * read offsets are marked as read.
7152 static int check_stack_range_initialized(
7153 struct bpf_verifier_env *env, int regno, int off,
7154 int access_size, bool zero_size_allowed,
7155 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7157 struct bpf_reg_state *reg = reg_state(env, regno);
7158 struct bpf_func_state *state = func(env, reg);
7159 int err, min_off, max_off, i, j, slot, spi;
7160 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7161 enum bpf_access_type bounds_check_type;
7162 /* Some accesses can write anything into the stack, others are
7165 bool clobber = false;
7167 if (access_size == 0 && !zero_size_allowed) {
7168 verbose(env, "invalid zero-sized read\n");
7172 if (type == ACCESS_HELPER) {
7173 /* The bounds checks for writes are more permissive than for
7174 * reads. However, if raw_mode is not set, we'll do extra
7177 bounds_check_type = BPF_WRITE;
7180 bounds_check_type = BPF_READ;
7182 err = check_stack_access_within_bounds(env, regno, off, access_size,
7183 type, bounds_check_type);
7188 if (tnum_is_const(reg->var_off)) {
7189 min_off = max_off = reg->var_off.value + off;
7191 /* Variable offset is prohibited for unprivileged mode for
7192 * simplicity since it requires corresponding support in
7193 * Spectre masking for stack ALU.
7194 * See also retrieve_ptr_limit().
7196 if (!env->bypass_spec_v1) {
7199 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7200 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7201 regno, err_extra, tn_buf);
7204 /* Only initialized buffer on stack is allowed to be accessed
7205 * with variable offset. With uninitialized buffer it's hard to
7206 * guarantee that whole memory is marked as initialized on
7207 * helper return since specific bounds are unknown what may
7208 * cause uninitialized stack leaking.
7210 if (meta && meta->raw_mode)
7213 min_off = reg->smin_value + off;
7214 max_off = reg->smax_value + off;
7217 if (meta && meta->raw_mode) {
7218 /* Ensure we won't be overwriting dynptrs when simulating byte
7219 * by byte access in check_helper_call using meta.access_size.
7220 * This would be a problem if we have a helper in the future
7223 * helper(uninit_mem, len, dynptr)
7225 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7226 * may end up writing to dynptr itself when touching memory from
7227 * arg 1. This can be relaxed on a case by case basis for known
7228 * safe cases, but reject due to the possibilitiy of aliasing by
7231 for (i = min_off; i < max_off + access_size; i++) {
7232 int stack_off = -i - 1;
7235 /* raw_mode may write past allocated_stack */
7236 if (state->allocated_stack <= stack_off)
7238 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7239 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7243 meta->access_size = access_size;
7244 meta->regno = regno;
7248 for (i = min_off; i < max_off + access_size; i++) {
7252 spi = slot / BPF_REG_SIZE;
7253 if (state->allocated_stack <= slot)
7255 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7256 if (*stype == STACK_MISC)
7258 if ((*stype == STACK_ZERO) ||
7259 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7261 /* helper can write anything into the stack */
7262 *stype = STACK_MISC;
7267 if (is_spilled_reg(&state->stack[spi]) &&
7268 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7269 env->allow_ptr_leaks)) {
7271 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7272 for (j = 0; j < BPF_REG_SIZE; j++)
7273 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7279 if (tnum_is_const(reg->var_off)) {
7280 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7281 err_extra, regno, min_off, i - min_off, access_size);
7285 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7286 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7287 err_extra, regno, tn_buf, i - min_off, access_size);
7291 /* reading any byte out of 8-byte 'spill_slot' will cause
7292 * the whole slot to be marked as 'read'
7294 mark_reg_read(env, &state->stack[spi].spilled_ptr,
7295 state->stack[spi].spilled_ptr.parent,
7297 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7298 * be sure that whether stack slot is written to or not. Hence,
7299 * we must still conservatively propagate reads upwards even if
7300 * helper may write to the entire memory range.
7303 return update_stack_depth(env, state, min_off);
7306 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7307 int access_size, bool zero_size_allowed,
7308 struct bpf_call_arg_meta *meta)
7310 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7313 switch (base_type(reg->type)) {
7315 case PTR_TO_PACKET_META:
7316 return check_packet_access(env, regno, reg->off, access_size,
7318 case PTR_TO_MAP_KEY:
7319 if (meta && meta->raw_mode) {
7320 verbose(env, "R%d cannot write into %s\n", regno,
7321 reg_type_str(env, reg->type));
7324 return check_mem_region_access(env, regno, reg->off, access_size,
7325 reg->map_ptr->key_size, false);
7326 case PTR_TO_MAP_VALUE:
7327 if (check_map_access_type(env, regno, reg->off, access_size,
7328 meta && meta->raw_mode ? BPF_WRITE :
7331 return check_map_access(env, regno, reg->off, access_size,
7332 zero_size_allowed, ACCESS_HELPER);
7334 if (type_is_rdonly_mem(reg->type)) {
7335 if (meta && meta->raw_mode) {
7336 verbose(env, "R%d cannot write into %s\n", regno,
7337 reg_type_str(env, reg->type));
7341 return check_mem_region_access(env, regno, reg->off,
7342 access_size, reg->mem_size,
7345 if (type_is_rdonly_mem(reg->type)) {
7346 if (meta && meta->raw_mode) {
7347 verbose(env, "R%d cannot write into %s\n", regno,
7348 reg_type_str(env, reg->type));
7352 max_access = &env->prog->aux->max_rdonly_access;
7354 max_access = &env->prog->aux->max_rdwr_access;
7356 return check_buffer_access(env, reg, regno, reg->off,
7357 access_size, zero_size_allowed,
7360 return check_stack_range_initialized(
7362 regno, reg->off, access_size,
7363 zero_size_allowed, ACCESS_HELPER, meta);
7365 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7366 access_size, BPF_READ, -1);
7368 /* in case the function doesn't know how to access the context,
7369 * (because we are in a program of type SYSCALL for example), we
7370 * can not statically check its size.
7371 * Dynamically check it now.
7373 if (!env->ops->convert_ctx_access) {
7374 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7375 int offset = access_size - 1;
7377 /* Allow zero-byte read from PTR_TO_CTX */
7378 if (access_size == 0)
7379 return zero_size_allowed ? 0 : -EACCES;
7381 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7382 atype, -1, false, false);
7386 default: /* scalar_value or invalid ptr */
7387 /* Allow zero-byte read from NULL, regardless of pointer type */
7388 if (zero_size_allowed && access_size == 0 &&
7389 register_is_null(reg))
7392 verbose(env, "R%d type=%s ", regno,
7393 reg_type_str(env, reg->type));
7394 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7399 static int check_mem_size_reg(struct bpf_verifier_env *env,
7400 struct bpf_reg_state *reg, u32 regno,
7401 bool zero_size_allowed,
7402 struct bpf_call_arg_meta *meta)
7406 /* This is used to refine r0 return value bounds for helpers
7407 * that enforce this value as an upper bound on return values.
7408 * See do_refine_retval_range() for helpers that can refine
7409 * the return value. C type of helper is u32 so we pull register
7410 * bound from umax_value however, if negative verifier errors
7411 * out. Only upper bounds can be learned because retval is an
7412 * int type and negative retvals are allowed.
7414 meta->msize_max_value = reg->umax_value;
7416 /* The register is SCALAR_VALUE; the access check
7417 * happens using its boundaries.
7419 if (!tnum_is_const(reg->var_off))
7420 /* For unprivileged variable accesses, disable raw
7421 * mode so that the program is required to
7422 * initialize all the memory that the helper could
7423 * just partially fill up.
7427 if (reg->smin_value < 0) {
7428 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7433 if (reg->umin_value == 0) {
7434 err = check_helper_mem_access(env, regno - 1, 0,
7441 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7442 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7446 err = check_helper_mem_access(env, regno - 1,
7448 zero_size_allowed, meta);
7450 err = mark_chain_precision(env, regno);
7454 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7455 u32 regno, u32 mem_size)
7457 bool may_be_null = type_may_be_null(reg->type);
7458 struct bpf_reg_state saved_reg;
7459 struct bpf_call_arg_meta meta;
7462 if (register_is_null(reg))
7465 memset(&meta, 0, sizeof(meta));
7466 /* Assuming that the register contains a value check if the memory
7467 * access is safe. Temporarily save and restore the register's state as
7468 * the conversion shouldn't be visible to a caller.
7472 mark_ptr_not_null_reg(reg);
7475 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7476 /* Check access for BPF_WRITE */
7477 meta.raw_mode = true;
7478 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7486 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7489 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7490 bool may_be_null = type_may_be_null(mem_reg->type);
7491 struct bpf_reg_state saved_reg;
7492 struct bpf_call_arg_meta meta;
7495 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7497 memset(&meta, 0, sizeof(meta));
7500 saved_reg = *mem_reg;
7501 mark_ptr_not_null_reg(mem_reg);
7504 err = check_mem_size_reg(env, reg, regno, true, &meta);
7505 /* Check access for BPF_WRITE */
7506 meta.raw_mode = true;
7507 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7510 *mem_reg = saved_reg;
7514 /* Implementation details:
7515 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7516 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7517 * Two bpf_map_lookups (even with the same key) will have different reg->id.
7518 * Two separate bpf_obj_new will also have different reg->id.
7519 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7520 * clears reg->id after value_or_null->value transition, since the verifier only
7521 * cares about the range of access to valid map value pointer and doesn't care
7522 * about actual address of the map element.
7523 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7524 * reg->id > 0 after value_or_null->value transition. By doing so
7525 * two bpf_map_lookups will be considered two different pointers that
7526 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7527 * returned from bpf_obj_new.
7528 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7530 * Since only one bpf_spin_lock is allowed the checks are simpler than
7531 * reg_is_refcounted() logic. The verifier needs to remember only
7532 * one spin_lock instead of array of acquired_refs.
7533 * cur_state->active_lock remembers which map value element or allocated
7534 * object got locked and clears it after bpf_spin_unlock.
7536 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7539 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7540 struct bpf_verifier_state *cur = env->cur_state;
7541 bool is_const = tnum_is_const(reg->var_off);
7542 u64 val = reg->var_off.value;
7543 struct bpf_map *map = NULL;
7544 struct btf *btf = NULL;
7545 struct btf_record *rec;
7549 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7553 if (reg->type == PTR_TO_MAP_VALUE) {
7557 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7565 rec = reg_btf_record(reg);
7566 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7567 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7568 map ? map->name : "kptr");
7571 if (rec->spin_lock_off != val + reg->off) {
7572 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7573 val + reg->off, rec->spin_lock_off);
7577 if (cur->active_lock.ptr) {
7579 "Locking two bpf_spin_locks are not allowed\n");
7583 cur->active_lock.ptr = map;
7585 cur->active_lock.ptr = btf;
7586 cur->active_lock.id = reg->id;
7595 if (!cur->active_lock.ptr) {
7596 verbose(env, "bpf_spin_unlock without taking a lock\n");
7599 if (cur->active_lock.ptr != ptr ||
7600 cur->active_lock.id != reg->id) {
7601 verbose(env, "bpf_spin_unlock of different lock\n");
7605 invalidate_non_owning_refs(env);
7607 cur->active_lock.ptr = NULL;
7608 cur->active_lock.id = 0;
7613 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7614 struct bpf_call_arg_meta *meta)
7616 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7617 bool is_const = tnum_is_const(reg->var_off);
7618 struct bpf_map *map = reg->map_ptr;
7619 u64 val = reg->var_off.value;
7623 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7628 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7632 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7633 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7636 if (map->record->timer_off != val + reg->off) {
7637 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7638 val + reg->off, map->record->timer_off);
7641 if (meta->map_ptr) {
7642 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7645 meta->map_uid = reg->map_uid;
7646 meta->map_ptr = map;
7650 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7651 struct bpf_call_arg_meta *meta)
7653 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7654 struct bpf_map *map_ptr = reg->map_ptr;
7655 struct btf_field *kptr_field;
7658 if (!tnum_is_const(reg->var_off)) {
7660 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7664 if (!map_ptr->btf) {
7665 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7669 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7670 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7674 meta->map_ptr = map_ptr;
7675 kptr_off = reg->off + reg->var_off.value;
7676 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7678 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7681 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7682 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7685 meta->kptr_field = kptr_field;
7689 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7690 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7692 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7693 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7694 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7696 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7697 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7698 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7699 * mutate the view of the dynptr and also possibly destroy it. In the latter
7700 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7701 * memory that dynptr points to.
7703 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7704 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7705 * readonly dynptr view yet, hence only the first case is tracked and checked.
7707 * This is consistent with how C applies the const modifier to a struct object,
7708 * where the pointer itself inside bpf_dynptr becomes const but not what it
7711 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7712 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7714 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7715 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7717 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7720 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7721 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7723 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7724 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7728 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7729 * constructing a mutable bpf_dynptr object.
7731 * Currently, this is only possible with PTR_TO_STACK
7732 * pointing to a region of at least 16 bytes which doesn't
7733 * contain an existing bpf_dynptr.
7735 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7736 * mutated or destroyed. However, the memory it points to
7739 * None - Points to a initialized dynptr that can be mutated and
7740 * destroyed, including mutation of the memory it points
7743 if (arg_type & MEM_UNINIT) {
7746 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7747 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7751 /* we write BPF_DW bits (8 bytes) at a time */
7752 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7753 err = check_mem_access(env, insn_idx, regno,
7754 i, BPF_DW, BPF_WRITE, -1, false, false);
7759 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7760 } else /* MEM_RDONLY and None case from above */ {
7761 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7762 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7763 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7767 if (!is_dynptr_reg_valid_init(env, reg)) {
7769 "Expected an initialized dynptr as arg #%d\n",
7774 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7775 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7777 "Expected a dynptr of type %s as arg #%d\n",
7778 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7782 err = mark_dynptr_read(env, reg);
7787 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7789 struct bpf_func_state *state = func(env, reg);
7791 return state->stack[spi].spilled_ptr.ref_obj_id;
7794 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7796 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7799 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7801 return meta->kfunc_flags & KF_ITER_NEW;
7804 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7806 return meta->kfunc_flags & KF_ITER_NEXT;
7809 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7811 return meta->kfunc_flags & KF_ITER_DESTROY;
7814 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7816 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7817 * kfunc is iter state pointer
7819 return arg == 0 && is_iter_kfunc(meta);
7822 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7823 struct bpf_kfunc_call_arg_meta *meta)
7825 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7826 const struct btf_type *t;
7827 const struct btf_param *arg;
7828 int spi, err, i, nr_slots;
7831 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7832 arg = &btf_params(meta->func_proto)[0];
7833 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7834 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7835 nr_slots = t->size / BPF_REG_SIZE;
7837 if (is_iter_new_kfunc(meta)) {
7838 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7839 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7840 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7841 iter_type_str(meta->btf, btf_id), regno);
7845 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7846 err = check_mem_access(env, insn_idx, regno,
7847 i, BPF_DW, BPF_WRITE, -1, false, false);
7852 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7856 /* iter_next() or iter_destroy() expect initialized iter state*/
7857 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7862 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7863 iter_type_str(meta->btf, btf_id), regno);
7866 verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7872 spi = iter_get_spi(env, reg, nr_slots);
7876 err = mark_iter_read(env, reg, spi, nr_slots);
7880 /* remember meta->iter info for process_iter_next_call() */
7881 meta->iter.spi = spi;
7882 meta->iter.frameno = reg->frameno;
7883 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7885 if (is_iter_destroy_kfunc(meta)) {
7886 err = unmark_stack_slots_iter(env, reg, nr_slots);
7895 /* Look for a previous loop entry at insn_idx: nearest parent state
7896 * stopped at insn_idx with callsites matching those in cur->frame.
7898 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7899 struct bpf_verifier_state *cur,
7902 struct bpf_verifier_state_list *sl;
7903 struct bpf_verifier_state *st;
7905 /* Explored states are pushed in stack order, most recent states come first */
7906 sl = *explored_state(env, insn_idx);
7907 for (; sl; sl = sl->next) {
7908 /* If st->branches != 0 state is a part of current DFS verification path,
7909 * hence cur & st for a loop.
7912 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7913 st->dfs_depth < cur->dfs_depth)
7920 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7921 static bool regs_exact(const struct bpf_reg_state *rold,
7922 const struct bpf_reg_state *rcur,
7923 struct bpf_idmap *idmap);
7925 static void maybe_widen_reg(struct bpf_verifier_env *env,
7926 struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7927 struct bpf_idmap *idmap)
7929 if (rold->type != SCALAR_VALUE)
7931 if (rold->type != rcur->type)
7933 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7935 __mark_reg_unknown(env, rcur);
7938 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7939 struct bpf_verifier_state *old,
7940 struct bpf_verifier_state *cur)
7942 struct bpf_func_state *fold, *fcur;
7945 reset_idmap_scratch(env);
7946 for (fr = old->curframe; fr >= 0; fr--) {
7947 fold = old->frame[fr];
7948 fcur = cur->frame[fr];
7950 for (i = 0; i < MAX_BPF_REG; i++)
7951 maybe_widen_reg(env,
7954 &env->idmap_scratch);
7956 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7957 if (!is_spilled_reg(&fold->stack[i]) ||
7958 !is_spilled_reg(&fcur->stack[i]))
7961 maybe_widen_reg(env,
7962 &fold->stack[i].spilled_ptr,
7963 &fcur->stack[i].spilled_ptr,
7964 &env->idmap_scratch);
7970 /* process_iter_next_call() is called when verifier gets to iterator's next
7971 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7972 * to it as just "iter_next()" in comments below.
7974 * BPF verifier relies on a crucial contract for any iter_next()
7975 * implementation: it should *eventually* return NULL, and once that happens
7976 * it should keep returning NULL. That is, once iterator exhausts elements to
7977 * iterate, it should never reset or spuriously return new elements.
7979 * With the assumption of such contract, process_iter_next_call() simulates
7980 * a fork in the verifier state to validate loop logic correctness and safety
7981 * without having to simulate infinite amount of iterations.
7983 * In current state, we first assume that iter_next() returned NULL and
7984 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7985 * conditions we should not form an infinite loop and should eventually reach
7988 * Besides that, we also fork current state and enqueue it for later
7989 * verification. In a forked state we keep iterator state as ACTIVE
7990 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7991 * also bump iteration depth to prevent erroneous infinite loop detection
7992 * later on (see iter_active_depths_differ() comment for details). In this
7993 * state we assume that we'll eventually loop back to another iter_next()
7994 * calls (it could be in exactly same location or in some other instruction,
7995 * it doesn't matter, we don't make any unnecessary assumptions about this,
7996 * everything revolves around iterator state in a stack slot, not which
7997 * instruction is calling iter_next()). When that happens, we either will come
7998 * to iter_next() with equivalent state and can conclude that next iteration
7999 * will proceed in exactly the same way as we just verified, so it's safe to
8000 * assume that loop converges. If not, we'll go on another iteration
8001 * simulation with a different input state, until all possible starting states
8002 * are validated or we reach maximum number of instructions limit.
8004 * This way, we will either exhaustively discover all possible input states
8005 * that iterator loop can start with and eventually will converge, or we'll
8006 * effectively regress into bounded loop simulation logic and either reach
8007 * maximum number of instructions if loop is not provably convergent, or there
8008 * is some statically known limit on number of iterations (e.g., if there is
8009 * an explicit `if n > 100 then break;` statement somewhere in the loop).
8011 * Iteration convergence logic in is_state_visited() relies on exact
8012 * states comparison, which ignores read and precision marks.
8013 * This is necessary because read and precision marks are not finalized
8014 * while in the loop. Exact comparison might preclude convergence for
8015 * simple programs like below:
8018 * while(iter_next(&it))
8021 * At each iteration step i++ would produce a new distinct state and
8022 * eventually instruction processing limit would be reached.
8024 * To avoid such behavior speculatively forget (widen) range for
8025 * imprecise scalar registers, if those registers were not precise at the
8026 * end of the previous iteration and do not match exactly.
8028 * This is a conservative heuristic that allows to verify wide range of programs,
8029 * however it precludes verification of programs that conjure an
8030 * imprecise value on the first loop iteration and use it as precise on a second.
8031 * For example, the following safe program would fail to verify:
8033 * struct bpf_num_iter it;
8036 * bpf_iter_num_new(&it, 0, 10);
8037 * while (bpf_iter_num_next(&it)) {
8040 * i = 7; // Because i changed verifier would forget
8041 * // it's range on second loop entry.
8043 * arr[i] = 42; // This would fail to verify.
8046 * bpf_iter_num_destroy(&it);
8048 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8049 struct bpf_kfunc_call_arg_meta *meta)
8051 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8052 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8053 struct bpf_reg_state *cur_iter, *queued_iter;
8054 int iter_frameno = meta->iter.frameno;
8055 int iter_spi = meta->iter.spi;
8057 BTF_TYPE_EMIT(struct bpf_iter);
8059 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8061 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8062 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8063 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
8064 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8068 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8069 /* Because iter_next() call is a checkpoint is_state_visitied()
8070 * should guarantee parent state with same call sites and insn_idx.
8072 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8073 !same_callsites(cur_st->parent, cur_st)) {
8074 verbose(env, "bug: bad parent state for iter next call");
8077 /* Note cur_st->parent in the call below, it is necessary to skip
8078 * checkpoint created for cur_st by is_state_visited()
8079 * right at this instruction.
8081 prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8082 /* branch out active iter state */
8083 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8087 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8088 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8089 queued_iter->iter.depth++;
8091 widen_imprecise_scalars(env, prev_st, queued_st);
8093 queued_fr = queued_st->frame[queued_st->curframe];
8094 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8097 /* switch to DRAINED state, but keep the depth unchanged */
8098 /* mark current iter state as drained and assume returned NULL */
8099 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8100 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
8105 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8107 return type == ARG_CONST_SIZE ||
8108 type == ARG_CONST_SIZE_OR_ZERO;
8111 static bool arg_type_is_release(enum bpf_arg_type type)
8113 return type & OBJ_RELEASE;
8116 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8118 return base_type(type) == ARG_PTR_TO_DYNPTR;
8121 static int int_ptr_type_to_size(enum bpf_arg_type type)
8123 if (type == ARG_PTR_TO_INT)
8125 else if (type == ARG_PTR_TO_LONG)
8131 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8132 const struct bpf_call_arg_meta *meta,
8133 enum bpf_arg_type *arg_type)
8135 if (!meta->map_ptr) {
8136 /* kernel subsystem misconfigured verifier */
8137 verbose(env, "invalid map_ptr to access map->type\n");
8141 switch (meta->map_ptr->map_type) {
8142 case BPF_MAP_TYPE_SOCKMAP:
8143 case BPF_MAP_TYPE_SOCKHASH:
8144 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8145 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8147 verbose(env, "invalid arg_type for sockmap/sockhash\n");
8151 case BPF_MAP_TYPE_BLOOM_FILTER:
8152 if (meta->func_id == BPF_FUNC_map_peek_elem)
8153 *arg_type = ARG_PTR_TO_MAP_VALUE;
8161 struct bpf_reg_types {
8162 const enum bpf_reg_type types[10];
8166 static const struct bpf_reg_types sock_types = {
8176 static const struct bpf_reg_types btf_id_sock_common_types = {
8183 PTR_TO_BTF_ID | PTR_TRUSTED,
8185 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8189 static const struct bpf_reg_types mem_types = {
8197 PTR_TO_MEM | MEM_RINGBUF,
8199 PTR_TO_BTF_ID | PTR_TRUSTED,
8203 static const struct bpf_reg_types int_ptr_types = {
8213 static const struct bpf_reg_types spin_lock_types = {
8216 PTR_TO_BTF_ID | MEM_ALLOC,
8220 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8221 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8222 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8223 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8224 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8225 static const struct bpf_reg_types btf_ptr_types = {
8228 PTR_TO_BTF_ID | PTR_TRUSTED,
8229 PTR_TO_BTF_ID | MEM_RCU,
8232 static const struct bpf_reg_types percpu_btf_ptr_types = {
8234 PTR_TO_BTF_ID | MEM_PERCPU,
8235 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8236 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8239 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8240 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8241 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8242 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8243 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8244 static const struct bpf_reg_types dynptr_types = {
8247 CONST_PTR_TO_DYNPTR,
8251 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8252 [ARG_PTR_TO_MAP_KEY] = &mem_types,
8253 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
8254 [ARG_CONST_SIZE] = &scalar_types,
8255 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
8256 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
8257 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
8258 [ARG_PTR_TO_CTX] = &context_types,
8259 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
8261 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
8263 [ARG_PTR_TO_SOCKET] = &fullsock_types,
8264 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
8265 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
8266 [ARG_PTR_TO_MEM] = &mem_types,
8267 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
8268 [ARG_PTR_TO_INT] = &int_ptr_types,
8269 [ARG_PTR_TO_LONG] = &int_ptr_types,
8270 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
8271 [ARG_PTR_TO_FUNC] = &func_ptr_types,
8272 [ARG_PTR_TO_STACK] = &stack_ptr_types,
8273 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
8274 [ARG_PTR_TO_TIMER] = &timer_types,
8275 [ARG_PTR_TO_KPTR] = &kptr_types,
8276 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
8279 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8280 enum bpf_arg_type arg_type,
8281 const u32 *arg_btf_id,
8282 struct bpf_call_arg_meta *meta)
8284 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8285 enum bpf_reg_type expected, type = reg->type;
8286 const struct bpf_reg_types *compatible;
8289 compatible = compatible_reg_types[base_type(arg_type)];
8291 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8295 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8296 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8298 * Same for MAYBE_NULL:
8300 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8301 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8303 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8305 * Therefore we fold these flags depending on the arg_type before comparison.
8307 if (arg_type & MEM_RDONLY)
8308 type &= ~MEM_RDONLY;
8309 if (arg_type & PTR_MAYBE_NULL)
8310 type &= ~PTR_MAYBE_NULL;
8311 if (base_type(arg_type) == ARG_PTR_TO_MEM)
8312 type &= ~DYNPTR_TYPE_FLAG_MASK;
8314 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8316 type &= ~MEM_PERCPU;
8319 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8320 expected = compatible->types[i];
8321 if (expected == NOT_INIT)
8324 if (type == expected)
8328 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8329 for (j = 0; j + 1 < i; j++)
8330 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8331 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8335 if (base_type(reg->type) != PTR_TO_BTF_ID)
8338 if (compatible == &mem_types) {
8339 if (!(arg_type & MEM_RDONLY)) {
8341 "%s() may write into memory pointed by R%d type=%s\n",
8342 func_id_name(meta->func_id),
8343 regno, reg_type_str(env, reg->type));
8349 switch ((int)reg->type) {
8351 case PTR_TO_BTF_ID | PTR_TRUSTED:
8352 case PTR_TO_BTF_ID | MEM_RCU:
8353 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8354 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8356 /* For bpf_sk_release, it needs to match against first member
8357 * 'struct sock_common', hence make an exception for it. This
8358 * allows bpf_sk_release to work for multiple socket types.
8360 bool strict_type_match = arg_type_is_release(arg_type) &&
8361 meta->func_id != BPF_FUNC_sk_release;
8363 if (type_may_be_null(reg->type) &&
8364 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8365 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8370 if (!compatible->btf_id) {
8371 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8374 arg_btf_id = compatible->btf_id;
8377 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8378 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8381 if (arg_btf_id == BPF_PTR_POISON) {
8382 verbose(env, "verifier internal error:");
8383 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8388 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8389 btf_vmlinux, *arg_btf_id,
8390 strict_type_match)) {
8391 verbose(env, "R%d is of type %s but %s is expected\n",
8392 regno, btf_type_name(reg->btf, reg->btf_id),
8393 btf_type_name(btf_vmlinux, *arg_btf_id));
8399 case PTR_TO_BTF_ID | MEM_ALLOC:
8400 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8401 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8402 meta->func_id != BPF_FUNC_kptr_xchg) {
8403 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8406 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8407 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8411 case PTR_TO_BTF_ID | MEM_PERCPU:
8412 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8413 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8414 /* Handled by helper specific checks */
8417 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8423 static struct btf_field *
8424 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8426 struct btf_field *field;
8427 struct btf_record *rec;
8429 rec = reg_btf_record(reg);
8433 field = btf_record_find(rec, off, fields);
8440 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8441 const struct bpf_reg_state *reg, int regno,
8442 enum bpf_arg_type arg_type)
8444 u32 type = reg->type;
8446 /* When referenced register is passed to release function, its fixed
8449 * We will check arg_type_is_release reg has ref_obj_id when storing
8450 * meta->release_regno.
8452 if (arg_type_is_release(arg_type)) {
8453 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8454 * may not directly point to the object being released, but to
8455 * dynptr pointing to such object, which might be at some offset
8456 * on the stack. In that case, we simply to fallback to the
8459 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8462 /* Doing check_ptr_off_reg check for the offset will catch this
8463 * because fixed_off_ok is false, but checking here allows us
8464 * to give the user a better error message.
8467 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8471 return __check_ptr_off_reg(env, reg, regno, false);
8475 /* Pointer types where both fixed and variable offset is explicitly allowed: */
8478 case PTR_TO_PACKET_META:
8479 case PTR_TO_MAP_KEY:
8480 case PTR_TO_MAP_VALUE:
8482 case PTR_TO_MEM | MEM_RDONLY:
8483 case PTR_TO_MEM | MEM_RINGBUF:
8485 case PTR_TO_BUF | MEM_RDONLY:
8488 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8492 case PTR_TO_BTF_ID | MEM_ALLOC:
8493 case PTR_TO_BTF_ID | PTR_TRUSTED:
8494 case PTR_TO_BTF_ID | MEM_RCU:
8495 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8496 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8497 /* When referenced PTR_TO_BTF_ID is passed to release function,
8498 * its fixed offset must be 0. In the other cases, fixed offset
8499 * can be non-zero. This was already checked above. So pass
8500 * fixed_off_ok as true to allow fixed offset for all other
8501 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8502 * still need to do checks instead of returning.
8504 return __check_ptr_off_reg(env, reg, regno, true);
8506 return __check_ptr_off_reg(env, reg, regno, false);
8510 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8511 const struct bpf_func_proto *fn,
8512 struct bpf_reg_state *regs)
8514 struct bpf_reg_state *state = NULL;
8517 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8518 if (arg_type_is_dynptr(fn->arg_type[i])) {
8520 verbose(env, "verifier internal error: multiple dynptr args\n");
8523 state = ®s[BPF_REG_1 + i];
8527 verbose(env, "verifier internal error: no dynptr arg found\n");
8532 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8534 struct bpf_func_state *state = func(env, reg);
8537 if (reg->type == CONST_PTR_TO_DYNPTR)
8539 spi = dynptr_get_spi(env, reg);
8542 return state->stack[spi].spilled_ptr.id;
8545 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8547 struct bpf_func_state *state = func(env, reg);
8550 if (reg->type == CONST_PTR_TO_DYNPTR)
8551 return reg->ref_obj_id;
8552 spi = dynptr_get_spi(env, reg);
8555 return state->stack[spi].spilled_ptr.ref_obj_id;
8558 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8559 struct bpf_reg_state *reg)
8561 struct bpf_func_state *state = func(env, reg);
8564 if (reg->type == CONST_PTR_TO_DYNPTR)
8565 return reg->dynptr.type;
8567 spi = __get_spi(reg->off);
8569 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8570 return BPF_DYNPTR_TYPE_INVALID;
8573 return state->stack[spi].spilled_ptr.dynptr.type;
8576 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8577 struct bpf_call_arg_meta *meta,
8578 const struct bpf_func_proto *fn,
8581 u32 regno = BPF_REG_1 + arg;
8582 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8583 enum bpf_arg_type arg_type = fn->arg_type[arg];
8584 enum bpf_reg_type type = reg->type;
8585 u32 *arg_btf_id = NULL;
8588 if (arg_type == ARG_DONTCARE)
8591 err = check_reg_arg(env, regno, SRC_OP);
8595 if (arg_type == ARG_ANYTHING) {
8596 if (is_pointer_value(env, regno)) {
8597 verbose(env, "R%d leaks addr into helper function\n",
8604 if (type_is_pkt_pointer(type) &&
8605 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8606 verbose(env, "helper access to the packet is not allowed\n");
8610 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8611 err = resolve_map_arg_type(env, meta, &arg_type);
8616 if (register_is_null(reg) && type_may_be_null(arg_type))
8617 /* A NULL register has a SCALAR_VALUE type, so skip
8620 goto skip_type_check;
8622 /* arg_btf_id and arg_size are in a union. */
8623 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8624 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8625 arg_btf_id = fn->arg_btf_id[arg];
8627 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8631 err = check_func_arg_reg_off(env, reg, regno, arg_type);
8636 if (arg_type_is_release(arg_type)) {
8637 if (arg_type_is_dynptr(arg_type)) {
8638 struct bpf_func_state *state = func(env, reg);
8641 /* Only dynptr created on stack can be released, thus
8642 * the get_spi and stack state checks for spilled_ptr
8643 * should only be done before process_dynptr_func for
8646 if (reg->type == PTR_TO_STACK) {
8647 spi = dynptr_get_spi(env, reg);
8648 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8649 verbose(env, "arg %d is an unacquired reference\n", regno);
8653 verbose(env, "cannot release unowned const bpf_dynptr\n");
8656 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8657 verbose(env, "R%d must be referenced when passed to release function\n",
8661 if (meta->release_regno) {
8662 verbose(env, "verifier internal error: more than one release argument\n");
8665 meta->release_regno = regno;
8668 if (reg->ref_obj_id) {
8669 if (meta->ref_obj_id) {
8670 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8671 regno, reg->ref_obj_id,
8675 meta->ref_obj_id = reg->ref_obj_id;
8678 switch (base_type(arg_type)) {
8679 case ARG_CONST_MAP_PTR:
8680 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8681 if (meta->map_ptr) {
8682 /* Use map_uid (which is unique id of inner map) to reject:
8683 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8684 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8685 * if (inner_map1 && inner_map2) {
8686 * timer = bpf_map_lookup_elem(inner_map1);
8688 * // mismatch would have been allowed
8689 * bpf_timer_init(timer, inner_map2);
8692 * Comparing map_ptr is enough to distinguish normal and outer maps.
8694 if (meta->map_ptr != reg->map_ptr ||
8695 meta->map_uid != reg->map_uid) {
8697 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8698 meta->map_uid, reg->map_uid);
8702 meta->map_ptr = reg->map_ptr;
8703 meta->map_uid = reg->map_uid;
8705 case ARG_PTR_TO_MAP_KEY:
8706 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8707 * check that [key, key + map->key_size) are within
8708 * stack limits and initialized
8710 if (!meta->map_ptr) {
8711 /* in function declaration map_ptr must come before
8712 * map_key, so that it's verified and known before
8713 * we have to check map_key here. Otherwise it means
8714 * that kernel subsystem misconfigured verifier
8716 verbose(env, "invalid map_ptr to access map->key\n");
8719 err = check_helper_mem_access(env, regno,
8720 meta->map_ptr->key_size, false,
8723 case ARG_PTR_TO_MAP_VALUE:
8724 if (type_may_be_null(arg_type) && register_is_null(reg))
8727 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8728 * check [value, value + map->value_size) validity
8730 if (!meta->map_ptr) {
8731 /* kernel subsystem misconfigured verifier */
8732 verbose(env, "invalid map_ptr to access map->value\n");
8735 meta->raw_mode = arg_type & MEM_UNINIT;
8736 err = check_helper_mem_access(env, regno,
8737 meta->map_ptr->value_size, false,
8740 case ARG_PTR_TO_PERCPU_BTF_ID:
8742 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8745 meta->ret_btf = reg->btf;
8746 meta->ret_btf_id = reg->btf_id;
8748 case ARG_PTR_TO_SPIN_LOCK:
8749 if (in_rbtree_lock_required_cb(env)) {
8750 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8753 if (meta->func_id == BPF_FUNC_spin_lock) {
8754 err = process_spin_lock(env, regno, true);
8757 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8758 err = process_spin_lock(env, regno, false);
8762 verbose(env, "verifier internal error\n");
8766 case ARG_PTR_TO_TIMER:
8767 err = process_timer_func(env, regno, meta);
8771 case ARG_PTR_TO_FUNC:
8772 meta->subprogno = reg->subprogno;
8774 case ARG_PTR_TO_MEM:
8775 /* The access to this pointer is only checked when we hit the
8776 * next is_mem_size argument below.
8778 meta->raw_mode = arg_type & MEM_UNINIT;
8779 if (arg_type & MEM_FIXED_SIZE) {
8780 err = check_helper_mem_access(env, regno,
8781 fn->arg_size[arg], false,
8785 case ARG_CONST_SIZE:
8786 err = check_mem_size_reg(env, reg, regno, false, meta);
8788 case ARG_CONST_SIZE_OR_ZERO:
8789 err = check_mem_size_reg(env, reg, regno, true, meta);
8791 case ARG_PTR_TO_DYNPTR:
8792 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8796 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8797 if (!tnum_is_const(reg->var_off)) {
8798 verbose(env, "R%d is not a known constant'\n",
8802 meta->mem_size = reg->var_off.value;
8803 err = mark_chain_precision(env, regno);
8807 case ARG_PTR_TO_INT:
8808 case ARG_PTR_TO_LONG:
8810 int size = int_ptr_type_to_size(arg_type);
8812 err = check_helper_mem_access(env, regno, size, false, meta);
8815 err = check_ptr_alignment(env, reg, 0, size, true);
8818 case ARG_PTR_TO_CONST_STR:
8820 struct bpf_map *map = reg->map_ptr;
8825 if (!bpf_map_is_rdonly(map)) {
8826 verbose(env, "R%d does not point to a readonly map'\n", regno);
8830 if (!tnum_is_const(reg->var_off)) {
8831 verbose(env, "R%d is not a constant address'\n", regno);
8835 if (!map->ops->map_direct_value_addr) {
8836 verbose(env, "no direct value access support for this map type\n");
8840 err = check_map_access(env, regno, reg->off,
8841 map->value_size - reg->off, false,
8846 map_off = reg->off + reg->var_off.value;
8847 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8849 verbose(env, "direct value access on string failed\n");
8853 str_ptr = (char *)(long)(map_addr);
8854 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8855 verbose(env, "string is not zero-terminated\n");
8860 case ARG_PTR_TO_KPTR:
8861 err = process_kptr_func(env, regno, meta);
8870 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8872 enum bpf_attach_type eatype = env->prog->expected_attach_type;
8873 enum bpf_prog_type type = resolve_prog_type(env->prog);
8875 if (func_id != BPF_FUNC_map_update_elem)
8878 /* It's not possible to get access to a locked struct sock in these
8879 * contexts, so updating is safe.
8882 case BPF_PROG_TYPE_TRACING:
8883 if (eatype == BPF_TRACE_ITER)
8886 case BPF_PROG_TYPE_SOCKET_FILTER:
8887 case BPF_PROG_TYPE_SCHED_CLS:
8888 case BPF_PROG_TYPE_SCHED_ACT:
8889 case BPF_PROG_TYPE_XDP:
8890 case BPF_PROG_TYPE_SK_REUSEPORT:
8891 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8892 case BPF_PROG_TYPE_SK_LOOKUP:
8898 verbose(env, "cannot update sockmap in this context\n");
8902 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8904 return env->prog->jit_requested &&
8905 bpf_jit_supports_subprog_tailcalls();
8908 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8909 struct bpf_map *map, int func_id)
8914 /* We need a two way check, first is from map perspective ... */
8915 switch (map->map_type) {
8916 case BPF_MAP_TYPE_PROG_ARRAY:
8917 if (func_id != BPF_FUNC_tail_call)
8920 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8921 if (func_id != BPF_FUNC_perf_event_read &&
8922 func_id != BPF_FUNC_perf_event_output &&
8923 func_id != BPF_FUNC_skb_output &&
8924 func_id != BPF_FUNC_perf_event_read_value &&
8925 func_id != BPF_FUNC_xdp_output)
8928 case BPF_MAP_TYPE_RINGBUF:
8929 if (func_id != BPF_FUNC_ringbuf_output &&
8930 func_id != BPF_FUNC_ringbuf_reserve &&
8931 func_id != BPF_FUNC_ringbuf_query &&
8932 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8933 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8934 func_id != BPF_FUNC_ringbuf_discard_dynptr)
8937 case BPF_MAP_TYPE_USER_RINGBUF:
8938 if (func_id != BPF_FUNC_user_ringbuf_drain)
8941 case BPF_MAP_TYPE_STACK_TRACE:
8942 if (func_id != BPF_FUNC_get_stackid)
8945 case BPF_MAP_TYPE_CGROUP_ARRAY:
8946 if (func_id != BPF_FUNC_skb_under_cgroup &&
8947 func_id != BPF_FUNC_current_task_under_cgroup)
8950 case BPF_MAP_TYPE_CGROUP_STORAGE:
8951 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8952 if (func_id != BPF_FUNC_get_local_storage)
8955 case BPF_MAP_TYPE_DEVMAP:
8956 case BPF_MAP_TYPE_DEVMAP_HASH:
8957 if (func_id != BPF_FUNC_redirect_map &&
8958 func_id != BPF_FUNC_map_lookup_elem)
8961 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8964 case BPF_MAP_TYPE_CPUMAP:
8965 if (func_id != BPF_FUNC_redirect_map)
8968 case BPF_MAP_TYPE_XSKMAP:
8969 if (func_id != BPF_FUNC_redirect_map &&
8970 func_id != BPF_FUNC_map_lookup_elem)
8973 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8974 case BPF_MAP_TYPE_HASH_OF_MAPS:
8975 if (func_id != BPF_FUNC_map_lookup_elem)
8978 case BPF_MAP_TYPE_SOCKMAP:
8979 if (func_id != BPF_FUNC_sk_redirect_map &&
8980 func_id != BPF_FUNC_sock_map_update &&
8981 func_id != BPF_FUNC_map_delete_elem &&
8982 func_id != BPF_FUNC_msg_redirect_map &&
8983 func_id != BPF_FUNC_sk_select_reuseport &&
8984 func_id != BPF_FUNC_map_lookup_elem &&
8985 !may_update_sockmap(env, func_id))
8988 case BPF_MAP_TYPE_SOCKHASH:
8989 if (func_id != BPF_FUNC_sk_redirect_hash &&
8990 func_id != BPF_FUNC_sock_hash_update &&
8991 func_id != BPF_FUNC_map_delete_elem &&
8992 func_id != BPF_FUNC_msg_redirect_hash &&
8993 func_id != BPF_FUNC_sk_select_reuseport &&
8994 func_id != BPF_FUNC_map_lookup_elem &&
8995 !may_update_sockmap(env, func_id))
8998 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8999 if (func_id != BPF_FUNC_sk_select_reuseport)
9002 case BPF_MAP_TYPE_QUEUE:
9003 case BPF_MAP_TYPE_STACK:
9004 if (func_id != BPF_FUNC_map_peek_elem &&
9005 func_id != BPF_FUNC_map_pop_elem &&
9006 func_id != BPF_FUNC_map_push_elem)
9009 case BPF_MAP_TYPE_SK_STORAGE:
9010 if (func_id != BPF_FUNC_sk_storage_get &&
9011 func_id != BPF_FUNC_sk_storage_delete &&
9012 func_id != BPF_FUNC_kptr_xchg)
9015 case BPF_MAP_TYPE_INODE_STORAGE:
9016 if (func_id != BPF_FUNC_inode_storage_get &&
9017 func_id != BPF_FUNC_inode_storage_delete &&
9018 func_id != BPF_FUNC_kptr_xchg)
9021 case BPF_MAP_TYPE_TASK_STORAGE:
9022 if (func_id != BPF_FUNC_task_storage_get &&
9023 func_id != BPF_FUNC_task_storage_delete &&
9024 func_id != BPF_FUNC_kptr_xchg)
9027 case BPF_MAP_TYPE_CGRP_STORAGE:
9028 if (func_id != BPF_FUNC_cgrp_storage_get &&
9029 func_id != BPF_FUNC_cgrp_storage_delete &&
9030 func_id != BPF_FUNC_kptr_xchg)
9033 case BPF_MAP_TYPE_BLOOM_FILTER:
9034 if (func_id != BPF_FUNC_map_peek_elem &&
9035 func_id != BPF_FUNC_map_push_elem)
9042 /* ... and second from the function itself. */
9044 case BPF_FUNC_tail_call:
9045 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9047 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
9048 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
9052 case BPF_FUNC_perf_event_read:
9053 case BPF_FUNC_perf_event_output:
9054 case BPF_FUNC_perf_event_read_value:
9055 case BPF_FUNC_skb_output:
9056 case BPF_FUNC_xdp_output:
9057 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9060 case BPF_FUNC_ringbuf_output:
9061 case BPF_FUNC_ringbuf_reserve:
9062 case BPF_FUNC_ringbuf_query:
9063 case BPF_FUNC_ringbuf_reserve_dynptr:
9064 case BPF_FUNC_ringbuf_submit_dynptr:
9065 case BPF_FUNC_ringbuf_discard_dynptr:
9066 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9069 case BPF_FUNC_user_ringbuf_drain:
9070 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9073 case BPF_FUNC_get_stackid:
9074 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9077 case BPF_FUNC_current_task_under_cgroup:
9078 case BPF_FUNC_skb_under_cgroup:
9079 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9082 case BPF_FUNC_redirect_map:
9083 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9084 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9085 map->map_type != BPF_MAP_TYPE_CPUMAP &&
9086 map->map_type != BPF_MAP_TYPE_XSKMAP)
9089 case BPF_FUNC_sk_redirect_map:
9090 case BPF_FUNC_msg_redirect_map:
9091 case BPF_FUNC_sock_map_update:
9092 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9095 case BPF_FUNC_sk_redirect_hash:
9096 case BPF_FUNC_msg_redirect_hash:
9097 case BPF_FUNC_sock_hash_update:
9098 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9101 case BPF_FUNC_get_local_storage:
9102 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9103 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9106 case BPF_FUNC_sk_select_reuseport:
9107 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9108 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9109 map->map_type != BPF_MAP_TYPE_SOCKHASH)
9112 case BPF_FUNC_map_pop_elem:
9113 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9114 map->map_type != BPF_MAP_TYPE_STACK)
9117 case BPF_FUNC_map_peek_elem:
9118 case BPF_FUNC_map_push_elem:
9119 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9120 map->map_type != BPF_MAP_TYPE_STACK &&
9121 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9124 case BPF_FUNC_map_lookup_percpu_elem:
9125 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9126 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9127 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9130 case BPF_FUNC_sk_storage_get:
9131 case BPF_FUNC_sk_storage_delete:
9132 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9135 case BPF_FUNC_inode_storage_get:
9136 case BPF_FUNC_inode_storage_delete:
9137 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9140 case BPF_FUNC_task_storage_get:
9141 case BPF_FUNC_task_storage_delete:
9142 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9145 case BPF_FUNC_cgrp_storage_get:
9146 case BPF_FUNC_cgrp_storage_delete:
9147 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9156 verbose(env, "cannot pass map_type %d into func %s#%d\n",
9157 map->map_type, func_id_name(func_id), func_id);
9161 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9165 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9167 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9169 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9171 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9173 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9176 /* We only support one arg being in raw mode at the moment,
9177 * which is sufficient for the helper functions we have
9183 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9185 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9186 bool has_size = fn->arg_size[arg] != 0;
9187 bool is_next_size = false;
9189 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9190 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9192 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9193 return is_next_size;
9195 return has_size == is_next_size || is_next_size == is_fixed;
9198 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9200 /* bpf_xxx(..., buf, len) call will access 'len'
9201 * bytes from memory 'buf'. Both arg types need
9202 * to be paired, so make sure there's no buggy
9203 * helper function specification.
9205 if (arg_type_is_mem_size(fn->arg1_type) ||
9206 check_args_pair_invalid(fn, 0) ||
9207 check_args_pair_invalid(fn, 1) ||
9208 check_args_pair_invalid(fn, 2) ||
9209 check_args_pair_invalid(fn, 3) ||
9210 check_args_pair_invalid(fn, 4))
9216 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9220 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9221 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9222 return !!fn->arg_btf_id[i];
9223 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9224 return fn->arg_btf_id[i] == BPF_PTR_POISON;
9225 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9226 /* arg_btf_id and arg_size are in a union. */
9227 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9228 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9235 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9237 return check_raw_mode_ok(fn) &&
9238 check_arg_pair_ok(fn) &&
9239 check_btf_id_ok(fn) ? 0 : -EINVAL;
9242 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9243 * are now invalid, so turn them into unknown SCALAR_VALUE.
9245 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9246 * since these slices point to packet data.
9248 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9250 struct bpf_func_state *state;
9251 struct bpf_reg_state *reg;
9253 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9254 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9255 mark_reg_invalid(env, reg);
9261 BEYOND_PKT_END = -2,
9264 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9266 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9267 struct bpf_reg_state *reg = &state->regs[regn];
9269 if (reg->type != PTR_TO_PACKET)
9270 /* PTR_TO_PACKET_META is not supported yet */
9273 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9274 * How far beyond pkt_end it goes is unknown.
9275 * if (!range_open) it's the case of pkt >= pkt_end
9276 * if (range_open) it's the case of pkt > pkt_end
9277 * hence this pointer is at least 1 byte bigger than pkt_end
9280 reg->range = BEYOND_PKT_END;
9282 reg->range = AT_PKT_END;
9285 /* The pointer with the specified id has released its reference to kernel
9286 * resources. Identify all copies of the same pointer and clear the reference.
9288 static int release_reference(struct bpf_verifier_env *env,
9291 struct bpf_func_state *state;
9292 struct bpf_reg_state *reg;
9295 err = release_reference_state(cur_func(env), ref_obj_id);
9299 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9300 if (reg->ref_obj_id == ref_obj_id)
9301 mark_reg_invalid(env, reg);
9307 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9309 struct bpf_func_state *unused;
9310 struct bpf_reg_state *reg;
9312 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9313 if (type_is_non_owning_ref(reg->type))
9314 mark_reg_invalid(env, reg);
9318 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9319 struct bpf_reg_state *regs)
9323 /* after the call registers r0 - r5 were scratched */
9324 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9325 mark_reg_not_init(env, regs, caller_saved[i]);
9326 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9330 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9331 struct bpf_func_state *caller,
9332 struct bpf_func_state *callee,
9335 static int set_callee_state(struct bpf_verifier_env *env,
9336 struct bpf_func_state *caller,
9337 struct bpf_func_state *callee, int insn_idx);
9339 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9340 int *insn_idx, int subprog,
9341 set_callee_state_fn set_callee_state_cb)
9343 struct bpf_verifier_state *state = env->cur_state;
9344 struct bpf_func_state *caller, *callee;
9347 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9348 verbose(env, "the call stack of %d frames is too deep\n",
9349 state->curframe + 2);
9353 caller = state->frame[state->curframe];
9354 if (state->frame[state->curframe + 1]) {
9355 verbose(env, "verifier bug. Frame %d already allocated\n",
9356 state->curframe + 1);
9360 err = btf_check_subprog_call(env, subprog, caller->regs);
9363 if (subprog_is_global(env, subprog)) {
9365 verbose(env, "Caller passes invalid args into func#%d\n",
9369 if (env->log.level & BPF_LOG_LEVEL)
9371 "Func#%d is global and valid. Skipping.\n",
9373 clear_caller_saved_regs(env, caller->regs);
9375 /* All global functions return a 64-bit SCALAR_VALUE */
9376 mark_reg_unknown(env, caller->regs, BPF_REG_0);
9377 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9379 /* continue with next insn after call */
9384 /* set_callee_state is used for direct subprog calls, but we are
9385 * interested in validating only BPF helpers that can call subprogs as
9388 if (set_callee_state_cb != set_callee_state) {
9389 env->subprog_info[subprog].is_cb = true;
9390 if (bpf_pseudo_kfunc_call(insn) &&
9391 !is_callback_calling_kfunc(insn->imm)) {
9392 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9393 func_id_name(insn->imm), insn->imm);
9395 } else if (!bpf_pseudo_kfunc_call(insn) &&
9396 !is_callback_calling_function(insn->imm)) { /* helper */
9397 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9398 func_id_name(insn->imm), insn->imm);
9403 if (insn->code == (BPF_JMP | BPF_CALL) &&
9404 insn->src_reg == 0 &&
9405 insn->imm == BPF_FUNC_timer_set_callback) {
9406 struct bpf_verifier_state *async_cb;
9408 /* there is no real recursion here. timer callbacks are async */
9409 env->subprog_info[subprog].is_async_cb = true;
9410 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9411 *insn_idx, subprog);
9414 callee = async_cb->frame[0];
9415 callee->async_entry_cnt = caller->async_entry_cnt + 1;
9417 /* Convert bpf_timer_set_callback() args into timer callback args */
9418 err = set_callee_state_cb(env, caller, callee, *insn_idx);
9422 clear_caller_saved_regs(env, caller->regs);
9423 mark_reg_unknown(env, caller->regs, BPF_REG_0);
9424 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9425 /* continue with next insn after call */
9429 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9432 state->frame[state->curframe + 1] = callee;
9434 /* callee cannot access r0, r6 - r9 for reading and has to write
9435 * into its own stack before reading from it.
9436 * callee can read/write into caller's stack
9438 init_func_state(env, callee,
9439 /* remember the callsite, it will be used by bpf_exit */
9440 *insn_idx /* callsite */,
9441 state->curframe + 1 /* frameno within this callchain */,
9442 subprog /* subprog number within this prog */);
9444 /* Transfer references to the callee */
9445 err = copy_reference_state(callee, caller);
9449 err = set_callee_state_cb(env, caller, callee, *insn_idx);
9453 clear_caller_saved_regs(env, caller->regs);
9455 /* only increment it after check_reg_arg() finished */
9458 /* and go analyze first insn of the callee */
9459 *insn_idx = env->subprog_info[subprog].start - 1;
9461 if (env->log.level & BPF_LOG_LEVEL) {
9462 verbose(env, "caller:\n");
9463 print_verifier_state(env, caller, true);
9464 verbose(env, "callee:\n");
9465 print_verifier_state(env, callee, true);
9470 free_func_state(callee);
9471 state->frame[state->curframe + 1] = NULL;
9475 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9476 struct bpf_func_state *caller,
9477 struct bpf_func_state *callee)
9479 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9480 * void *callback_ctx, u64 flags);
9481 * callback_fn(struct bpf_map *map, void *key, void *value,
9482 * void *callback_ctx);
9484 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9486 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9487 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9488 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9490 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9491 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9492 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9494 /* pointer to stack or null */
9495 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9498 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9502 static int set_callee_state(struct bpf_verifier_env *env,
9503 struct bpf_func_state *caller,
9504 struct bpf_func_state *callee, int insn_idx)
9508 /* copy r1 - r5 args that callee can access. The copy includes parent
9509 * pointers, which connects us up to the liveness chain
9511 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9512 callee->regs[i] = caller->regs[i];
9516 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9519 int subprog, target_insn;
9521 target_insn = *insn_idx + insn->imm + 1;
9522 subprog = find_subprog(env, target_insn);
9524 verbose(env, "verifier bug. No program starts at insn %d\n",
9529 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
9532 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9533 struct bpf_func_state *caller,
9534 struct bpf_func_state *callee,
9537 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9538 struct bpf_map *map;
9541 if (bpf_map_ptr_poisoned(insn_aux)) {
9542 verbose(env, "tail_call abusing map_ptr\n");
9546 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9547 if (!map->ops->map_set_for_each_callback_args ||
9548 !map->ops->map_for_each_callback) {
9549 verbose(env, "callback function not allowed for map\n");
9553 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9557 callee->in_callback_fn = true;
9558 callee->callback_ret_range = tnum_range(0, 1);
9562 static int set_loop_callback_state(struct bpf_verifier_env *env,
9563 struct bpf_func_state *caller,
9564 struct bpf_func_state *callee,
9567 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9569 * callback_fn(u32 index, void *callback_ctx);
9571 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9572 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9575 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9576 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9577 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9579 callee->in_callback_fn = true;
9580 callee->callback_ret_range = tnum_range(0, 1);
9584 static int set_timer_callback_state(struct bpf_verifier_env *env,
9585 struct bpf_func_state *caller,
9586 struct bpf_func_state *callee,
9589 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9591 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9592 * callback_fn(struct bpf_map *map, void *key, void *value);
9594 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9595 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9596 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9598 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9599 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9600 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9602 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9603 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9604 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9607 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9608 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9609 callee->in_async_callback_fn = true;
9610 callee->callback_ret_range = tnum_range(0, 1);
9614 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9615 struct bpf_func_state *caller,
9616 struct bpf_func_state *callee,
9619 /* bpf_find_vma(struct task_struct *task, u64 addr,
9620 * void *callback_fn, void *callback_ctx, u64 flags)
9621 * (callback_fn)(struct task_struct *task,
9622 * struct vm_area_struct *vma, void *callback_ctx);
9624 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9626 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9627 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9628 callee->regs[BPF_REG_2].btf = btf_vmlinux;
9629 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9631 /* pointer to stack or null */
9632 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9635 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9636 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9637 callee->in_callback_fn = true;
9638 callee->callback_ret_range = tnum_range(0, 1);
9642 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9643 struct bpf_func_state *caller,
9644 struct bpf_func_state *callee,
9647 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9648 * callback_ctx, u64 flags);
9649 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9651 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9652 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9653 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9656 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9657 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9658 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9660 callee->in_callback_fn = true;
9661 callee->callback_ret_range = tnum_range(0, 1);
9665 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9666 struct bpf_func_state *caller,
9667 struct bpf_func_state *callee,
9670 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9671 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9673 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9674 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9675 * by this point, so look at 'root'
9677 struct btf_field *field;
9679 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9681 if (!field || !field->graph_root.value_btf_id)
9684 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9685 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9686 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9687 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9689 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9690 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9691 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9692 callee->in_callback_fn = true;
9693 callee->callback_ret_range = tnum_range(0, 1);
9697 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9699 /* Are we currently verifying the callback for a rbtree helper that must
9700 * be called with lock held? If so, no need to complain about unreleased
9703 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9705 struct bpf_verifier_state *state = env->cur_state;
9706 struct bpf_insn *insn = env->prog->insnsi;
9707 struct bpf_func_state *callee;
9710 if (!state->curframe)
9713 callee = state->frame[state->curframe];
9715 if (!callee->in_callback_fn)
9718 kfunc_btf_id = insn[callee->callsite].imm;
9719 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9722 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9724 struct bpf_verifier_state *state = env->cur_state;
9725 struct bpf_func_state *caller, *callee;
9726 struct bpf_reg_state *r0;
9729 callee = state->frame[state->curframe];
9730 r0 = &callee->regs[BPF_REG_0];
9731 if (r0->type == PTR_TO_STACK) {
9732 /* technically it's ok to return caller's stack pointer
9733 * (or caller's caller's pointer) back to the caller,
9734 * since these pointers are valid. Only current stack
9735 * pointer will be invalid as soon as function exits,
9736 * but let's be conservative
9738 verbose(env, "cannot return stack pointer to the caller\n");
9742 caller = state->frame[state->curframe - 1];
9743 if (callee->in_callback_fn) {
9744 /* enforce R0 return value range [0, 1]. */
9745 struct tnum range = callee->callback_ret_range;
9747 if (r0->type != SCALAR_VALUE) {
9748 verbose(env, "R0 not a scalar value\n");
9751 if (!tnum_in(range, r0->var_off)) {
9752 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9756 /* return to the caller whatever r0 had in the callee */
9757 caller->regs[BPF_REG_0] = *r0;
9760 /* callback_fn frame should have released its own additions to parent's
9761 * reference state at this point, or check_reference_leak would
9762 * complain, hence it must be the same as the caller. There is no need
9765 if (!callee->in_callback_fn) {
9766 /* Transfer references to the caller */
9767 err = copy_reference_state(caller, callee);
9772 *insn_idx = callee->callsite + 1;
9773 if (env->log.level & BPF_LOG_LEVEL) {
9774 verbose(env, "returning from callee:\n");
9775 print_verifier_state(env, callee, true);
9776 verbose(env, "to caller at %d:\n", *insn_idx);
9777 print_verifier_state(env, caller, true);
9779 /* clear everything in the callee. In case of exceptional exits using
9780 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9781 free_func_state(callee);
9782 state->frame[state->curframe--] = NULL;
9786 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9788 struct bpf_call_arg_meta *meta)
9790 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
9792 if (ret_type != RET_INTEGER)
9796 case BPF_FUNC_get_stack:
9797 case BPF_FUNC_get_task_stack:
9798 case BPF_FUNC_probe_read_str:
9799 case BPF_FUNC_probe_read_kernel_str:
9800 case BPF_FUNC_probe_read_user_str:
9801 ret_reg->smax_value = meta->msize_max_value;
9802 ret_reg->s32_max_value = meta->msize_max_value;
9803 ret_reg->smin_value = -MAX_ERRNO;
9804 ret_reg->s32_min_value = -MAX_ERRNO;
9805 reg_bounds_sync(ret_reg);
9807 case BPF_FUNC_get_smp_processor_id:
9808 ret_reg->umax_value = nr_cpu_ids - 1;
9809 ret_reg->u32_max_value = nr_cpu_ids - 1;
9810 ret_reg->smax_value = nr_cpu_ids - 1;
9811 ret_reg->s32_max_value = nr_cpu_ids - 1;
9812 ret_reg->umin_value = 0;
9813 ret_reg->u32_min_value = 0;
9814 ret_reg->smin_value = 0;
9815 ret_reg->s32_min_value = 0;
9816 reg_bounds_sync(ret_reg);
9822 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9823 int func_id, int insn_idx)
9825 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9826 struct bpf_map *map = meta->map_ptr;
9828 if (func_id != BPF_FUNC_tail_call &&
9829 func_id != BPF_FUNC_map_lookup_elem &&
9830 func_id != BPF_FUNC_map_update_elem &&
9831 func_id != BPF_FUNC_map_delete_elem &&
9832 func_id != BPF_FUNC_map_push_elem &&
9833 func_id != BPF_FUNC_map_pop_elem &&
9834 func_id != BPF_FUNC_map_peek_elem &&
9835 func_id != BPF_FUNC_for_each_map_elem &&
9836 func_id != BPF_FUNC_redirect_map &&
9837 func_id != BPF_FUNC_map_lookup_percpu_elem)
9841 verbose(env, "kernel subsystem misconfigured verifier\n");
9845 /* In case of read-only, some additional restrictions
9846 * need to be applied in order to prevent altering the
9847 * state of the map from program side.
9849 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9850 (func_id == BPF_FUNC_map_delete_elem ||
9851 func_id == BPF_FUNC_map_update_elem ||
9852 func_id == BPF_FUNC_map_push_elem ||
9853 func_id == BPF_FUNC_map_pop_elem)) {
9854 verbose(env, "write into map forbidden\n");
9858 if (!BPF_MAP_PTR(aux->map_ptr_state))
9859 bpf_map_ptr_store(aux, meta->map_ptr,
9860 !meta->map_ptr->bypass_spec_v1);
9861 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9862 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9863 !meta->map_ptr->bypass_spec_v1);
9868 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9869 int func_id, int insn_idx)
9871 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9872 struct bpf_reg_state *regs = cur_regs(env), *reg;
9873 struct bpf_map *map = meta->map_ptr;
9877 if (func_id != BPF_FUNC_tail_call)
9879 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9880 verbose(env, "kernel subsystem misconfigured verifier\n");
9884 reg = ®s[BPF_REG_3];
9885 val = reg->var_off.value;
9886 max = map->max_entries;
9888 if (!(register_is_const(reg) && val < max)) {
9889 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9893 err = mark_chain_precision(env, BPF_REG_3);
9896 if (bpf_map_key_unseen(aux))
9897 bpf_map_key_store(aux, val);
9898 else if (!bpf_map_key_poisoned(aux) &&
9899 bpf_map_key_immediate(aux) != val)
9900 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9904 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
9906 struct bpf_func_state *state = cur_func(env);
9907 bool refs_lingering = false;
9910 if (!exception_exit && state->frameno && !state->in_callback_fn)
9913 for (i = 0; i < state->acquired_refs; i++) {
9914 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9916 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9917 state->refs[i].id, state->refs[i].insn_idx);
9918 refs_lingering = true;
9920 return refs_lingering ? -EINVAL : 0;
9923 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9924 struct bpf_reg_state *regs)
9926 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
9927 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
9928 struct bpf_map *fmt_map = fmt_reg->map_ptr;
9929 struct bpf_bprintf_data data = {};
9930 int err, fmt_map_off, num_args;
9934 /* data must be an array of u64 */
9935 if (data_len_reg->var_off.value % 8)
9937 num_args = data_len_reg->var_off.value / 8;
9939 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9940 * and map_direct_value_addr is set.
9942 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9943 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9946 verbose(env, "verifier bug\n");
9949 fmt = (char *)(long)fmt_addr + fmt_map_off;
9951 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9952 * can focus on validating the format specifiers.
9954 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9956 verbose(env, "Invalid format string\n");
9961 static int check_get_func_ip(struct bpf_verifier_env *env)
9963 enum bpf_prog_type type = resolve_prog_type(env->prog);
9964 int func_id = BPF_FUNC_get_func_ip;
9966 if (type == BPF_PROG_TYPE_TRACING) {
9967 if (!bpf_prog_has_trampoline(env->prog)) {
9968 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9969 func_id_name(func_id), func_id);
9973 } else if (type == BPF_PROG_TYPE_KPROBE) {
9977 verbose(env, "func %s#%d not supported for program type %d\n",
9978 func_id_name(func_id), func_id, type);
9982 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9984 return &env->insn_aux_data[env->insn_idx];
9987 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9989 struct bpf_reg_state *regs = cur_regs(env);
9990 struct bpf_reg_state *reg = ®s[BPF_REG_4];
9991 bool reg_is_null = register_is_null(reg);
9994 mark_chain_precision(env, BPF_REG_4);
9999 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10001 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10003 if (!state->initialized) {
10004 state->initialized = 1;
10005 state->fit_for_inline = loop_flag_is_zero(env);
10006 state->callback_subprogno = subprogno;
10010 if (!state->fit_for_inline)
10013 state->fit_for_inline = (loop_flag_is_zero(env) &&
10014 state->callback_subprogno == subprogno);
10017 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10020 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10021 bool returns_cpu_specific_alloc_ptr = false;
10022 const struct bpf_func_proto *fn = NULL;
10023 enum bpf_return_type ret_type;
10024 enum bpf_type_flag ret_flag;
10025 struct bpf_reg_state *regs;
10026 struct bpf_call_arg_meta meta;
10027 int insn_idx = *insn_idx_p;
10029 int i, err, func_id;
10031 /* find function prototype */
10032 func_id = insn->imm;
10033 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
10034 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10039 if (env->ops->get_func_proto)
10040 fn = env->ops->get_func_proto(func_id, env->prog);
10042 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
10047 /* eBPF programs must be GPL compatible to use GPL-ed functions */
10048 if (!env->prog->gpl_compatible && fn->gpl_only) {
10049 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10053 if (fn->allowed && !fn->allowed(env->prog)) {
10054 verbose(env, "helper call is not allowed in probe\n");
10058 if (!env->prog->aux->sleepable && fn->might_sleep) {
10059 verbose(env, "helper call might sleep in a non-sleepable prog\n");
10063 /* With LD_ABS/IND some JITs save/restore skb from r1. */
10064 changes_data = bpf_helper_changes_pkt_data(fn->func);
10065 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10066 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10067 func_id_name(func_id), func_id);
10071 memset(&meta, 0, sizeof(meta));
10072 meta.pkt_access = fn->pkt_access;
10074 err = check_func_proto(fn, func_id);
10076 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10077 func_id_name(func_id), func_id);
10081 if (env->cur_state->active_rcu_lock) {
10082 if (fn->might_sleep) {
10083 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10084 func_id_name(func_id), func_id);
10088 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10089 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10092 meta.func_id = func_id;
10094 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10095 err = check_func_arg(env, i, &meta, fn, insn_idx);
10100 err = record_func_map(env, &meta, func_id, insn_idx);
10104 err = record_func_key(env, &meta, func_id, insn_idx);
10108 /* Mark slots with STACK_MISC in case of raw mode, stack offset
10109 * is inferred from register state.
10111 for (i = 0; i < meta.access_size; i++) {
10112 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10113 BPF_WRITE, -1, false, false);
10118 regs = cur_regs(env);
10120 if (meta.release_regno) {
10122 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10123 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10124 * is safe to do directly.
10126 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10127 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10128 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10131 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
10132 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10133 u32 ref_obj_id = meta.ref_obj_id;
10134 bool in_rcu = in_rcu_cs(env);
10135 struct bpf_func_state *state;
10136 struct bpf_reg_state *reg;
10138 err = release_reference_state(cur_func(env), ref_obj_id);
10140 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10141 if (reg->ref_obj_id == ref_obj_id) {
10142 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10143 reg->ref_obj_id = 0;
10144 reg->type &= ~MEM_ALLOC;
10145 reg->type |= MEM_RCU;
10147 mark_reg_invalid(env, reg);
10152 } else if (meta.ref_obj_id) {
10153 err = release_reference(env, meta.ref_obj_id);
10154 } else if (register_is_null(®s[meta.release_regno])) {
10155 /* meta.ref_obj_id can only be 0 if register that is meant to be
10156 * released is NULL, which must be > R0.
10161 verbose(env, "func %s#%d reference has not been acquired before\n",
10162 func_id_name(func_id), func_id);
10168 case BPF_FUNC_tail_call:
10169 err = check_reference_leak(env, false);
10171 verbose(env, "tail_call would lead to reference leak\n");
10175 case BPF_FUNC_get_local_storage:
10176 /* check that flags argument in get_local_storage(map, flags) is 0,
10177 * this is required because get_local_storage() can't return an error.
10179 if (!register_is_null(®s[BPF_REG_2])) {
10180 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10184 case BPF_FUNC_for_each_map_elem:
10185 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10186 set_map_elem_callback_state);
10188 case BPF_FUNC_timer_set_callback:
10189 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10190 set_timer_callback_state);
10192 case BPF_FUNC_find_vma:
10193 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10194 set_find_vma_callback_state);
10196 case BPF_FUNC_snprintf:
10197 err = check_bpf_snprintf_call(env, regs);
10199 case BPF_FUNC_loop:
10200 update_loop_inline_state(env, meta.subprogno);
10201 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10202 set_loop_callback_state);
10204 case BPF_FUNC_dynptr_from_mem:
10205 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10206 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10207 reg_type_str(env, regs[BPF_REG_1].type));
10211 case BPF_FUNC_set_retval:
10212 if (prog_type == BPF_PROG_TYPE_LSM &&
10213 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10214 if (!env->prog->aux->attach_func_proto->type) {
10215 /* Make sure programs that attach to void
10216 * hooks don't try to modify return value.
10218 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10223 case BPF_FUNC_dynptr_data:
10225 struct bpf_reg_state *reg;
10226 int id, ref_obj_id;
10228 reg = get_dynptr_arg_reg(env, fn, regs);
10233 if (meta.dynptr_id) {
10234 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10237 if (meta.ref_obj_id) {
10238 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10242 id = dynptr_id(env, reg);
10244 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10248 ref_obj_id = dynptr_ref_obj_id(env, reg);
10249 if (ref_obj_id < 0) {
10250 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10254 meta.dynptr_id = id;
10255 meta.ref_obj_id = ref_obj_id;
10259 case BPF_FUNC_dynptr_write:
10261 enum bpf_dynptr_type dynptr_type;
10262 struct bpf_reg_state *reg;
10264 reg = get_dynptr_arg_reg(env, fn, regs);
10268 dynptr_type = dynptr_get_type(env, reg);
10269 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10272 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10273 /* this will trigger clear_all_pkt_pointers(), which will
10274 * invalidate all dynptr slices associated with the skb
10276 changes_data = true;
10280 case BPF_FUNC_per_cpu_ptr:
10281 case BPF_FUNC_this_cpu_ptr:
10283 struct bpf_reg_state *reg = ®s[BPF_REG_1];
10284 const struct btf_type *type;
10286 if (reg->type & MEM_RCU) {
10287 type = btf_type_by_id(reg->btf, reg->btf_id);
10288 if (!type || !btf_type_is_struct(type)) {
10289 verbose(env, "Helper has invalid btf/btf_id in R1\n");
10292 returns_cpu_specific_alloc_ptr = true;
10293 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10297 case BPF_FUNC_user_ringbuf_drain:
10298 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10299 set_user_ringbuf_callback_state);
10306 /* reset caller saved regs */
10307 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10308 mark_reg_not_init(env, regs, caller_saved[i]);
10309 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10312 /* helper call returns 64-bit value. */
10313 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10315 /* update return register (already marked as written above) */
10316 ret_type = fn->ret_type;
10317 ret_flag = type_flag(ret_type);
10319 switch (base_type(ret_type)) {
10321 /* sets type to SCALAR_VALUE */
10322 mark_reg_unknown(env, regs, BPF_REG_0);
10325 regs[BPF_REG_0].type = NOT_INIT;
10327 case RET_PTR_TO_MAP_VALUE:
10328 /* There is no offset yet applied, variable or fixed */
10329 mark_reg_known_zero(env, regs, BPF_REG_0);
10330 /* remember map_ptr, so that check_map_access()
10331 * can check 'value_size' boundary of memory access
10332 * to map element returned from bpf_map_lookup_elem()
10334 if (meta.map_ptr == NULL) {
10336 "kernel subsystem misconfigured verifier\n");
10339 regs[BPF_REG_0].map_ptr = meta.map_ptr;
10340 regs[BPF_REG_0].map_uid = meta.map_uid;
10341 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10342 if (!type_may_be_null(ret_type) &&
10343 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10344 regs[BPF_REG_0].id = ++env->id_gen;
10347 case RET_PTR_TO_SOCKET:
10348 mark_reg_known_zero(env, regs, BPF_REG_0);
10349 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10351 case RET_PTR_TO_SOCK_COMMON:
10352 mark_reg_known_zero(env, regs, BPF_REG_0);
10353 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10355 case RET_PTR_TO_TCP_SOCK:
10356 mark_reg_known_zero(env, regs, BPF_REG_0);
10357 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10359 case RET_PTR_TO_MEM:
10360 mark_reg_known_zero(env, regs, BPF_REG_0);
10361 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10362 regs[BPF_REG_0].mem_size = meta.mem_size;
10364 case RET_PTR_TO_MEM_OR_BTF_ID:
10366 const struct btf_type *t;
10368 mark_reg_known_zero(env, regs, BPF_REG_0);
10369 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10370 if (!btf_type_is_struct(t)) {
10372 const struct btf_type *ret;
10375 /* resolve the type size of ksym. */
10376 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10378 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10379 verbose(env, "unable to resolve the size of type '%s': %ld\n",
10380 tname, PTR_ERR(ret));
10383 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10384 regs[BPF_REG_0].mem_size = tsize;
10386 if (returns_cpu_specific_alloc_ptr) {
10387 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10389 /* MEM_RDONLY may be carried from ret_flag, but it
10390 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10391 * it will confuse the check of PTR_TO_BTF_ID in
10392 * check_mem_access().
10394 ret_flag &= ~MEM_RDONLY;
10395 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10398 regs[BPF_REG_0].btf = meta.ret_btf;
10399 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10403 case RET_PTR_TO_BTF_ID:
10405 struct btf *ret_btf;
10408 mark_reg_known_zero(env, regs, BPF_REG_0);
10409 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10410 if (func_id == BPF_FUNC_kptr_xchg) {
10411 ret_btf = meta.kptr_field->kptr.btf;
10412 ret_btf_id = meta.kptr_field->kptr.btf_id;
10413 if (!btf_is_kernel(ret_btf)) {
10414 regs[BPF_REG_0].type |= MEM_ALLOC;
10415 if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10416 regs[BPF_REG_0].type |= MEM_PERCPU;
10419 if (fn->ret_btf_id == BPF_PTR_POISON) {
10420 verbose(env, "verifier internal error:");
10421 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10422 func_id_name(func_id));
10425 ret_btf = btf_vmlinux;
10426 ret_btf_id = *fn->ret_btf_id;
10428 if (ret_btf_id == 0) {
10429 verbose(env, "invalid return type %u of func %s#%d\n",
10430 base_type(ret_type), func_id_name(func_id),
10434 regs[BPF_REG_0].btf = ret_btf;
10435 regs[BPF_REG_0].btf_id = ret_btf_id;
10439 verbose(env, "unknown return type %u of func %s#%d\n",
10440 base_type(ret_type), func_id_name(func_id), func_id);
10444 if (type_may_be_null(regs[BPF_REG_0].type))
10445 regs[BPF_REG_0].id = ++env->id_gen;
10447 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10448 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10449 func_id_name(func_id), func_id);
10453 if (is_dynptr_ref_function(func_id))
10454 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10456 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10457 /* For release_reference() */
10458 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10459 } else if (is_acquire_function(func_id, meta.map_ptr)) {
10460 int id = acquire_reference_state(env, insn_idx);
10464 /* For mark_ptr_or_null_reg() */
10465 regs[BPF_REG_0].id = id;
10466 /* For release_reference() */
10467 regs[BPF_REG_0].ref_obj_id = id;
10470 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10472 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10476 if ((func_id == BPF_FUNC_get_stack ||
10477 func_id == BPF_FUNC_get_task_stack) &&
10478 !env->prog->has_callchain_buf) {
10479 const char *err_str;
10481 #ifdef CONFIG_PERF_EVENTS
10482 err = get_callchain_buffers(sysctl_perf_event_max_stack);
10483 err_str = "cannot get callchain buffer for func %s#%d\n";
10486 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10489 verbose(env, err_str, func_id_name(func_id), func_id);
10493 env->prog->has_callchain_buf = true;
10496 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10497 env->prog->call_get_stack = true;
10499 if (func_id == BPF_FUNC_get_func_ip) {
10500 if (check_get_func_ip(env))
10502 env->prog->call_get_func_ip = true;
10506 clear_all_pkt_pointers(env);
10510 /* mark_btf_func_reg_size() is used when the reg size is determined by
10511 * the BTF func_proto's return value size and argument.
10513 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10516 struct bpf_reg_state *reg = &cur_regs(env)[regno];
10518 if (regno == BPF_REG_0) {
10519 /* Function return value */
10520 reg->live |= REG_LIVE_WRITTEN;
10521 reg->subreg_def = reg_size == sizeof(u64) ?
10522 DEF_NOT_SUBREG : env->insn_idx + 1;
10524 /* Function argument */
10525 if (reg_size == sizeof(u64)) {
10526 mark_insn_zext(env, reg);
10527 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10529 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10534 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10536 return meta->kfunc_flags & KF_ACQUIRE;
10539 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10541 return meta->kfunc_flags & KF_RELEASE;
10544 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10546 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10549 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10551 return meta->kfunc_flags & KF_SLEEPABLE;
10554 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10556 return meta->kfunc_flags & KF_DESTRUCTIVE;
10559 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10561 return meta->kfunc_flags & KF_RCU;
10564 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10566 return meta->kfunc_flags & KF_RCU_PROTECTED;
10569 static bool __kfunc_param_match_suffix(const struct btf *btf,
10570 const struct btf_param *arg,
10571 const char *suffix)
10573 int suffix_len = strlen(suffix), len;
10574 const char *param_name;
10576 /* In the future, this can be ported to use BTF tagging */
10577 param_name = btf_name_by_offset(btf, arg->name_off);
10578 if (str_is_empty(param_name))
10580 len = strlen(param_name);
10581 if (len < suffix_len)
10583 param_name += len - suffix_len;
10584 return !strncmp(param_name, suffix, suffix_len);
10587 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10588 const struct btf_param *arg,
10589 const struct bpf_reg_state *reg)
10591 const struct btf_type *t;
10593 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10594 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10597 return __kfunc_param_match_suffix(btf, arg, "__sz");
10600 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10601 const struct btf_param *arg,
10602 const struct bpf_reg_state *reg)
10604 const struct btf_type *t;
10606 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10607 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10610 return __kfunc_param_match_suffix(btf, arg, "__szk");
10613 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10615 return __kfunc_param_match_suffix(btf, arg, "__opt");
10618 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10620 return __kfunc_param_match_suffix(btf, arg, "__k");
10623 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10625 return __kfunc_param_match_suffix(btf, arg, "__ign");
10628 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10630 return __kfunc_param_match_suffix(btf, arg, "__alloc");
10633 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10635 return __kfunc_param_match_suffix(btf, arg, "__uninit");
10638 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10640 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10643 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10645 return __kfunc_param_match_suffix(btf, arg, "__nullable");
10648 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10649 const struct btf_param *arg,
10652 int len, target_len = strlen(name);
10653 const char *param_name;
10655 param_name = btf_name_by_offset(btf, arg->name_off);
10656 if (str_is_empty(param_name))
10658 len = strlen(param_name);
10659 if (len != target_len)
10661 if (strcmp(param_name, name))
10669 KF_ARG_LIST_HEAD_ID,
10670 KF_ARG_LIST_NODE_ID,
10675 BTF_ID_LIST(kf_arg_btf_ids)
10676 BTF_ID(struct, bpf_dynptr_kern)
10677 BTF_ID(struct, bpf_list_head)
10678 BTF_ID(struct, bpf_list_node)
10679 BTF_ID(struct, bpf_rb_root)
10680 BTF_ID(struct, bpf_rb_node)
10682 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10683 const struct btf_param *arg, int type)
10685 const struct btf_type *t;
10688 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10691 if (!btf_type_is_ptr(t))
10693 t = btf_type_skip_modifiers(btf, t->type, &res_id);
10696 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10699 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10701 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10704 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10706 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10709 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10711 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10714 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10716 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10719 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10721 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10724 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10725 const struct btf_param *arg)
10727 const struct btf_type *t;
10729 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10736 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10737 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10738 const struct btf *btf,
10739 const struct btf_type *t, int rec)
10741 const struct btf_type *member_type;
10742 const struct btf_member *member;
10745 if (!btf_type_is_struct(t))
10748 for_each_member(i, t, member) {
10749 const struct btf_array *array;
10751 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10752 if (btf_type_is_struct(member_type)) {
10754 verbose(env, "max struct nesting depth exceeded\n");
10757 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10761 if (btf_type_is_array(member_type)) {
10762 array = btf_array(member_type);
10763 if (!array->nelems)
10765 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10766 if (!btf_type_is_scalar(member_type))
10770 if (!btf_type_is_scalar(member_type))
10776 enum kfunc_ptr_arg_type {
10778 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10779 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10780 KF_ARG_PTR_TO_DYNPTR,
10781 KF_ARG_PTR_TO_ITER,
10782 KF_ARG_PTR_TO_LIST_HEAD,
10783 KF_ARG_PTR_TO_LIST_NODE,
10784 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
10786 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
10787 KF_ARG_PTR_TO_CALLBACK,
10788 KF_ARG_PTR_TO_RB_ROOT,
10789 KF_ARG_PTR_TO_RB_NODE,
10790 KF_ARG_PTR_TO_NULL,
10793 enum special_kfunc_type {
10794 KF_bpf_obj_new_impl,
10795 KF_bpf_obj_drop_impl,
10796 KF_bpf_refcount_acquire_impl,
10797 KF_bpf_list_push_front_impl,
10798 KF_bpf_list_push_back_impl,
10799 KF_bpf_list_pop_front,
10800 KF_bpf_list_pop_back,
10801 KF_bpf_cast_to_kern_ctx,
10802 KF_bpf_rdonly_cast,
10803 KF_bpf_rcu_read_lock,
10804 KF_bpf_rcu_read_unlock,
10805 KF_bpf_rbtree_remove,
10806 KF_bpf_rbtree_add_impl,
10807 KF_bpf_rbtree_first,
10808 KF_bpf_dynptr_from_skb,
10809 KF_bpf_dynptr_from_xdp,
10810 KF_bpf_dynptr_slice,
10811 KF_bpf_dynptr_slice_rdwr,
10812 KF_bpf_dynptr_clone,
10813 KF_bpf_percpu_obj_new_impl,
10814 KF_bpf_percpu_obj_drop_impl,
10816 KF_bpf_iter_css_task_new,
10819 BTF_SET_START(special_kfunc_set)
10820 BTF_ID(func, bpf_obj_new_impl)
10821 BTF_ID(func, bpf_obj_drop_impl)
10822 BTF_ID(func, bpf_refcount_acquire_impl)
10823 BTF_ID(func, bpf_list_push_front_impl)
10824 BTF_ID(func, bpf_list_push_back_impl)
10825 BTF_ID(func, bpf_list_pop_front)
10826 BTF_ID(func, bpf_list_pop_back)
10827 BTF_ID(func, bpf_cast_to_kern_ctx)
10828 BTF_ID(func, bpf_rdonly_cast)
10829 BTF_ID(func, bpf_rbtree_remove)
10830 BTF_ID(func, bpf_rbtree_add_impl)
10831 BTF_ID(func, bpf_rbtree_first)
10832 BTF_ID(func, bpf_dynptr_from_skb)
10833 BTF_ID(func, bpf_dynptr_from_xdp)
10834 BTF_ID(func, bpf_dynptr_slice)
10835 BTF_ID(func, bpf_dynptr_slice_rdwr)
10836 BTF_ID(func, bpf_dynptr_clone)
10837 BTF_ID(func, bpf_percpu_obj_new_impl)
10838 BTF_ID(func, bpf_percpu_obj_drop_impl)
10839 BTF_ID(func, bpf_throw)
10840 #ifdef CONFIG_CGROUPS
10841 BTF_ID(func, bpf_iter_css_task_new)
10843 BTF_SET_END(special_kfunc_set)
10845 BTF_ID_LIST(special_kfunc_list)
10846 BTF_ID(func, bpf_obj_new_impl)
10847 BTF_ID(func, bpf_obj_drop_impl)
10848 BTF_ID(func, bpf_refcount_acquire_impl)
10849 BTF_ID(func, bpf_list_push_front_impl)
10850 BTF_ID(func, bpf_list_push_back_impl)
10851 BTF_ID(func, bpf_list_pop_front)
10852 BTF_ID(func, bpf_list_pop_back)
10853 BTF_ID(func, bpf_cast_to_kern_ctx)
10854 BTF_ID(func, bpf_rdonly_cast)
10855 BTF_ID(func, bpf_rcu_read_lock)
10856 BTF_ID(func, bpf_rcu_read_unlock)
10857 BTF_ID(func, bpf_rbtree_remove)
10858 BTF_ID(func, bpf_rbtree_add_impl)
10859 BTF_ID(func, bpf_rbtree_first)
10860 BTF_ID(func, bpf_dynptr_from_skb)
10861 BTF_ID(func, bpf_dynptr_from_xdp)
10862 BTF_ID(func, bpf_dynptr_slice)
10863 BTF_ID(func, bpf_dynptr_slice_rdwr)
10864 BTF_ID(func, bpf_dynptr_clone)
10865 BTF_ID(func, bpf_percpu_obj_new_impl)
10866 BTF_ID(func, bpf_percpu_obj_drop_impl)
10867 BTF_ID(func, bpf_throw)
10868 #ifdef CONFIG_CGROUPS
10869 BTF_ID(func, bpf_iter_css_task_new)
10874 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10876 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10877 meta->arg_owning_ref) {
10881 return meta->kfunc_flags & KF_RET_NULL;
10884 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10886 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10889 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10891 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10894 static enum kfunc_ptr_arg_type
10895 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10896 struct bpf_kfunc_call_arg_meta *meta,
10897 const struct btf_type *t, const struct btf_type *ref_t,
10898 const char *ref_tname, const struct btf_param *args,
10899 int argno, int nargs)
10901 u32 regno = argno + 1;
10902 struct bpf_reg_state *regs = cur_regs(env);
10903 struct bpf_reg_state *reg = ®s[regno];
10904 bool arg_mem_size = false;
10906 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10907 return KF_ARG_PTR_TO_CTX;
10909 /* In this function, we verify the kfunc's BTF as per the argument type,
10910 * leaving the rest of the verification with respect to the register
10911 * type to our caller. When a set of conditions hold in the BTF type of
10912 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10914 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10915 return KF_ARG_PTR_TO_CTX;
10917 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10918 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10920 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10921 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10923 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10924 return KF_ARG_PTR_TO_DYNPTR;
10926 if (is_kfunc_arg_iter(meta, argno))
10927 return KF_ARG_PTR_TO_ITER;
10929 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10930 return KF_ARG_PTR_TO_LIST_HEAD;
10932 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10933 return KF_ARG_PTR_TO_LIST_NODE;
10935 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10936 return KF_ARG_PTR_TO_RB_ROOT;
10938 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10939 return KF_ARG_PTR_TO_RB_NODE;
10941 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10942 if (!btf_type_is_struct(ref_t)) {
10943 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10944 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10947 return KF_ARG_PTR_TO_BTF_ID;
10950 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10951 return KF_ARG_PTR_TO_CALLBACK;
10953 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
10954 return KF_ARG_PTR_TO_NULL;
10956 if (argno + 1 < nargs &&
10957 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
10958 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
10959 arg_mem_size = true;
10961 /* This is the catch all argument type of register types supported by
10962 * check_helper_mem_access. However, we only allow when argument type is
10963 * pointer to scalar, or struct composed (recursively) of scalars. When
10964 * arg_mem_size is true, the pointer can be void *.
10966 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10967 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10968 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10969 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10972 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10975 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10976 struct bpf_reg_state *reg,
10977 const struct btf_type *ref_t,
10978 const char *ref_tname, u32 ref_id,
10979 struct bpf_kfunc_call_arg_meta *meta,
10982 const struct btf_type *reg_ref_t;
10983 bool strict_type_match = false;
10984 const struct btf *reg_btf;
10985 const char *reg_ref_tname;
10988 if (base_type(reg->type) == PTR_TO_BTF_ID) {
10989 reg_btf = reg->btf;
10990 reg_ref_id = reg->btf_id;
10992 reg_btf = btf_vmlinux;
10993 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10996 /* Enforce strict type matching for calls to kfuncs that are acquiring
10997 * or releasing a reference, or are no-cast aliases. We do _not_
10998 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10999 * as we want to enable BPF programs to pass types that are bitwise
11000 * equivalent without forcing them to explicitly cast with something
11001 * like bpf_cast_to_kern_ctx().
11003 * For example, say we had a type like the following:
11005 * struct bpf_cpumask {
11006 * cpumask_t cpumask;
11007 * refcount_t usage;
11010 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11011 * to a struct cpumask, so it would be safe to pass a struct
11012 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11014 * The philosophy here is similar to how we allow scalars of different
11015 * types to be passed to kfuncs as long as the size is the same. The
11016 * only difference here is that we're simply allowing
11017 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11020 if (is_kfunc_acquire(meta) ||
11021 (is_kfunc_release(meta) && reg->ref_obj_id) ||
11022 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11023 strict_type_match = true;
11025 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
11027 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
11028 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11029 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
11030 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11031 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11032 btf_type_str(reg_ref_t), reg_ref_tname);
11038 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11040 struct bpf_verifier_state *state = env->cur_state;
11041 struct btf_record *rec = reg_btf_record(reg);
11043 if (!state->active_lock.ptr) {
11044 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11048 if (type_flag(reg->type) & NON_OWN_REF) {
11049 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11053 reg->type |= NON_OWN_REF;
11054 if (rec->refcount_off >= 0)
11055 reg->type |= MEM_RCU;
11060 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11062 struct bpf_func_state *state, *unused;
11063 struct bpf_reg_state *reg;
11066 state = cur_func(env);
11069 verbose(env, "verifier internal error: ref_obj_id is zero for "
11070 "owning -> non-owning conversion\n");
11074 for (i = 0; i < state->acquired_refs; i++) {
11075 if (state->refs[i].id != ref_obj_id)
11078 /* Clear ref_obj_id here so release_reference doesn't clobber
11081 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11082 if (reg->ref_obj_id == ref_obj_id) {
11083 reg->ref_obj_id = 0;
11084 ref_set_non_owning(env, reg);
11090 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11094 /* Implementation details:
11096 * Each register points to some region of memory, which we define as an
11097 * allocation. Each allocation may embed a bpf_spin_lock which protects any
11098 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11099 * allocation. The lock and the data it protects are colocated in the same
11102 * Hence, everytime a register holds a pointer value pointing to such
11103 * allocation, the verifier preserves a unique reg->id for it.
11105 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11106 * bpf_spin_lock is called.
11108 * To enable this, lock state in the verifier captures two values:
11109 * active_lock.ptr = Register's type specific pointer
11110 * active_lock.id = A unique ID for each register pointer value
11112 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11113 * supported register types.
11115 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11116 * allocated objects is the reg->btf pointer.
11118 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11119 * can establish the provenance of the map value statically for each distinct
11120 * lookup into such maps. They always contain a single map value hence unique
11121 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11123 * So, in case of global variables, they use array maps with max_entries = 1,
11124 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11125 * into the same map value as max_entries is 1, as described above).
11127 * In case of inner map lookups, the inner map pointer has same map_ptr as the
11128 * outer map pointer (in verifier context), but each lookup into an inner map
11129 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11130 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11131 * will get different reg->id assigned to each lookup, hence different
11134 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11135 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11136 * returned from bpf_obj_new. Each allocation receives a new reg->id.
11138 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11143 switch ((int)reg->type) {
11144 case PTR_TO_MAP_VALUE:
11145 ptr = reg->map_ptr;
11147 case PTR_TO_BTF_ID | MEM_ALLOC:
11151 verbose(env, "verifier internal error: unknown reg type for lock check\n");
11156 if (!env->cur_state->active_lock.ptr)
11158 if (env->cur_state->active_lock.ptr != ptr ||
11159 env->cur_state->active_lock.id != id) {
11160 verbose(env, "held lock and object are not in the same allocation\n");
11166 static bool is_bpf_list_api_kfunc(u32 btf_id)
11168 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11169 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11170 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11171 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11174 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11176 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11177 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11178 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11181 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11183 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11184 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11187 static bool is_callback_calling_kfunc(u32 btf_id)
11189 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11192 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11194 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11195 insn->imm == special_kfunc_list[KF_bpf_throw];
11198 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11200 return is_bpf_rbtree_api_kfunc(btf_id);
11203 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11204 enum btf_field_type head_field_type,
11209 switch (head_field_type) {
11210 case BPF_LIST_HEAD:
11211 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11214 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11217 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11218 btf_field_type_name(head_field_type));
11223 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11224 btf_field_type_name(head_field_type));
11228 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11229 enum btf_field_type node_field_type,
11234 switch (node_field_type) {
11235 case BPF_LIST_NODE:
11236 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11237 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11240 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11241 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11244 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11245 btf_field_type_name(node_field_type));
11250 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11251 btf_field_type_name(node_field_type));
11256 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11257 struct bpf_reg_state *reg, u32 regno,
11258 struct bpf_kfunc_call_arg_meta *meta,
11259 enum btf_field_type head_field_type,
11260 struct btf_field **head_field)
11262 const char *head_type_name;
11263 struct btf_field *field;
11264 struct btf_record *rec;
11267 if (meta->btf != btf_vmlinux) {
11268 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11272 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11275 head_type_name = btf_field_type_name(head_field_type);
11276 if (!tnum_is_const(reg->var_off)) {
11278 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11279 regno, head_type_name);
11283 rec = reg_btf_record(reg);
11284 head_off = reg->off + reg->var_off.value;
11285 field = btf_record_find(rec, head_off, head_field_type);
11287 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11291 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11292 if (check_reg_allocation_locked(env, reg)) {
11293 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11294 rec->spin_lock_off, head_type_name);
11299 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11302 *head_field = field;
11306 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11307 struct bpf_reg_state *reg, u32 regno,
11308 struct bpf_kfunc_call_arg_meta *meta)
11310 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11311 &meta->arg_list_head.field);
11314 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11315 struct bpf_reg_state *reg, u32 regno,
11316 struct bpf_kfunc_call_arg_meta *meta)
11318 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11319 &meta->arg_rbtree_root.field);
11323 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11324 struct bpf_reg_state *reg, u32 regno,
11325 struct bpf_kfunc_call_arg_meta *meta,
11326 enum btf_field_type head_field_type,
11327 enum btf_field_type node_field_type,
11328 struct btf_field **node_field)
11330 const char *node_type_name;
11331 const struct btf_type *et, *t;
11332 struct btf_field *field;
11335 if (meta->btf != btf_vmlinux) {
11336 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11340 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11343 node_type_name = btf_field_type_name(node_field_type);
11344 if (!tnum_is_const(reg->var_off)) {
11346 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11347 regno, node_type_name);
11351 node_off = reg->off + reg->var_off.value;
11352 field = reg_find_field_offset(reg, node_off, node_field_type);
11353 if (!field || field->offset != node_off) {
11354 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11358 field = *node_field;
11360 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11361 t = btf_type_by_id(reg->btf, reg->btf_id);
11362 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11363 field->graph_root.value_btf_id, true)) {
11364 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11365 "in struct %s, but arg is at offset=%d in struct %s\n",
11366 btf_field_type_name(head_field_type),
11367 btf_field_type_name(node_field_type),
11368 field->graph_root.node_offset,
11369 btf_name_by_offset(field->graph_root.btf, et->name_off),
11370 node_off, btf_name_by_offset(reg->btf, t->name_off));
11373 meta->arg_btf = reg->btf;
11374 meta->arg_btf_id = reg->btf_id;
11376 if (node_off != field->graph_root.node_offset) {
11377 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11378 node_off, btf_field_type_name(node_field_type),
11379 field->graph_root.node_offset,
11380 btf_name_by_offset(field->graph_root.btf, et->name_off));
11387 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11388 struct bpf_reg_state *reg, u32 regno,
11389 struct bpf_kfunc_call_arg_meta *meta)
11391 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11392 BPF_LIST_HEAD, BPF_LIST_NODE,
11393 &meta->arg_list_head.field);
11396 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11397 struct bpf_reg_state *reg, u32 regno,
11398 struct bpf_kfunc_call_arg_meta *meta)
11400 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11401 BPF_RB_ROOT, BPF_RB_NODE,
11402 &meta->arg_rbtree_root.field);
11405 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11407 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11409 switch (prog_type) {
11410 case BPF_PROG_TYPE_LSM:
11412 case BPF_TRACE_ITER:
11413 return env->prog->aux->sleepable;
11419 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11422 const char *func_name = meta->func_name, *ref_tname;
11423 const struct btf *btf = meta->btf;
11424 const struct btf_param *args;
11425 struct btf_record *rec;
11429 args = (const struct btf_param *)(meta->func_proto + 1);
11430 nargs = btf_type_vlen(meta->func_proto);
11431 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11432 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11433 MAX_BPF_FUNC_REG_ARGS);
11437 /* Check that BTF function arguments match actual types that the
11440 for (i = 0; i < nargs; i++) {
11441 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
11442 const struct btf_type *t, *ref_t, *resolve_ret;
11443 enum bpf_arg_type arg_type = ARG_DONTCARE;
11444 u32 regno = i + 1, ref_id, type_size;
11445 bool is_ret_buf_sz = false;
11448 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11450 if (is_kfunc_arg_ignore(btf, &args[i]))
11453 if (btf_type_is_scalar(t)) {
11454 if (reg->type != SCALAR_VALUE) {
11455 verbose(env, "R%d is not a scalar\n", regno);
11459 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11460 if (meta->arg_constant.found) {
11461 verbose(env, "verifier internal error: only one constant argument permitted\n");
11464 if (!tnum_is_const(reg->var_off)) {
11465 verbose(env, "R%d must be a known constant\n", regno);
11468 ret = mark_chain_precision(env, regno);
11471 meta->arg_constant.found = true;
11472 meta->arg_constant.value = reg->var_off.value;
11473 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11474 meta->r0_rdonly = true;
11475 is_ret_buf_sz = true;
11476 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11477 is_ret_buf_sz = true;
11480 if (is_ret_buf_sz) {
11481 if (meta->r0_size) {
11482 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11486 if (!tnum_is_const(reg->var_off)) {
11487 verbose(env, "R%d is not a const\n", regno);
11491 meta->r0_size = reg->var_off.value;
11492 ret = mark_chain_precision(env, regno);
11499 if (!btf_type_is_ptr(t)) {
11500 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11504 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11505 (register_is_null(reg) || type_may_be_null(reg->type)) &&
11506 !is_kfunc_arg_nullable(meta->btf, &args[i])) {
11507 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11511 if (reg->ref_obj_id) {
11512 if (is_kfunc_release(meta) && meta->ref_obj_id) {
11513 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11514 regno, reg->ref_obj_id,
11518 meta->ref_obj_id = reg->ref_obj_id;
11519 if (is_kfunc_release(meta))
11520 meta->release_regno = regno;
11523 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11524 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11526 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11527 if (kf_arg_type < 0)
11528 return kf_arg_type;
11530 switch (kf_arg_type) {
11531 case KF_ARG_PTR_TO_NULL:
11533 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11534 case KF_ARG_PTR_TO_BTF_ID:
11535 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11538 if (!is_trusted_reg(reg)) {
11539 if (!is_kfunc_rcu(meta)) {
11540 verbose(env, "R%d must be referenced or trusted\n", regno);
11543 if (!is_rcu_reg(reg)) {
11544 verbose(env, "R%d must be a rcu pointer\n", regno);
11550 case KF_ARG_PTR_TO_CTX:
11551 /* Trusted arguments have the same offset checks as release arguments */
11552 arg_type |= OBJ_RELEASE;
11554 case KF_ARG_PTR_TO_DYNPTR:
11555 case KF_ARG_PTR_TO_ITER:
11556 case KF_ARG_PTR_TO_LIST_HEAD:
11557 case KF_ARG_PTR_TO_LIST_NODE:
11558 case KF_ARG_PTR_TO_RB_ROOT:
11559 case KF_ARG_PTR_TO_RB_NODE:
11560 case KF_ARG_PTR_TO_MEM:
11561 case KF_ARG_PTR_TO_MEM_SIZE:
11562 case KF_ARG_PTR_TO_CALLBACK:
11563 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11564 /* Trusted by default */
11571 if (is_kfunc_release(meta) && reg->ref_obj_id)
11572 arg_type |= OBJ_RELEASE;
11573 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11577 switch (kf_arg_type) {
11578 case KF_ARG_PTR_TO_CTX:
11579 if (reg->type != PTR_TO_CTX) {
11580 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11584 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11585 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11588 meta->ret_btf_id = ret;
11591 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11592 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11593 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11594 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11597 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11598 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11599 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11603 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11606 if (!reg->ref_obj_id) {
11607 verbose(env, "allocated object must be referenced\n");
11610 if (meta->btf == btf_vmlinux) {
11611 meta->arg_btf = reg->btf;
11612 meta->arg_btf_id = reg->btf_id;
11615 case KF_ARG_PTR_TO_DYNPTR:
11617 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11618 int clone_ref_obj_id = 0;
11620 if (reg->type != PTR_TO_STACK &&
11621 reg->type != CONST_PTR_TO_DYNPTR) {
11622 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11626 if (reg->type == CONST_PTR_TO_DYNPTR)
11627 dynptr_arg_type |= MEM_RDONLY;
11629 if (is_kfunc_arg_uninit(btf, &args[i]))
11630 dynptr_arg_type |= MEM_UNINIT;
11632 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11633 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11634 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11635 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11636 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11637 (dynptr_arg_type & MEM_UNINIT)) {
11638 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11640 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11641 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11645 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11646 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11647 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11648 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11653 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11657 if (!(dynptr_arg_type & MEM_UNINIT)) {
11658 int id = dynptr_id(env, reg);
11661 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11664 meta->initialized_dynptr.id = id;
11665 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11666 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11671 case KF_ARG_PTR_TO_ITER:
11672 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
11673 if (!check_css_task_iter_allowlist(env)) {
11674 verbose(env, "css_task_iter is only allowed in bpf_lsm and bpf iter-s\n");
11678 ret = process_iter_arg(env, regno, insn_idx, meta);
11682 case KF_ARG_PTR_TO_LIST_HEAD:
11683 if (reg->type != PTR_TO_MAP_VALUE &&
11684 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11685 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11688 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11689 verbose(env, "allocated object must be referenced\n");
11692 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11696 case KF_ARG_PTR_TO_RB_ROOT:
11697 if (reg->type != PTR_TO_MAP_VALUE &&
11698 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11699 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11702 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11703 verbose(env, "allocated object must be referenced\n");
11706 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11710 case KF_ARG_PTR_TO_LIST_NODE:
11711 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11712 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11715 if (!reg->ref_obj_id) {
11716 verbose(env, "allocated object must be referenced\n");
11719 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11723 case KF_ARG_PTR_TO_RB_NODE:
11724 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11725 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11726 verbose(env, "rbtree_remove node input must be non-owning ref\n");
11729 if (in_rbtree_lock_required_cb(env)) {
11730 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11734 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11735 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11738 if (!reg->ref_obj_id) {
11739 verbose(env, "allocated object must be referenced\n");
11744 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11748 case KF_ARG_PTR_TO_BTF_ID:
11749 /* Only base_type is checked, further checks are done here */
11750 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11751 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11752 !reg2btf_ids[base_type(reg->type)]) {
11753 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11754 verbose(env, "expected %s or socket\n",
11755 reg_type_str(env, base_type(reg->type) |
11756 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11759 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11763 case KF_ARG_PTR_TO_MEM:
11764 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11765 if (IS_ERR(resolve_ret)) {
11766 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11767 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11770 ret = check_mem_reg(env, reg, regno, type_size);
11774 case KF_ARG_PTR_TO_MEM_SIZE:
11776 struct bpf_reg_state *buff_reg = ®s[regno];
11777 const struct btf_param *buff_arg = &args[i];
11778 struct bpf_reg_state *size_reg = ®s[regno + 1];
11779 const struct btf_param *size_arg = &args[i + 1];
11781 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11782 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11784 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11789 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11790 if (meta->arg_constant.found) {
11791 verbose(env, "verifier internal error: only one constant argument permitted\n");
11794 if (!tnum_is_const(size_reg->var_off)) {
11795 verbose(env, "R%d must be a known constant\n", regno + 1);
11798 meta->arg_constant.found = true;
11799 meta->arg_constant.value = size_reg->var_off.value;
11802 /* Skip next '__sz' or '__szk' argument */
11806 case KF_ARG_PTR_TO_CALLBACK:
11807 if (reg->type != PTR_TO_FUNC) {
11808 verbose(env, "arg%d expected pointer to func\n", i);
11811 meta->subprogno = reg->subprogno;
11813 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11814 if (!type_is_ptr_alloc_obj(reg->type)) {
11815 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11818 if (!type_is_non_owning_ref(reg->type))
11819 meta->arg_owning_ref = true;
11821 rec = reg_btf_record(reg);
11823 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11827 if (rec->refcount_off < 0) {
11828 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11832 meta->arg_btf = reg->btf;
11833 meta->arg_btf_id = reg->btf_id;
11838 if (is_kfunc_release(meta) && !meta->release_regno) {
11839 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11847 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11848 struct bpf_insn *insn,
11849 struct bpf_kfunc_call_arg_meta *meta,
11850 const char **kfunc_name)
11852 const struct btf_type *func, *func_proto;
11853 u32 func_id, *kfunc_flags;
11854 const char *func_name;
11855 struct btf *desc_btf;
11858 *kfunc_name = NULL;
11863 desc_btf = find_kfunc_desc_btf(env, insn->off);
11864 if (IS_ERR(desc_btf))
11865 return PTR_ERR(desc_btf);
11867 func_id = insn->imm;
11868 func = btf_type_by_id(desc_btf, func_id);
11869 func_name = btf_name_by_offset(desc_btf, func->name_off);
11871 *kfunc_name = func_name;
11872 func_proto = btf_type_by_id(desc_btf, func->type);
11874 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11875 if (!kfunc_flags) {
11879 memset(meta, 0, sizeof(*meta));
11880 meta->btf = desc_btf;
11881 meta->func_id = func_id;
11882 meta->kfunc_flags = *kfunc_flags;
11883 meta->func_proto = func_proto;
11884 meta->func_name = func_name;
11889 static int check_return_code(struct bpf_verifier_env *env, int regno);
11891 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11894 const struct btf_type *t, *ptr_type;
11895 u32 i, nargs, ptr_type_id, release_ref_obj_id;
11896 struct bpf_reg_state *regs = cur_regs(env);
11897 const char *func_name, *ptr_type_name;
11898 bool sleepable, rcu_lock, rcu_unlock;
11899 struct bpf_kfunc_call_arg_meta meta;
11900 struct bpf_insn_aux_data *insn_aux;
11901 int err, insn_idx = *insn_idx_p;
11902 const struct btf_param *args;
11903 const struct btf_type *ret_t;
11904 struct btf *desc_btf;
11906 /* skip for now, but return error when we find this in fixup_kfunc_call */
11910 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11911 if (err == -EACCES && func_name)
11912 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11915 desc_btf = meta.btf;
11916 insn_aux = &env->insn_aux_data[insn_idx];
11918 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11920 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11921 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11925 sleepable = is_kfunc_sleepable(&meta);
11926 if (sleepable && !env->prog->aux->sleepable) {
11927 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11931 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11932 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11934 if (env->cur_state->active_rcu_lock) {
11935 struct bpf_func_state *state;
11936 struct bpf_reg_state *reg;
11937 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
11939 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11940 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11945 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11947 } else if (rcu_unlock) {
11948 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
11949 if (reg->type & MEM_RCU) {
11950 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11951 reg->type |= PTR_UNTRUSTED;
11954 env->cur_state->active_rcu_lock = false;
11955 } else if (sleepable) {
11956 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11959 } else if (rcu_lock) {
11960 env->cur_state->active_rcu_lock = true;
11961 } else if (rcu_unlock) {
11962 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11966 /* Check the arguments */
11967 err = check_kfunc_args(env, &meta, insn_idx);
11970 /* In case of release function, we get register number of refcounted
11971 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11973 if (meta.release_regno) {
11974 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11976 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11977 func_name, meta.func_id);
11982 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11983 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11984 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11985 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11986 insn_aux->insert_off = regs[BPF_REG_2].off;
11987 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11988 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11990 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11991 func_name, meta.func_id);
11995 err = release_reference(env, release_ref_obj_id);
11997 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11998 func_name, meta.func_id);
12003 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12004 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
12005 set_rbtree_add_callback_state);
12007 verbose(env, "kfunc %s#%d failed callback verification\n",
12008 func_name, meta.func_id);
12013 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12014 if (!bpf_jit_supports_exceptions()) {
12015 verbose(env, "JIT does not support calling kfunc %s#%d\n",
12016 func_name, meta.func_id);
12019 env->seen_exception = true;
12021 /* In the case of the default callback, the cookie value passed
12022 * to bpf_throw becomes the return value of the program.
12024 if (!env->exception_callback_subprog) {
12025 err = check_return_code(env, BPF_REG_1);
12031 for (i = 0; i < CALLER_SAVED_REGS; i++)
12032 mark_reg_not_init(env, regs, caller_saved[i]);
12034 /* Check return type */
12035 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12037 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12038 /* Only exception is bpf_obj_new_impl */
12039 if (meta.btf != btf_vmlinux ||
12040 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12041 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12042 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12043 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12048 if (btf_type_is_scalar(t)) {
12049 mark_reg_unknown(env, regs, BPF_REG_0);
12050 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12051 } else if (btf_type_is_ptr(t)) {
12052 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12054 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12055 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12056 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12057 struct btf_struct_meta *struct_meta;
12058 struct btf *ret_btf;
12061 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12064 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && !bpf_global_percpu_ma_set)
12067 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12068 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12072 ret_btf = env->prog->aux->btf;
12073 ret_btf_id = meta.arg_constant.value;
12075 /* This may be NULL due to user not supplying a BTF */
12077 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12081 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12082 if (!ret_t || !__btf_type_is_struct(ret_t)) {
12083 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12087 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12088 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12089 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12090 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12095 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12100 mark_reg_known_zero(env, regs, BPF_REG_0);
12101 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12102 regs[BPF_REG_0].btf = ret_btf;
12103 regs[BPF_REG_0].btf_id = ret_btf_id;
12104 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12105 regs[BPF_REG_0].type |= MEM_PERCPU;
12107 insn_aux->obj_new_size = ret_t->size;
12108 insn_aux->kptr_struct_meta = struct_meta;
12109 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12110 mark_reg_known_zero(env, regs, BPF_REG_0);
12111 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12112 regs[BPF_REG_0].btf = meta.arg_btf;
12113 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12115 insn_aux->kptr_struct_meta =
12116 btf_find_struct_meta(meta.arg_btf,
12118 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12119 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12120 struct btf_field *field = meta.arg_list_head.field;
12122 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12123 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12124 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12125 struct btf_field *field = meta.arg_rbtree_root.field;
12127 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12128 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12129 mark_reg_known_zero(env, regs, BPF_REG_0);
12130 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12131 regs[BPF_REG_0].btf = desc_btf;
12132 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12133 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12134 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12135 if (!ret_t || !btf_type_is_struct(ret_t)) {
12137 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12141 mark_reg_known_zero(env, regs, BPF_REG_0);
12142 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12143 regs[BPF_REG_0].btf = desc_btf;
12144 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12145 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12146 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12147 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12149 mark_reg_known_zero(env, regs, BPF_REG_0);
12151 if (!meta.arg_constant.found) {
12152 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12156 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12158 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12159 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12161 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12162 regs[BPF_REG_0].type |= MEM_RDONLY;
12164 /* this will set env->seen_direct_write to true */
12165 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12166 verbose(env, "the prog does not allow writes to packet data\n");
12171 if (!meta.initialized_dynptr.id) {
12172 verbose(env, "verifier internal error: no dynptr id\n");
12175 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12177 /* we don't need to set BPF_REG_0's ref obj id
12178 * because packet slices are not refcounted (see
12179 * dynptr_type_refcounted)
12182 verbose(env, "kernel function %s unhandled dynamic return type\n",
12186 } else if (!__btf_type_is_struct(ptr_type)) {
12187 if (!meta.r0_size) {
12190 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12192 meta.r0_rdonly = true;
12195 if (!meta.r0_size) {
12196 ptr_type_name = btf_name_by_offset(desc_btf,
12197 ptr_type->name_off);
12199 "kernel function %s returns pointer type %s %s is not supported\n",
12201 btf_type_str(ptr_type),
12206 mark_reg_known_zero(env, regs, BPF_REG_0);
12207 regs[BPF_REG_0].type = PTR_TO_MEM;
12208 regs[BPF_REG_0].mem_size = meta.r0_size;
12210 if (meta.r0_rdonly)
12211 regs[BPF_REG_0].type |= MEM_RDONLY;
12213 /* Ensures we don't access the memory after a release_reference() */
12214 if (meta.ref_obj_id)
12215 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12217 mark_reg_known_zero(env, regs, BPF_REG_0);
12218 regs[BPF_REG_0].btf = desc_btf;
12219 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12220 regs[BPF_REG_0].btf_id = ptr_type_id;
12223 if (is_kfunc_ret_null(&meta)) {
12224 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12225 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12226 regs[BPF_REG_0].id = ++env->id_gen;
12228 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12229 if (is_kfunc_acquire(&meta)) {
12230 int id = acquire_reference_state(env, insn_idx);
12234 if (is_kfunc_ret_null(&meta))
12235 regs[BPF_REG_0].id = id;
12236 regs[BPF_REG_0].ref_obj_id = id;
12237 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12238 ref_set_non_owning(env, ®s[BPF_REG_0]);
12241 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
12242 regs[BPF_REG_0].id = ++env->id_gen;
12243 } else if (btf_type_is_void(t)) {
12244 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12245 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12246 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12247 insn_aux->kptr_struct_meta =
12248 btf_find_struct_meta(meta.arg_btf,
12254 nargs = btf_type_vlen(meta.func_proto);
12255 args = (const struct btf_param *)(meta.func_proto + 1);
12256 for (i = 0; i < nargs; i++) {
12259 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12260 if (btf_type_is_ptr(t))
12261 mark_btf_func_reg_size(env, regno, sizeof(void *));
12263 /* scalar. ensured by btf_check_kfunc_arg_match() */
12264 mark_btf_func_reg_size(env, regno, t->size);
12267 if (is_iter_next_kfunc(&meta)) {
12268 err = process_iter_next_call(env, insn_idx, &meta);
12276 static bool signed_add_overflows(s64 a, s64 b)
12278 /* Do the add in u64, where overflow is well-defined */
12279 s64 res = (s64)((u64)a + (u64)b);
12286 static bool signed_add32_overflows(s32 a, s32 b)
12288 /* Do the add in u32, where overflow is well-defined */
12289 s32 res = (s32)((u32)a + (u32)b);
12296 static bool signed_sub_overflows(s64 a, s64 b)
12298 /* Do the sub in u64, where overflow is well-defined */
12299 s64 res = (s64)((u64)a - (u64)b);
12306 static bool signed_sub32_overflows(s32 a, s32 b)
12308 /* Do the sub in u32, where overflow is well-defined */
12309 s32 res = (s32)((u32)a - (u32)b);
12316 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12317 const struct bpf_reg_state *reg,
12318 enum bpf_reg_type type)
12320 bool known = tnum_is_const(reg->var_off);
12321 s64 val = reg->var_off.value;
12322 s64 smin = reg->smin_value;
12324 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12325 verbose(env, "math between %s pointer and %lld is not allowed\n",
12326 reg_type_str(env, type), val);
12330 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12331 verbose(env, "%s pointer offset %d is not allowed\n",
12332 reg_type_str(env, type), reg->off);
12336 if (smin == S64_MIN) {
12337 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12338 reg_type_str(env, type));
12342 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12343 verbose(env, "value %lld makes %s pointer be out of bounds\n",
12344 smin, reg_type_str(env, type));
12352 REASON_BOUNDS = -1,
12359 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12360 u32 *alu_limit, bool mask_to_left)
12362 u32 max = 0, ptr_limit = 0;
12364 switch (ptr_reg->type) {
12366 /* Offset 0 is out-of-bounds, but acceptable start for the
12367 * left direction, see BPF_REG_FP. Also, unknown scalar
12368 * offset where we would need to deal with min/max bounds is
12369 * currently prohibited for unprivileged.
12371 max = MAX_BPF_STACK + mask_to_left;
12372 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12374 case PTR_TO_MAP_VALUE:
12375 max = ptr_reg->map_ptr->value_size;
12376 ptr_limit = (mask_to_left ?
12377 ptr_reg->smin_value :
12378 ptr_reg->umax_value) + ptr_reg->off;
12381 return REASON_TYPE;
12384 if (ptr_limit >= max)
12385 return REASON_LIMIT;
12386 *alu_limit = ptr_limit;
12390 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12391 const struct bpf_insn *insn)
12393 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12396 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12397 u32 alu_state, u32 alu_limit)
12399 /* If we arrived here from different branches with different
12400 * state or limits to sanitize, then this won't work.
12402 if (aux->alu_state &&
12403 (aux->alu_state != alu_state ||
12404 aux->alu_limit != alu_limit))
12405 return REASON_PATHS;
12407 /* Corresponding fixup done in do_misc_fixups(). */
12408 aux->alu_state = alu_state;
12409 aux->alu_limit = alu_limit;
12413 static int sanitize_val_alu(struct bpf_verifier_env *env,
12414 struct bpf_insn *insn)
12416 struct bpf_insn_aux_data *aux = cur_aux(env);
12418 if (can_skip_alu_sanitation(env, insn))
12421 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12424 static bool sanitize_needed(u8 opcode)
12426 return opcode == BPF_ADD || opcode == BPF_SUB;
12429 struct bpf_sanitize_info {
12430 struct bpf_insn_aux_data aux;
12434 static struct bpf_verifier_state *
12435 sanitize_speculative_path(struct bpf_verifier_env *env,
12436 const struct bpf_insn *insn,
12437 u32 next_idx, u32 curr_idx)
12439 struct bpf_verifier_state *branch;
12440 struct bpf_reg_state *regs;
12442 branch = push_stack(env, next_idx, curr_idx, true);
12443 if (branch && insn) {
12444 regs = branch->frame[branch->curframe]->regs;
12445 if (BPF_SRC(insn->code) == BPF_K) {
12446 mark_reg_unknown(env, regs, insn->dst_reg);
12447 } else if (BPF_SRC(insn->code) == BPF_X) {
12448 mark_reg_unknown(env, regs, insn->dst_reg);
12449 mark_reg_unknown(env, regs, insn->src_reg);
12455 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12456 struct bpf_insn *insn,
12457 const struct bpf_reg_state *ptr_reg,
12458 const struct bpf_reg_state *off_reg,
12459 struct bpf_reg_state *dst_reg,
12460 struct bpf_sanitize_info *info,
12461 const bool commit_window)
12463 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12464 struct bpf_verifier_state *vstate = env->cur_state;
12465 bool off_is_imm = tnum_is_const(off_reg->var_off);
12466 bool off_is_neg = off_reg->smin_value < 0;
12467 bool ptr_is_dst_reg = ptr_reg == dst_reg;
12468 u8 opcode = BPF_OP(insn->code);
12469 u32 alu_state, alu_limit;
12470 struct bpf_reg_state tmp;
12474 if (can_skip_alu_sanitation(env, insn))
12477 /* We already marked aux for masking from non-speculative
12478 * paths, thus we got here in the first place. We only care
12479 * to explore bad access from here.
12481 if (vstate->speculative)
12484 if (!commit_window) {
12485 if (!tnum_is_const(off_reg->var_off) &&
12486 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12487 return REASON_BOUNDS;
12489 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
12490 (opcode == BPF_SUB && !off_is_neg);
12493 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12497 if (commit_window) {
12498 /* In commit phase we narrow the masking window based on
12499 * the observed pointer move after the simulated operation.
12501 alu_state = info->aux.alu_state;
12502 alu_limit = abs(info->aux.alu_limit - alu_limit);
12504 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12505 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12506 alu_state |= ptr_is_dst_reg ?
12507 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12509 /* Limit pruning on unknown scalars to enable deep search for
12510 * potential masking differences from other program paths.
12513 env->explore_alu_limits = true;
12516 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12520 /* If we're in commit phase, we're done here given we already
12521 * pushed the truncated dst_reg into the speculative verification
12524 * Also, when register is a known constant, we rewrite register-based
12525 * operation to immediate-based, and thus do not need masking (and as
12526 * a consequence, do not need to simulate the zero-truncation either).
12528 if (commit_window || off_is_imm)
12531 /* Simulate and find potential out-of-bounds access under
12532 * speculative execution from truncation as a result of
12533 * masking when off was not within expected range. If off
12534 * sits in dst, then we temporarily need to move ptr there
12535 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12536 * for cases where we use K-based arithmetic in one direction
12537 * and truncated reg-based in the other in order to explore
12540 if (!ptr_is_dst_reg) {
12542 copy_register_state(dst_reg, ptr_reg);
12544 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12546 if (!ptr_is_dst_reg && ret)
12548 return !ret ? REASON_STACK : 0;
12551 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12553 struct bpf_verifier_state *vstate = env->cur_state;
12555 /* If we simulate paths under speculation, we don't update the
12556 * insn as 'seen' such that when we verify unreachable paths in
12557 * the non-speculative domain, sanitize_dead_code() can still
12558 * rewrite/sanitize them.
12560 if (!vstate->speculative)
12561 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12564 static int sanitize_err(struct bpf_verifier_env *env,
12565 const struct bpf_insn *insn, int reason,
12566 const struct bpf_reg_state *off_reg,
12567 const struct bpf_reg_state *dst_reg)
12569 static const char *err = "pointer arithmetic with it prohibited for !root";
12570 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12571 u32 dst = insn->dst_reg, src = insn->src_reg;
12574 case REASON_BOUNDS:
12575 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12576 off_reg == dst_reg ? dst : src, err);
12579 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12580 off_reg == dst_reg ? src : dst, err);
12583 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12587 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12591 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12595 verbose(env, "verifier internal error: unknown reason (%d)\n",
12603 /* check that stack access falls within stack limits and that 'reg' doesn't
12604 * have a variable offset.
12606 * Variable offset is prohibited for unprivileged mode for simplicity since it
12607 * requires corresponding support in Spectre masking for stack ALU. See also
12608 * retrieve_ptr_limit().
12611 * 'off' includes 'reg->off'.
12613 static int check_stack_access_for_ptr_arithmetic(
12614 struct bpf_verifier_env *env,
12616 const struct bpf_reg_state *reg,
12619 if (!tnum_is_const(reg->var_off)) {
12622 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12623 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12624 regno, tn_buf, off);
12628 if (off >= 0 || off < -MAX_BPF_STACK) {
12629 verbose(env, "R%d stack pointer arithmetic goes out of range, "
12630 "prohibited for !root; off=%d\n", regno, off);
12637 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12638 const struct bpf_insn *insn,
12639 const struct bpf_reg_state *dst_reg)
12641 u32 dst = insn->dst_reg;
12643 /* For unprivileged we require that resulting offset must be in bounds
12644 * in order to be able to sanitize access later on.
12646 if (env->bypass_spec_v1)
12649 switch (dst_reg->type) {
12651 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12652 dst_reg->off + dst_reg->var_off.value))
12655 case PTR_TO_MAP_VALUE:
12656 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12657 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12658 "prohibited for !root\n", dst);
12669 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12670 * Caller should also handle BPF_MOV case separately.
12671 * If we return -EACCES, caller may want to try again treating pointer as a
12672 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
12674 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12675 struct bpf_insn *insn,
12676 const struct bpf_reg_state *ptr_reg,
12677 const struct bpf_reg_state *off_reg)
12679 struct bpf_verifier_state *vstate = env->cur_state;
12680 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12681 struct bpf_reg_state *regs = state->regs, *dst_reg;
12682 bool known = tnum_is_const(off_reg->var_off);
12683 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12684 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12685 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12686 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12687 struct bpf_sanitize_info info = {};
12688 u8 opcode = BPF_OP(insn->code);
12689 u32 dst = insn->dst_reg;
12692 dst_reg = ®s[dst];
12694 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12695 smin_val > smax_val || umin_val > umax_val) {
12696 /* Taint dst register if offset had invalid bounds derived from
12697 * e.g. dead branches.
12699 __mark_reg_unknown(env, dst_reg);
12703 if (BPF_CLASS(insn->code) != BPF_ALU64) {
12704 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12705 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12706 __mark_reg_unknown(env, dst_reg);
12711 "R%d 32-bit pointer arithmetic prohibited\n",
12716 if (ptr_reg->type & PTR_MAYBE_NULL) {
12717 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12718 dst, reg_type_str(env, ptr_reg->type));
12722 switch (base_type(ptr_reg->type)) {
12723 case CONST_PTR_TO_MAP:
12724 /* smin_val represents the known value */
12725 if (known && smin_val == 0 && opcode == BPF_ADD)
12728 case PTR_TO_PACKET_END:
12729 case PTR_TO_SOCKET:
12730 case PTR_TO_SOCK_COMMON:
12731 case PTR_TO_TCP_SOCK:
12732 case PTR_TO_XDP_SOCK:
12733 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12734 dst, reg_type_str(env, ptr_reg->type));
12740 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12741 * The id may be overwritten later if we create a new variable offset.
12743 dst_reg->type = ptr_reg->type;
12744 dst_reg->id = ptr_reg->id;
12746 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12747 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12750 /* pointer types do not carry 32-bit bounds at the moment. */
12751 __mark_reg32_unbounded(dst_reg);
12753 if (sanitize_needed(opcode)) {
12754 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12757 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12762 /* We can take a fixed offset as long as it doesn't overflow
12763 * the s32 'off' field
12765 if (known && (ptr_reg->off + smin_val ==
12766 (s64)(s32)(ptr_reg->off + smin_val))) {
12767 /* pointer += K. Accumulate it into fixed offset */
12768 dst_reg->smin_value = smin_ptr;
12769 dst_reg->smax_value = smax_ptr;
12770 dst_reg->umin_value = umin_ptr;
12771 dst_reg->umax_value = umax_ptr;
12772 dst_reg->var_off = ptr_reg->var_off;
12773 dst_reg->off = ptr_reg->off + smin_val;
12774 dst_reg->raw = ptr_reg->raw;
12777 /* A new variable offset is created. Note that off_reg->off
12778 * == 0, since it's a scalar.
12779 * dst_reg gets the pointer type and since some positive
12780 * integer value was added to the pointer, give it a new 'id'
12781 * if it's a PTR_TO_PACKET.
12782 * this creates a new 'base' pointer, off_reg (variable) gets
12783 * added into the variable offset, and we copy the fixed offset
12786 if (signed_add_overflows(smin_ptr, smin_val) ||
12787 signed_add_overflows(smax_ptr, smax_val)) {
12788 dst_reg->smin_value = S64_MIN;
12789 dst_reg->smax_value = S64_MAX;
12791 dst_reg->smin_value = smin_ptr + smin_val;
12792 dst_reg->smax_value = smax_ptr + smax_val;
12794 if (umin_ptr + umin_val < umin_ptr ||
12795 umax_ptr + umax_val < umax_ptr) {
12796 dst_reg->umin_value = 0;
12797 dst_reg->umax_value = U64_MAX;
12799 dst_reg->umin_value = umin_ptr + umin_val;
12800 dst_reg->umax_value = umax_ptr + umax_val;
12802 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12803 dst_reg->off = ptr_reg->off;
12804 dst_reg->raw = ptr_reg->raw;
12805 if (reg_is_pkt_pointer(ptr_reg)) {
12806 dst_reg->id = ++env->id_gen;
12807 /* something was added to pkt_ptr, set range to zero */
12808 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12812 if (dst_reg == off_reg) {
12813 /* scalar -= pointer. Creates an unknown scalar */
12814 verbose(env, "R%d tried to subtract pointer from scalar\n",
12818 /* We don't allow subtraction from FP, because (according to
12819 * test_verifier.c test "invalid fp arithmetic", JITs might not
12820 * be able to deal with it.
12822 if (ptr_reg->type == PTR_TO_STACK) {
12823 verbose(env, "R%d subtraction from stack pointer prohibited\n",
12827 if (known && (ptr_reg->off - smin_val ==
12828 (s64)(s32)(ptr_reg->off - smin_val))) {
12829 /* pointer -= K. Subtract it from fixed offset */
12830 dst_reg->smin_value = smin_ptr;
12831 dst_reg->smax_value = smax_ptr;
12832 dst_reg->umin_value = umin_ptr;
12833 dst_reg->umax_value = umax_ptr;
12834 dst_reg->var_off = ptr_reg->var_off;
12835 dst_reg->id = ptr_reg->id;
12836 dst_reg->off = ptr_reg->off - smin_val;
12837 dst_reg->raw = ptr_reg->raw;
12840 /* A new variable offset is created. If the subtrahend is known
12841 * nonnegative, then any reg->range we had before is still good.
12843 if (signed_sub_overflows(smin_ptr, smax_val) ||
12844 signed_sub_overflows(smax_ptr, smin_val)) {
12845 /* Overflow possible, we know nothing */
12846 dst_reg->smin_value = S64_MIN;
12847 dst_reg->smax_value = S64_MAX;
12849 dst_reg->smin_value = smin_ptr - smax_val;
12850 dst_reg->smax_value = smax_ptr - smin_val;
12852 if (umin_ptr < umax_val) {
12853 /* Overflow possible, we know nothing */
12854 dst_reg->umin_value = 0;
12855 dst_reg->umax_value = U64_MAX;
12857 /* Cannot overflow (as long as bounds are consistent) */
12858 dst_reg->umin_value = umin_ptr - umax_val;
12859 dst_reg->umax_value = umax_ptr - umin_val;
12861 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12862 dst_reg->off = ptr_reg->off;
12863 dst_reg->raw = ptr_reg->raw;
12864 if (reg_is_pkt_pointer(ptr_reg)) {
12865 dst_reg->id = ++env->id_gen;
12866 /* something was added to pkt_ptr, set range to zero */
12868 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12874 /* bitwise ops on pointers are troublesome, prohibit. */
12875 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12876 dst, bpf_alu_string[opcode >> 4]);
12879 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12880 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12881 dst, bpf_alu_string[opcode >> 4]);
12885 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12887 reg_bounds_sync(dst_reg);
12888 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12890 if (sanitize_needed(opcode)) {
12891 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12894 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12900 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12901 struct bpf_reg_state *src_reg)
12903 s32 smin_val = src_reg->s32_min_value;
12904 s32 smax_val = src_reg->s32_max_value;
12905 u32 umin_val = src_reg->u32_min_value;
12906 u32 umax_val = src_reg->u32_max_value;
12908 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12909 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12910 dst_reg->s32_min_value = S32_MIN;
12911 dst_reg->s32_max_value = S32_MAX;
12913 dst_reg->s32_min_value += smin_val;
12914 dst_reg->s32_max_value += smax_val;
12916 if (dst_reg->u32_min_value + umin_val < umin_val ||
12917 dst_reg->u32_max_value + umax_val < umax_val) {
12918 dst_reg->u32_min_value = 0;
12919 dst_reg->u32_max_value = U32_MAX;
12921 dst_reg->u32_min_value += umin_val;
12922 dst_reg->u32_max_value += umax_val;
12926 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12927 struct bpf_reg_state *src_reg)
12929 s64 smin_val = src_reg->smin_value;
12930 s64 smax_val = src_reg->smax_value;
12931 u64 umin_val = src_reg->umin_value;
12932 u64 umax_val = src_reg->umax_value;
12934 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12935 signed_add_overflows(dst_reg->smax_value, smax_val)) {
12936 dst_reg->smin_value = S64_MIN;
12937 dst_reg->smax_value = S64_MAX;
12939 dst_reg->smin_value += smin_val;
12940 dst_reg->smax_value += smax_val;
12942 if (dst_reg->umin_value + umin_val < umin_val ||
12943 dst_reg->umax_value + umax_val < umax_val) {
12944 dst_reg->umin_value = 0;
12945 dst_reg->umax_value = U64_MAX;
12947 dst_reg->umin_value += umin_val;
12948 dst_reg->umax_value += umax_val;
12952 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12953 struct bpf_reg_state *src_reg)
12955 s32 smin_val = src_reg->s32_min_value;
12956 s32 smax_val = src_reg->s32_max_value;
12957 u32 umin_val = src_reg->u32_min_value;
12958 u32 umax_val = src_reg->u32_max_value;
12960 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12961 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12962 /* Overflow possible, we know nothing */
12963 dst_reg->s32_min_value = S32_MIN;
12964 dst_reg->s32_max_value = S32_MAX;
12966 dst_reg->s32_min_value -= smax_val;
12967 dst_reg->s32_max_value -= smin_val;
12969 if (dst_reg->u32_min_value < umax_val) {
12970 /* Overflow possible, we know nothing */
12971 dst_reg->u32_min_value = 0;
12972 dst_reg->u32_max_value = U32_MAX;
12974 /* Cannot overflow (as long as bounds are consistent) */
12975 dst_reg->u32_min_value -= umax_val;
12976 dst_reg->u32_max_value -= umin_val;
12980 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12981 struct bpf_reg_state *src_reg)
12983 s64 smin_val = src_reg->smin_value;
12984 s64 smax_val = src_reg->smax_value;
12985 u64 umin_val = src_reg->umin_value;
12986 u64 umax_val = src_reg->umax_value;
12988 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12989 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12990 /* Overflow possible, we know nothing */
12991 dst_reg->smin_value = S64_MIN;
12992 dst_reg->smax_value = S64_MAX;
12994 dst_reg->smin_value -= smax_val;
12995 dst_reg->smax_value -= smin_val;
12997 if (dst_reg->umin_value < umax_val) {
12998 /* Overflow possible, we know nothing */
12999 dst_reg->umin_value = 0;
13000 dst_reg->umax_value = U64_MAX;
13002 /* Cannot overflow (as long as bounds are consistent) */
13003 dst_reg->umin_value -= umax_val;
13004 dst_reg->umax_value -= umin_val;
13008 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13009 struct bpf_reg_state *src_reg)
13011 s32 smin_val = src_reg->s32_min_value;
13012 u32 umin_val = src_reg->u32_min_value;
13013 u32 umax_val = src_reg->u32_max_value;
13015 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13016 /* Ain't nobody got time to multiply that sign */
13017 __mark_reg32_unbounded(dst_reg);
13020 /* Both values are positive, so we can work with unsigned and
13021 * copy the result to signed (unless it exceeds S32_MAX).
13023 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13024 /* Potential overflow, we know nothing */
13025 __mark_reg32_unbounded(dst_reg);
13028 dst_reg->u32_min_value *= umin_val;
13029 dst_reg->u32_max_value *= umax_val;
13030 if (dst_reg->u32_max_value > S32_MAX) {
13031 /* Overflow possible, we know nothing */
13032 dst_reg->s32_min_value = S32_MIN;
13033 dst_reg->s32_max_value = S32_MAX;
13035 dst_reg->s32_min_value = dst_reg->u32_min_value;
13036 dst_reg->s32_max_value = dst_reg->u32_max_value;
13040 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13041 struct bpf_reg_state *src_reg)
13043 s64 smin_val = src_reg->smin_value;
13044 u64 umin_val = src_reg->umin_value;
13045 u64 umax_val = src_reg->umax_value;
13047 if (smin_val < 0 || dst_reg->smin_value < 0) {
13048 /* Ain't nobody got time to multiply that sign */
13049 __mark_reg64_unbounded(dst_reg);
13052 /* Both values are positive, so we can work with unsigned and
13053 * copy the result to signed (unless it exceeds S64_MAX).
13055 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13056 /* Potential overflow, we know nothing */
13057 __mark_reg64_unbounded(dst_reg);
13060 dst_reg->umin_value *= umin_val;
13061 dst_reg->umax_value *= umax_val;
13062 if (dst_reg->umax_value > S64_MAX) {
13063 /* Overflow possible, we know nothing */
13064 dst_reg->smin_value = S64_MIN;
13065 dst_reg->smax_value = S64_MAX;
13067 dst_reg->smin_value = dst_reg->umin_value;
13068 dst_reg->smax_value = dst_reg->umax_value;
13072 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13073 struct bpf_reg_state *src_reg)
13075 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13076 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13077 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13078 s32 smin_val = src_reg->s32_min_value;
13079 u32 umax_val = src_reg->u32_max_value;
13081 if (src_known && dst_known) {
13082 __mark_reg32_known(dst_reg, var32_off.value);
13086 /* We get our minimum from the var_off, since that's inherently
13087 * bitwise. Our maximum is the minimum of the operands' maxima.
13089 dst_reg->u32_min_value = var32_off.value;
13090 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13091 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13092 /* Lose signed bounds when ANDing negative numbers,
13093 * ain't nobody got time for that.
13095 dst_reg->s32_min_value = S32_MIN;
13096 dst_reg->s32_max_value = S32_MAX;
13098 /* ANDing two positives gives a positive, so safe to
13099 * cast result into s64.
13101 dst_reg->s32_min_value = dst_reg->u32_min_value;
13102 dst_reg->s32_max_value = dst_reg->u32_max_value;
13106 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13107 struct bpf_reg_state *src_reg)
13109 bool src_known = tnum_is_const(src_reg->var_off);
13110 bool dst_known = tnum_is_const(dst_reg->var_off);
13111 s64 smin_val = src_reg->smin_value;
13112 u64 umax_val = src_reg->umax_value;
13114 if (src_known && dst_known) {
13115 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13119 /* We get our minimum from the var_off, since that's inherently
13120 * bitwise. Our maximum is the minimum of the operands' maxima.
13122 dst_reg->umin_value = dst_reg->var_off.value;
13123 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13124 if (dst_reg->smin_value < 0 || smin_val < 0) {
13125 /* Lose signed bounds when ANDing negative numbers,
13126 * ain't nobody got time for that.
13128 dst_reg->smin_value = S64_MIN;
13129 dst_reg->smax_value = S64_MAX;
13131 /* ANDing two positives gives a positive, so safe to
13132 * cast result into s64.
13134 dst_reg->smin_value = dst_reg->umin_value;
13135 dst_reg->smax_value = dst_reg->umax_value;
13137 /* We may learn something more from the var_off */
13138 __update_reg_bounds(dst_reg);
13141 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13142 struct bpf_reg_state *src_reg)
13144 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13145 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13146 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13147 s32 smin_val = src_reg->s32_min_value;
13148 u32 umin_val = src_reg->u32_min_value;
13150 if (src_known && dst_known) {
13151 __mark_reg32_known(dst_reg, var32_off.value);
13155 /* We get our maximum from the var_off, and our minimum is the
13156 * maximum of the operands' minima
13158 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13159 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13160 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13161 /* Lose signed bounds when ORing negative numbers,
13162 * ain't nobody got time for that.
13164 dst_reg->s32_min_value = S32_MIN;
13165 dst_reg->s32_max_value = S32_MAX;
13167 /* ORing two positives gives a positive, so safe to
13168 * cast result into s64.
13170 dst_reg->s32_min_value = dst_reg->u32_min_value;
13171 dst_reg->s32_max_value = dst_reg->u32_max_value;
13175 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13176 struct bpf_reg_state *src_reg)
13178 bool src_known = tnum_is_const(src_reg->var_off);
13179 bool dst_known = tnum_is_const(dst_reg->var_off);
13180 s64 smin_val = src_reg->smin_value;
13181 u64 umin_val = src_reg->umin_value;
13183 if (src_known && dst_known) {
13184 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13188 /* We get our maximum from the var_off, and our minimum is the
13189 * maximum of the operands' minima
13191 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13192 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13193 if (dst_reg->smin_value < 0 || smin_val < 0) {
13194 /* Lose signed bounds when ORing negative numbers,
13195 * ain't nobody got time for that.
13197 dst_reg->smin_value = S64_MIN;
13198 dst_reg->smax_value = S64_MAX;
13200 /* ORing two positives gives a positive, so safe to
13201 * cast result into s64.
13203 dst_reg->smin_value = dst_reg->umin_value;
13204 dst_reg->smax_value = dst_reg->umax_value;
13206 /* We may learn something more from the var_off */
13207 __update_reg_bounds(dst_reg);
13210 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13211 struct bpf_reg_state *src_reg)
13213 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13214 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13215 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13216 s32 smin_val = src_reg->s32_min_value;
13218 if (src_known && dst_known) {
13219 __mark_reg32_known(dst_reg, var32_off.value);
13223 /* We get both minimum and maximum from the var32_off. */
13224 dst_reg->u32_min_value = var32_off.value;
13225 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13227 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13228 /* XORing two positive sign numbers gives a positive,
13229 * so safe to cast u32 result into s32.
13231 dst_reg->s32_min_value = dst_reg->u32_min_value;
13232 dst_reg->s32_max_value = dst_reg->u32_max_value;
13234 dst_reg->s32_min_value = S32_MIN;
13235 dst_reg->s32_max_value = S32_MAX;
13239 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13240 struct bpf_reg_state *src_reg)
13242 bool src_known = tnum_is_const(src_reg->var_off);
13243 bool dst_known = tnum_is_const(dst_reg->var_off);
13244 s64 smin_val = src_reg->smin_value;
13246 if (src_known && dst_known) {
13247 /* dst_reg->var_off.value has been updated earlier */
13248 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13252 /* We get both minimum and maximum from the var_off. */
13253 dst_reg->umin_value = dst_reg->var_off.value;
13254 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13256 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13257 /* XORing two positive sign numbers gives a positive,
13258 * so safe to cast u64 result into s64.
13260 dst_reg->smin_value = dst_reg->umin_value;
13261 dst_reg->smax_value = dst_reg->umax_value;
13263 dst_reg->smin_value = S64_MIN;
13264 dst_reg->smax_value = S64_MAX;
13267 __update_reg_bounds(dst_reg);
13270 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13271 u64 umin_val, u64 umax_val)
13273 /* We lose all sign bit information (except what we can pick
13276 dst_reg->s32_min_value = S32_MIN;
13277 dst_reg->s32_max_value = S32_MAX;
13278 /* If we might shift our top bit out, then we know nothing */
13279 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13280 dst_reg->u32_min_value = 0;
13281 dst_reg->u32_max_value = U32_MAX;
13283 dst_reg->u32_min_value <<= umin_val;
13284 dst_reg->u32_max_value <<= umax_val;
13288 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13289 struct bpf_reg_state *src_reg)
13291 u32 umax_val = src_reg->u32_max_value;
13292 u32 umin_val = src_reg->u32_min_value;
13293 /* u32 alu operation will zext upper bits */
13294 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13296 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13297 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13298 /* Not required but being careful mark reg64 bounds as unknown so
13299 * that we are forced to pick them up from tnum and zext later and
13300 * if some path skips this step we are still safe.
13302 __mark_reg64_unbounded(dst_reg);
13303 __update_reg32_bounds(dst_reg);
13306 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13307 u64 umin_val, u64 umax_val)
13309 /* Special case <<32 because it is a common compiler pattern to sign
13310 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13311 * positive we know this shift will also be positive so we can track
13312 * bounds correctly. Otherwise we lose all sign bit information except
13313 * what we can pick up from var_off. Perhaps we can generalize this
13314 * later to shifts of any length.
13316 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13317 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13319 dst_reg->smax_value = S64_MAX;
13321 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13322 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13324 dst_reg->smin_value = S64_MIN;
13326 /* If we might shift our top bit out, then we know nothing */
13327 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13328 dst_reg->umin_value = 0;
13329 dst_reg->umax_value = U64_MAX;
13331 dst_reg->umin_value <<= umin_val;
13332 dst_reg->umax_value <<= umax_val;
13336 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13337 struct bpf_reg_state *src_reg)
13339 u64 umax_val = src_reg->umax_value;
13340 u64 umin_val = src_reg->umin_value;
13342 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
13343 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13344 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13346 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13347 /* We may learn something more from the var_off */
13348 __update_reg_bounds(dst_reg);
13351 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13352 struct bpf_reg_state *src_reg)
13354 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13355 u32 umax_val = src_reg->u32_max_value;
13356 u32 umin_val = src_reg->u32_min_value;
13358 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13359 * be negative, then either:
13360 * 1) src_reg might be zero, so the sign bit of the result is
13361 * unknown, so we lose our signed bounds
13362 * 2) it's known negative, thus the unsigned bounds capture the
13364 * 3) the signed bounds cross zero, so they tell us nothing
13366 * If the value in dst_reg is known nonnegative, then again the
13367 * unsigned bounds capture the signed bounds.
13368 * Thus, in all cases it suffices to blow away our signed bounds
13369 * and rely on inferring new ones from the unsigned bounds and
13370 * var_off of the result.
13372 dst_reg->s32_min_value = S32_MIN;
13373 dst_reg->s32_max_value = S32_MAX;
13375 dst_reg->var_off = tnum_rshift(subreg, umin_val);
13376 dst_reg->u32_min_value >>= umax_val;
13377 dst_reg->u32_max_value >>= umin_val;
13379 __mark_reg64_unbounded(dst_reg);
13380 __update_reg32_bounds(dst_reg);
13383 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13384 struct bpf_reg_state *src_reg)
13386 u64 umax_val = src_reg->umax_value;
13387 u64 umin_val = src_reg->umin_value;
13389 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13390 * be negative, then either:
13391 * 1) src_reg might be zero, so the sign bit of the result is
13392 * unknown, so we lose our signed bounds
13393 * 2) it's known negative, thus the unsigned bounds capture the
13395 * 3) the signed bounds cross zero, so they tell us nothing
13397 * If the value in dst_reg is known nonnegative, then again the
13398 * unsigned bounds capture the signed bounds.
13399 * Thus, in all cases it suffices to blow away our signed bounds
13400 * and rely on inferring new ones from the unsigned bounds and
13401 * var_off of the result.
13403 dst_reg->smin_value = S64_MIN;
13404 dst_reg->smax_value = S64_MAX;
13405 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13406 dst_reg->umin_value >>= umax_val;
13407 dst_reg->umax_value >>= umin_val;
13409 /* Its not easy to operate on alu32 bounds here because it depends
13410 * on bits being shifted in. Take easy way out and mark unbounded
13411 * so we can recalculate later from tnum.
13413 __mark_reg32_unbounded(dst_reg);
13414 __update_reg_bounds(dst_reg);
13417 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13418 struct bpf_reg_state *src_reg)
13420 u64 umin_val = src_reg->u32_min_value;
13422 /* Upon reaching here, src_known is true and
13423 * umax_val is equal to umin_val.
13425 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13426 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13428 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13430 /* blow away the dst_reg umin_value/umax_value and rely on
13431 * dst_reg var_off to refine the result.
13433 dst_reg->u32_min_value = 0;
13434 dst_reg->u32_max_value = U32_MAX;
13436 __mark_reg64_unbounded(dst_reg);
13437 __update_reg32_bounds(dst_reg);
13440 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13441 struct bpf_reg_state *src_reg)
13443 u64 umin_val = src_reg->umin_value;
13445 /* Upon reaching here, src_known is true and umax_val is equal
13448 dst_reg->smin_value >>= umin_val;
13449 dst_reg->smax_value >>= umin_val;
13451 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13453 /* blow away the dst_reg umin_value/umax_value and rely on
13454 * dst_reg var_off to refine the result.
13456 dst_reg->umin_value = 0;
13457 dst_reg->umax_value = U64_MAX;
13459 /* Its not easy to operate on alu32 bounds here because it depends
13460 * on bits being shifted in from upper 32-bits. Take easy way out
13461 * and mark unbounded so we can recalculate later from tnum.
13463 __mark_reg32_unbounded(dst_reg);
13464 __update_reg_bounds(dst_reg);
13467 /* WARNING: This function does calculations on 64-bit values, but the actual
13468 * execution may occur on 32-bit values. Therefore, things like bitshifts
13469 * need extra checks in the 32-bit case.
13471 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13472 struct bpf_insn *insn,
13473 struct bpf_reg_state *dst_reg,
13474 struct bpf_reg_state src_reg)
13476 struct bpf_reg_state *regs = cur_regs(env);
13477 u8 opcode = BPF_OP(insn->code);
13479 s64 smin_val, smax_val;
13480 u64 umin_val, umax_val;
13481 s32 s32_min_val, s32_max_val;
13482 u32 u32_min_val, u32_max_val;
13483 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13484 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13487 smin_val = src_reg.smin_value;
13488 smax_val = src_reg.smax_value;
13489 umin_val = src_reg.umin_value;
13490 umax_val = src_reg.umax_value;
13492 s32_min_val = src_reg.s32_min_value;
13493 s32_max_val = src_reg.s32_max_value;
13494 u32_min_val = src_reg.u32_min_value;
13495 u32_max_val = src_reg.u32_max_value;
13498 src_known = tnum_subreg_is_const(src_reg.var_off);
13500 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13501 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13502 /* Taint dst register if offset had invalid bounds
13503 * derived from e.g. dead branches.
13505 __mark_reg_unknown(env, dst_reg);
13509 src_known = tnum_is_const(src_reg.var_off);
13511 (smin_val != smax_val || umin_val != umax_val)) ||
13512 smin_val > smax_val || umin_val > umax_val) {
13513 /* Taint dst register if offset had invalid bounds
13514 * derived from e.g. dead branches.
13516 __mark_reg_unknown(env, dst_reg);
13522 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13523 __mark_reg_unknown(env, dst_reg);
13527 if (sanitize_needed(opcode)) {
13528 ret = sanitize_val_alu(env, insn);
13530 return sanitize_err(env, insn, ret, NULL, NULL);
13533 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13534 * There are two classes of instructions: The first class we track both
13535 * alu32 and alu64 sign/unsigned bounds independently this provides the
13536 * greatest amount of precision when alu operations are mixed with jmp32
13537 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13538 * and BPF_OR. This is possible because these ops have fairly easy to
13539 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13540 * See alu32 verifier tests for examples. The second class of
13541 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13542 * with regards to tracking sign/unsigned bounds because the bits may
13543 * cross subreg boundaries in the alu64 case. When this happens we mark
13544 * the reg unbounded in the subreg bound space and use the resulting
13545 * tnum to calculate an approximation of the sign/unsigned bounds.
13549 scalar32_min_max_add(dst_reg, &src_reg);
13550 scalar_min_max_add(dst_reg, &src_reg);
13551 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13554 scalar32_min_max_sub(dst_reg, &src_reg);
13555 scalar_min_max_sub(dst_reg, &src_reg);
13556 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13559 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13560 scalar32_min_max_mul(dst_reg, &src_reg);
13561 scalar_min_max_mul(dst_reg, &src_reg);
13564 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13565 scalar32_min_max_and(dst_reg, &src_reg);
13566 scalar_min_max_and(dst_reg, &src_reg);
13569 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13570 scalar32_min_max_or(dst_reg, &src_reg);
13571 scalar_min_max_or(dst_reg, &src_reg);
13574 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13575 scalar32_min_max_xor(dst_reg, &src_reg);
13576 scalar_min_max_xor(dst_reg, &src_reg);
13579 if (umax_val >= insn_bitness) {
13580 /* Shifts greater than 31 or 63 are undefined.
13581 * This includes shifts by a negative number.
13583 mark_reg_unknown(env, regs, insn->dst_reg);
13587 scalar32_min_max_lsh(dst_reg, &src_reg);
13589 scalar_min_max_lsh(dst_reg, &src_reg);
13592 if (umax_val >= insn_bitness) {
13593 /* Shifts greater than 31 or 63 are undefined.
13594 * This includes shifts by a negative number.
13596 mark_reg_unknown(env, regs, insn->dst_reg);
13600 scalar32_min_max_rsh(dst_reg, &src_reg);
13602 scalar_min_max_rsh(dst_reg, &src_reg);
13605 if (umax_val >= insn_bitness) {
13606 /* Shifts greater than 31 or 63 are undefined.
13607 * This includes shifts by a negative number.
13609 mark_reg_unknown(env, regs, insn->dst_reg);
13613 scalar32_min_max_arsh(dst_reg, &src_reg);
13615 scalar_min_max_arsh(dst_reg, &src_reg);
13618 mark_reg_unknown(env, regs, insn->dst_reg);
13622 /* ALU32 ops are zero extended into 64bit register */
13624 zext_32_to_64(dst_reg);
13625 reg_bounds_sync(dst_reg);
13629 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13632 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13633 struct bpf_insn *insn)
13635 struct bpf_verifier_state *vstate = env->cur_state;
13636 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13637 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13638 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13639 u8 opcode = BPF_OP(insn->code);
13642 dst_reg = ®s[insn->dst_reg];
13644 if (dst_reg->type != SCALAR_VALUE)
13647 /* Make sure ID is cleared otherwise dst_reg min/max could be
13648 * incorrectly propagated into other registers by find_equal_scalars()
13651 if (BPF_SRC(insn->code) == BPF_X) {
13652 src_reg = ®s[insn->src_reg];
13653 if (src_reg->type != SCALAR_VALUE) {
13654 if (dst_reg->type != SCALAR_VALUE) {
13655 /* Combining two pointers by any ALU op yields
13656 * an arbitrary scalar. Disallow all math except
13657 * pointer subtraction
13659 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13660 mark_reg_unknown(env, regs, insn->dst_reg);
13663 verbose(env, "R%d pointer %s pointer prohibited\n",
13665 bpf_alu_string[opcode >> 4]);
13668 /* scalar += pointer
13669 * This is legal, but we have to reverse our
13670 * src/dest handling in computing the range
13672 err = mark_chain_precision(env, insn->dst_reg);
13675 return adjust_ptr_min_max_vals(env, insn,
13678 } else if (ptr_reg) {
13679 /* pointer += scalar */
13680 err = mark_chain_precision(env, insn->src_reg);
13683 return adjust_ptr_min_max_vals(env, insn,
13685 } else if (dst_reg->precise) {
13686 /* if dst_reg is precise, src_reg should be precise as well */
13687 err = mark_chain_precision(env, insn->src_reg);
13692 /* Pretend the src is a reg with a known value, since we only
13693 * need to be able to read from this state.
13695 off_reg.type = SCALAR_VALUE;
13696 __mark_reg_known(&off_reg, insn->imm);
13697 src_reg = &off_reg;
13698 if (ptr_reg) /* pointer += K */
13699 return adjust_ptr_min_max_vals(env, insn,
13703 /* Got here implies adding two SCALAR_VALUEs */
13704 if (WARN_ON_ONCE(ptr_reg)) {
13705 print_verifier_state(env, state, true);
13706 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13709 if (WARN_ON(!src_reg)) {
13710 print_verifier_state(env, state, true);
13711 verbose(env, "verifier internal error: no src_reg\n");
13714 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13717 /* check validity of 32-bit and 64-bit arithmetic operations */
13718 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13720 struct bpf_reg_state *regs = cur_regs(env);
13721 u8 opcode = BPF_OP(insn->code);
13724 if (opcode == BPF_END || opcode == BPF_NEG) {
13725 if (opcode == BPF_NEG) {
13726 if (BPF_SRC(insn->code) != BPF_K ||
13727 insn->src_reg != BPF_REG_0 ||
13728 insn->off != 0 || insn->imm != 0) {
13729 verbose(env, "BPF_NEG uses reserved fields\n");
13733 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13734 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13735 (BPF_CLASS(insn->code) == BPF_ALU64 &&
13736 BPF_SRC(insn->code) != BPF_TO_LE)) {
13737 verbose(env, "BPF_END uses reserved fields\n");
13742 /* check src operand */
13743 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13747 if (is_pointer_value(env, insn->dst_reg)) {
13748 verbose(env, "R%d pointer arithmetic prohibited\n",
13753 /* check dest operand */
13754 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13758 } else if (opcode == BPF_MOV) {
13760 if (BPF_SRC(insn->code) == BPF_X) {
13761 if (insn->imm != 0) {
13762 verbose(env, "BPF_MOV uses reserved fields\n");
13766 if (BPF_CLASS(insn->code) == BPF_ALU) {
13767 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13768 verbose(env, "BPF_MOV uses reserved fields\n");
13772 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13774 verbose(env, "BPF_MOV uses reserved fields\n");
13779 /* check src operand */
13780 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13784 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13785 verbose(env, "BPF_MOV uses reserved fields\n");
13790 /* check dest operand, mark as required later */
13791 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13795 if (BPF_SRC(insn->code) == BPF_X) {
13796 struct bpf_reg_state *src_reg = regs + insn->src_reg;
13797 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13798 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13799 !tnum_is_const(src_reg->var_off);
13801 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13802 if (insn->off == 0) {
13804 * copy register state to dest reg
13807 /* Assign src and dst registers the same ID
13808 * that will be used by find_equal_scalars()
13809 * to propagate min/max range.
13811 src_reg->id = ++env->id_gen;
13812 copy_register_state(dst_reg, src_reg);
13813 dst_reg->live |= REG_LIVE_WRITTEN;
13814 dst_reg->subreg_def = DEF_NOT_SUBREG;
13816 /* case: R1 = (s8, s16 s32)R2 */
13817 if (is_pointer_value(env, insn->src_reg)) {
13819 "R%d sign-extension part of pointer\n",
13822 } else if (src_reg->type == SCALAR_VALUE) {
13825 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13826 if (no_sext && need_id)
13827 src_reg->id = ++env->id_gen;
13828 copy_register_state(dst_reg, src_reg);
13831 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13832 dst_reg->live |= REG_LIVE_WRITTEN;
13833 dst_reg->subreg_def = DEF_NOT_SUBREG;
13835 mark_reg_unknown(env, regs, insn->dst_reg);
13839 /* R1 = (u32) R2 */
13840 if (is_pointer_value(env, insn->src_reg)) {
13842 "R%d partial copy of pointer\n",
13845 } else if (src_reg->type == SCALAR_VALUE) {
13846 if (insn->off == 0) {
13847 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13849 if (is_src_reg_u32 && need_id)
13850 src_reg->id = ++env->id_gen;
13851 copy_register_state(dst_reg, src_reg);
13852 /* Make sure ID is cleared if src_reg is not in u32
13853 * range otherwise dst_reg min/max could be incorrectly
13854 * propagated into src_reg by find_equal_scalars()
13856 if (!is_src_reg_u32)
13858 dst_reg->live |= REG_LIVE_WRITTEN;
13859 dst_reg->subreg_def = env->insn_idx + 1;
13861 /* case: W1 = (s8, s16)W2 */
13862 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13864 if (no_sext && need_id)
13865 src_reg->id = ++env->id_gen;
13866 copy_register_state(dst_reg, src_reg);
13869 dst_reg->live |= REG_LIVE_WRITTEN;
13870 dst_reg->subreg_def = env->insn_idx + 1;
13871 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13874 mark_reg_unknown(env, regs,
13877 zext_32_to_64(dst_reg);
13878 reg_bounds_sync(dst_reg);
13882 * remember the value we stored into this reg
13884 /* clear any state __mark_reg_known doesn't set */
13885 mark_reg_unknown(env, regs, insn->dst_reg);
13886 regs[insn->dst_reg].type = SCALAR_VALUE;
13887 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13888 __mark_reg_known(regs + insn->dst_reg,
13891 __mark_reg_known(regs + insn->dst_reg,
13896 } else if (opcode > BPF_END) {
13897 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13900 } else { /* all other ALU ops: and, sub, xor, add, ... */
13902 if (BPF_SRC(insn->code) == BPF_X) {
13903 if (insn->imm != 0 || insn->off > 1 ||
13904 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13905 verbose(env, "BPF_ALU uses reserved fields\n");
13908 /* check src1 operand */
13909 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13913 if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13914 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13915 verbose(env, "BPF_ALU uses reserved fields\n");
13920 /* check src2 operand */
13921 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13925 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13926 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13927 verbose(env, "div by zero\n");
13931 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13932 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13933 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13935 if (insn->imm < 0 || insn->imm >= size) {
13936 verbose(env, "invalid shift %d\n", insn->imm);
13941 /* check dest operand */
13942 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13946 return adjust_reg_min_max_vals(env, insn);
13952 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13953 struct bpf_reg_state *dst_reg,
13954 enum bpf_reg_type type,
13955 bool range_right_open)
13957 struct bpf_func_state *state;
13958 struct bpf_reg_state *reg;
13961 if (dst_reg->off < 0 ||
13962 (dst_reg->off == 0 && range_right_open))
13963 /* This doesn't give us any range */
13966 if (dst_reg->umax_value > MAX_PACKET_OFF ||
13967 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13968 /* Risk of overflow. For instance, ptr + (1<<63) may be less
13969 * than pkt_end, but that's because it's also less than pkt.
13973 new_range = dst_reg->off;
13974 if (range_right_open)
13977 /* Examples for register markings:
13979 * pkt_data in dst register:
13983 * if (r2 > pkt_end) goto <handle exception>
13988 * if (r2 < pkt_end) goto <access okay>
13989 * <handle exception>
13992 * r2 == dst_reg, pkt_end == src_reg
13993 * r2=pkt(id=n,off=8,r=0)
13994 * r3=pkt(id=n,off=0,r=0)
13996 * pkt_data in src register:
14000 * if (pkt_end >= r2) goto <access okay>
14001 * <handle exception>
14005 * if (pkt_end <= r2) goto <handle exception>
14009 * pkt_end == dst_reg, r2 == src_reg
14010 * r2=pkt(id=n,off=8,r=0)
14011 * r3=pkt(id=n,off=0,r=0)
14013 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14014 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14015 * and [r3, r3 + 8-1) respectively is safe to access depending on
14019 /* If our ids match, then we must have the same max_value. And we
14020 * don't care about the other reg's fixed offset, since if it's too big
14021 * the range won't allow anything.
14022 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14024 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14025 if (reg->type == type && reg->id == dst_reg->id)
14026 /* keep the maximum range already checked */
14027 reg->range = max(reg->range, new_range);
14031 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
14033 struct tnum subreg = tnum_subreg(reg->var_off);
14034 s32 sval = (s32)val;
14038 if (tnum_is_const(subreg))
14039 return !!tnum_equals_const(subreg, val);
14040 else if (val < reg->u32_min_value || val > reg->u32_max_value)
14042 else if (sval < reg->s32_min_value || sval > reg->s32_max_value)
14046 if (tnum_is_const(subreg))
14047 return !tnum_equals_const(subreg, val);
14048 else if (val < reg->u32_min_value || val > reg->u32_max_value)
14050 else if (sval < reg->s32_min_value || sval > reg->s32_max_value)
14054 if ((~subreg.mask & subreg.value) & val)
14056 if (!((subreg.mask | subreg.value) & val))
14060 if (reg->u32_min_value > val)
14062 else if (reg->u32_max_value <= val)
14066 if (reg->s32_min_value > sval)
14068 else if (reg->s32_max_value <= sval)
14072 if (reg->u32_max_value < val)
14074 else if (reg->u32_min_value >= val)
14078 if (reg->s32_max_value < sval)
14080 else if (reg->s32_min_value >= sval)
14084 if (reg->u32_min_value >= val)
14086 else if (reg->u32_max_value < val)
14090 if (reg->s32_min_value >= sval)
14092 else if (reg->s32_max_value < sval)
14096 if (reg->u32_max_value <= val)
14098 else if (reg->u32_min_value > val)
14102 if (reg->s32_max_value <= sval)
14104 else if (reg->s32_min_value > sval)
14113 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
14115 s64 sval = (s64)val;
14119 if (tnum_is_const(reg->var_off))
14120 return !!tnum_equals_const(reg->var_off, val);
14121 else if (val < reg->umin_value || val > reg->umax_value)
14123 else if (sval < reg->smin_value || sval > reg->smax_value)
14127 if (tnum_is_const(reg->var_off))
14128 return !tnum_equals_const(reg->var_off, val);
14129 else if (val < reg->umin_value || val > reg->umax_value)
14131 else if (sval < reg->smin_value || sval > reg->smax_value)
14135 if ((~reg->var_off.mask & reg->var_off.value) & val)
14137 if (!((reg->var_off.mask | reg->var_off.value) & val))
14141 if (reg->umin_value > val)
14143 else if (reg->umax_value <= val)
14147 if (reg->smin_value > sval)
14149 else if (reg->smax_value <= sval)
14153 if (reg->umax_value < val)
14155 else if (reg->umin_value >= val)
14159 if (reg->smax_value < sval)
14161 else if (reg->smin_value >= sval)
14165 if (reg->umin_value >= val)
14167 else if (reg->umax_value < val)
14171 if (reg->smin_value >= sval)
14173 else if (reg->smax_value < sval)
14177 if (reg->umax_value <= val)
14179 else if (reg->umin_value > val)
14183 if (reg->smax_value <= sval)
14185 else if (reg->smin_value > sval)
14193 /* compute branch direction of the expression "if (reg opcode val) goto target;"
14195 * 1 - branch will be taken and "goto target" will be executed
14196 * 0 - branch will not be taken and fall-through to next insn
14197 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
14200 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
14203 if (__is_pointer_value(false, reg)) {
14204 if (!reg_not_null(reg))
14207 /* If pointer is valid tests against zero will fail so we can
14208 * use this to direct branch taken.
14224 return is_branch32_taken(reg, val, opcode);
14225 return is_branch64_taken(reg, val, opcode);
14228 static int flip_opcode(u32 opcode)
14230 /* How can we transform "a <op> b" into "b <op> a"? */
14231 static const u8 opcode_flip[16] = {
14232 /* these stay the same */
14233 [BPF_JEQ >> 4] = BPF_JEQ,
14234 [BPF_JNE >> 4] = BPF_JNE,
14235 [BPF_JSET >> 4] = BPF_JSET,
14236 /* these swap "lesser" and "greater" (L and G in the opcodes) */
14237 [BPF_JGE >> 4] = BPF_JLE,
14238 [BPF_JGT >> 4] = BPF_JLT,
14239 [BPF_JLE >> 4] = BPF_JGE,
14240 [BPF_JLT >> 4] = BPF_JGT,
14241 [BPF_JSGE >> 4] = BPF_JSLE,
14242 [BPF_JSGT >> 4] = BPF_JSLT,
14243 [BPF_JSLE >> 4] = BPF_JSGE,
14244 [BPF_JSLT >> 4] = BPF_JSGT
14246 return opcode_flip[opcode >> 4];
14249 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14250 struct bpf_reg_state *src_reg,
14253 struct bpf_reg_state *pkt;
14255 if (src_reg->type == PTR_TO_PACKET_END) {
14257 } else if (dst_reg->type == PTR_TO_PACKET_END) {
14259 opcode = flip_opcode(opcode);
14264 if (pkt->range >= 0)
14269 /* pkt <= pkt_end */
14272 /* pkt > pkt_end */
14273 if (pkt->range == BEYOND_PKT_END)
14274 /* pkt has at last one extra byte beyond pkt_end */
14275 return opcode == BPF_JGT;
14278 /* pkt < pkt_end */
14281 /* pkt >= pkt_end */
14282 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14283 return opcode == BPF_JGE;
14289 /* Adjusts the register min/max values in the case that the dst_reg is the
14290 * variable register that we are working on, and src_reg is a constant or we're
14291 * simply doing a BPF_K check.
14292 * In JEQ/JNE cases we also adjust the var_off values.
14294 static void reg_set_min_max(struct bpf_reg_state *true_reg,
14295 struct bpf_reg_state *false_reg,
14296 u64 val, u32 val32,
14297 u8 opcode, bool is_jmp32)
14299 struct tnum false_32off = tnum_subreg(false_reg->var_off);
14300 struct tnum false_64off = false_reg->var_off;
14301 struct tnum true_32off = tnum_subreg(true_reg->var_off);
14302 struct tnum true_64off = true_reg->var_off;
14303 s64 sval = (s64)val;
14304 s32 sval32 = (s32)val32;
14306 /* If the dst_reg is a pointer, we can't learn anything about its
14307 * variable offset from the compare (unless src_reg were a pointer into
14308 * the same object, but we don't bother with that.
14309 * Since false_reg and true_reg have the same type by construction, we
14310 * only need to check one of them for pointerness.
14312 if (__is_pointer_value(false, false_reg))
14316 /* JEQ/JNE comparison doesn't change the register equivalence.
14319 * if (r1 == 42) goto label;
14321 * label: // here both r1 and r2 are known to be 42.
14323 * Hence when marking register as known preserve it's ID.
14327 __mark_reg32_known(true_reg, val32);
14328 true_32off = tnum_subreg(true_reg->var_off);
14330 ___mark_reg_known(true_reg, val);
14331 true_64off = true_reg->var_off;
14336 __mark_reg32_known(false_reg, val32);
14337 false_32off = tnum_subreg(false_reg->var_off);
14339 ___mark_reg_known(false_reg, val);
14340 false_64off = false_reg->var_off;
14345 false_32off = tnum_and(false_32off, tnum_const(~val32));
14346 if (is_power_of_2(val32))
14347 true_32off = tnum_or(true_32off,
14348 tnum_const(val32));
14350 false_64off = tnum_and(false_64off, tnum_const(~val));
14351 if (is_power_of_2(val))
14352 true_64off = tnum_or(true_64off,
14360 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
14361 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14363 false_reg->u32_max_value = min(false_reg->u32_max_value,
14365 true_reg->u32_min_value = max(true_reg->u32_min_value,
14368 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
14369 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14371 false_reg->umax_value = min(false_reg->umax_value, false_umax);
14372 true_reg->umin_value = max(true_reg->umin_value, true_umin);
14380 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
14381 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14383 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14384 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14386 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
14387 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14389 false_reg->smax_value = min(false_reg->smax_value, false_smax);
14390 true_reg->smin_value = max(true_reg->smin_value, true_smin);
14398 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
14399 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14401 false_reg->u32_min_value = max(false_reg->u32_min_value,
14403 true_reg->u32_max_value = min(true_reg->u32_max_value,
14406 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
14407 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14409 false_reg->umin_value = max(false_reg->umin_value, false_umin);
14410 true_reg->umax_value = min(true_reg->umax_value, true_umax);
14418 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
14419 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14421 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14422 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14424 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
14425 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14427 false_reg->smin_value = max(false_reg->smin_value, false_smin);
14428 true_reg->smax_value = min(true_reg->smax_value, true_smax);
14437 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14438 tnum_subreg(false_32off));
14439 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14440 tnum_subreg(true_32off));
14441 __reg_combine_32_into_64(false_reg);
14442 __reg_combine_32_into_64(true_reg);
14444 false_reg->var_off = false_64off;
14445 true_reg->var_off = true_64off;
14446 __reg_combine_64_into_32(false_reg);
14447 __reg_combine_64_into_32(true_reg);
14451 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14452 * the variable reg.
14454 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14455 struct bpf_reg_state *false_reg,
14456 u64 val, u32 val32,
14457 u8 opcode, bool is_jmp32)
14459 opcode = flip_opcode(opcode);
14460 /* This uses zero as "not present in table"; luckily the zero opcode,
14461 * BPF_JA, can't get here.
14464 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14467 /* Regs are known to be equal, so intersect their min/max/var_off */
14468 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14469 struct bpf_reg_state *dst_reg)
14471 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14472 dst_reg->umin_value);
14473 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14474 dst_reg->umax_value);
14475 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14476 dst_reg->smin_value);
14477 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14478 dst_reg->smax_value);
14479 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14481 reg_bounds_sync(src_reg);
14482 reg_bounds_sync(dst_reg);
14485 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14486 struct bpf_reg_state *true_dst,
14487 struct bpf_reg_state *false_src,
14488 struct bpf_reg_state *false_dst,
14493 __reg_combine_min_max(true_src, true_dst);
14496 __reg_combine_min_max(false_src, false_dst);
14501 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14502 struct bpf_reg_state *reg, u32 id,
14505 if (type_may_be_null(reg->type) && reg->id == id &&
14506 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14507 /* Old offset (both fixed and variable parts) should have been
14508 * known-zero, because we don't allow pointer arithmetic on
14509 * pointers that might be NULL. If we see this happening, don't
14510 * convert the register.
14512 * But in some cases, some helpers that return local kptrs
14513 * advance offset for the returned pointer. In those cases, it
14514 * is fine to expect to see reg->off.
14516 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14518 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14519 WARN_ON_ONCE(reg->off))
14523 reg->type = SCALAR_VALUE;
14524 /* We don't need id and ref_obj_id from this point
14525 * onwards anymore, thus we should better reset it,
14526 * so that state pruning has chances to take effect.
14529 reg->ref_obj_id = 0;
14534 mark_ptr_not_null_reg(reg);
14536 if (!reg_may_point_to_spin_lock(reg)) {
14537 /* For not-NULL ptr, reg->ref_obj_id will be reset
14538 * in release_reference().
14540 * reg->id is still used by spin_lock ptr. Other
14541 * than spin_lock ptr type, reg->id can be reset.
14548 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14549 * be folded together at some point.
14551 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14554 struct bpf_func_state *state = vstate->frame[vstate->curframe];
14555 struct bpf_reg_state *regs = state->regs, *reg;
14556 u32 ref_obj_id = regs[regno].ref_obj_id;
14557 u32 id = regs[regno].id;
14559 if (ref_obj_id && ref_obj_id == id && is_null)
14560 /* regs[regno] is in the " == NULL" branch.
14561 * No one could have freed the reference state before
14562 * doing the NULL check.
14564 WARN_ON_ONCE(release_reference_state(state, id));
14566 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14567 mark_ptr_or_null_reg(state, reg, id, is_null);
14571 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14572 struct bpf_reg_state *dst_reg,
14573 struct bpf_reg_state *src_reg,
14574 struct bpf_verifier_state *this_branch,
14575 struct bpf_verifier_state *other_branch)
14577 if (BPF_SRC(insn->code) != BPF_X)
14580 /* Pointers are always 64-bit. */
14581 if (BPF_CLASS(insn->code) == BPF_JMP32)
14584 switch (BPF_OP(insn->code)) {
14586 if ((dst_reg->type == PTR_TO_PACKET &&
14587 src_reg->type == PTR_TO_PACKET_END) ||
14588 (dst_reg->type == PTR_TO_PACKET_META &&
14589 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14590 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14591 find_good_pkt_pointers(this_branch, dst_reg,
14592 dst_reg->type, false);
14593 mark_pkt_end(other_branch, insn->dst_reg, true);
14594 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14595 src_reg->type == PTR_TO_PACKET) ||
14596 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14597 src_reg->type == PTR_TO_PACKET_META)) {
14598 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
14599 find_good_pkt_pointers(other_branch, src_reg,
14600 src_reg->type, true);
14601 mark_pkt_end(this_branch, insn->src_reg, false);
14607 if ((dst_reg->type == PTR_TO_PACKET &&
14608 src_reg->type == PTR_TO_PACKET_END) ||
14609 (dst_reg->type == PTR_TO_PACKET_META &&
14610 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14611 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14612 find_good_pkt_pointers(other_branch, dst_reg,
14613 dst_reg->type, true);
14614 mark_pkt_end(this_branch, insn->dst_reg, false);
14615 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14616 src_reg->type == PTR_TO_PACKET) ||
14617 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14618 src_reg->type == PTR_TO_PACKET_META)) {
14619 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
14620 find_good_pkt_pointers(this_branch, src_reg,
14621 src_reg->type, false);
14622 mark_pkt_end(other_branch, insn->src_reg, true);
14628 if ((dst_reg->type == PTR_TO_PACKET &&
14629 src_reg->type == PTR_TO_PACKET_END) ||
14630 (dst_reg->type == PTR_TO_PACKET_META &&
14631 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14632 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14633 find_good_pkt_pointers(this_branch, dst_reg,
14634 dst_reg->type, true);
14635 mark_pkt_end(other_branch, insn->dst_reg, false);
14636 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14637 src_reg->type == PTR_TO_PACKET) ||
14638 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14639 src_reg->type == PTR_TO_PACKET_META)) {
14640 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14641 find_good_pkt_pointers(other_branch, src_reg,
14642 src_reg->type, false);
14643 mark_pkt_end(this_branch, insn->src_reg, true);
14649 if ((dst_reg->type == PTR_TO_PACKET &&
14650 src_reg->type == PTR_TO_PACKET_END) ||
14651 (dst_reg->type == PTR_TO_PACKET_META &&
14652 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14653 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14654 find_good_pkt_pointers(other_branch, dst_reg,
14655 dst_reg->type, false);
14656 mark_pkt_end(this_branch, insn->dst_reg, true);
14657 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14658 src_reg->type == PTR_TO_PACKET) ||
14659 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14660 src_reg->type == PTR_TO_PACKET_META)) {
14661 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14662 find_good_pkt_pointers(this_branch, src_reg,
14663 src_reg->type, true);
14664 mark_pkt_end(other_branch, insn->src_reg, false);
14676 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14677 struct bpf_reg_state *known_reg)
14679 struct bpf_func_state *state;
14680 struct bpf_reg_state *reg;
14682 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14683 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14684 copy_register_state(reg, known_reg);
14688 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14689 struct bpf_insn *insn, int *insn_idx)
14691 struct bpf_verifier_state *this_branch = env->cur_state;
14692 struct bpf_verifier_state *other_branch;
14693 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14694 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14695 struct bpf_reg_state *eq_branch_regs;
14696 u8 opcode = BPF_OP(insn->code);
14701 /* Only conditional jumps are expected to reach here. */
14702 if (opcode == BPF_JA || opcode > BPF_JSLE) {
14703 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14707 /* check src2 operand */
14708 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14712 dst_reg = ®s[insn->dst_reg];
14713 if (BPF_SRC(insn->code) == BPF_X) {
14714 if (insn->imm != 0) {
14715 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14719 /* check src1 operand */
14720 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14724 src_reg = ®s[insn->src_reg];
14725 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14726 is_pointer_value(env, insn->src_reg)) {
14727 verbose(env, "R%d pointer comparison prohibited\n",
14732 if (insn->src_reg != BPF_REG_0) {
14733 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14738 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14740 if (BPF_SRC(insn->code) == BPF_K) {
14741 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14742 } else if (src_reg->type == SCALAR_VALUE &&
14743 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14744 pred = is_branch_taken(dst_reg,
14745 tnum_subreg(src_reg->var_off).value,
14748 } else if (src_reg->type == SCALAR_VALUE &&
14749 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14750 pred = is_branch_taken(dst_reg,
14751 src_reg->var_off.value,
14754 } else if (dst_reg->type == SCALAR_VALUE &&
14755 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14756 pred = is_branch_taken(src_reg,
14757 tnum_subreg(dst_reg->var_off).value,
14758 flip_opcode(opcode),
14760 } else if (dst_reg->type == SCALAR_VALUE &&
14761 !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14762 pred = is_branch_taken(src_reg,
14763 dst_reg->var_off.value,
14764 flip_opcode(opcode),
14766 } else if (reg_is_pkt_pointer_any(dst_reg) &&
14767 reg_is_pkt_pointer_any(src_reg) &&
14769 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14773 /* If we get here with a dst_reg pointer type it is because
14774 * above is_branch_taken() special cased the 0 comparison.
14776 if (!__is_pointer_value(false, dst_reg))
14777 err = mark_chain_precision(env, insn->dst_reg);
14778 if (BPF_SRC(insn->code) == BPF_X && !err &&
14779 !__is_pointer_value(false, src_reg))
14780 err = mark_chain_precision(env, insn->src_reg);
14786 /* Only follow the goto, ignore fall-through. If needed, push
14787 * the fall-through branch for simulation under speculative
14790 if (!env->bypass_spec_v1 &&
14791 !sanitize_speculative_path(env, insn, *insn_idx + 1,
14794 if (env->log.level & BPF_LOG_LEVEL)
14795 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14796 *insn_idx += insn->off;
14798 } else if (pred == 0) {
14799 /* Only follow the fall-through branch, since that's where the
14800 * program will go. If needed, push the goto branch for
14801 * simulation under speculative execution.
14803 if (!env->bypass_spec_v1 &&
14804 !sanitize_speculative_path(env, insn,
14805 *insn_idx + insn->off + 1,
14808 if (env->log.level & BPF_LOG_LEVEL)
14809 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14813 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14817 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14819 /* detect if we are comparing against a constant value so we can adjust
14820 * our min/max values for our dst register.
14821 * this is only legit if both are scalars (or pointers to the same
14822 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14823 * because otherwise the different base pointers mean the offsets aren't
14826 if (BPF_SRC(insn->code) == BPF_X) {
14827 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
14829 if (dst_reg->type == SCALAR_VALUE &&
14830 src_reg->type == SCALAR_VALUE) {
14831 if (tnum_is_const(src_reg->var_off) ||
14833 tnum_is_const(tnum_subreg(src_reg->var_off))))
14834 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14836 src_reg->var_off.value,
14837 tnum_subreg(src_reg->var_off).value,
14839 else if (tnum_is_const(dst_reg->var_off) ||
14841 tnum_is_const(tnum_subreg(dst_reg->var_off))))
14842 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14844 dst_reg->var_off.value,
14845 tnum_subreg(dst_reg->var_off).value,
14847 else if (!is_jmp32 &&
14848 (opcode == BPF_JEQ || opcode == BPF_JNE))
14849 /* Comparing for equality, we can combine knowledge */
14850 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14851 &other_branch_regs[insn->dst_reg],
14852 src_reg, dst_reg, opcode);
14854 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14855 find_equal_scalars(this_branch, src_reg);
14856 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14860 } else if (dst_reg->type == SCALAR_VALUE) {
14861 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14862 dst_reg, insn->imm, (u32)insn->imm,
14866 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14867 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14868 find_equal_scalars(this_branch, dst_reg);
14869 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14872 /* if one pointer register is compared to another pointer
14873 * register check if PTR_MAYBE_NULL could be lifted.
14874 * E.g. register A - maybe null
14875 * register B - not null
14876 * for JNE A, B, ... - A is not null in the false branch;
14877 * for JEQ A, B, ... - A is not null in the true branch.
14879 * Since PTR_TO_BTF_ID points to a kernel struct that does
14880 * not need to be null checked by the BPF program, i.e.,
14881 * could be null even without PTR_MAYBE_NULL marking, so
14882 * only propagate nullness when neither reg is that type.
14884 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14885 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14886 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14887 base_type(src_reg->type) != PTR_TO_BTF_ID &&
14888 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14889 eq_branch_regs = NULL;
14892 eq_branch_regs = other_branch_regs;
14895 eq_branch_regs = regs;
14901 if (eq_branch_regs) {
14902 if (type_may_be_null(src_reg->type))
14903 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14905 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14909 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14910 * NOTE: these optimizations below are related with pointer comparison
14911 * which will never be JMP32.
14913 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14914 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14915 type_may_be_null(dst_reg->type)) {
14916 /* Mark all identical registers in each branch as either
14917 * safe or unknown depending R == 0 or R != 0 conditional.
14919 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14920 opcode == BPF_JNE);
14921 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14922 opcode == BPF_JEQ);
14923 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
14924 this_branch, other_branch) &&
14925 is_pointer_value(env, insn->dst_reg)) {
14926 verbose(env, "R%d pointer comparison prohibited\n",
14930 if (env->log.level & BPF_LOG_LEVEL)
14931 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14935 /* verify BPF_LD_IMM64 instruction */
14936 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14938 struct bpf_insn_aux_data *aux = cur_aux(env);
14939 struct bpf_reg_state *regs = cur_regs(env);
14940 struct bpf_reg_state *dst_reg;
14941 struct bpf_map *map;
14944 if (BPF_SIZE(insn->code) != BPF_DW) {
14945 verbose(env, "invalid BPF_LD_IMM insn\n");
14948 if (insn->off != 0) {
14949 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14953 err = check_reg_arg(env, insn->dst_reg, DST_OP);
14957 dst_reg = ®s[insn->dst_reg];
14958 if (insn->src_reg == 0) {
14959 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14961 dst_reg->type = SCALAR_VALUE;
14962 __mark_reg_known(®s[insn->dst_reg], imm);
14966 /* All special src_reg cases are listed below. From this point onwards
14967 * we either succeed and assign a corresponding dst_reg->type after
14968 * zeroing the offset, or fail and reject the program.
14970 mark_reg_known_zero(env, regs, insn->dst_reg);
14972 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14973 dst_reg->type = aux->btf_var.reg_type;
14974 switch (base_type(dst_reg->type)) {
14976 dst_reg->mem_size = aux->btf_var.mem_size;
14978 case PTR_TO_BTF_ID:
14979 dst_reg->btf = aux->btf_var.btf;
14980 dst_reg->btf_id = aux->btf_var.btf_id;
14983 verbose(env, "bpf verifier is misconfigured\n");
14989 if (insn->src_reg == BPF_PSEUDO_FUNC) {
14990 struct bpf_prog_aux *aux = env->prog->aux;
14991 u32 subprogno = find_subprog(env,
14992 env->insn_idx + insn->imm + 1);
14994 if (!aux->func_info) {
14995 verbose(env, "missing btf func_info\n");
14998 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14999 verbose(env, "callback function not static\n");
15003 dst_reg->type = PTR_TO_FUNC;
15004 dst_reg->subprogno = subprogno;
15008 map = env->used_maps[aux->map_index];
15009 dst_reg->map_ptr = map;
15011 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15012 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15013 dst_reg->type = PTR_TO_MAP_VALUE;
15014 dst_reg->off = aux->map_off;
15015 WARN_ON_ONCE(map->max_entries != 1);
15016 /* We want reg->id to be same (0) as map_value is not distinct */
15017 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15018 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15019 dst_reg->type = CONST_PTR_TO_MAP;
15021 verbose(env, "bpf verifier is misconfigured\n");
15028 static bool may_access_skb(enum bpf_prog_type type)
15031 case BPF_PROG_TYPE_SOCKET_FILTER:
15032 case BPF_PROG_TYPE_SCHED_CLS:
15033 case BPF_PROG_TYPE_SCHED_ACT:
15040 /* verify safety of LD_ABS|LD_IND instructions:
15041 * - they can only appear in the programs where ctx == skb
15042 * - since they are wrappers of function calls, they scratch R1-R5 registers,
15043 * preserve R6-R9, and store return value into R0
15046 * ctx == skb == R6 == CTX
15049 * SRC == any register
15050 * IMM == 32-bit immediate
15053 * R0 - 8/16/32-bit skb data converted to cpu endianness
15055 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15057 struct bpf_reg_state *regs = cur_regs(env);
15058 static const int ctx_reg = BPF_REG_6;
15059 u8 mode = BPF_MODE(insn->code);
15062 if (!may_access_skb(resolve_prog_type(env->prog))) {
15063 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15067 if (!env->ops->gen_ld_abs) {
15068 verbose(env, "bpf verifier is misconfigured\n");
15072 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15073 BPF_SIZE(insn->code) == BPF_DW ||
15074 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15075 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15079 /* check whether implicit source operand (register R6) is readable */
15080 err = check_reg_arg(env, ctx_reg, SRC_OP);
15084 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15085 * gen_ld_abs() may terminate the program at runtime, leading to
15088 err = check_reference_leak(env, false);
15090 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15094 if (env->cur_state->active_lock.ptr) {
15095 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15099 if (env->cur_state->active_rcu_lock) {
15100 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15104 if (regs[ctx_reg].type != PTR_TO_CTX) {
15106 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15110 if (mode == BPF_IND) {
15111 /* check explicit source operand */
15112 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15117 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
15121 /* reset caller saved regs to unreadable */
15122 for (i = 0; i < CALLER_SAVED_REGS; i++) {
15123 mark_reg_not_init(env, regs, caller_saved[i]);
15124 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15127 /* mark destination R0 register as readable, since it contains
15128 * the value fetched from the packet.
15129 * Already marked as written above.
15131 mark_reg_unknown(env, regs, BPF_REG_0);
15132 /* ld_abs load up to 32-bit skb data. */
15133 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15137 static int check_return_code(struct bpf_verifier_env *env, int regno)
15139 struct tnum enforce_attach_type_range = tnum_unknown;
15140 const struct bpf_prog *prog = env->prog;
15141 struct bpf_reg_state *reg;
15142 struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
15143 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15145 struct bpf_func_state *frame = env->cur_state->frame[0];
15146 const bool is_subprog = frame->subprogno;
15148 /* LSM and struct_ops func-ptr's return type could be "void" */
15149 if (!is_subprog || frame->in_exception_callback_fn) {
15150 switch (prog_type) {
15151 case BPF_PROG_TYPE_LSM:
15152 if (prog->expected_attach_type == BPF_LSM_CGROUP)
15153 /* See below, can be 0 or 0-1 depending on hook. */
15156 case BPF_PROG_TYPE_STRUCT_OPS:
15157 if (!prog->aux->attach_func_proto->type)
15165 /* eBPF calling convention is such that R0 is used
15166 * to return the value from eBPF program.
15167 * Make sure that it's readable at this time
15168 * of bpf_exit, which means that program wrote
15169 * something into it earlier
15171 err = check_reg_arg(env, regno, SRC_OP);
15175 if (is_pointer_value(env, regno)) {
15176 verbose(env, "R%d leaks addr as return value\n", regno);
15180 reg = cur_regs(env) + regno;
15182 if (frame->in_async_callback_fn) {
15183 /* enforce return zero from async callbacks like timer */
15184 if (reg->type != SCALAR_VALUE) {
15185 verbose(env, "In async callback the register R%d is not a known value (%s)\n",
15186 regno, reg_type_str(env, reg->type));
15190 if (!tnum_in(const_0, reg->var_off)) {
15191 verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
15197 if (is_subprog && !frame->in_exception_callback_fn) {
15198 if (reg->type != SCALAR_VALUE) {
15199 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15200 regno, reg_type_str(env, reg->type));
15206 switch (prog_type) {
15207 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15208 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15209 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15210 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15211 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15212 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15213 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15214 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15215 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15216 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15217 range = tnum_range(1, 1);
15218 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15219 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15220 range = tnum_range(0, 3);
15222 case BPF_PROG_TYPE_CGROUP_SKB:
15223 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15224 range = tnum_range(0, 3);
15225 enforce_attach_type_range = tnum_range(2, 3);
15228 case BPF_PROG_TYPE_CGROUP_SOCK:
15229 case BPF_PROG_TYPE_SOCK_OPS:
15230 case BPF_PROG_TYPE_CGROUP_DEVICE:
15231 case BPF_PROG_TYPE_CGROUP_SYSCTL:
15232 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15234 case BPF_PROG_TYPE_RAW_TRACEPOINT:
15235 if (!env->prog->aux->attach_btf_id)
15237 range = tnum_const(0);
15239 case BPF_PROG_TYPE_TRACING:
15240 switch (env->prog->expected_attach_type) {
15241 case BPF_TRACE_FENTRY:
15242 case BPF_TRACE_FEXIT:
15243 range = tnum_const(0);
15245 case BPF_TRACE_RAW_TP:
15246 case BPF_MODIFY_RETURN:
15248 case BPF_TRACE_ITER:
15254 case BPF_PROG_TYPE_SK_LOOKUP:
15255 range = tnum_range(SK_DROP, SK_PASS);
15258 case BPF_PROG_TYPE_LSM:
15259 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15260 /* Regular BPF_PROG_TYPE_LSM programs can return
15265 if (!env->prog->aux->attach_func_proto->type) {
15266 /* Make sure programs that attach to void
15267 * hooks don't try to modify return value.
15269 range = tnum_range(1, 1);
15273 case BPF_PROG_TYPE_NETFILTER:
15274 range = tnum_range(NF_DROP, NF_ACCEPT);
15276 case BPF_PROG_TYPE_EXT:
15277 /* freplace program can return anything as its return value
15278 * depends on the to-be-replaced kernel func or bpf program.
15284 if (reg->type != SCALAR_VALUE) {
15285 verbose(env, "At program exit the register R%d is not a known value (%s)\n",
15286 regno, reg_type_str(env, reg->type));
15290 if (!tnum_in(range, reg->var_off)) {
15291 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15292 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15293 prog_type == BPF_PROG_TYPE_LSM &&
15294 !prog->aux->attach_func_proto->type)
15295 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15299 if (!tnum_is_unknown(enforce_attach_type_range) &&
15300 tnum_in(enforce_attach_type_range, reg->var_off))
15301 env->prog->enforce_expected_attach_type = 1;
15305 /* non-recursive DFS pseudo code
15306 * 1 procedure DFS-iterative(G,v):
15307 * 2 label v as discovered
15308 * 3 let S be a stack
15310 * 5 while S is not empty
15312 * 7 if t is what we're looking for:
15314 * 9 for all edges e in G.adjacentEdges(t) do
15315 * 10 if edge e is already labelled
15316 * 11 continue with the next edge
15317 * 12 w <- G.adjacentVertex(t,e)
15318 * 13 if vertex w is not discovered and not explored
15319 * 14 label e as tree-edge
15320 * 15 label w as discovered
15323 * 18 else if vertex w is discovered
15324 * 19 label e as back-edge
15326 * 21 // vertex w is explored
15327 * 22 label e as forward- or cross-edge
15328 * 23 label t as explored
15332 * 0x10 - discovered
15333 * 0x11 - discovered and fall-through edge labelled
15334 * 0x12 - discovered and fall-through and branch edges labelled
15345 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15347 env->insn_aux_data[idx].prune_point = true;
15350 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15352 return env->insn_aux_data[insn_idx].prune_point;
15355 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15357 env->insn_aux_data[idx].force_checkpoint = true;
15360 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15362 return env->insn_aux_data[insn_idx].force_checkpoint;
15367 DONE_EXPLORING = 0,
15368 KEEP_EXPLORING = 1,
15371 /* t, w, e - match pseudo-code above:
15372 * t - index of current instruction
15373 * w - next instruction
15376 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
15379 int *insn_stack = env->cfg.insn_stack;
15380 int *insn_state = env->cfg.insn_state;
15382 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15383 return DONE_EXPLORING;
15385 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15386 return DONE_EXPLORING;
15388 if (w < 0 || w >= env->prog->len) {
15389 verbose_linfo(env, t, "%d: ", t);
15390 verbose(env, "jump out of range from insn %d to %d\n", t, w);
15395 /* mark branch target for state pruning */
15396 mark_prune_point(env, w);
15397 mark_jmp_point(env, w);
15400 if (insn_state[w] == 0) {
15402 insn_state[t] = DISCOVERED | e;
15403 insn_state[w] = DISCOVERED;
15404 if (env->cfg.cur_stack >= env->prog->len)
15406 insn_stack[env->cfg.cur_stack++] = w;
15407 return KEEP_EXPLORING;
15408 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15409 if (loop_ok && env->bpf_capable)
15410 return DONE_EXPLORING;
15411 verbose_linfo(env, t, "%d: ", t);
15412 verbose_linfo(env, w, "%d: ", w);
15413 verbose(env, "back-edge from insn %d to %d\n", t, w);
15415 } else if (insn_state[w] == EXPLORED) {
15416 /* forward- or cross-edge */
15417 insn_state[t] = DISCOVERED | e;
15419 verbose(env, "insn state internal bug\n");
15422 return DONE_EXPLORING;
15425 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15426 struct bpf_verifier_env *env,
15431 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
15435 mark_prune_point(env, t + 1);
15436 /* when we exit from subprog, we need to record non-linear history */
15437 mark_jmp_point(env, t + 1);
15439 if (visit_callee) {
15440 mark_prune_point(env, t);
15441 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
15442 /* It's ok to allow recursion from CFG point of
15443 * view. __check_func_call() will do the actual
15446 bpf_pseudo_func(insns + t));
15451 /* Visits the instruction at index t and returns one of the following:
15452 * < 0 - an error occurred
15453 * DONE_EXPLORING - the instruction was fully explored
15454 * KEEP_EXPLORING - there is still work to be done before it is fully explored
15456 static int visit_insn(int t, struct bpf_verifier_env *env)
15458 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15461 if (bpf_pseudo_func(insn))
15462 return visit_func_call_insn(t, insns, env, true);
15464 /* All non-branch instructions have a single fall-through edge. */
15465 if (BPF_CLASS(insn->code) != BPF_JMP &&
15466 BPF_CLASS(insn->code) != BPF_JMP32)
15467 return push_insn(t, t + 1, FALLTHROUGH, env, false);
15469 switch (BPF_OP(insn->code)) {
15471 return DONE_EXPLORING;
15474 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15475 /* Mark this call insn as a prune point to trigger
15476 * is_state_visited() check before call itself is
15477 * processed by __check_func_call(). Otherwise new
15478 * async state will be pushed for further exploration.
15480 mark_prune_point(env, t);
15481 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15482 struct bpf_kfunc_call_arg_meta meta;
15484 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15485 if (ret == 0 && is_iter_next_kfunc(&meta)) {
15486 mark_prune_point(env, t);
15487 /* Checking and saving state checkpoints at iter_next() call
15488 * is crucial for fast convergence of open-coded iterator loop
15489 * logic, so we need to force it. If we don't do that,
15490 * is_state_visited() might skip saving a checkpoint, causing
15491 * unnecessarily long sequence of not checkpointed
15492 * instructions and jumps, leading to exhaustion of jump
15493 * history buffer, and potentially other undesired outcomes.
15494 * It is expected that with correct open-coded iterators
15495 * convergence will happen quickly, so we don't run a risk of
15496 * exhausting memory.
15498 mark_force_checkpoint(env, t);
15501 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15504 if (BPF_SRC(insn->code) != BPF_K)
15507 if (BPF_CLASS(insn->code) == BPF_JMP)
15512 /* unconditional jump with single edge */
15513 ret = push_insn(t, t + off + 1, FALLTHROUGH, env,
15518 mark_prune_point(env, t + off + 1);
15519 mark_jmp_point(env, t + off + 1);
15524 /* conditional jump with two edges */
15525 mark_prune_point(env, t);
15527 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
15531 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
15535 /* non-recursive depth-first-search to detect loops in BPF program
15536 * loop == back-edge in directed graph
15538 static int check_cfg(struct bpf_verifier_env *env)
15540 int insn_cnt = env->prog->len;
15541 int *insn_stack, *insn_state;
15542 int ex_insn_beg, i, ret = 0;
15543 bool ex_done = false;
15545 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15549 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15551 kvfree(insn_state);
15555 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15556 insn_stack[0] = 0; /* 0 is the first instruction */
15557 env->cfg.cur_stack = 1;
15560 while (env->cfg.cur_stack > 0) {
15561 int t = insn_stack[env->cfg.cur_stack - 1];
15563 ret = visit_insn(t, env);
15565 case DONE_EXPLORING:
15566 insn_state[t] = EXPLORED;
15567 env->cfg.cur_stack--;
15569 case KEEP_EXPLORING:
15573 verbose(env, "visit_insn internal bug\n");
15580 if (env->cfg.cur_stack < 0) {
15581 verbose(env, "pop stack internal bug\n");
15586 if (env->exception_callback_subprog && !ex_done) {
15587 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
15589 insn_state[ex_insn_beg] = DISCOVERED;
15590 insn_stack[0] = ex_insn_beg;
15591 env->cfg.cur_stack = 1;
15596 for (i = 0; i < insn_cnt; i++) {
15597 if (insn_state[i] != EXPLORED) {
15598 verbose(env, "unreachable insn %d\n", i);
15603 ret = 0; /* cfg looks good */
15606 kvfree(insn_state);
15607 kvfree(insn_stack);
15608 env->cfg.insn_state = env->cfg.insn_stack = NULL;
15612 static int check_abnormal_return(struct bpf_verifier_env *env)
15616 for (i = 1; i < env->subprog_cnt; i++) {
15617 if (env->subprog_info[i].has_ld_abs) {
15618 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15621 if (env->subprog_info[i].has_tail_call) {
15622 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15629 /* The minimum supported BTF func info size */
15630 #define MIN_BPF_FUNCINFO_SIZE 8
15631 #define MAX_FUNCINFO_REC_SIZE 252
15633 static int check_btf_func_early(struct bpf_verifier_env *env,
15634 const union bpf_attr *attr,
15637 u32 krec_size = sizeof(struct bpf_func_info);
15638 const struct btf_type *type, *func_proto;
15639 u32 i, nfuncs, urec_size, min_size;
15640 struct bpf_func_info *krecord;
15641 struct bpf_prog *prog;
15642 const struct btf *btf;
15643 u32 prev_offset = 0;
15647 nfuncs = attr->func_info_cnt;
15649 if (check_abnormal_return(env))
15654 urec_size = attr->func_info_rec_size;
15655 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15656 urec_size > MAX_FUNCINFO_REC_SIZE ||
15657 urec_size % sizeof(u32)) {
15658 verbose(env, "invalid func info rec size %u\n", urec_size);
15663 btf = prog->aux->btf;
15665 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15666 min_size = min_t(u32, krec_size, urec_size);
15668 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15672 for (i = 0; i < nfuncs; i++) {
15673 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15675 if (ret == -E2BIG) {
15676 verbose(env, "nonzero tailing record in func info");
15677 /* set the size kernel expects so loader can zero
15678 * out the rest of the record.
15680 if (copy_to_bpfptr_offset(uattr,
15681 offsetof(union bpf_attr, func_info_rec_size),
15682 &min_size, sizeof(min_size)))
15688 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15693 /* check insn_off */
15696 if (krecord[i].insn_off) {
15698 "nonzero insn_off %u for the first func info record",
15699 krecord[i].insn_off);
15702 } else if (krecord[i].insn_off <= prev_offset) {
15704 "same or smaller insn offset (%u) than previous func info record (%u)",
15705 krecord[i].insn_off, prev_offset);
15709 /* check type_id */
15710 type = btf_type_by_id(btf, krecord[i].type_id);
15711 if (!type || !btf_type_is_func(type)) {
15712 verbose(env, "invalid type id %d in func info",
15713 krecord[i].type_id);
15717 func_proto = btf_type_by_id(btf, type->type);
15718 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15719 /* btf_func_check() already verified it during BTF load */
15722 prev_offset = krecord[i].insn_off;
15723 bpfptr_add(&urecord, urec_size);
15726 prog->aux->func_info = krecord;
15727 prog->aux->func_info_cnt = nfuncs;
15735 static int check_btf_func(struct bpf_verifier_env *env,
15736 const union bpf_attr *attr,
15739 const struct btf_type *type, *func_proto, *ret_type;
15740 u32 i, nfuncs, urec_size;
15741 struct bpf_func_info *krecord;
15742 struct bpf_func_info_aux *info_aux = NULL;
15743 struct bpf_prog *prog;
15744 const struct btf *btf;
15746 bool scalar_return;
15749 nfuncs = attr->func_info_cnt;
15751 if (check_abnormal_return(env))
15755 if (nfuncs != env->subprog_cnt) {
15756 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15760 urec_size = attr->func_info_rec_size;
15763 btf = prog->aux->btf;
15765 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15767 krecord = prog->aux->func_info;
15768 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15772 for (i = 0; i < nfuncs; i++) {
15773 /* check insn_off */
15776 if (env->subprog_info[i].start != krecord[i].insn_off) {
15777 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15781 /* Already checked type_id */
15782 type = btf_type_by_id(btf, krecord[i].type_id);
15783 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15784 /* Already checked func_proto */
15785 func_proto = btf_type_by_id(btf, type->type);
15787 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15789 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15790 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15791 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15794 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15795 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15799 bpfptr_add(&urecord, urec_size);
15802 prog->aux->func_info_aux = info_aux;
15810 static void adjust_btf_func(struct bpf_verifier_env *env)
15812 struct bpf_prog_aux *aux = env->prog->aux;
15815 if (!aux->func_info)
15818 /* func_info is not available for hidden subprogs */
15819 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
15820 aux->func_info[i].insn_off = env->subprog_info[i].start;
15823 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
15824 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
15826 static int check_btf_line(struct bpf_verifier_env *env,
15827 const union bpf_attr *attr,
15830 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15831 struct bpf_subprog_info *sub;
15832 struct bpf_line_info *linfo;
15833 struct bpf_prog *prog;
15834 const struct btf *btf;
15838 nr_linfo = attr->line_info_cnt;
15841 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15844 rec_size = attr->line_info_rec_size;
15845 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15846 rec_size > MAX_LINEINFO_REC_SIZE ||
15847 rec_size & (sizeof(u32) - 1))
15850 /* Need to zero it in case the userspace may
15851 * pass in a smaller bpf_line_info object.
15853 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15854 GFP_KERNEL | __GFP_NOWARN);
15859 btf = prog->aux->btf;
15862 sub = env->subprog_info;
15863 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15864 expected_size = sizeof(struct bpf_line_info);
15865 ncopy = min_t(u32, expected_size, rec_size);
15866 for (i = 0; i < nr_linfo; i++) {
15867 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15869 if (err == -E2BIG) {
15870 verbose(env, "nonzero tailing record in line_info");
15871 if (copy_to_bpfptr_offset(uattr,
15872 offsetof(union bpf_attr, line_info_rec_size),
15873 &expected_size, sizeof(expected_size)))
15879 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15885 * Check insn_off to ensure
15886 * 1) strictly increasing AND
15887 * 2) bounded by prog->len
15889 * The linfo[0].insn_off == 0 check logically falls into
15890 * the later "missing bpf_line_info for func..." case
15891 * because the first linfo[0].insn_off must be the
15892 * first sub also and the first sub must have
15893 * subprog_info[0].start == 0.
15895 if ((i && linfo[i].insn_off <= prev_offset) ||
15896 linfo[i].insn_off >= prog->len) {
15897 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15898 i, linfo[i].insn_off, prev_offset,
15904 if (!prog->insnsi[linfo[i].insn_off].code) {
15906 "Invalid insn code at line_info[%u].insn_off\n",
15912 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15913 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15914 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15919 if (s != env->subprog_cnt) {
15920 if (linfo[i].insn_off == sub[s].start) {
15921 sub[s].linfo_idx = i;
15923 } else if (sub[s].start < linfo[i].insn_off) {
15924 verbose(env, "missing bpf_line_info for func#%u\n", s);
15930 prev_offset = linfo[i].insn_off;
15931 bpfptr_add(&ulinfo, rec_size);
15934 if (s != env->subprog_cnt) {
15935 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15936 env->subprog_cnt - s, s);
15941 prog->aux->linfo = linfo;
15942 prog->aux->nr_linfo = nr_linfo;
15951 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
15952 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
15954 static int check_core_relo(struct bpf_verifier_env *env,
15955 const union bpf_attr *attr,
15958 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15959 struct bpf_core_relo core_relo = {};
15960 struct bpf_prog *prog = env->prog;
15961 const struct btf *btf = prog->aux->btf;
15962 struct bpf_core_ctx ctx = {
15966 bpfptr_t u_core_relo;
15969 nr_core_relo = attr->core_relo_cnt;
15972 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15975 rec_size = attr->core_relo_rec_size;
15976 if (rec_size < MIN_CORE_RELO_SIZE ||
15977 rec_size > MAX_CORE_RELO_SIZE ||
15978 rec_size % sizeof(u32))
15981 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15982 expected_size = sizeof(struct bpf_core_relo);
15983 ncopy = min_t(u32, expected_size, rec_size);
15985 /* Unlike func_info and line_info, copy and apply each CO-RE
15986 * relocation record one at a time.
15988 for (i = 0; i < nr_core_relo; i++) {
15989 /* future proofing when sizeof(bpf_core_relo) changes */
15990 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15992 if (err == -E2BIG) {
15993 verbose(env, "nonzero tailing record in core_relo");
15994 if (copy_to_bpfptr_offset(uattr,
15995 offsetof(union bpf_attr, core_relo_rec_size),
15996 &expected_size, sizeof(expected_size)))
16002 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16007 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16008 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16009 i, core_relo.insn_off, prog->len);
16014 err = bpf_core_apply(&ctx, &core_relo, i,
16015 &prog->insnsi[core_relo.insn_off / 8]);
16018 bpfptr_add(&u_core_relo, rec_size);
16023 static int check_btf_info_early(struct bpf_verifier_env *env,
16024 const union bpf_attr *attr,
16030 if (!attr->func_info_cnt && !attr->line_info_cnt) {
16031 if (check_abnormal_return(env))
16036 btf = btf_get_by_fd(attr->prog_btf_fd);
16038 return PTR_ERR(btf);
16039 if (btf_is_kernel(btf)) {
16043 env->prog->aux->btf = btf;
16045 err = check_btf_func_early(env, attr, uattr);
16051 static int check_btf_info(struct bpf_verifier_env *env,
16052 const union bpf_attr *attr,
16057 if (!attr->func_info_cnt && !attr->line_info_cnt) {
16058 if (check_abnormal_return(env))
16063 err = check_btf_func(env, attr, uattr);
16067 err = check_btf_line(env, attr, uattr);
16071 err = check_core_relo(env, attr, uattr);
16078 /* check %cur's range satisfies %old's */
16079 static bool range_within(struct bpf_reg_state *old,
16080 struct bpf_reg_state *cur)
16082 return old->umin_value <= cur->umin_value &&
16083 old->umax_value >= cur->umax_value &&
16084 old->smin_value <= cur->smin_value &&
16085 old->smax_value >= cur->smax_value &&
16086 old->u32_min_value <= cur->u32_min_value &&
16087 old->u32_max_value >= cur->u32_max_value &&
16088 old->s32_min_value <= cur->s32_min_value &&
16089 old->s32_max_value >= cur->s32_max_value;
16092 /* If in the old state two registers had the same id, then they need to have
16093 * the same id in the new state as well. But that id could be different from
16094 * the old state, so we need to track the mapping from old to new ids.
16095 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16096 * regs with old id 5 must also have new id 9 for the new state to be safe. But
16097 * regs with a different old id could still have new id 9, we don't care about
16099 * So we look through our idmap to see if this old id has been seen before. If
16100 * so, we require the new id to match; otherwise, we add the id pair to the map.
16102 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16104 struct bpf_id_pair *map = idmap->map;
16107 /* either both IDs should be set or both should be zero */
16108 if (!!old_id != !!cur_id)
16111 if (old_id == 0) /* cur_id == 0 as well */
16114 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16116 /* Reached an empty slot; haven't seen this id before */
16117 map[i].old = old_id;
16118 map[i].cur = cur_id;
16121 if (map[i].old == old_id)
16122 return map[i].cur == cur_id;
16123 if (map[i].cur == cur_id)
16126 /* We ran out of idmap slots, which should be impossible */
16131 /* Similar to check_ids(), but allocate a unique temporary ID
16132 * for 'old_id' or 'cur_id' of zero.
16133 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16135 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16137 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16138 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16140 return check_ids(old_id, cur_id, idmap);
16143 static void clean_func_state(struct bpf_verifier_env *env,
16144 struct bpf_func_state *st)
16146 enum bpf_reg_liveness live;
16149 for (i = 0; i < BPF_REG_FP; i++) {
16150 live = st->regs[i].live;
16151 /* liveness must not touch this register anymore */
16152 st->regs[i].live |= REG_LIVE_DONE;
16153 if (!(live & REG_LIVE_READ))
16154 /* since the register is unused, clear its state
16155 * to make further comparison simpler
16157 __mark_reg_not_init(env, &st->regs[i]);
16160 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16161 live = st->stack[i].spilled_ptr.live;
16162 /* liveness must not touch this stack slot anymore */
16163 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16164 if (!(live & REG_LIVE_READ)) {
16165 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16166 for (j = 0; j < BPF_REG_SIZE; j++)
16167 st->stack[i].slot_type[j] = STACK_INVALID;
16172 static void clean_verifier_state(struct bpf_verifier_env *env,
16173 struct bpf_verifier_state *st)
16177 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16178 /* all regs in this state in all frames were already marked */
16181 for (i = 0; i <= st->curframe; i++)
16182 clean_func_state(env, st->frame[i]);
16185 /* the parentage chains form a tree.
16186 * the verifier states are added to state lists at given insn and
16187 * pushed into state stack for future exploration.
16188 * when the verifier reaches bpf_exit insn some of the verifer states
16189 * stored in the state lists have their final liveness state already,
16190 * but a lot of states will get revised from liveness point of view when
16191 * the verifier explores other branches.
16194 * 2: if r1 == 100 goto pc+1
16197 * when the verifier reaches exit insn the register r0 in the state list of
16198 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16199 * of insn 2 and goes exploring further. At the insn 4 it will walk the
16200 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16202 * Since the verifier pushes the branch states as it sees them while exploring
16203 * the program the condition of walking the branch instruction for the second
16204 * time means that all states below this branch were already explored and
16205 * their final liveness marks are already propagated.
16206 * Hence when the verifier completes the search of state list in is_state_visited()
16207 * we can call this clean_live_states() function to mark all liveness states
16208 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16209 * will not be used.
16210 * This function also clears the registers and stack for states that !READ
16211 * to simplify state merging.
16213 * Important note here that walking the same branch instruction in the callee
16214 * doesn't meant that the states are DONE. The verifier has to compare
16217 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16218 struct bpf_verifier_state *cur)
16220 struct bpf_verifier_state_list *sl;
16222 sl = *explored_state(env, insn);
16224 if (sl->state.branches)
16226 if (sl->state.insn_idx != insn ||
16227 !same_callsites(&sl->state, cur))
16229 clean_verifier_state(env, &sl->state);
16235 static bool regs_exact(const struct bpf_reg_state *rold,
16236 const struct bpf_reg_state *rcur,
16237 struct bpf_idmap *idmap)
16239 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16240 check_ids(rold->id, rcur->id, idmap) &&
16241 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16244 /* Returns true if (rold safe implies rcur safe) */
16245 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16246 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
16249 return regs_exact(rold, rcur, idmap);
16251 if (!(rold->live & REG_LIVE_READ))
16252 /* explored state didn't use this */
16254 if (rold->type == NOT_INIT)
16255 /* explored state can't have used this */
16257 if (rcur->type == NOT_INIT)
16260 /* Enforce that register types have to match exactly, including their
16261 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16264 * One can make a point that using a pointer register as unbounded
16265 * SCALAR would be technically acceptable, but this could lead to
16266 * pointer leaks because scalars are allowed to leak while pointers
16267 * are not. We could make this safe in special cases if root is
16268 * calling us, but it's probably not worth the hassle.
16270 * Also, register types that are *not* MAYBE_NULL could technically be
16271 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16272 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16273 * to the same map).
16274 * However, if the old MAYBE_NULL register then got NULL checked,
16275 * doing so could have affected others with the same id, and we can't
16276 * check for that because we lost the id when we converted to
16277 * a non-MAYBE_NULL variant.
16278 * So, as a general rule we don't allow mixing MAYBE_NULL and
16279 * non-MAYBE_NULL registers as well.
16281 if (rold->type != rcur->type)
16284 switch (base_type(rold->type)) {
16286 if (env->explore_alu_limits) {
16287 /* explore_alu_limits disables tnum_in() and range_within()
16288 * logic and requires everything to be strict
16290 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16291 check_scalar_ids(rold->id, rcur->id, idmap);
16293 if (!rold->precise)
16295 /* Why check_ids() for scalar registers?
16297 * Consider the following BPF code:
16298 * 1: r6 = ... unbound scalar, ID=a ...
16299 * 2: r7 = ... unbound scalar, ID=b ...
16300 * 3: if (r6 > r7) goto +1
16302 * 5: if (r6 > X) goto ...
16303 * 6: ... memory operation using r7 ...
16305 * First verification path is [1-6]:
16306 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16307 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16308 * r7 <= X, because r6 and r7 share same id.
16309 * Next verification path is [1-4, 6].
16311 * Instruction (6) would be reached in two states:
16312 * I. r6{.id=b}, r7{.id=b} via path 1-6;
16313 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16315 * Use check_ids() to distinguish these states.
16317 * Also verify that new value satisfies old value range knowledge.
16319 return range_within(rold, rcur) &&
16320 tnum_in(rold->var_off, rcur->var_off) &&
16321 check_scalar_ids(rold->id, rcur->id, idmap);
16322 case PTR_TO_MAP_KEY:
16323 case PTR_TO_MAP_VALUE:
16326 case PTR_TO_TP_BUFFER:
16327 /* If the new min/max/var_off satisfy the old ones and
16328 * everything else matches, we are OK.
16330 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16331 range_within(rold, rcur) &&
16332 tnum_in(rold->var_off, rcur->var_off) &&
16333 check_ids(rold->id, rcur->id, idmap) &&
16334 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16335 case PTR_TO_PACKET_META:
16336 case PTR_TO_PACKET:
16337 /* We must have at least as much range as the old ptr
16338 * did, so that any accesses which were safe before are
16339 * still safe. This is true even if old range < old off,
16340 * since someone could have accessed through (ptr - k), or
16341 * even done ptr -= k in a register, to get a safe access.
16343 if (rold->range > rcur->range)
16345 /* If the offsets don't match, we can't trust our alignment;
16346 * nor can we be sure that we won't fall out of range.
16348 if (rold->off != rcur->off)
16350 /* id relations must be preserved */
16351 if (!check_ids(rold->id, rcur->id, idmap))
16353 /* new val must satisfy old val knowledge */
16354 return range_within(rold, rcur) &&
16355 tnum_in(rold->var_off, rcur->var_off);
16357 /* two stack pointers are equal only if they're pointing to
16358 * the same stack frame, since fp-8 in foo != fp-8 in bar
16360 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16362 return regs_exact(rold, rcur, idmap);
16366 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16367 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16371 /* walk slots of the explored stack and ignore any additional
16372 * slots in the current stack, since explored(safe) state
16375 for (i = 0; i < old->allocated_stack; i++) {
16376 struct bpf_reg_state *old_reg, *cur_reg;
16378 spi = i / BPF_REG_SIZE;
16381 old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16382 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16385 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16386 i += BPF_REG_SIZE - 1;
16387 /* explored state didn't use this */
16391 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16394 if (env->allow_uninit_stack &&
16395 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16398 /* explored stack has more populated slots than current stack
16399 * and these slots were used
16401 if (i >= cur->allocated_stack)
16404 /* if old state was safe with misc data in the stack
16405 * it will be safe with zero-initialized stack.
16406 * The opposite is not true
16408 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16409 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16411 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16412 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16413 /* Ex: old explored (safe) state has STACK_SPILL in
16414 * this stack slot, but current has STACK_MISC ->
16415 * this verifier states are not equivalent,
16416 * return false to continue verification of this path
16419 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16421 /* Both old and cur are having same slot_type */
16422 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16424 /* when explored and current stack slot are both storing
16425 * spilled registers, check that stored pointers types
16426 * are the same as well.
16427 * Ex: explored safe path could have stored
16428 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16429 * but current path has stored:
16430 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16431 * such verifier states are not equivalent.
16432 * return false to continue verification of this path
16434 if (!regsafe(env, &old->stack[spi].spilled_ptr,
16435 &cur->stack[spi].spilled_ptr, idmap, exact))
16439 old_reg = &old->stack[spi].spilled_ptr;
16440 cur_reg = &cur->stack[spi].spilled_ptr;
16441 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16442 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16443 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16447 old_reg = &old->stack[spi].spilled_ptr;
16448 cur_reg = &cur->stack[spi].spilled_ptr;
16449 /* iter.depth is not compared between states as it
16450 * doesn't matter for correctness and would otherwise
16451 * prevent convergence; we maintain it only to prevent
16452 * infinite loop check triggering, see
16453 * iter_active_depths_differ()
16455 if (old_reg->iter.btf != cur_reg->iter.btf ||
16456 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16457 old_reg->iter.state != cur_reg->iter.state ||
16458 /* ignore {old_reg,cur_reg}->iter.depth, see above */
16459 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16464 case STACK_INVALID:
16466 /* Ensure that new unhandled slot types return false by default */
16474 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16475 struct bpf_idmap *idmap)
16479 if (old->acquired_refs != cur->acquired_refs)
16482 for (i = 0; i < old->acquired_refs; i++) {
16483 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16490 /* compare two verifier states
16492 * all states stored in state_list are known to be valid, since
16493 * verifier reached 'bpf_exit' instruction through them
16495 * this function is called when verifier exploring different branches of
16496 * execution popped from the state stack. If it sees an old state that has
16497 * more strict register state and more strict stack state then this execution
16498 * branch doesn't need to be explored further, since verifier already
16499 * concluded that more strict state leads to valid finish.
16501 * Therefore two states are equivalent if register state is more conservative
16502 * and explored stack state is more conservative than the current one.
16505 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16506 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16508 * In other words if current stack state (one being explored) has more
16509 * valid slots than old one that already passed validation, it means
16510 * the verifier can stop exploring and conclude that current state is valid too
16512 * Similarly with registers. If explored state has register type as invalid
16513 * whereas register type in current state is meaningful, it means that
16514 * the current state will reach 'bpf_exit' instruction safely
16516 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16517 struct bpf_func_state *cur, bool exact)
16521 for (i = 0; i < MAX_BPF_REG; i++)
16522 if (!regsafe(env, &old->regs[i], &cur->regs[i],
16523 &env->idmap_scratch, exact))
16526 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16529 if (!refsafe(old, cur, &env->idmap_scratch))
16535 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16537 env->idmap_scratch.tmp_id_gen = env->id_gen;
16538 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16541 static bool states_equal(struct bpf_verifier_env *env,
16542 struct bpf_verifier_state *old,
16543 struct bpf_verifier_state *cur,
16548 if (old->curframe != cur->curframe)
16551 reset_idmap_scratch(env);
16553 /* Verification state from speculative execution simulation
16554 * must never prune a non-speculative execution one.
16556 if (old->speculative && !cur->speculative)
16559 if (old->active_lock.ptr != cur->active_lock.ptr)
16562 /* Old and cur active_lock's have to be either both present
16565 if (!!old->active_lock.id != !!cur->active_lock.id)
16568 if (old->active_lock.id &&
16569 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16572 if (old->active_rcu_lock != cur->active_rcu_lock)
16575 /* for states to be equal callsites have to be the same
16576 * and all frame states need to be equivalent
16578 for (i = 0; i <= old->curframe; i++) {
16579 if (old->frame[i]->callsite != cur->frame[i]->callsite)
16581 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16587 /* Return 0 if no propagation happened. Return negative error code if error
16588 * happened. Otherwise, return the propagated bit.
16590 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16591 struct bpf_reg_state *reg,
16592 struct bpf_reg_state *parent_reg)
16594 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16595 u8 flag = reg->live & REG_LIVE_READ;
16598 /* When comes here, read flags of PARENT_REG or REG could be any of
16599 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16600 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16602 if (parent_flag == REG_LIVE_READ64 ||
16603 /* Or if there is no read flag from REG. */
16605 /* Or if the read flag from REG is the same as PARENT_REG. */
16606 parent_flag == flag)
16609 err = mark_reg_read(env, reg, parent_reg, flag);
16616 /* A write screens off any subsequent reads; but write marks come from the
16617 * straight-line code between a state and its parent. When we arrive at an
16618 * equivalent state (jump target or such) we didn't arrive by the straight-line
16619 * code, so read marks in the state must propagate to the parent regardless
16620 * of the state's write marks. That's what 'parent == state->parent' comparison
16621 * in mark_reg_read() is for.
16623 static int propagate_liveness(struct bpf_verifier_env *env,
16624 const struct bpf_verifier_state *vstate,
16625 struct bpf_verifier_state *vparent)
16627 struct bpf_reg_state *state_reg, *parent_reg;
16628 struct bpf_func_state *state, *parent;
16629 int i, frame, err = 0;
16631 if (vparent->curframe != vstate->curframe) {
16632 WARN(1, "propagate_live: parent frame %d current frame %d\n",
16633 vparent->curframe, vstate->curframe);
16636 /* Propagate read liveness of registers... */
16637 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16638 for (frame = 0; frame <= vstate->curframe; frame++) {
16639 parent = vparent->frame[frame];
16640 state = vstate->frame[frame];
16641 parent_reg = parent->regs;
16642 state_reg = state->regs;
16643 /* We don't need to worry about FP liveness, it's read-only */
16644 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16645 err = propagate_liveness_reg(env, &state_reg[i],
16649 if (err == REG_LIVE_READ64)
16650 mark_insn_zext(env, &parent_reg[i]);
16653 /* Propagate stack slots. */
16654 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16655 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16656 parent_reg = &parent->stack[i].spilled_ptr;
16657 state_reg = &state->stack[i].spilled_ptr;
16658 err = propagate_liveness_reg(env, state_reg,
16667 /* find precise scalars in the previous equivalent state and
16668 * propagate them into the current state
16670 static int propagate_precision(struct bpf_verifier_env *env,
16671 const struct bpf_verifier_state *old)
16673 struct bpf_reg_state *state_reg;
16674 struct bpf_func_state *state;
16675 int i, err = 0, fr;
16678 for (fr = old->curframe; fr >= 0; fr--) {
16679 state = old->frame[fr];
16680 state_reg = state->regs;
16682 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16683 if (state_reg->type != SCALAR_VALUE ||
16684 !state_reg->precise ||
16685 !(state_reg->live & REG_LIVE_READ))
16687 if (env->log.level & BPF_LOG_LEVEL2) {
16689 verbose(env, "frame %d: propagating r%d", fr, i);
16691 verbose(env, ",r%d", i);
16693 bt_set_frame_reg(&env->bt, fr, i);
16697 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16698 if (!is_spilled_reg(&state->stack[i]))
16700 state_reg = &state->stack[i].spilled_ptr;
16701 if (state_reg->type != SCALAR_VALUE ||
16702 !state_reg->precise ||
16703 !(state_reg->live & REG_LIVE_READ))
16705 if (env->log.level & BPF_LOG_LEVEL2) {
16707 verbose(env, "frame %d: propagating fp%d",
16708 fr, (-i - 1) * BPF_REG_SIZE);
16710 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16712 bt_set_frame_slot(&env->bt, fr, i);
16716 verbose(env, "\n");
16719 err = mark_chain_precision_batch(env);
16726 static bool states_maybe_looping(struct bpf_verifier_state *old,
16727 struct bpf_verifier_state *cur)
16729 struct bpf_func_state *fold, *fcur;
16730 int i, fr = cur->curframe;
16732 if (old->curframe != fr)
16735 fold = old->frame[fr];
16736 fcur = cur->frame[fr];
16737 for (i = 0; i < MAX_BPF_REG; i++)
16738 if (memcmp(&fold->regs[i], &fcur->regs[i],
16739 offsetof(struct bpf_reg_state, parent)))
16744 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16746 return env->insn_aux_data[insn_idx].is_iter_next;
16749 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16750 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16751 * states to match, which otherwise would look like an infinite loop. So while
16752 * iter_next() calls are taken care of, we still need to be careful and
16753 * prevent erroneous and too eager declaration of "ininite loop", when
16754 * iterators are involved.
16756 * Here's a situation in pseudo-BPF assembly form:
16758 * 0: again: ; set up iter_next() call args
16759 * 1: r1 = &it ; <CHECKPOINT HERE>
16760 * 2: call bpf_iter_num_next ; this is iter_next() call
16761 * 3: if r0 == 0 goto done
16762 * 4: ... something useful here ...
16763 * 5: goto again ; another iteration
16766 * 8: call bpf_iter_num_destroy ; clean up iter state
16769 * This is a typical loop. Let's assume that we have a prune point at 1:,
16770 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16771 * again`, assuming other heuristics don't get in a way).
16773 * When we first time come to 1:, let's say we have some state X. We proceed
16774 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16775 * Now we come back to validate that forked ACTIVE state. We proceed through
16776 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16777 * are converging. But the problem is that we don't know that yet, as this
16778 * convergence has to happen at iter_next() call site only. So if nothing is
16779 * done, at 1: verifier will use bounded loop logic and declare infinite
16780 * looping (and would be *technically* correct, if not for iterator's
16781 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16782 * don't want that. So what we do in process_iter_next_call() when we go on
16783 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16784 * a different iteration. So when we suspect an infinite loop, we additionally
16785 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16786 * pretend we are not looping and wait for next iter_next() call.
16788 * This only applies to ACTIVE state. In DRAINED state we don't expect to
16789 * loop, because that would actually mean infinite loop, as DRAINED state is
16790 * "sticky", and so we'll keep returning into the same instruction with the
16791 * same state (at least in one of possible code paths).
16793 * This approach allows to keep infinite loop heuristic even in the face of
16794 * active iterator. E.g., C snippet below is and will be detected as
16795 * inifintely looping:
16797 * struct bpf_iter_num it;
16800 * bpf_iter_num_new(&it, 0, 10);
16801 * while ((p = bpf_iter_num_next(&t))) {
16803 * while (x--) {} // <<-- infinite loop here
16807 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16809 struct bpf_reg_state *slot, *cur_slot;
16810 struct bpf_func_state *state;
16813 for (fr = old->curframe; fr >= 0; fr--) {
16814 state = old->frame[fr];
16815 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16816 if (state->stack[i].slot_type[0] != STACK_ITER)
16819 slot = &state->stack[i].spilled_ptr;
16820 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16823 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16824 if (cur_slot->iter.depth != slot->iter.depth)
16831 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16833 struct bpf_verifier_state_list *new_sl;
16834 struct bpf_verifier_state_list *sl, **pprev;
16835 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16836 int i, j, n, err, states_cnt = 0;
16837 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16838 bool add_new_state = force_new_state;
16841 /* bpf progs typically have pruning point every 4 instructions
16842 * http://vger.kernel.org/bpfconf2019.html#session-1
16843 * Do not add new state for future pruning if the verifier hasn't seen
16844 * at least 2 jumps and at least 8 instructions.
16845 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16846 * In tests that amounts to up to 50% reduction into total verifier
16847 * memory consumption and 20% verifier time speedup.
16849 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16850 env->insn_processed - env->prev_insn_processed >= 8)
16851 add_new_state = true;
16853 pprev = explored_state(env, insn_idx);
16856 clean_live_states(env, insn_idx, cur);
16860 if (sl->state.insn_idx != insn_idx)
16863 if (sl->state.branches) {
16864 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16866 if (frame->in_async_callback_fn &&
16867 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16868 /* Different async_entry_cnt means that the verifier is
16869 * processing another entry into async callback.
16870 * Seeing the same state is not an indication of infinite
16871 * loop or infinite recursion.
16872 * But finding the same state doesn't mean that it's safe
16873 * to stop processing the current state. The previous state
16874 * hasn't yet reached bpf_exit, since state.branches > 0.
16875 * Checking in_async_callback_fn alone is not enough either.
16876 * Since the verifier still needs to catch infinite loops
16877 * inside async callbacks.
16879 goto skip_inf_loop_check;
16881 /* BPF open-coded iterators loop detection is special.
16882 * states_maybe_looping() logic is too simplistic in detecting
16883 * states that *might* be equivalent, because it doesn't know
16884 * about ID remapping, so don't even perform it.
16885 * See process_iter_next_call() and iter_active_depths_differ()
16886 * for overview of the logic. When current and one of parent
16887 * states are detected as equivalent, it's a good thing: we prove
16888 * convergence and can stop simulating further iterations.
16889 * It's safe to assume that iterator loop will finish, taking into
16890 * account iter_next() contract of eventually returning
16891 * sticky NULL result.
16893 * Note, that states have to be compared exactly in this case because
16894 * read and precision marks might not be finalized inside the loop.
16895 * E.g. as in the program below:
16898 * 2. r6 = bpf_get_prandom_u32()
16899 * 3. while (bpf_iter_num_next(&fp[-8])) {
16900 * 4. if (r6 != 42) {
16902 * 6. r6 = bpf_get_prandom_u32()
16907 * 11. r8 = *(u64 *)(r0 + 0)
16908 * 12. r6 = bpf_get_prandom_u32()
16911 * Here verifier would first visit path 1-3, create a checkpoint at 3
16912 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16913 * not have read or precision mark for r7 yet, thus inexact states
16914 * comparison would discard current state with r7=-32
16915 * => unsafe memory access at 11 would not be caught.
16917 if (is_iter_next_insn(env, insn_idx)) {
16918 if (states_equal(env, &sl->state, cur, true)) {
16919 struct bpf_func_state *cur_frame;
16920 struct bpf_reg_state *iter_state, *iter_reg;
16923 cur_frame = cur->frame[cur->curframe];
16924 /* btf_check_iter_kfuncs() enforces that
16925 * iter state pointer is always the first arg
16927 iter_reg = &cur_frame->regs[BPF_REG_1];
16928 /* current state is valid due to states_equal(),
16929 * so we can assume valid iter and reg state,
16930 * no need for extra (re-)validations
16932 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16933 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16934 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16935 update_loop_entry(cur, &sl->state);
16939 goto skip_inf_loop_check;
16941 /* attempt to detect infinite loop to avoid unnecessary doomed work */
16942 if (states_maybe_looping(&sl->state, cur) &&
16943 states_equal(env, &sl->state, cur, false) &&
16944 !iter_active_depths_differ(&sl->state, cur)) {
16945 verbose_linfo(env, insn_idx, "; ");
16946 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16947 verbose(env, "cur state:");
16948 print_verifier_state(env, cur->frame[cur->curframe], true);
16949 verbose(env, "old state:");
16950 print_verifier_state(env, sl->state.frame[cur->curframe], true);
16953 /* if the verifier is processing a loop, avoid adding new state
16954 * too often, since different loop iterations have distinct
16955 * states and may not help future pruning.
16956 * This threshold shouldn't be too low to make sure that
16957 * a loop with large bound will be rejected quickly.
16958 * The most abusive loop will be:
16960 * if r1 < 1000000 goto pc-2
16961 * 1M insn_procssed limit / 100 == 10k peak states.
16962 * This threshold shouldn't be too high either, since states
16963 * at the end of the loop are likely to be useful in pruning.
16965 skip_inf_loop_check:
16966 if (!force_new_state &&
16967 env->jmps_processed - env->prev_jmps_processed < 20 &&
16968 env->insn_processed - env->prev_insn_processed < 100)
16969 add_new_state = false;
16972 /* If sl->state is a part of a loop and this loop's entry is a part of
16973 * current verification path then states have to be compared exactly.
16974 * 'force_exact' is needed to catch the following case:
16976 * initial Here state 'succ' was processed first,
16977 * | it was eventually tracked to produce a
16978 * V state identical to 'hdr'.
16979 * .---------> hdr All branches from 'succ' had been explored
16980 * | | and thus 'succ' has its .branches == 0.
16982 * | .------... Suppose states 'cur' and 'succ' correspond
16983 * | | | to the same instruction + callsites.
16984 * | V V In such case it is necessary to check
16985 * | ... ... if 'succ' and 'cur' are states_equal().
16986 * | | | If 'succ' and 'cur' are a part of the
16987 * | V V same loop exact flag has to be set.
16988 * | succ <- cur To check if that is the case, verify
16989 * | | if loop entry of 'succ' is in current
16995 * Additional details are in the comment before get_loop_entry().
16997 loop_entry = get_loop_entry(&sl->state);
16998 force_exact = loop_entry && loop_entry->branches > 0;
16999 if (states_equal(env, &sl->state, cur, force_exact)) {
17001 update_loop_entry(cur, loop_entry);
17004 /* reached equivalent register/stack state,
17005 * prune the search.
17006 * Registers read by the continuation are read by us.
17007 * If we have any write marks in env->cur_state, they
17008 * will prevent corresponding reads in the continuation
17009 * from reaching our parent (an explored_state). Our
17010 * own state will get the read marks recorded, but
17011 * they'll be immediately forgotten as we're pruning
17012 * this state and will pop a new one.
17014 err = propagate_liveness(env, &sl->state, cur);
17016 /* if previous state reached the exit with precision and
17017 * current state is equivalent to it (except precsion marks)
17018 * the precision needs to be propagated back in
17019 * the current state.
17021 err = err ? : push_jmp_history(env, cur);
17022 err = err ? : propagate_precision(env, &sl->state);
17028 /* when new state is not going to be added do not increase miss count.
17029 * Otherwise several loop iterations will remove the state
17030 * recorded earlier. The goal of these heuristics is to have
17031 * states from some iterations of the loop (some in the beginning
17032 * and some at the end) to help pruning.
17036 /* heuristic to determine whether this state is beneficial
17037 * to keep checking from state equivalence point of view.
17038 * Higher numbers increase max_states_per_insn and verification time,
17039 * but do not meaningfully decrease insn_processed.
17040 * 'n' controls how many times state could miss before eviction.
17041 * Use bigger 'n' for checkpoints because evicting checkpoint states
17042 * too early would hinder iterator convergence.
17044 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17045 if (sl->miss_cnt > sl->hit_cnt * n + n) {
17046 /* the state is unlikely to be useful. Remove it to
17047 * speed up verification
17050 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17051 !sl->state.used_as_loop_entry) {
17052 u32 br = sl->state.branches;
17055 "BUG live_done but branches_to_explore %d\n",
17057 free_verifier_state(&sl->state, false);
17059 env->peak_states--;
17061 /* cannot free this state, since parentage chain may
17062 * walk it later. Add it for free_list instead to
17063 * be freed at the end of verification
17065 sl->next = env->free_list;
17066 env->free_list = sl;
17076 if (env->max_states_per_insn < states_cnt)
17077 env->max_states_per_insn = states_cnt;
17079 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17082 if (!add_new_state)
17085 /* There were no equivalent states, remember the current one.
17086 * Technically the current state is not proven to be safe yet,
17087 * but it will either reach outer most bpf_exit (which means it's safe)
17088 * or it will be rejected. When there are no loops the verifier won't be
17089 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17090 * again on the way to bpf_exit.
17091 * When looping the sl->state.branches will be > 0 and this state
17092 * will not be considered for equivalence until branches == 0.
17094 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17097 env->total_states++;
17098 env->peak_states++;
17099 env->prev_jmps_processed = env->jmps_processed;
17100 env->prev_insn_processed = env->insn_processed;
17102 /* forget precise markings we inherited, see __mark_chain_precision */
17103 if (env->bpf_capable)
17104 mark_all_scalars_imprecise(env, cur);
17106 /* add new state to the head of linked list */
17107 new = &new_sl->state;
17108 err = copy_verifier_state(new, cur);
17110 free_verifier_state(new, false);
17114 new->insn_idx = insn_idx;
17115 WARN_ONCE(new->branches != 1,
17116 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17119 cur->first_insn_idx = insn_idx;
17120 cur->dfs_depth = new->dfs_depth + 1;
17121 clear_jmp_history(cur);
17122 new_sl->next = *explored_state(env, insn_idx);
17123 *explored_state(env, insn_idx) = new_sl;
17124 /* connect new state to parentage chain. Current frame needs all
17125 * registers connected. Only r6 - r9 of the callers are alive (pushed
17126 * to the stack implicitly by JITs) so in callers' frames connect just
17127 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17128 * the state of the call instruction (with WRITTEN set), and r0 comes
17129 * from callee with its full parentage chain, anyway.
17131 /* clear write marks in current state: the writes we did are not writes
17132 * our child did, so they don't screen off its reads from us.
17133 * (There are no read marks in current state, because reads always mark
17134 * their parent and current state never has children yet. Only
17135 * explored_states can get read marks.)
17137 for (j = 0; j <= cur->curframe; j++) {
17138 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17139 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17140 for (i = 0; i < BPF_REG_FP; i++)
17141 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17144 /* all stack frames are accessible from callee, clear them all */
17145 for (j = 0; j <= cur->curframe; j++) {
17146 struct bpf_func_state *frame = cur->frame[j];
17147 struct bpf_func_state *newframe = new->frame[j];
17149 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17150 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17151 frame->stack[i].spilled_ptr.parent =
17152 &newframe->stack[i].spilled_ptr;
17158 /* Return true if it's OK to have the same insn return a different type. */
17159 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17161 switch (base_type(type)) {
17163 case PTR_TO_SOCKET:
17164 case PTR_TO_SOCK_COMMON:
17165 case PTR_TO_TCP_SOCK:
17166 case PTR_TO_XDP_SOCK:
17167 case PTR_TO_BTF_ID:
17174 /* If an instruction was previously used with particular pointer types, then we
17175 * need to be careful to avoid cases such as the below, where it may be ok
17176 * for one branch accessing the pointer, but not ok for the other branch:
17181 * R1 = some_other_valid_ptr;
17184 * R2 = *(u32 *)(R1 + 0);
17186 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17188 return src != prev && (!reg_type_mismatch_ok(src) ||
17189 !reg_type_mismatch_ok(prev));
17192 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17193 bool allow_trust_missmatch)
17195 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17197 if (*prev_type == NOT_INIT) {
17198 /* Saw a valid insn
17199 * dst_reg = *(u32 *)(src_reg + off)
17200 * save type to validate intersecting paths
17203 } else if (reg_type_mismatch(type, *prev_type)) {
17204 /* Abuser program is trying to use the same insn
17205 * dst_reg = *(u32*) (src_reg + off)
17206 * with different pointer types:
17207 * src_reg == ctx in one branch and
17208 * src_reg == stack|map in some other branch.
17211 if (allow_trust_missmatch &&
17212 base_type(type) == PTR_TO_BTF_ID &&
17213 base_type(*prev_type) == PTR_TO_BTF_ID) {
17215 * Have to support a use case when one path through
17216 * the program yields TRUSTED pointer while another
17217 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17218 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17220 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17222 verbose(env, "same insn cannot be used with different pointers\n");
17230 static int do_check(struct bpf_verifier_env *env)
17232 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17233 struct bpf_verifier_state *state = env->cur_state;
17234 struct bpf_insn *insns = env->prog->insnsi;
17235 struct bpf_reg_state *regs;
17236 int insn_cnt = env->prog->len;
17237 bool do_print_state = false;
17238 int prev_insn_idx = -1;
17241 bool exception_exit = false;
17242 struct bpf_insn *insn;
17246 env->prev_insn_idx = prev_insn_idx;
17247 if (env->insn_idx >= insn_cnt) {
17248 verbose(env, "invalid insn idx %d insn_cnt %d\n",
17249 env->insn_idx, insn_cnt);
17253 insn = &insns[env->insn_idx];
17254 class = BPF_CLASS(insn->code);
17256 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17258 "BPF program is too large. Processed %d insn\n",
17259 env->insn_processed);
17263 state->last_insn_idx = env->prev_insn_idx;
17265 if (is_prune_point(env, env->insn_idx)) {
17266 err = is_state_visited(env, env->insn_idx);
17270 /* found equivalent state, can prune the search */
17271 if (env->log.level & BPF_LOG_LEVEL) {
17272 if (do_print_state)
17273 verbose(env, "\nfrom %d to %d%s: safe\n",
17274 env->prev_insn_idx, env->insn_idx,
17275 env->cur_state->speculative ?
17276 " (speculative execution)" : "");
17278 verbose(env, "%d: safe\n", env->insn_idx);
17280 goto process_bpf_exit;
17284 if (is_jmp_point(env, env->insn_idx)) {
17285 err = push_jmp_history(env, state);
17290 if (signal_pending(current))
17293 if (need_resched())
17296 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17297 verbose(env, "\nfrom %d to %d%s:",
17298 env->prev_insn_idx, env->insn_idx,
17299 env->cur_state->speculative ?
17300 " (speculative execution)" : "");
17301 print_verifier_state(env, state->frame[state->curframe], true);
17302 do_print_state = false;
17305 if (env->log.level & BPF_LOG_LEVEL) {
17306 const struct bpf_insn_cbs cbs = {
17307 .cb_call = disasm_kfunc_name,
17308 .cb_print = verbose,
17309 .private_data = env,
17312 if (verifier_state_scratched(env))
17313 print_insn_state(env, state->frame[state->curframe]);
17315 verbose_linfo(env, env->insn_idx, "; ");
17316 env->prev_log_pos = env->log.end_pos;
17317 verbose(env, "%d: ", env->insn_idx);
17318 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17319 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17320 env->prev_log_pos = env->log.end_pos;
17323 if (bpf_prog_is_offloaded(env->prog->aux)) {
17324 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17325 env->prev_insn_idx);
17330 regs = cur_regs(env);
17331 sanitize_mark_insn_seen(env);
17332 prev_insn_idx = env->insn_idx;
17334 if (class == BPF_ALU || class == BPF_ALU64) {
17335 err = check_alu_op(env, insn);
17339 } else if (class == BPF_LDX) {
17340 enum bpf_reg_type src_reg_type;
17342 /* check for reserved fields is already done */
17344 /* check src operand */
17345 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17349 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17353 src_reg_type = regs[insn->src_reg].type;
17355 /* check that memory (src_reg + off) is readable,
17356 * the state of dst_reg will be updated by this func
17358 err = check_mem_access(env, env->insn_idx, insn->src_reg,
17359 insn->off, BPF_SIZE(insn->code),
17360 BPF_READ, insn->dst_reg, false,
17361 BPF_MODE(insn->code) == BPF_MEMSX);
17365 err = save_aux_ptr_type(env, src_reg_type, true);
17368 } else if (class == BPF_STX) {
17369 enum bpf_reg_type dst_reg_type;
17371 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17372 err = check_atomic(env, env->insn_idx, insn);
17379 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17380 verbose(env, "BPF_STX uses reserved fields\n");
17384 /* check src1 operand */
17385 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17388 /* check src2 operand */
17389 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17393 dst_reg_type = regs[insn->dst_reg].type;
17395 /* check that memory (dst_reg + off) is writeable */
17396 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17397 insn->off, BPF_SIZE(insn->code),
17398 BPF_WRITE, insn->src_reg, false, false);
17402 err = save_aux_ptr_type(env, dst_reg_type, false);
17405 } else if (class == BPF_ST) {
17406 enum bpf_reg_type dst_reg_type;
17408 if (BPF_MODE(insn->code) != BPF_MEM ||
17409 insn->src_reg != BPF_REG_0) {
17410 verbose(env, "BPF_ST uses reserved fields\n");
17413 /* check src operand */
17414 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17418 dst_reg_type = regs[insn->dst_reg].type;
17420 /* check that memory (dst_reg + off) is writeable */
17421 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17422 insn->off, BPF_SIZE(insn->code),
17423 BPF_WRITE, -1, false, false);
17427 err = save_aux_ptr_type(env, dst_reg_type, false);
17430 } else if (class == BPF_JMP || class == BPF_JMP32) {
17431 u8 opcode = BPF_OP(insn->code);
17433 env->jmps_processed++;
17434 if (opcode == BPF_CALL) {
17435 if (BPF_SRC(insn->code) != BPF_K ||
17436 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17437 && insn->off != 0) ||
17438 (insn->src_reg != BPF_REG_0 &&
17439 insn->src_reg != BPF_PSEUDO_CALL &&
17440 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17441 insn->dst_reg != BPF_REG_0 ||
17442 class == BPF_JMP32) {
17443 verbose(env, "BPF_CALL uses reserved fields\n");
17447 if (env->cur_state->active_lock.ptr) {
17448 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17449 (insn->src_reg == BPF_PSEUDO_CALL) ||
17450 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17451 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17452 verbose(env, "function calls are not allowed while holding a lock\n");
17456 if (insn->src_reg == BPF_PSEUDO_CALL) {
17457 err = check_func_call(env, insn, &env->insn_idx);
17458 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17459 err = check_kfunc_call(env, insn, &env->insn_idx);
17460 if (!err && is_bpf_throw_kfunc(insn)) {
17461 exception_exit = true;
17462 goto process_bpf_exit_full;
17465 err = check_helper_call(env, insn, &env->insn_idx);
17470 mark_reg_scratched(env, BPF_REG_0);
17471 } else if (opcode == BPF_JA) {
17472 if (BPF_SRC(insn->code) != BPF_K ||
17473 insn->src_reg != BPF_REG_0 ||
17474 insn->dst_reg != BPF_REG_0 ||
17475 (class == BPF_JMP && insn->imm != 0) ||
17476 (class == BPF_JMP32 && insn->off != 0)) {
17477 verbose(env, "BPF_JA uses reserved fields\n");
17481 if (class == BPF_JMP)
17482 env->insn_idx += insn->off + 1;
17484 env->insn_idx += insn->imm + 1;
17487 } else if (opcode == BPF_EXIT) {
17488 if (BPF_SRC(insn->code) != BPF_K ||
17490 insn->src_reg != BPF_REG_0 ||
17491 insn->dst_reg != BPF_REG_0 ||
17492 class == BPF_JMP32) {
17493 verbose(env, "BPF_EXIT uses reserved fields\n");
17496 process_bpf_exit_full:
17497 if (env->cur_state->active_lock.ptr &&
17498 !in_rbtree_lock_required_cb(env)) {
17499 verbose(env, "bpf_spin_unlock is missing\n");
17503 if (env->cur_state->active_rcu_lock &&
17504 !in_rbtree_lock_required_cb(env)) {
17505 verbose(env, "bpf_rcu_read_unlock is missing\n");
17509 /* We must do check_reference_leak here before
17510 * prepare_func_exit to handle the case when
17511 * state->curframe > 0, it may be a callback
17512 * function, for which reference_state must
17513 * match caller reference state when it exits.
17515 err = check_reference_leak(env, exception_exit);
17519 /* The side effect of the prepare_func_exit
17520 * which is being skipped is that it frees
17521 * bpf_func_state. Typically, process_bpf_exit
17522 * will only be hit with outermost exit.
17523 * copy_verifier_state in pop_stack will handle
17524 * freeing of any extra bpf_func_state left over
17525 * from not processing all nested function
17526 * exits. We also skip return code checks as
17527 * they are not needed for exceptional exits.
17529 if (exception_exit)
17530 goto process_bpf_exit;
17532 if (state->curframe) {
17533 /* exit from nested function */
17534 err = prepare_func_exit(env, &env->insn_idx);
17537 do_print_state = true;
17541 err = check_return_code(env, BPF_REG_0);
17545 mark_verifier_state_scratched(env);
17546 update_branch_counts(env, env->cur_state);
17547 err = pop_stack(env, &prev_insn_idx,
17548 &env->insn_idx, pop_log);
17550 if (err != -ENOENT)
17554 do_print_state = true;
17558 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17562 } else if (class == BPF_LD) {
17563 u8 mode = BPF_MODE(insn->code);
17565 if (mode == BPF_ABS || mode == BPF_IND) {
17566 err = check_ld_abs(env, insn);
17570 } else if (mode == BPF_IMM) {
17571 err = check_ld_imm(env, insn);
17576 sanitize_mark_insn_seen(env);
17578 verbose(env, "invalid BPF_LD mode\n");
17582 verbose(env, "unknown insn class %d\n", class);
17592 static int find_btf_percpu_datasec(struct btf *btf)
17594 const struct btf_type *t;
17599 * Both vmlinux and module each have their own ".data..percpu"
17600 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17601 * types to look at only module's own BTF types.
17603 n = btf_nr_types(btf);
17604 if (btf_is_module(btf))
17605 i = btf_nr_types(btf_vmlinux);
17609 for(; i < n; i++) {
17610 t = btf_type_by_id(btf, i);
17611 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17614 tname = btf_name_by_offset(btf, t->name_off);
17615 if (!strcmp(tname, ".data..percpu"))
17622 /* replace pseudo btf_id with kernel symbol address */
17623 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17624 struct bpf_insn *insn,
17625 struct bpf_insn_aux_data *aux)
17627 const struct btf_var_secinfo *vsi;
17628 const struct btf_type *datasec;
17629 struct btf_mod_pair *btf_mod;
17630 const struct btf_type *t;
17631 const char *sym_name;
17632 bool percpu = false;
17633 u32 type, id = insn->imm;
17637 int i, btf_fd, err;
17639 btf_fd = insn[1].imm;
17641 btf = btf_get_by_fd(btf_fd);
17643 verbose(env, "invalid module BTF object FD specified.\n");
17647 if (!btf_vmlinux) {
17648 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17655 t = btf_type_by_id(btf, id);
17657 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17662 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17663 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17668 sym_name = btf_name_by_offset(btf, t->name_off);
17669 addr = kallsyms_lookup_name(sym_name);
17671 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17676 insn[0].imm = (u32)addr;
17677 insn[1].imm = addr >> 32;
17679 if (btf_type_is_func(t)) {
17680 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17681 aux->btf_var.mem_size = 0;
17685 datasec_id = find_btf_percpu_datasec(btf);
17686 if (datasec_id > 0) {
17687 datasec = btf_type_by_id(btf, datasec_id);
17688 for_each_vsi(i, datasec, vsi) {
17689 if (vsi->type == id) {
17697 t = btf_type_skip_modifiers(btf, type, NULL);
17699 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17700 aux->btf_var.btf = btf;
17701 aux->btf_var.btf_id = type;
17702 } else if (!btf_type_is_struct(t)) {
17703 const struct btf_type *ret;
17707 /* resolve the type size of ksym. */
17708 ret = btf_resolve_size(btf, t, &tsize);
17710 tname = btf_name_by_offset(btf, t->name_off);
17711 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17712 tname, PTR_ERR(ret));
17716 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17717 aux->btf_var.mem_size = tsize;
17719 aux->btf_var.reg_type = PTR_TO_BTF_ID;
17720 aux->btf_var.btf = btf;
17721 aux->btf_var.btf_id = type;
17724 /* check whether we recorded this BTF (and maybe module) already */
17725 for (i = 0; i < env->used_btf_cnt; i++) {
17726 if (env->used_btfs[i].btf == btf) {
17732 if (env->used_btf_cnt >= MAX_USED_BTFS) {
17737 btf_mod = &env->used_btfs[env->used_btf_cnt];
17738 btf_mod->btf = btf;
17739 btf_mod->module = NULL;
17741 /* if we reference variables from kernel module, bump its refcount */
17742 if (btf_is_module(btf)) {
17743 btf_mod->module = btf_try_get_module(btf);
17744 if (!btf_mod->module) {
17750 env->used_btf_cnt++;
17758 static bool is_tracing_prog_type(enum bpf_prog_type type)
17761 case BPF_PROG_TYPE_KPROBE:
17762 case BPF_PROG_TYPE_TRACEPOINT:
17763 case BPF_PROG_TYPE_PERF_EVENT:
17764 case BPF_PROG_TYPE_RAW_TRACEPOINT:
17765 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17772 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17773 struct bpf_map *map,
17774 struct bpf_prog *prog)
17777 enum bpf_prog_type prog_type = resolve_prog_type(prog);
17779 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17780 btf_record_has_field(map->record, BPF_RB_ROOT)) {
17781 if (is_tracing_prog_type(prog_type)) {
17782 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17787 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17788 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17789 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17793 if (is_tracing_prog_type(prog_type)) {
17794 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17799 if (btf_record_has_field(map->record, BPF_TIMER)) {
17800 if (is_tracing_prog_type(prog_type)) {
17801 verbose(env, "tracing progs cannot use bpf_timer yet\n");
17806 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17807 !bpf_offload_prog_map_match(prog, map)) {
17808 verbose(env, "offload device mismatch between prog and map\n");
17812 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17813 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17817 if (prog->aux->sleepable)
17818 switch (map->map_type) {
17819 case BPF_MAP_TYPE_HASH:
17820 case BPF_MAP_TYPE_LRU_HASH:
17821 case BPF_MAP_TYPE_ARRAY:
17822 case BPF_MAP_TYPE_PERCPU_HASH:
17823 case BPF_MAP_TYPE_PERCPU_ARRAY:
17824 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17825 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17826 case BPF_MAP_TYPE_HASH_OF_MAPS:
17827 case BPF_MAP_TYPE_RINGBUF:
17828 case BPF_MAP_TYPE_USER_RINGBUF:
17829 case BPF_MAP_TYPE_INODE_STORAGE:
17830 case BPF_MAP_TYPE_SK_STORAGE:
17831 case BPF_MAP_TYPE_TASK_STORAGE:
17832 case BPF_MAP_TYPE_CGRP_STORAGE:
17836 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17843 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17845 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17846 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17849 /* find and rewrite pseudo imm in ld_imm64 instructions:
17851 * 1. if it accesses map FD, replace it with actual map pointer.
17852 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17854 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17856 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17858 struct bpf_insn *insn = env->prog->insnsi;
17859 int insn_cnt = env->prog->len;
17862 err = bpf_prog_calc_tag(env->prog);
17866 for (i = 0; i < insn_cnt; i++, insn++) {
17867 if (BPF_CLASS(insn->code) == BPF_LDX &&
17868 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17870 verbose(env, "BPF_LDX uses reserved fields\n");
17874 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17875 struct bpf_insn_aux_data *aux;
17876 struct bpf_map *map;
17881 if (i == insn_cnt - 1 || insn[1].code != 0 ||
17882 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17883 insn[1].off != 0) {
17884 verbose(env, "invalid bpf_ld_imm64 insn\n");
17888 if (insn[0].src_reg == 0)
17889 /* valid generic load 64-bit imm */
17892 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17893 aux = &env->insn_aux_data[i];
17894 err = check_pseudo_btf_id(env, insn, aux);
17900 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17901 aux = &env->insn_aux_data[i];
17902 aux->ptr_type = PTR_TO_FUNC;
17906 /* In final convert_pseudo_ld_imm64() step, this is
17907 * converted into regular 64-bit imm load insn.
17909 switch (insn[0].src_reg) {
17910 case BPF_PSEUDO_MAP_VALUE:
17911 case BPF_PSEUDO_MAP_IDX_VALUE:
17913 case BPF_PSEUDO_MAP_FD:
17914 case BPF_PSEUDO_MAP_IDX:
17915 if (insn[1].imm == 0)
17919 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17923 switch (insn[0].src_reg) {
17924 case BPF_PSEUDO_MAP_IDX_VALUE:
17925 case BPF_PSEUDO_MAP_IDX:
17926 if (bpfptr_is_null(env->fd_array)) {
17927 verbose(env, "fd_idx without fd_array is invalid\n");
17930 if (copy_from_bpfptr_offset(&fd, env->fd_array,
17931 insn[0].imm * sizeof(fd),
17941 map = __bpf_map_get(f);
17943 verbose(env, "fd %d is not pointing to valid bpf_map\n",
17945 return PTR_ERR(map);
17948 err = check_map_prog_compatibility(env, map, env->prog);
17954 aux = &env->insn_aux_data[i];
17955 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17956 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17957 addr = (unsigned long)map;
17959 u32 off = insn[1].imm;
17961 if (off >= BPF_MAX_VAR_OFF) {
17962 verbose(env, "direct value offset of %u is not allowed\n", off);
17967 if (!map->ops->map_direct_value_addr) {
17968 verbose(env, "no direct value access support for this map type\n");
17973 err = map->ops->map_direct_value_addr(map, &addr, off);
17975 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17976 map->value_size, off);
17981 aux->map_off = off;
17985 insn[0].imm = (u32)addr;
17986 insn[1].imm = addr >> 32;
17988 /* check whether we recorded this map already */
17989 for (j = 0; j < env->used_map_cnt; j++) {
17990 if (env->used_maps[j] == map) {
17991 aux->map_index = j;
17997 if (env->used_map_cnt >= MAX_USED_MAPS) {
18002 /* hold the map. If the program is rejected by verifier,
18003 * the map will be released by release_maps() or it
18004 * will be used by the valid program until it's unloaded
18005 * and all maps are released in free_used_maps()
18009 aux->map_index = env->used_map_cnt;
18010 env->used_maps[env->used_map_cnt++] = map;
18012 if (bpf_map_is_cgroup_storage(map) &&
18013 bpf_cgroup_storage_assign(env->prog->aux, map)) {
18014 verbose(env, "only one cgroup storage of each type is allowed\n");
18026 /* Basic sanity check before we invest more work here. */
18027 if (!bpf_opcode_in_insntable(insn->code)) {
18028 verbose(env, "unknown opcode %02x\n", insn->code);
18033 /* now all pseudo BPF_LD_IMM64 instructions load valid
18034 * 'struct bpf_map *' into a register instead of user map_fd.
18035 * These pointers will be used later by verifier to validate map access.
18040 /* drop refcnt of maps used by the rejected program */
18041 static void release_maps(struct bpf_verifier_env *env)
18043 __bpf_free_used_maps(env->prog->aux, env->used_maps,
18044 env->used_map_cnt);
18047 /* drop refcnt of maps used by the rejected program */
18048 static void release_btfs(struct bpf_verifier_env *env)
18050 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18051 env->used_btf_cnt);
18054 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18055 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18057 struct bpf_insn *insn = env->prog->insnsi;
18058 int insn_cnt = env->prog->len;
18061 for (i = 0; i < insn_cnt; i++, insn++) {
18062 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18064 if (insn->src_reg == BPF_PSEUDO_FUNC)
18070 /* single env->prog->insni[off] instruction was replaced with the range
18071 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
18072 * [0, off) and [off, end) to new locations, so the patched range stays zero
18074 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18075 struct bpf_insn_aux_data *new_data,
18076 struct bpf_prog *new_prog, u32 off, u32 cnt)
18078 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18079 struct bpf_insn *insn = new_prog->insnsi;
18080 u32 old_seen = old_data[off].seen;
18084 /* aux info at OFF always needs adjustment, no matter fast path
18085 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18086 * original insn at old prog.
18088 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18092 prog_len = new_prog->len;
18094 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18095 memcpy(new_data + off + cnt - 1, old_data + off,
18096 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18097 for (i = off; i < off + cnt - 1; i++) {
18098 /* Expand insni[off]'s seen count to the patched range. */
18099 new_data[i].seen = old_seen;
18100 new_data[i].zext_dst = insn_has_def32(env, insn + i);
18102 env->insn_aux_data = new_data;
18106 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18112 /* NOTE: fake 'exit' subprog should be updated as well. */
18113 for (i = 0; i <= env->subprog_cnt; i++) {
18114 if (env->subprog_info[i].start <= off)
18116 env->subprog_info[i].start += len - 1;
18120 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18122 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18123 int i, sz = prog->aux->size_poke_tab;
18124 struct bpf_jit_poke_descriptor *desc;
18126 for (i = 0; i < sz; i++) {
18128 if (desc->insn_idx <= off)
18130 desc->insn_idx += len - 1;
18134 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18135 const struct bpf_insn *patch, u32 len)
18137 struct bpf_prog *new_prog;
18138 struct bpf_insn_aux_data *new_data = NULL;
18141 new_data = vzalloc(array_size(env->prog->len + len - 1,
18142 sizeof(struct bpf_insn_aux_data)));
18147 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18148 if (IS_ERR(new_prog)) {
18149 if (PTR_ERR(new_prog) == -ERANGE)
18151 "insn %d cannot be patched due to 16-bit range\n",
18152 env->insn_aux_data[off].orig_idx);
18156 adjust_insn_aux_data(env, new_data, new_prog, off, len);
18157 adjust_subprog_starts(env, off, len);
18158 adjust_poke_descs(new_prog, off, len);
18162 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18167 /* find first prog starting at or after off (first to remove) */
18168 for (i = 0; i < env->subprog_cnt; i++)
18169 if (env->subprog_info[i].start >= off)
18171 /* find first prog starting at or after off + cnt (first to stay) */
18172 for (j = i; j < env->subprog_cnt; j++)
18173 if (env->subprog_info[j].start >= off + cnt)
18175 /* if j doesn't start exactly at off + cnt, we are just removing
18176 * the front of previous prog
18178 if (env->subprog_info[j].start != off + cnt)
18182 struct bpf_prog_aux *aux = env->prog->aux;
18185 /* move fake 'exit' subprog as well */
18186 move = env->subprog_cnt + 1 - j;
18188 memmove(env->subprog_info + i,
18189 env->subprog_info + j,
18190 sizeof(*env->subprog_info) * move);
18191 env->subprog_cnt -= j - i;
18193 /* remove func_info */
18194 if (aux->func_info) {
18195 move = aux->func_info_cnt - j;
18197 memmove(aux->func_info + i,
18198 aux->func_info + j,
18199 sizeof(*aux->func_info) * move);
18200 aux->func_info_cnt -= j - i;
18201 /* func_info->insn_off is set after all code rewrites,
18202 * in adjust_btf_func() - no need to adjust
18206 /* convert i from "first prog to remove" to "first to adjust" */
18207 if (env->subprog_info[i].start == off)
18211 /* update fake 'exit' subprog as well */
18212 for (; i <= env->subprog_cnt; i++)
18213 env->subprog_info[i].start -= cnt;
18218 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18221 struct bpf_prog *prog = env->prog;
18222 u32 i, l_off, l_cnt, nr_linfo;
18223 struct bpf_line_info *linfo;
18225 nr_linfo = prog->aux->nr_linfo;
18229 linfo = prog->aux->linfo;
18231 /* find first line info to remove, count lines to be removed */
18232 for (i = 0; i < nr_linfo; i++)
18233 if (linfo[i].insn_off >= off)
18238 for (; i < nr_linfo; i++)
18239 if (linfo[i].insn_off < off + cnt)
18244 /* First live insn doesn't match first live linfo, it needs to "inherit"
18245 * last removed linfo. prog is already modified, so prog->len == off
18246 * means no live instructions after (tail of the program was removed).
18248 if (prog->len != off && l_cnt &&
18249 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18251 linfo[--i].insn_off = off + cnt;
18254 /* remove the line info which refer to the removed instructions */
18256 memmove(linfo + l_off, linfo + i,
18257 sizeof(*linfo) * (nr_linfo - i));
18259 prog->aux->nr_linfo -= l_cnt;
18260 nr_linfo = prog->aux->nr_linfo;
18263 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
18264 for (i = l_off; i < nr_linfo; i++)
18265 linfo[i].insn_off -= cnt;
18267 /* fix up all subprogs (incl. 'exit') which start >= off */
18268 for (i = 0; i <= env->subprog_cnt; i++)
18269 if (env->subprog_info[i].linfo_idx > l_off) {
18270 /* program may have started in the removed region but
18271 * may not be fully removed
18273 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18274 env->subprog_info[i].linfo_idx -= l_cnt;
18276 env->subprog_info[i].linfo_idx = l_off;
18282 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18284 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18285 unsigned int orig_prog_len = env->prog->len;
18288 if (bpf_prog_is_offloaded(env->prog->aux))
18289 bpf_prog_offload_remove_insns(env, off, cnt);
18291 err = bpf_remove_insns(env->prog, off, cnt);
18295 err = adjust_subprog_starts_after_remove(env, off, cnt);
18299 err = bpf_adj_linfo_after_remove(env, off, cnt);
18303 memmove(aux_data + off, aux_data + off + cnt,
18304 sizeof(*aux_data) * (orig_prog_len - off - cnt));
18309 /* The verifier does more data flow analysis than llvm and will not
18310 * explore branches that are dead at run time. Malicious programs can
18311 * have dead code too. Therefore replace all dead at-run-time code
18314 * Just nops are not optimal, e.g. if they would sit at the end of the
18315 * program and through another bug we would manage to jump there, then
18316 * we'd execute beyond program memory otherwise. Returning exception
18317 * code also wouldn't work since we can have subprogs where the dead
18318 * code could be located.
18320 static void sanitize_dead_code(struct bpf_verifier_env *env)
18322 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18323 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18324 struct bpf_insn *insn = env->prog->insnsi;
18325 const int insn_cnt = env->prog->len;
18328 for (i = 0; i < insn_cnt; i++) {
18329 if (aux_data[i].seen)
18331 memcpy(insn + i, &trap, sizeof(trap));
18332 aux_data[i].zext_dst = false;
18336 static bool insn_is_cond_jump(u8 code)
18341 if (BPF_CLASS(code) == BPF_JMP32)
18342 return op != BPF_JA;
18344 if (BPF_CLASS(code) != BPF_JMP)
18347 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18350 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18352 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18353 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18354 struct bpf_insn *insn = env->prog->insnsi;
18355 const int insn_cnt = env->prog->len;
18358 for (i = 0; i < insn_cnt; i++, insn++) {
18359 if (!insn_is_cond_jump(insn->code))
18362 if (!aux_data[i + 1].seen)
18363 ja.off = insn->off;
18364 else if (!aux_data[i + 1 + insn->off].seen)
18369 if (bpf_prog_is_offloaded(env->prog->aux))
18370 bpf_prog_offload_replace_insn(env, i, &ja);
18372 memcpy(insn, &ja, sizeof(ja));
18376 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18378 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18379 int insn_cnt = env->prog->len;
18382 for (i = 0; i < insn_cnt; i++) {
18386 while (i + j < insn_cnt && !aux_data[i + j].seen)
18391 err = verifier_remove_insns(env, i, j);
18394 insn_cnt = env->prog->len;
18400 static int opt_remove_nops(struct bpf_verifier_env *env)
18402 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18403 struct bpf_insn *insn = env->prog->insnsi;
18404 int insn_cnt = env->prog->len;
18407 for (i = 0; i < insn_cnt; i++) {
18408 if (memcmp(&insn[i], &ja, sizeof(ja)))
18411 err = verifier_remove_insns(env, i, 1);
18421 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18422 const union bpf_attr *attr)
18424 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18425 struct bpf_insn_aux_data *aux = env->insn_aux_data;
18426 int i, patch_len, delta = 0, len = env->prog->len;
18427 struct bpf_insn *insns = env->prog->insnsi;
18428 struct bpf_prog *new_prog;
18431 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18432 zext_patch[1] = BPF_ZEXT_REG(0);
18433 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18434 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18435 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18436 for (i = 0; i < len; i++) {
18437 int adj_idx = i + delta;
18438 struct bpf_insn insn;
18441 insn = insns[adj_idx];
18442 load_reg = insn_def_regno(&insn);
18443 if (!aux[adj_idx].zext_dst) {
18451 class = BPF_CLASS(code);
18452 if (load_reg == -1)
18455 /* NOTE: arg "reg" (the fourth one) is only used for
18456 * BPF_STX + SRC_OP, so it is safe to pass NULL
18459 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18460 if (class == BPF_LD &&
18461 BPF_MODE(code) == BPF_IMM)
18466 /* ctx load could be transformed into wider load. */
18467 if (class == BPF_LDX &&
18468 aux[adj_idx].ptr_type == PTR_TO_CTX)
18471 imm_rnd = get_random_u32();
18472 rnd_hi32_patch[0] = insn;
18473 rnd_hi32_patch[1].imm = imm_rnd;
18474 rnd_hi32_patch[3].dst_reg = load_reg;
18475 patch = rnd_hi32_patch;
18477 goto apply_patch_buffer;
18480 /* Add in an zero-extend instruction if a) the JIT has requested
18481 * it or b) it's a CMPXCHG.
18483 * The latter is because: BPF_CMPXCHG always loads a value into
18484 * R0, therefore always zero-extends. However some archs'
18485 * equivalent instruction only does this load when the
18486 * comparison is successful. This detail of CMPXCHG is
18487 * orthogonal to the general zero-extension behaviour of the
18488 * CPU, so it's treated independently of bpf_jit_needs_zext.
18490 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18493 /* Zero-extension is done by the caller. */
18494 if (bpf_pseudo_kfunc_call(&insn))
18497 if (WARN_ON(load_reg == -1)) {
18498 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18502 zext_patch[0] = insn;
18503 zext_patch[1].dst_reg = load_reg;
18504 zext_patch[1].src_reg = load_reg;
18505 patch = zext_patch;
18507 apply_patch_buffer:
18508 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18511 env->prog = new_prog;
18512 insns = new_prog->insnsi;
18513 aux = env->insn_aux_data;
18514 delta += patch_len - 1;
18520 /* convert load instructions that access fields of a context type into a
18521 * sequence of instructions that access fields of the underlying structure:
18522 * struct __sk_buff -> struct sk_buff
18523 * struct bpf_sock_ops -> struct sock
18525 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18527 const struct bpf_verifier_ops *ops = env->ops;
18528 int i, cnt, size, ctx_field_size, delta = 0;
18529 const int insn_cnt = env->prog->len;
18530 struct bpf_insn insn_buf[16], *insn;
18531 u32 target_size, size_default, off;
18532 struct bpf_prog *new_prog;
18533 enum bpf_access_type type;
18534 bool is_narrower_load;
18536 if (ops->gen_prologue || env->seen_direct_write) {
18537 if (!ops->gen_prologue) {
18538 verbose(env, "bpf verifier is misconfigured\n");
18541 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18543 if (cnt >= ARRAY_SIZE(insn_buf)) {
18544 verbose(env, "bpf verifier is misconfigured\n");
18547 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18551 env->prog = new_prog;
18556 if (bpf_prog_is_offloaded(env->prog->aux))
18559 insn = env->prog->insnsi + delta;
18561 for (i = 0; i < insn_cnt; i++, insn++) {
18562 bpf_convert_ctx_access_t convert_ctx_access;
18565 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18566 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18567 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18568 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18569 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18570 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18571 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18573 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18574 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18575 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18576 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18577 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18578 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18579 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18580 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18586 if (type == BPF_WRITE &&
18587 env->insn_aux_data[i + delta].sanitize_stack_spill) {
18588 struct bpf_insn patch[] = {
18593 cnt = ARRAY_SIZE(patch);
18594 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18599 env->prog = new_prog;
18600 insn = new_prog->insnsi + i + delta;
18604 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18606 if (!ops->convert_ctx_access)
18608 convert_ctx_access = ops->convert_ctx_access;
18610 case PTR_TO_SOCKET:
18611 case PTR_TO_SOCK_COMMON:
18612 convert_ctx_access = bpf_sock_convert_ctx_access;
18614 case PTR_TO_TCP_SOCK:
18615 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18617 case PTR_TO_XDP_SOCK:
18618 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18620 case PTR_TO_BTF_ID:
18621 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18622 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18623 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18624 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18625 * any faults for loads into such types. BPF_WRITE is disallowed
18628 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18629 if (type == BPF_READ) {
18630 if (BPF_MODE(insn->code) == BPF_MEM)
18631 insn->code = BPF_LDX | BPF_PROBE_MEM |
18632 BPF_SIZE((insn)->code);
18634 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18635 BPF_SIZE((insn)->code);
18636 env->prog->aux->num_exentries++;
18643 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18644 size = BPF_LDST_BYTES(insn);
18645 mode = BPF_MODE(insn->code);
18647 /* If the read access is a narrower load of the field,
18648 * convert to a 4/8-byte load, to minimum program type specific
18649 * convert_ctx_access changes. If conversion is successful,
18650 * we will apply proper mask to the result.
18652 is_narrower_load = size < ctx_field_size;
18653 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18655 if (is_narrower_load) {
18658 if (type == BPF_WRITE) {
18659 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18664 if (ctx_field_size == 4)
18666 else if (ctx_field_size == 8)
18667 size_code = BPF_DW;
18669 insn->off = off & ~(size_default - 1);
18670 insn->code = BPF_LDX | BPF_MEM | size_code;
18674 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18676 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18677 (ctx_field_size && !target_size)) {
18678 verbose(env, "bpf verifier is misconfigured\n");
18682 if (is_narrower_load && size < target_size) {
18683 u8 shift = bpf_ctx_narrow_access_offset(
18684 off, size, size_default) * 8;
18685 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18686 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18689 if (ctx_field_size <= 4) {
18691 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18694 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18695 (1 << size * 8) - 1);
18698 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18701 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18702 (1ULL << size * 8) - 1);
18705 if (mode == BPF_MEMSX)
18706 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18707 insn->dst_reg, insn->dst_reg,
18710 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18716 /* keep walking new program and skip insns we just inserted */
18717 env->prog = new_prog;
18718 insn = new_prog->insnsi + i + delta;
18724 static int jit_subprogs(struct bpf_verifier_env *env)
18726 struct bpf_prog *prog = env->prog, **func, *tmp;
18727 int i, j, subprog_start, subprog_end = 0, len, subprog;
18728 struct bpf_map *map_ptr;
18729 struct bpf_insn *insn;
18730 void *old_bpf_func;
18731 int err, num_exentries;
18733 if (env->subprog_cnt <= 1)
18736 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18737 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18740 /* Upon error here we cannot fall back to interpreter but
18741 * need a hard reject of the program. Thus -EFAULT is
18742 * propagated in any case.
18744 subprog = find_subprog(env, i + insn->imm + 1);
18746 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18747 i + insn->imm + 1);
18750 /* temporarily remember subprog id inside insn instead of
18751 * aux_data, since next loop will split up all insns into funcs
18753 insn->off = subprog;
18754 /* remember original imm in case JIT fails and fallback
18755 * to interpreter will be needed
18757 env->insn_aux_data[i].call_imm = insn->imm;
18758 /* point imm to __bpf_call_base+1 from JITs point of view */
18760 if (bpf_pseudo_func(insn))
18761 /* jit (e.g. x86_64) may emit fewer instructions
18762 * if it learns a u32 imm is the same as a u64 imm.
18763 * Force a non zero here.
18768 err = bpf_prog_alloc_jited_linfo(prog);
18770 goto out_undo_insn;
18773 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18775 goto out_undo_insn;
18777 for (i = 0; i < env->subprog_cnt; i++) {
18778 subprog_start = subprog_end;
18779 subprog_end = env->subprog_info[i + 1].start;
18781 len = subprog_end - subprog_start;
18782 /* bpf_prog_run() doesn't call subprogs directly,
18783 * hence main prog stats include the runtime of subprogs.
18784 * subprogs don't have IDs and not reachable via prog_get_next_id
18785 * func[i]->stats will never be accessed and stays NULL
18787 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18790 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18791 len * sizeof(struct bpf_insn));
18792 func[i]->type = prog->type;
18793 func[i]->len = len;
18794 if (bpf_prog_calc_tag(func[i]))
18796 func[i]->is_func = 1;
18797 func[i]->aux->func_idx = i;
18798 /* Below members will be freed only at prog->aux */
18799 func[i]->aux->btf = prog->aux->btf;
18800 func[i]->aux->func_info = prog->aux->func_info;
18801 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18802 func[i]->aux->poke_tab = prog->aux->poke_tab;
18803 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18805 for (j = 0; j < prog->aux->size_poke_tab; j++) {
18806 struct bpf_jit_poke_descriptor *poke;
18808 poke = &prog->aux->poke_tab[j];
18809 if (poke->insn_idx < subprog_end &&
18810 poke->insn_idx >= subprog_start)
18811 poke->aux = func[i]->aux;
18814 func[i]->aux->name[0] = 'F';
18815 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18816 func[i]->jit_requested = 1;
18817 func[i]->blinding_requested = prog->blinding_requested;
18818 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18819 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18820 func[i]->aux->linfo = prog->aux->linfo;
18821 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18822 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18823 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18825 insn = func[i]->insnsi;
18826 for (j = 0; j < func[i]->len; j++, insn++) {
18827 if (BPF_CLASS(insn->code) == BPF_LDX &&
18828 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18829 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18832 func[i]->aux->num_exentries = num_exentries;
18833 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18834 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
18836 func[i]->aux->exception_boundary = env->seen_exception;
18837 func[i] = bpf_int_jit_compile(func[i]);
18838 if (!func[i]->jited) {
18845 /* at this point all bpf functions were successfully JITed
18846 * now populate all bpf_calls with correct addresses and
18847 * run last pass of JIT
18849 for (i = 0; i < env->subprog_cnt; i++) {
18850 insn = func[i]->insnsi;
18851 for (j = 0; j < func[i]->len; j++, insn++) {
18852 if (bpf_pseudo_func(insn)) {
18853 subprog = insn->off;
18854 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18855 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18858 if (!bpf_pseudo_call(insn))
18860 subprog = insn->off;
18861 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18864 /* we use the aux data to keep a list of the start addresses
18865 * of the JITed images for each function in the program
18867 * for some architectures, such as powerpc64, the imm field
18868 * might not be large enough to hold the offset of the start
18869 * address of the callee's JITed image from __bpf_call_base
18871 * in such cases, we can lookup the start address of a callee
18872 * by using its subprog id, available from the off field of
18873 * the call instruction, as an index for this list
18875 func[i]->aux->func = func;
18876 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
18877 func[i]->aux->real_func_cnt = env->subprog_cnt;
18879 for (i = 0; i < env->subprog_cnt; i++) {
18880 old_bpf_func = func[i]->bpf_func;
18881 tmp = bpf_int_jit_compile(func[i]);
18882 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18883 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18890 /* finally lock prog and jit images for all functions and
18891 * populate kallsysm. Begin at the first subprogram, since
18892 * bpf_prog_load will add the kallsyms for the main program.
18894 for (i = 1; i < env->subprog_cnt; i++) {
18895 bpf_prog_lock_ro(func[i]);
18896 bpf_prog_kallsyms_add(func[i]);
18899 /* Last step: make now unused interpreter insns from main
18900 * prog consistent for later dump requests, so they can
18901 * later look the same as if they were interpreted only.
18903 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18904 if (bpf_pseudo_func(insn)) {
18905 insn[0].imm = env->insn_aux_data[i].call_imm;
18906 insn[1].imm = insn->off;
18910 if (!bpf_pseudo_call(insn))
18912 insn->off = env->insn_aux_data[i].call_imm;
18913 subprog = find_subprog(env, i + insn->off + 1);
18914 insn->imm = subprog;
18918 prog->bpf_func = func[0]->bpf_func;
18919 prog->jited_len = func[0]->jited_len;
18920 prog->aux->extable = func[0]->aux->extable;
18921 prog->aux->num_exentries = func[0]->aux->num_exentries;
18922 prog->aux->func = func;
18923 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
18924 prog->aux->real_func_cnt = env->subprog_cnt;
18925 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
18926 prog->aux->exception_boundary = func[0]->aux->exception_boundary;
18927 bpf_prog_jit_attempt_done(prog);
18930 /* We failed JIT'ing, so at this point we need to unregister poke
18931 * descriptors from subprogs, so that kernel is not attempting to
18932 * patch it anymore as we're freeing the subprog JIT memory.
18934 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18935 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18936 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18938 /* At this point we're guaranteed that poke descriptors are not
18939 * live anymore. We can just unlink its descriptor table as it's
18940 * released with the main prog.
18942 for (i = 0; i < env->subprog_cnt; i++) {
18945 func[i]->aux->poke_tab = NULL;
18946 bpf_jit_free(func[i]);
18950 /* cleanup main prog to be interpreted */
18951 prog->jit_requested = 0;
18952 prog->blinding_requested = 0;
18953 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18954 if (!bpf_pseudo_call(insn))
18957 insn->imm = env->insn_aux_data[i].call_imm;
18959 bpf_prog_jit_attempt_done(prog);
18963 static int fixup_call_args(struct bpf_verifier_env *env)
18965 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18966 struct bpf_prog *prog = env->prog;
18967 struct bpf_insn *insn = prog->insnsi;
18968 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18973 if (env->prog->jit_requested &&
18974 !bpf_prog_is_offloaded(env->prog->aux)) {
18975 err = jit_subprogs(env);
18978 if (err == -EFAULT)
18981 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18982 if (has_kfunc_call) {
18983 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18986 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18987 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18988 * have to be rejected, since interpreter doesn't support them yet.
18990 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18993 for (i = 0; i < prog->len; i++, insn++) {
18994 if (bpf_pseudo_func(insn)) {
18995 /* When JIT fails the progs with callback calls
18996 * have to be rejected, since interpreter doesn't support them yet.
18998 verbose(env, "callbacks are not allowed in non-JITed programs\n");
19002 if (!bpf_pseudo_call(insn))
19004 depth = get_callee_stack_depth(env, insn, i);
19007 bpf_patch_call_args(insn, depth);
19014 /* replace a generic kfunc with a specialized version if necessary */
19015 static void specialize_kfunc(struct bpf_verifier_env *env,
19016 u32 func_id, u16 offset, unsigned long *addr)
19018 struct bpf_prog *prog = env->prog;
19019 bool seen_direct_write;
19023 if (bpf_dev_bound_kfunc_id(func_id)) {
19024 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19026 *addr = (unsigned long)xdp_kfunc;
19029 /* fallback to default kfunc when not supported by netdev */
19035 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19036 seen_direct_write = env->seen_direct_write;
19037 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19040 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19042 /* restore env->seen_direct_write to its original value, since
19043 * may_access_direct_pkt_data mutates it
19045 env->seen_direct_write = seen_direct_write;
19049 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19050 u16 struct_meta_reg,
19051 u16 node_offset_reg,
19052 struct bpf_insn *insn,
19053 struct bpf_insn *insn_buf,
19056 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19057 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19059 insn_buf[0] = addr[0];
19060 insn_buf[1] = addr[1];
19061 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19062 insn_buf[3] = *insn;
19066 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19067 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19069 const struct bpf_kfunc_desc *desc;
19072 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19078 /* insn->imm has the btf func_id. Replace it with an offset relative to
19079 * __bpf_call_base, unless the JIT needs to call functions that are
19080 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19082 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19084 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19089 if (!bpf_jit_supports_far_kfunc_call())
19090 insn->imm = BPF_CALL_IMM(desc->addr);
19093 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19094 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19095 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19096 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19097 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19099 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19100 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19105 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19106 insn_buf[1] = addr[0];
19107 insn_buf[2] = addr[1];
19108 insn_buf[3] = *insn;
19110 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19111 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19112 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19113 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19114 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19116 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19117 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19122 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19123 !kptr_struct_meta) {
19124 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19129 insn_buf[0] = addr[0];
19130 insn_buf[1] = addr[1];
19131 insn_buf[2] = *insn;
19133 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19134 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19135 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19136 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19137 int struct_meta_reg = BPF_REG_3;
19138 int node_offset_reg = BPF_REG_4;
19140 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19141 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19142 struct_meta_reg = BPF_REG_4;
19143 node_offset_reg = BPF_REG_5;
19146 if (!kptr_struct_meta) {
19147 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19152 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19153 node_offset_reg, insn, insn_buf, cnt);
19154 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19155 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19156 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19162 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19163 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19165 struct bpf_subprog_info *info = env->subprog_info;
19166 int cnt = env->subprog_cnt;
19167 struct bpf_prog *prog;
19169 /* We only reserve one slot for hidden subprogs in subprog_info. */
19170 if (env->hidden_subprog_cnt) {
19171 verbose(env, "verifier internal error: only one hidden subprog supported\n");
19174 /* We're not patching any existing instruction, just appending the new
19175 * ones for the hidden subprog. Hence all of the adjustment operations
19176 * in bpf_patch_insn_data are no-ops.
19178 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19182 info[cnt + 1].start = info[cnt].start;
19183 info[cnt].start = prog->len - len + 1;
19184 env->subprog_cnt++;
19185 env->hidden_subprog_cnt++;
19189 /* Do various post-verification rewrites in a single program pass.
19190 * These rewrites simplify JIT and interpreter implementations.
19192 static int do_misc_fixups(struct bpf_verifier_env *env)
19194 struct bpf_prog *prog = env->prog;
19195 enum bpf_attach_type eatype = prog->expected_attach_type;
19196 enum bpf_prog_type prog_type = resolve_prog_type(prog);
19197 struct bpf_insn *insn = prog->insnsi;
19198 const struct bpf_func_proto *fn;
19199 const int insn_cnt = prog->len;
19200 const struct bpf_map_ops *ops;
19201 struct bpf_insn_aux_data *aux;
19202 struct bpf_insn insn_buf[16];
19203 struct bpf_prog *new_prog;
19204 struct bpf_map *map_ptr;
19205 int i, ret, cnt, delta = 0;
19207 if (env->seen_exception && !env->exception_callback_subprog) {
19208 struct bpf_insn patch[] = {
19209 env->prog->insnsi[insn_cnt - 1],
19210 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19214 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19218 insn = prog->insnsi;
19220 env->exception_callback_subprog = env->subprog_cnt - 1;
19221 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19222 env->subprog_info[env->exception_callback_subprog].is_cb = true;
19223 env->subprog_info[env->exception_callback_subprog].is_async_cb = true;
19224 env->subprog_info[env->exception_callback_subprog].is_exception_cb = true;
19227 for (i = 0; i < insn_cnt; i++, insn++) {
19228 /* Make divide-by-zero exceptions impossible. */
19229 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19230 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19231 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19232 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19233 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19234 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19235 struct bpf_insn *patchlet;
19236 struct bpf_insn chk_and_div[] = {
19237 /* [R,W]x div 0 -> 0 */
19238 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19239 BPF_JNE | BPF_K, insn->src_reg,
19241 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19242 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19245 struct bpf_insn chk_and_mod[] = {
19246 /* [R,W]x mod 0 -> [R,W]x */
19247 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19248 BPF_JEQ | BPF_K, insn->src_reg,
19249 0, 1 + (is64 ? 0 : 1), 0),
19251 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19252 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19255 patchlet = isdiv ? chk_and_div : chk_and_mod;
19256 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19257 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19259 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19264 env->prog = prog = new_prog;
19265 insn = new_prog->insnsi + i + delta;
19269 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19270 if (BPF_CLASS(insn->code) == BPF_LD &&
19271 (BPF_MODE(insn->code) == BPF_ABS ||
19272 BPF_MODE(insn->code) == BPF_IND)) {
19273 cnt = env->ops->gen_ld_abs(insn, insn_buf);
19274 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19275 verbose(env, "bpf verifier is misconfigured\n");
19279 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19284 env->prog = prog = new_prog;
19285 insn = new_prog->insnsi + i + delta;
19289 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
19290 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19291 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19292 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19293 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19294 struct bpf_insn *patch = &insn_buf[0];
19295 bool issrc, isneg, isimm;
19298 aux = &env->insn_aux_data[i + delta];
19299 if (!aux->alu_state ||
19300 aux->alu_state == BPF_ALU_NON_POINTER)
19303 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19304 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19305 BPF_ALU_SANITIZE_SRC;
19306 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19308 off_reg = issrc ? insn->src_reg : insn->dst_reg;
19310 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19313 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19314 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19315 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19316 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19317 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19318 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19319 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19322 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19323 insn->src_reg = BPF_REG_AX;
19325 insn->code = insn->code == code_add ?
19326 code_sub : code_add;
19328 if (issrc && isneg && !isimm)
19329 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19330 cnt = patch - insn_buf;
19332 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19337 env->prog = prog = new_prog;
19338 insn = new_prog->insnsi + i + delta;
19342 if (insn->code != (BPF_JMP | BPF_CALL))
19344 if (insn->src_reg == BPF_PSEUDO_CALL)
19346 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19347 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19353 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19358 env->prog = prog = new_prog;
19359 insn = new_prog->insnsi + i + delta;
19363 if (insn->imm == BPF_FUNC_get_route_realm)
19364 prog->dst_needed = 1;
19365 if (insn->imm == BPF_FUNC_get_prandom_u32)
19366 bpf_user_rnd_init_once();
19367 if (insn->imm == BPF_FUNC_override_return)
19368 prog->kprobe_override = 1;
19369 if (insn->imm == BPF_FUNC_tail_call) {
19370 /* If we tail call into other programs, we
19371 * cannot make any assumptions since they can
19372 * be replaced dynamically during runtime in
19373 * the program array.
19375 prog->cb_access = 1;
19376 if (!allow_tail_call_in_subprogs(env))
19377 prog->aux->stack_depth = MAX_BPF_STACK;
19378 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19380 /* mark bpf_tail_call as different opcode to avoid
19381 * conditional branch in the interpreter for every normal
19382 * call and to prevent accidental JITing by JIT compiler
19383 * that doesn't support bpf_tail_call yet
19386 insn->code = BPF_JMP | BPF_TAIL_CALL;
19388 aux = &env->insn_aux_data[i + delta];
19389 if (env->bpf_capable && !prog->blinding_requested &&
19390 prog->jit_requested &&
19391 !bpf_map_key_poisoned(aux) &&
19392 !bpf_map_ptr_poisoned(aux) &&
19393 !bpf_map_ptr_unpriv(aux)) {
19394 struct bpf_jit_poke_descriptor desc = {
19395 .reason = BPF_POKE_REASON_TAIL_CALL,
19396 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19397 .tail_call.key = bpf_map_key_immediate(aux),
19398 .insn_idx = i + delta,
19401 ret = bpf_jit_add_poke_descriptor(prog, &desc);
19403 verbose(env, "adding tail call poke descriptor failed\n");
19407 insn->imm = ret + 1;
19411 if (!bpf_map_ptr_unpriv(aux))
19414 /* instead of changing every JIT dealing with tail_call
19415 * emit two extra insns:
19416 * if (index >= max_entries) goto out;
19417 * index &= array->index_mask;
19418 * to avoid out-of-bounds cpu speculation
19420 if (bpf_map_ptr_poisoned(aux)) {
19421 verbose(env, "tail_call abusing map_ptr\n");
19425 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19426 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19427 map_ptr->max_entries, 2);
19428 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19429 container_of(map_ptr,
19432 insn_buf[2] = *insn;
19434 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19439 env->prog = prog = new_prog;
19440 insn = new_prog->insnsi + i + delta;
19444 if (insn->imm == BPF_FUNC_timer_set_callback) {
19445 /* The verifier will process callback_fn as many times as necessary
19446 * with different maps and the register states prepared by
19447 * set_timer_callback_state will be accurate.
19449 * The following use case is valid:
19450 * map1 is shared by prog1, prog2, prog3.
19451 * prog1 calls bpf_timer_init for some map1 elements
19452 * prog2 calls bpf_timer_set_callback for some map1 elements.
19453 * Those that were not bpf_timer_init-ed will return -EINVAL.
19454 * prog3 calls bpf_timer_start for some map1 elements.
19455 * Those that were not both bpf_timer_init-ed and
19456 * bpf_timer_set_callback-ed will return -EINVAL.
19458 struct bpf_insn ld_addrs[2] = {
19459 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19462 insn_buf[0] = ld_addrs[0];
19463 insn_buf[1] = ld_addrs[1];
19464 insn_buf[2] = *insn;
19467 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19472 env->prog = prog = new_prog;
19473 insn = new_prog->insnsi + i + delta;
19474 goto patch_call_imm;
19477 if (is_storage_get_function(insn->imm)) {
19478 if (!env->prog->aux->sleepable ||
19479 env->insn_aux_data[i + delta].storage_get_func_atomic)
19480 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19482 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19483 insn_buf[1] = *insn;
19486 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19491 env->prog = prog = new_prog;
19492 insn = new_prog->insnsi + i + delta;
19493 goto patch_call_imm;
19496 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
19497 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
19498 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
19499 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
19501 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
19502 insn_buf[1] = *insn;
19505 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19510 env->prog = prog = new_prog;
19511 insn = new_prog->insnsi + i + delta;
19512 goto patch_call_imm;
19515 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19516 * and other inlining handlers are currently limited to 64 bit
19519 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19520 (insn->imm == BPF_FUNC_map_lookup_elem ||
19521 insn->imm == BPF_FUNC_map_update_elem ||
19522 insn->imm == BPF_FUNC_map_delete_elem ||
19523 insn->imm == BPF_FUNC_map_push_elem ||
19524 insn->imm == BPF_FUNC_map_pop_elem ||
19525 insn->imm == BPF_FUNC_map_peek_elem ||
19526 insn->imm == BPF_FUNC_redirect_map ||
19527 insn->imm == BPF_FUNC_for_each_map_elem ||
19528 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19529 aux = &env->insn_aux_data[i + delta];
19530 if (bpf_map_ptr_poisoned(aux))
19531 goto patch_call_imm;
19533 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19534 ops = map_ptr->ops;
19535 if (insn->imm == BPF_FUNC_map_lookup_elem &&
19536 ops->map_gen_lookup) {
19537 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19538 if (cnt == -EOPNOTSUPP)
19539 goto patch_map_ops_generic;
19540 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19541 verbose(env, "bpf verifier is misconfigured\n");
19545 new_prog = bpf_patch_insn_data(env, i + delta,
19551 env->prog = prog = new_prog;
19552 insn = new_prog->insnsi + i + delta;
19556 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19557 (void *(*)(struct bpf_map *map, void *key))NULL));
19558 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19559 (long (*)(struct bpf_map *map, void *key))NULL));
19560 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19561 (long (*)(struct bpf_map *map, void *key, void *value,
19563 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19564 (long (*)(struct bpf_map *map, void *value,
19566 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19567 (long (*)(struct bpf_map *map, void *value))NULL));
19568 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19569 (long (*)(struct bpf_map *map, void *value))NULL));
19570 BUILD_BUG_ON(!__same_type(ops->map_redirect,
19571 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19572 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19573 (long (*)(struct bpf_map *map,
19574 bpf_callback_t callback_fn,
19575 void *callback_ctx,
19577 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19578 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19580 patch_map_ops_generic:
19581 switch (insn->imm) {
19582 case BPF_FUNC_map_lookup_elem:
19583 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19585 case BPF_FUNC_map_update_elem:
19586 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19588 case BPF_FUNC_map_delete_elem:
19589 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19591 case BPF_FUNC_map_push_elem:
19592 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19594 case BPF_FUNC_map_pop_elem:
19595 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19597 case BPF_FUNC_map_peek_elem:
19598 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19600 case BPF_FUNC_redirect_map:
19601 insn->imm = BPF_CALL_IMM(ops->map_redirect);
19603 case BPF_FUNC_for_each_map_elem:
19604 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19606 case BPF_FUNC_map_lookup_percpu_elem:
19607 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19611 goto patch_call_imm;
19614 /* Implement bpf_jiffies64 inline. */
19615 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19616 insn->imm == BPF_FUNC_jiffies64) {
19617 struct bpf_insn ld_jiffies_addr[2] = {
19618 BPF_LD_IMM64(BPF_REG_0,
19619 (unsigned long)&jiffies),
19622 insn_buf[0] = ld_jiffies_addr[0];
19623 insn_buf[1] = ld_jiffies_addr[1];
19624 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19628 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19634 env->prog = prog = new_prog;
19635 insn = new_prog->insnsi + i + delta;
19639 /* Implement bpf_get_func_arg inline. */
19640 if (prog_type == BPF_PROG_TYPE_TRACING &&
19641 insn->imm == BPF_FUNC_get_func_arg) {
19642 /* Load nr_args from ctx - 8 */
19643 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19644 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19645 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19646 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19647 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19648 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19649 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19650 insn_buf[7] = BPF_JMP_A(1);
19651 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19654 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19659 env->prog = prog = new_prog;
19660 insn = new_prog->insnsi + i + delta;
19664 /* Implement bpf_get_func_ret inline. */
19665 if (prog_type == BPF_PROG_TYPE_TRACING &&
19666 insn->imm == BPF_FUNC_get_func_ret) {
19667 if (eatype == BPF_TRACE_FEXIT ||
19668 eatype == BPF_MODIFY_RETURN) {
19669 /* Load nr_args from ctx - 8 */
19670 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19671 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19672 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19673 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19674 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19675 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19678 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19682 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19687 env->prog = prog = new_prog;
19688 insn = new_prog->insnsi + i + delta;
19692 /* Implement get_func_arg_cnt inline. */
19693 if (prog_type == BPF_PROG_TYPE_TRACING &&
19694 insn->imm == BPF_FUNC_get_func_arg_cnt) {
19695 /* Load nr_args from ctx - 8 */
19696 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19698 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19702 env->prog = prog = new_prog;
19703 insn = new_prog->insnsi + i + delta;
19707 /* Implement bpf_get_func_ip inline. */
19708 if (prog_type == BPF_PROG_TYPE_TRACING &&
19709 insn->imm == BPF_FUNC_get_func_ip) {
19710 /* Load IP address from ctx - 16 */
19711 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19713 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19717 env->prog = prog = new_prog;
19718 insn = new_prog->insnsi + i + delta;
19723 fn = env->ops->get_func_proto(insn->imm, env->prog);
19724 /* all functions that have prototype and verifier allowed
19725 * programs to call them, must be real in-kernel functions
19729 "kernel subsystem misconfigured func %s#%d\n",
19730 func_id_name(insn->imm), insn->imm);
19733 insn->imm = fn->func - __bpf_call_base;
19736 /* Since poke tab is now finalized, publish aux to tracker. */
19737 for (i = 0; i < prog->aux->size_poke_tab; i++) {
19738 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19739 if (!map_ptr->ops->map_poke_track ||
19740 !map_ptr->ops->map_poke_untrack ||
19741 !map_ptr->ops->map_poke_run) {
19742 verbose(env, "bpf verifier is misconfigured\n");
19746 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19748 verbose(env, "tracking tail call prog failed\n");
19753 sort_kfunc_descs_by_imm_off(env->prog);
19758 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19761 u32 callback_subprogno,
19764 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19765 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19766 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19767 int reg_loop_max = BPF_REG_6;
19768 int reg_loop_cnt = BPF_REG_7;
19769 int reg_loop_ctx = BPF_REG_8;
19771 struct bpf_prog *new_prog;
19772 u32 callback_start;
19773 u32 call_insn_offset;
19774 s32 callback_offset;
19776 /* This represents an inlined version of bpf_iter.c:bpf_loop,
19777 * be careful to modify this code in sync.
19779 struct bpf_insn insn_buf[] = {
19780 /* Return error and jump to the end of the patch if
19781 * expected number of iterations is too big.
19783 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19784 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19785 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19786 /* spill R6, R7, R8 to use these as loop vars */
19787 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19788 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19789 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19790 /* initialize loop vars */
19791 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19792 BPF_MOV32_IMM(reg_loop_cnt, 0),
19793 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19795 * if reg_loop_cnt >= reg_loop_max skip the loop body
19797 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19799 * correct callback offset would be set after patching
19801 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19802 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19804 /* increment loop counter */
19805 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19806 /* jump to loop header if callback returned 0 */
19807 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19808 /* return value of bpf_loop,
19809 * set R0 to the number of iterations
19811 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19812 /* restore original values of R6, R7, R8 */
19813 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19814 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19815 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19818 *cnt = ARRAY_SIZE(insn_buf);
19819 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19823 /* callback start is known only after patching */
19824 callback_start = env->subprog_info[callback_subprogno].start;
19825 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19826 call_insn_offset = position + 12;
19827 callback_offset = callback_start - call_insn_offset - 1;
19828 new_prog->insnsi[call_insn_offset].imm = callback_offset;
19833 static bool is_bpf_loop_call(struct bpf_insn *insn)
19835 return insn->code == (BPF_JMP | BPF_CALL) &&
19836 insn->src_reg == 0 &&
19837 insn->imm == BPF_FUNC_loop;
19840 /* For all sub-programs in the program (including main) check
19841 * insn_aux_data to see if there are bpf_loop calls that require
19842 * inlining. If such calls are found the calls are replaced with a
19843 * sequence of instructions produced by `inline_bpf_loop` function and
19844 * subprog stack_depth is increased by the size of 3 registers.
19845 * This stack space is used to spill values of the R6, R7, R8. These
19846 * registers are used to store the loop bound, counter and context
19849 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19851 struct bpf_subprog_info *subprogs = env->subprog_info;
19852 int i, cur_subprog = 0, cnt, delta = 0;
19853 struct bpf_insn *insn = env->prog->insnsi;
19854 int insn_cnt = env->prog->len;
19855 u16 stack_depth = subprogs[cur_subprog].stack_depth;
19856 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19857 u16 stack_depth_extra = 0;
19859 for (i = 0; i < insn_cnt; i++, insn++) {
19860 struct bpf_loop_inline_state *inline_state =
19861 &env->insn_aux_data[i + delta].loop_inline_state;
19863 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19864 struct bpf_prog *new_prog;
19866 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19867 new_prog = inline_bpf_loop(env,
19869 -(stack_depth + stack_depth_extra),
19870 inline_state->callback_subprogno,
19876 env->prog = new_prog;
19877 insn = new_prog->insnsi + i + delta;
19880 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19881 subprogs[cur_subprog].stack_depth += stack_depth_extra;
19883 stack_depth = subprogs[cur_subprog].stack_depth;
19884 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19885 stack_depth_extra = 0;
19889 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19894 static void free_states(struct bpf_verifier_env *env)
19896 struct bpf_verifier_state_list *sl, *sln;
19899 sl = env->free_list;
19902 free_verifier_state(&sl->state, false);
19906 env->free_list = NULL;
19908 if (!env->explored_states)
19911 for (i = 0; i < state_htab_size(env); i++) {
19912 sl = env->explored_states[i];
19916 free_verifier_state(&sl->state, false);
19920 env->explored_states[i] = NULL;
19924 static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_ex_cb)
19926 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19927 struct bpf_verifier_state *state;
19928 struct bpf_reg_state *regs;
19931 env->prev_linfo = NULL;
19934 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19937 state->curframe = 0;
19938 state->speculative = false;
19939 state->branches = 1;
19940 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19941 if (!state->frame[0]) {
19945 env->cur_state = state;
19946 init_func_state(env, state->frame[0],
19947 BPF_MAIN_FUNC /* callsite */,
19950 state->first_insn_idx = env->subprog_info[subprog].start;
19951 state->last_insn_idx = -1;
19953 regs = state->frame[state->curframe]->regs;
19954 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19955 ret = btf_prepare_func_args(env, subprog, regs, is_ex_cb);
19958 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19959 if (regs[i].type == PTR_TO_CTX)
19960 mark_reg_known_zero(env, regs, i);
19961 else if (regs[i].type == SCALAR_VALUE)
19962 mark_reg_unknown(env, regs, i);
19963 else if (base_type(regs[i].type) == PTR_TO_MEM) {
19964 const u32 mem_size = regs[i].mem_size;
19966 mark_reg_known_zero(env, regs, i);
19967 regs[i].mem_size = mem_size;
19968 regs[i].id = ++env->id_gen;
19972 state->frame[0]->in_exception_callback_fn = true;
19973 env->subprog_info[subprog].is_cb = true;
19974 env->subprog_info[subprog].is_async_cb = true;
19975 env->subprog_info[subprog].is_exception_cb = true;
19978 /* 1st arg to a function */
19979 regs[BPF_REG_1].type = PTR_TO_CTX;
19980 mark_reg_known_zero(env, regs, BPF_REG_1);
19981 ret = btf_check_subprog_arg_match(env, subprog, regs);
19982 if (ret == -EFAULT)
19983 /* unlikely verifier bug. abort.
19984 * ret == 0 and ret < 0 are sadly acceptable for
19985 * main() function due to backward compatibility.
19986 * Like socket filter program may be written as:
19987 * int bpf_prog(struct pt_regs *ctx)
19988 * and never dereference that ctx in the program.
19989 * 'struct pt_regs' is a type mismatch for socket
19990 * filter that should be using 'struct __sk_buff'.
19995 ret = do_check(env);
19997 /* check for NULL is necessary, since cur_state can be freed inside
19998 * do_check() under memory pressure.
20000 if (env->cur_state) {
20001 free_verifier_state(env->cur_state, true);
20002 env->cur_state = NULL;
20004 while (!pop_stack(env, NULL, NULL, false));
20005 if (!ret && pop_log)
20006 bpf_vlog_reset(&env->log, 0);
20011 /* Verify all global functions in a BPF program one by one based on their BTF.
20012 * All global functions must pass verification. Otherwise the whole program is rejected.
20023 * foo() will be verified first for R1=any_scalar_value. During verification it
20024 * will be assumed that bar() already verified successfully and call to bar()
20025 * from foo() will be checked for type match only. Later bar() will be verified
20026 * independently to check that it's safe for R1=any_scalar_value.
20028 static int do_check_subprogs(struct bpf_verifier_env *env)
20030 struct bpf_prog_aux *aux = env->prog->aux;
20033 if (!aux->func_info)
20036 for (i = 1; i < env->subprog_cnt; i++) {
20037 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
20039 env->insn_idx = env->subprog_info[i].start;
20040 WARN_ON_ONCE(env->insn_idx == 0);
20041 ret = do_check_common(env, i, env->exception_callback_subprog == i);
20044 } else if (env->log.level & BPF_LOG_LEVEL) {
20046 "Func#%d is safe for any args that match its prototype\n",
20053 static int do_check_main(struct bpf_verifier_env *env)
20058 ret = do_check_common(env, 0, false);
20060 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20065 static void print_verification_stats(struct bpf_verifier_env *env)
20069 if (env->log.level & BPF_LOG_STATS) {
20070 verbose(env, "verification time %lld usec\n",
20071 div_u64(env->verification_time, 1000));
20072 verbose(env, "stack depth ");
20073 for (i = 0; i < env->subprog_cnt; i++) {
20074 u32 depth = env->subprog_info[i].stack_depth;
20076 verbose(env, "%d", depth);
20077 if (i + 1 < env->subprog_cnt)
20080 verbose(env, "\n");
20082 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20083 "total_states %d peak_states %d mark_read %d\n",
20084 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20085 env->max_states_per_insn, env->total_states,
20086 env->peak_states, env->longest_mark_read_walk);
20089 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20091 const struct btf_type *t, *func_proto;
20092 const struct bpf_struct_ops *st_ops;
20093 const struct btf_member *member;
20094 struct bpf_prog *prog = env->prog;
20095 u32 btf_id, member_idx;
20098 if (!prog->gpl_compatible) {
20099 verbose(env, "struct ops programs must have a GPL compatible license\n");
20103 btf_id = prog->aux->attach_btf_id;
20104 st_ops = bpf_struct_ops_find(btf_id);
20106 verbose(env, "attach_btf_id %u is not a supported struct\n",
20112 member_idx = prog->expected_attach_type;
20113 if (member_idx >= btf_type_vlen(t)) {
20114 verbose(env, "attach to invalid member idx %u of struct %s\n",
20115 member_idx, st_ops->name);
20119 member = &btf_type_member(t)[member_idx];
20120 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
20121 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
20124 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20125 mname, member_idx, st_ops->name);
20129 if (st_ops->check_member) {
20130 int err = st_ops->check_member(t, member, prog);
20133 verbose(env, "attach to unsupported member %s of struct %s\n",
20134 mname, st_ops->name);
20139 prog->aux->attach_func_proto = func_proto;
20140 prog->aux->attach_func_name = mname;
20141 env->ops = st_ops->verifier_ops;
20145 #define SECURITY_PREFIX "security_"
20147 static int check_attach_modify_return(unsigned long addr, const char *func_name)
20149 if (within_error_injection_list(addr) ||
20150 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
20156 /* list of non-sleepable functions that are otherwise on
20157 * ALLOW_ERROR_INJECTION list
20159 BTF_SET_START(btf_non_sleepable_error_inject)
20160 /* Three functions below can be called from sleepable and non-sleepable context.
20161 * Assume non-sleepable from bpf safety point of view.
20163 BTF_ID(func, __filemap_add_folio)
20164 BTF_ID(func, should_fail_alloc_page)
20165 BTF_ID(func, should_failslab)
20166 BTF_SET_END(btf_non_sleepable_error_inject)
20168 static int check_non_sleepable_error_inject(u32 btf_id)
20170 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
20173 int bpf_check_attach_target(struct bpf_verifier_log *log,
20174 const struct bpf_prog *prog,
20175 const struct bpf_prog *tgt_prog,
20177 struct bpf_attach_target_info *tgt_info)
20179 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
20180 const char prefix[] = "btf_trace_";
20181 int ret = 0, subprog = -1, i;
20182 const struct btf_type *t;
20183 bool conservative = true;
20187 struct module *mod = NULL;
20190 bpf_log(log, "Tracing programs must provide btf_id\n");
20193 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
20196 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
20199 t = btf_type_by_id(btf, btf_id);
20201 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
20204 tname = btf_name_by_offset(btf, t->name_off);
20206 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
20210 struct bpf_prog_aux *aux = tgt_prog->aux;
20212 if (bpf_prog_is_dev_bound(prog->aux) &&
20213 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20214 bpf_log(log, "Target program bound device mismatch");
20218 for (i = 0; i < aux->func_info_cnt; i++)
20219 if (aux->func_info[i].type_id == btf_id) {
20223 if (subprog == -1) {
20224 bpf_log(log, "Subprog %s doesn't exist\n", tname);
20227 if (aux->func && aux->func[subprog]->aux->exception_cb) {
20229 "%s programs cannot attach to exception callback\n",
20230 prog_extension ? "Extension" : "FENTRY/FEXIT");
20233 conservative = aux->func_info_aux[subprog].unreliable;
20234 if (prog_extension) {
20235 if (conservative) {
20237 "Cannot replace static functions\n");
20240 if (!prog->jit_requested) {
20242 "Extension programs should be JITed\n");
20246 if (!tgt_prog->jited) {
20247 bpf_log(log, "Can attach to only JITed progs\n");
20250 if (tgt_prog->type == prog->type) {
20251 /* Cannot fentry/fexit another fentry/fexit program.
20252 * Cannot attach program extension to another extension.
20253 * It's ok to attach fentry/fexit to extension program.
20255 bpf_log(log, "Cannot recursively attach\n");
20258 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20260 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20261 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
20262 /* Program extensions can extend all program types
20263 * except fentry/fexit. The reason is the following.
20264 * The fentry/fexit programs are used for performance
20265 * analysis, stats and can be attached to any program
20266 * type except themselves. When extension program is
20267 * replacing XDP function it is necessary to allow
20268 * performance analysis of all functions. Both original
20269 * XDP program and its program extension. Hence
20270 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
20271 * allowed. If extending of fentry/fexit was allowed it
20272 * would be possible to create long call chain
20273 * fentry->extension->fentry->extension beyond
20274 * reasonable stack size. Hence extending fentry is not
20277 bpf_log(log, "Cannot extend fentry/fexit\n");
20281 if (prog_extension) {
20282 bpf_log(log, "Cannot replace kernel functions\n");
20287 switch (prog->expected_attach_type) {
20288 case BPF_TRACE_RAW_TP:
20291 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
20294 if (!btf_type_is_typedef(t)) {
20295 bpf_log(log, "attach_btf_id %u is not a typedef\n",
20299 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20300 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20304 tname += sizeof(prefix) - 1;
20305 t = btf_type_by_id(btf, t->type);
20306 if (!btf_type_is_ptr(t))
20307 /* should never happen in valid vmlinux build */
20309 t = btf_type_by_id(btf, t->type);
20310 if (!btf_type_is_func_proto(t))
20311 /* should never happen in valid vmlinux build */
20315 case BPF_TRACE_ITER:
20316 if (!btf_type_is_func(t)) {
20317 bpf_log(log, "attach_btf_id %u is not a function\n",
20321 t = btf_type_by_id(btf, t->type);
20322 if (!btf_type_is_func_proto(t))
20324 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20329 if (!prog_extension)
20332 case BPF_MODIFY_RETURN:
20334 case BPF_LSM_CGROUP:
20335 case BPF_TRACE_FENTRY:
20336 case BPF_TRACE_FEXIT:
20337 if (!btf_type_is_func(t)) {
20338 bpf_log(log, "attach_btf_id %u is not a function\n",
20342 if (prog_extension &&
20343 btf_check_type_match(log, prog, btf, t))
20345 t = btf_type_by_id(btf, t->type);
20346 if (!btf_type_is_func_proto(t))
20349 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20350 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20351 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20354 if (tgt_prog && conservative)
20357 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20363 addr = (long) tgt_prog->bpf_func;
20365 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20367 if (btf_is_module(btf)) {
20368 mod = btf_try_get_module(btf);
20370 addr = find_kallsyms_symbol_value(mod, tname);
20374 addr = kallsyms_lookup_name(tname);
20379 "The address of function %s cannot be found\n",
20385 if (prog->aux->sleepable) {
20387 switch (prog->type) {
20388 case BPF_PROG_TYPE_TRACING:
20390 /* fentry/fexit/fmod_ret progs can be sleepable if they are
20391 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20393 if (!check_non_sleepable_error_inject(btf_id) &&
20394 within_error_injection_list(addr))
20396 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
20397 * in the fmodret id set with the KF_SLEEPABLE flag.
20400 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20403 if (flags && (*flags & KF_SLEEPABLE))
20407 case BPF_PROG_TYPE_LSM:
20408 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
20409 * Only some of them are sleepable.
20411 if (bpf_lsm_is_sleepable_hook(btf_id))
20419 bpf_log(log, "%s is not sleepable\n", tname);
20422 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20425 bpf_log(log, "can't modify return codes of BPF programs\n");
20429 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20430 !check_attach_modify_return(addr, tname))
20434 bpf_log(log, "%s() is not modifiable\n", tname);
20441 tgt_info->tgt_addr = addr;
20442 tgt_info->tgt_name = tname;
20443 tgt_info->tgt_type = t;
20444 tgt_info->tgt_mod = mod;
20448 BTF_SET_START(btf_id_deny)
20451 BTF_ID(func, migrate_disable)
20452 BTF_ID(func, migrate_enable)
20454 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20455 BTF_ID(func, rcu_read_unlock_strict)
20457 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20458 BTF_ID(func, preempt_count_add)
20459 BTF_ID(func, preempt_count_sub)
20461 #ifdef CONFIG_PREEMPT_RCU
20462 BTF_ID(func, __rcu_read_lock)
20463 BTF_ID(func, __rcu_read_unlock)
20465 BTF_SET_END(btf_id_deny)
20467 static bool can_be_sleepable(struct bpf_prog *prog)
20469 if (prog->type == BPF_PROG_TYPE_TRACING) {
20470 switch (prog->expected_attach_type) {
20471 case BPF_TRACE_FENTRY:
20472 case BPF_TRACE_FEXIT:
20473 case BPF_MODIFY_RETURN:
20474 case BPF_TRACE_ITER:
20480 return prog->type == BPF_PROG_TYPE_LSM ||
20481 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20482 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20485 static int check_attach_btf_id(struct bpf_verifier_env *env)
20487 struct bpf_prog *prog = env->prog;
20488 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20489 struct bpf_attach_target_info tgt_info = {};
20490 u32 btf_id = prog->aux->attach_btf_id;
20491 struct bpf_trampoline *tr;
20495 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20496 if (prog->aux->sleepable)
20497 /* attach_btf_id checked to be zero already */
20499 verbose(env, "Syscall programs can only be sleepable\n");
20503 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20504 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20508 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20509 return check_struct_ops_btf_id(env);
20511 if (prog->type != BPF_PROG_TYPE_TRACING &&
20512 prog->type != BPF_PROG_TYPE_LSM &&
20513 prog->type != BPF_PROG_TYPE_EXT)
20516 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20520 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20521 /* to make freplace equivalent to their targets, they need to
20522 * inherit env->ops and expected_attach_type for the rest of the
20525 env->ops = bpf_verifier_ops[tgt_prog->type];
20526 prog->expected_attach_type = tgt_prog->expected_attach_type;
20529 /* store info about the attachment target that will be used later */
20530 prog->aux->attach_func_proto = tgt_info.tgt_type;
20531 prog->aux->attach_func_name = tgt_info.tgt_name;
20532 prog->aux->mod = tgt_info.tgt_mod;
20535 prog->aux->saved_dst_prog_type = tgt_prog->type;
20536 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20539 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20540 prog->aux->attach_btf_trace = true;
20542 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20543 if (!bpf_iter_prog_supported(prog))
20548 if (prog->type == BPF_PROG_TYPE_LSM) {
20549 ret = bpf_lsm_verify_prog(&env->log, prog);
20552 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
20553 btf_id_set_contains(&btf_id_deny, btf_id)) {
20557 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20558 tr = bpf_trampoline_get(key, &tgt_info);
20562 if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20563 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20565 prog->aux->dst_trampoline = tr;
20569 struct btf *bpf_get_btf_vmlinux(void)
20571 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20572 mutex_lock(&bpf_verifier_lock);
20574 btf_vmlinux = btf_parse_vmlinux();
20575 mutex_unlock(&bpf_verifier_lock);
20577 return btf_vmlinux;
20580 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20582 u64 start_time = ktime_get_ns();
20583 struct bpf_verifier_env *env;
20584 int i, len, ret = -EINVAL, err;
20588 /* no program is valid */
20589 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20592 /* 'struct bpf_verifier_env' can be global, but since it's not small,
20593 * allocate/free it every time bpf_check() is called
20595 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20601 len = (*prog)->len;
20602 env->insn_aux_data =
20603 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20605 if (!env->insn_aux_data)
20607 for (i = 0; i < len; i++)
20608 env->insn_aux_data[i].orig_idx = i;
20610 env->ops = bpf_verifier_ops[env->prog->type];
20611 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20612 is_priv = bpf_capable();
20614 bpf_get_btf_vmlinux();
20616 /* grab the mutex to protect few globals used by verifier */
20618 mutex_lock(&bpf_verifier_lock);
20620 /* user could have requested verbose verifier output
20621 * and supplied buffer to store the verification trace
20623 ret = bpf_vlog_init(&env->log, attr->log_level,
20624 (char __user *) (unsigned long) attr->log_buf,
20629 mark_verifier_state_clean(env);
20631 if (IS_ERR(btf_vmlinux)) {
20632 /* Either gcc or pahole or kernel are broken. */
20633 verbose(env, "in-kernel BTF is malformed\n");
20634 ret = PTR_ERR(btf_vmlinux);
20635 goto skip_full_check;
20638 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20639 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20640 env->strict_alignment = true;
20641 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20642 env->strict_alignment = false;
20644 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20645 env->allow_uninit_stack = bpf_allow_uninit_stack();
20646 env->bypass_spec_v1 = bpf_bypass_spec_v1();
20647 env->bypass_spec_v4 = bpf_bypass_spec_v4();
20648 env->bpf_capable = bpf_capable();
20651 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20653 env->explored_states = kvcalloc(state_htab_size(env),
20654 sizeof(struct bpf_verifier_state_list *),
20657 if (!env->explored_states)
20658 goto skip_full_check;
20660 ret = check_btf_info_early(env, attr, uattr);
20662 goto skip_full_check;
20664 ret = add_subprog_and_kfunc(env);
20666 goto skip_full_check;
20668 ret = check_subprogs(env);
20670 goto skip_full_check;
20672 ret = check_btf_info(env, attr, uattr);
20674 goto skip_full_check;
20676 ret = check_attach_btf_id(env);
20678 goto skip_full_check;
20680 ret = resolve_pseudo_ldimm64(env);
20682 goto skip_full_check;
20684 if (bpf_prog_is_offloaded(env->prog->aux)) {
20685 ret = bpf_prog_offload_verifier_prep(env->prog);
20687 goto skip_full_check;
20690 ret = check_cfg(env);
20692 goto skip_full_check;
20694 ret = do_check_subprogs(env);
20695 ret = ret ?: do_check_main(env);
20697 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20698 ret = bpf_prog_offload_finalize(env);
20701 kvfree(env->explored_states);
20704 ret = check_max_stack_depth(env);
20706 /* instruction rewrites happen after this point */
20708 ret = optimize_bpf_loop(env);
20712 opt_hard_wire_dead_code_branches(env);
20714 ret = opt_remove_dead_code(env);
20716 ret = opt_remove_nops(env);
20719 sanitize_dead_code(env);
20723 /* program is valid, convert *(u32*)(ctx + off) accesses */
20724 ret = convert_ctx_accesses(env);
20727 ret = do_misc_fixups(env);
20729 /* do 32-bit optimization after insn patching has done so those patched
20730 * insns could be handled correctly.
20732 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20733 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20734 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20739 ret = fixup_call_args(env);
20741 env->verification_time = ktime_get_ns() - start_time;
20742 print_verification_stats(env);
20743 env->prog->aux->verified_insns = env->insn_processed;
20745 /* preserve original error even if log finalization is successful */
20746 err = bpf_vlog_finalize(&env->log, &log_true_size);
20750 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20751 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20752 &log_true_size, sizeof(log_true_size))) {
20754 goto err_release_maps;
20758 goto err_release_maps;
20760 if (env->used_map_cnt) {
20761 /* if program passed verifier, update used_maps in bpf_prog_info */
20762 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20763 sizeof(env->used_maps[0]),
20766 if (!env->prog->aux->used_maps) {
20768 goto err_release_maps;
20771 memcpy(env->prog->aux->used_maps, env->used_maps,
20772 sizeof(env->used_maps[0]) * env->used_map_cnt);
20773 env->prog->aux->used_map_cnt = env->used_map_cnt;
20775 if (env->used_btf_cnt) {
20776 /* if program passed verifier, update used_btfs in bpf_prog_aux */
20777 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20778 sizeof(env->used_btfs[0]),
20780 if (!env->prog->aux->used_btfs) {
20782 goto err_release_maps;
20785 memcpy(env->prog->aux->used_btfs, env->used_btfs,
20786 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20787 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20789 if (env->used_map_cnt || env->used_btf_cnt) {
20790 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
20791 * bpf_ld_imm64 instructions
20793 convert_pseudo_ld_imm64(env);
20796 adjust_btf_func(env);
20799 if (!env->prog->aux->used_maps)
20800 /* if we didn't copy map pointers into bpf_prog_info, release
20801 * them now. Otherwise free_used_maps() will release them.
20804 if (!env->prog->aux->used_btfs)
20807 /* extension progs temporarily inherit the attach_type of their targets
20808 for verification purposes, so set it back to zero before returning
20810 if (env->prog->type == BPF_PROG_TYPE_EXT)
20811 env->prog->expected_attach_type = 0;
20816 mutex_unlock(&bpf_verifier_lock);
20817 vfree(env->insn_aux_data);