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
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);
547 static bool is_callback_calling_function(enum bpf_func_id func_id)
549 return func_id == BPF_FUNC_for_each_map_elem ||
550 func_id == BPF_FUNC_timer_set_callback ||
551 func_id == BPF_FUNC_find_vma ||
552 func_id == BPF_FUNC_loop ||
553 func_id == BPF_FUNC_user_ringbuf_drain;
556 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
558 return func_id == BPF_FUNC_timer_set_callback;
561 static bool is_storage_get_function(enum bpf_func_id func_id)
563 return func_id == BPF_FUNC_sk_storage_get ||
564 func_id == BPF_FUNC_inode_storage_get ||
565 func_id == BPF_FUNC_task_storage_get ||
566 func_id == BPF_FUNC_cgrp_storage_get;
569 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
570 const struct bpf_map *map)
572 int ref_obj_uses = 0;
574 if (is_ptr_cast_function(func_id))
576 if (is_acquire_function(func_id, map))
578 if (is_dynptr_ref_function(func_id))
581 return ref_obj_uses > 1;
584 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
586 return BPF_CLASS(insn->code) == BPF_STX &&
587 BPF_MODE(insn->code) == BPF_ATOMIC &&
588 insn->imm == BPF_CMPXCHG;
591 /* string representation of 'enum bpf_reg_type'
593 * Note that reg_type_str() can not appear more than once in a single verbose()
596 static const char *reg_type_str(struct bpf_verifier_env *env,
597 enum bpf_reg_type type)
599 char postfix[16] = {0}, prefix[64] = {0};
600 static const char * const str[] = {
602 [SCALAR_VALUE] = "scalar",
603 [PTR_TO_CTX] = "ctx",
604 [CONST_PTR_TO_MAP] = "map_ptr",
605 [PTR_TO_MAP_VALUE] = "map_value",
606 [PTR_TO_STACK] = "fp",
607 [PTR_TO_PACKET] = "pkt",
608 [PTR_TO_PACKET_META] = "pkt_meta",
609 [PTR_TO_PACKET_END] = "pkt_end",
610 [PTR_TO_FLOW_KEYS] = "flow_keys",
611 [PTR_TO_SOCKET] = "sock",
612 [PTR_TO_SOCK_COMMON] = "sock_common",
613 [PTR_TO_TCP_SOCK] = "tcp_sock",
614 [PTR_TO_TP_BUFFER] = "tp_buffer",
615 [PTR_TO_XDP_SOCK] = "xdp_sock",
616 [PTR_TO_BTF_ID] = "ptr_",
617 [PTR_TO_MEM] = "mem",
618 [PTR_TO_BUF] = "buf",
619 [PTR_TO_FUNC] = "func",
620 [PTR_TO_MAP_KEY] = "map_key",
621 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr",
624 if (type & PTR_MAYBE_NULL) {
625 if (base_type(type) == PTR_TO_BTF_ID)
626 strncpy(postfix, "or_null_", 16);
628 strncpy(postfix, "_or_null", 16);
631 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
632 type & MEM_RDONLY ? "rdonly_" : "",
633 type & MEM_RINGBUF ? "ringbuf_" : "",
634 type & MEM_USER ? "user_" : "",
635 type & MEM_PERCPU ? "percpu_" : "",
636 type & MEM_RCU ? "rcu_" : "",
637 type & PTR_UNTRUSTED ? "untrusted_" : "",
638 type & PTR_TRUSTED ? "trusted_" : ""
641 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
642 prefix, str[base_type(type)], postfix);
643 return env->tmp_str_buf;
646 static char slot_type_char[] = {
647 [STACK_INVALID] = '?',
651 [STACK_DYNPTR] = 'd',
655 static void print_liveness(struct bpf_verifier_env *env,
656 enum bpf_reg_liveness live)
658 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
660 if (live & REG_LIVE_READ)
662 if (live & REG_LIVE_WRITTEN)
664 if (live & REG_LIVE_DONE)
668 static int __get_spi(s32 off)
670 return (-off - 1) / BPF_REG_SIZE;
673 static struct bpf_func_state *func(struct bpf_verifier_env *env,
674 const struct bpf_reg_state *reg)
676 struct bpf_verifier_state *cur = env->cur_state;
678 return cur->frame[reg->frameno];
681 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
683 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
685 /* We need to check that slots between [spi - nr_slots + 1, spi] are
686 * within [0, allocated_stack).
688 * Please note that the spi grows downwards. For example, a dynptr
689 * takes the size of two stack slots; the first slot will be at
690 * spi and the second slot will be at spi - 1.
692 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
695 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
696 const char *obj_kind, int nr_slots)
700 if (!tnum_is_const(reg->var_off)) {
701 verbose(env, "%s has to be at a constant offset\n", obj_kind);
705 off = reg->off + reg->var_off.value;
706 if (off % BPF_REG_SIZE) {
707 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
711 spi = __get_spi(off);
712 if (spi + 1 < nr_slots) {
713 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
717 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
722 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
724 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
727 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
729 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
732 static const char *btf_type_name(const struct btf *btf, u32 id)
734 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
737 static const char *dynptr_type_str(enum bpf_dynptr_type type)
740 case BPF_DYNPTR_TYPE_LOCAL:
742 case BPF_DYNPTR_TYPE_RINGBUF:
744 case BPF_DYNPTR_TYPE_SKB:
746 case BPF_DYNPTR_TYPE_XDP:
748 case BPF_DYNPTR_TYPE_INVALID:
751 WARN_ONCE(1, "unknown dynptr type %d\n", type);
756 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
758 if (!btf || btf_id == 0)
761 /* we already validated that type is valid and has conforming name */
762 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
765 static const char *iter_state_str(enum bpf_iter_state state)
768 case BPF_ITER_STATE_ACTIVE:
770 case BPF_ITER_STATE_DRAINED:
772 case BPF_ITER_STATE_INVALID:
775 WARN_ONCE(1, "unknown iter state %d\n", state);
780 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
782 env->scratched_regs |= 1U << regno;
785 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
787 env->scratched_stack_slots |= 1ULL << spi;
790 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
792 return (env->scratched_regs >> regno) & 1;
795 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
797 return (env->scratched_stack_slots >> regno) & 1;
800 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
802 return env->scratched_regs || env->scratched_stack_slots;
805 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
807 env->scratched_regs = 0U;
808 env->scratched_stack_slots = 0ULL;
811 /* Used for printing the entire verifier state. */
812 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
814 env->scratched_regs = ~0U;
815 env->scratched_stack_slots = ~0ULL;
818 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
820 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
821 case DYNPTR_TYPE_LOCAL:
822 return BPF_DYNPTR_TYPE_LOCAL;
823 case DYNPTR_TYPE_RINGBUF:
824 return BPF_DYNPTR_TYPE_RINGBUF;
825 case DYNPTR_TYPE_SKB:
826 return BPF_DYNPTR_TYPE_SKB;
827 case DYNPTR_TYPE_XDP:
828 return BPF_DYNPTR_TYPE_XDP;
830 return BPF_DYNPTR_TYPE_INVALID;
834 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
837 case BPF_DYNPTR_TYPE_LOCAL:
838 return DYNPTR_TYPE_LOCAL;
839 case BPF_DYNPTR_TYPE_RINGBUF:
840 return DYNPTR_TYPE_RINGBUF;
841 case BPF_DYNPTR_TYPE_SKB:
842 return DYNPTR_TYPE_SKB;
843 case BPF_DYNPTR_TYPE_XDP:
844 return DYNPTR_TYPE_XDP;
850 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
852 return type == BPF_DYNPTR_TYPE_RINGBUF;
855 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
856 enum bpf_dynptr_type type,
857 bool first_slot, int dynptr_id);
859 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
860 struct bpf_reg_state *reg);
862 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
863 struct bpf_reg_state *sreg1,
864 struct bpf_reg_state *sreg2,
865 enum bpf_dynptr_type type)
867 int id = ++env->id_gen;
869 __mark_dynptr_reg(sreg1, type, true, id);
870 __mark_dynptr_reg(sreg2, type, false, id);
873 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
874 struct bpf_reg_state *reg,
875 enum bpf_dynptr_type type)
877 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
880 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
881 struct bpf_func_state *state, int spi);
883 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
884 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
886 struct bpf_func_state *state = func(env, reg);
887 enum bpf_dynptr_type type;
890 spi = dynptr_get_spi(env, reg);
894 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
895 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
896 * to ensure that for the following example:
899 * So marking spi = 2 should lead to destruction of both d1 and d2. In
900 * case they do belong to same dynptr, second call won't see slot_type
901 * as STACK_DYNPTR and will simply skip destruction.
903 err = destroy_if_dynptr_stack_slot(env, state, spi);
906 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
910 for (i = 0; i < BPF_REG_SIZE; i++) {
911 state->stack[spi].slot_type[i] = STACK_DYNPTR;
912 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
915 type = arg_to_dynptr_type(arg_type);
916 if (type == BPF_DYNPTR_TYPE_INVALID)
919 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
920 &state->stack[spi - 1].spilled_ptr, type);
922 if (dynptr_type_refcounted(type)) {
923 /* The id is used to track proper releasing */
926 if (clone_ref_obj_id)
927 id = clone_ref_obj_id;
929 id = acquire_reference_state(env, insn_idx);
934 state->stack[spi].spilled_ptr.ref_obj_id = id;
935 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
938 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
939 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
944 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
948 for (i = 0; i < BPF_REG_SIZE; i++) {
949 state->stack[spi].slot_type[i] = STACK_INVALID;
950 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
953 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
954 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
956 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
958 * While we don't allow reading STACK_INVALID, it is still possible to
959 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
960 * helpers or insns can do partial read of that part without failing,
961 * but check_stack_range_initialized, check_stack_read_var_off, and
962 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
963 * the slot conservatively. Hence we need to prevent those liveness
966 * This was not a problem before because STACK_INVALID is only set by
967 * default (where the default reg state has its reg->parent as NULL), or
968 * in clean_live_states after REG_LIVE_DONE (at which point
969 * mark_reg_read won't walk reg->parent chain), but not randomly during
970 * verifier state exploration (like we did above). Hence, for our case
971 * parentage chain will still be live (i.e. reg->parent may be
972 * non-NULL), while earlier reg->parent was NULL, so we need
973 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
974 * done later on reads or by mark_dynptr_read as well to unnecessary
975 * mark registers in verifier state.
977 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
978 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
981 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
983 struct bpf_func_state *state = func(env, reg);
984 int spi, ref_obj_id, i;
986 spi = dynptr_get_spi(env, reg);
990 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
991 invalidate_dynptr(env, state, spi);
995 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
997 /* If the dynptr has a ref_obj_id, then we need to invalidate
1000 * 1) Any dynptrs with a matching ref_obj_id (clones)
1001 * 2) Any slices derived from this dynptr.
1004 /* Invalidate any slices associated with this dynptr */
1005 WARN_ON_ONCE(release_reference(env, ref_obj_id));
1007 /* Invalidate any dynptr clones */
1008 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1009 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1012 /* it should always be the case that if the ref obj id
1013 * matches then the stack slot also belongs to a
1016 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1017 verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1020 if (state->stack[i].spilled_ptr.dynptr.first_slot)
1021 invalidate_dynptr(env, state, i);
1027 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1028 struct bpf_reg_state *reg);
1030 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1032 if (!env->allow_ptr_leaks)
1033 __mark_reg_not_init(env, reg);
1035 __mark_reg_unknown(env, reg);
1038 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1039 struct bpf_func_state *state, int spi)
1041 struct bpf_func_state *fstate;
1042 struct bpf_reg_state *dreg;
1045 /* We always ensure that STACK_DYNPTR is never set partially,
1046 * hence just checking for slot_type[0] is enough. This is
1047 * different for STACK_SPILL, where it may be only set for
1048 * 1 byte, so code has to use is_spilled_reg.
1050 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1053 /* Reposition spi to first slot */
1054 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1057 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1058 verbose(env, "cannot overwrite referenced dynptr\n");
1062 mark_stack_slot_scratched(env, spi);
1063 mark_stack_slot_scratched(env, spi - 1);
1065 /* Writing partially to one dynptr stack slot destroys both. */
1066 for (i = 0; i < BPF_REG_SIZE; i++) {
1067 state->stack[spi].slot_type[i] = STACK_INVALID;
1068 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1071 dynptr_id = state->stack[spi].spilled_ptr.id;
1072 /* Invalidate any slices associated with this dynptr */
1073 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1074 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1075 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1077 if (dreg->dynptr_id == dynptr_id)
1078 mark_reg_invalid(env, dreg);
1081 /* Do not release reference state, we are destroying dynptr on stack,
1082 * not using some helper to release it. Just reset register.
1084 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1085 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1087 /* Same reason as unmark_stack_slots_dynptr above */
1088 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1089 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1094 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1098 if (reg->type == CONST_PTR_TO_DYNPTR)
1101 spi = dynptr_get_spi(env, reg);
1103 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1104 * error because this just means the stack state hasn't been updated yet.
1105 * We will do check_mem_access to check and update stack bounds later.
1107 if (spi < 0 && spi != -ERANGE)
1110 /* We don't need to check if the stack slots are marked by previous
1111 * dynptr initializations because we allow overwriting existing unreferenced
1112 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1113 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1114 * touching are completely destructed before we reinitialize them for a new
1115 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1116 * instead of delaying it until the end where the user will get "Unreleased
1122 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1124 struct bpf_func_state *state = func(env, reg);
1127 /* This already represents first slot of initialized bpf_dynptr.
1129 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1130 * check_func_arg_reg_off's logic, so we don't need to check its
1131 * offset and alignment.
1133 if (reg->type == CONST_PTR_TO_DYNPTR)
1136 spi = dynptr_get_spi(env, reg);
1139 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1142 for (i = 0; i < BPF_REG_SIZE; i++) {
1143 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1144 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1151 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1152 enum bpf_arg_type arg_type)
1154 struct bpf_func_state *state = func(env, reg);
1155 enum bpf_dynptr_type dynptr_type;
1158 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1159 if (arg_type == ARG_PTR_TO_DYNPTR)
1162 dynptr_type = arg_to_dynptr_type(arg_type);
1163 if (reg->type == CONST_PTR_TO_DYNPTR) {
1164 return reg->dynptr.type == dynptr_type;
1166 spi = dynptr_get_spi(env, reg);
1169 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1173 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1175 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1176 struct bpf_reg_state *reg, int insn_idx,
1177 struct btf *btf, u32 btf_id, int nr_slots)
1179 struct bpf_func_state *state = func(env, reg);
1182 spi = iter_get_spi(env, reg, nr_slots);
1186 id = acquire_reference_state(env, insn_idx);
1190 for (i = 0; i < nr_slots; i++) {
1191 struct bpf_stack_state *slot = &state->stack[spi - i];
1192 struct bpf_reg_state *st = &slot->spilled_ptr;
1194 __mark_reg_known_zero(st);
1195 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1196 st->live |= REG_LIVE_WRITTEN;
1197 st->ref_obj_id = i == 0 ? id : 0;
1199 st->iter.btf_id = btf_id;
1200 st->iter.state = BPF_ITER_STATE_ACTIVE;
1203 for (j = 0; j < BPF_REG_SIZE; j++)
1204 slot->slot_type[j] = STACK_ITER;
1206 mark_stack_slot_scratched(env, spi - i);
1212 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1213 struct bpf_reg_state *reg, int nr_slots)
1215 struct bpf_func_state *state = func(env, reg);
1218 spi = iter_get_spi(env, reg, nr_slots);
1222 for (i = 0; i < nr_slots; i++) {
1223 struct bpf_stack_state *slot = &state->stack[spi - i];
1224 struct bpf_reg_state *st = &slot->spilled_ptr;
1227 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1229 __mark_reg_not_init(env, st);
1231 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1232 st->live |= REG_LIVE_WRITTEN;
1234 for (j = 0; j < BPF_REG_SIZE; j++)
1235 slot->slot_type[j] = STACK_INVALID;
1237 mark_stack_slot_scratched(env, spi - i);
1243 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1244 struct bpf_reg_state *reg, int nr_slots)
1246 struct bpf_func_state *state = func(env, reg);
1249 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1250 * will do check_mem_access to check and update stack bounds later, so
1251 * return true for that case.
1253 spi = iter_get_spi(env, reg, nr_slots);
1259 for (i = 0; i < nr_slots; i++) {
1260 struct bpf_stack_state *slot = &state->stack[spi - i];
1262 for (j = 0; j < BPF_REG_SIZE; j++)
1263 if (slot->slot_type[j] == STACK_ITER)
1270 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1271 struct btf *btf, u32 btf_id, int nr_slots)
1273 struct bpf_func_state *state = func(env, reg);
1276 spi = iter_get_spi(env, reg, nr_slots);
1280 for (i = 0; i < nr_slots; i++) {
1281 struct bpf_stack_state *slot = &state->stack[spi - i];
1282 struct bpf_reg_state *st = &slot->spilled_ptr;
1284 /* only main (first) slot has ref_obj_id set */
1285 if (i == 0 && !st->ref_obj_id)
1287 if (i != 0 && st->ref_obj_id)
1289 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1292 for (j = 0; j < BPF_REG_SIZE; j++)
1293 if (slot->slot_type[j] != STACK_ITER)
1300 /* Check if given stack slot is "special":
1301 * - spilled register state (STACK_SPILL);
1302 * - dynptr state (STACK_DYNPTR);
1303 * - iter state (STACK_ITER).
1305 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1307 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1319 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1324 /* The reg state of a pointer or a bounded scalar was saved when
1325 * it was spilled to the stack.
1327 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1329 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1332 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1334 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1335 stack->spilled_ptr.type == SCALAR_VALUE;
1338 static void scrub_spilled_slot(u8 *stype)
1340 if (*stype != STACK_INVALID)
1341 *stype = STACK_MISC;
1344 static void print_verifier_state(struct bpf_verifier_env *env,
1345 const struct bpf_func_state *state,
1348 const struct bpf_reg_state *reg;
1349 enum bpf_reg_type t;
1353 verbose(env, " frame%d:", state->frameno);
1354 for (i = 0; i < MAX_BPF_REG; i++) {
1355 reg = &state->regs[i];
1359 if (!print_all && !reg_scratched(env, i))
1361 verbose(env, " R%d", i);
1362 print_liveness(env, reg->live);
1364 if (t == SCALAR_VALUE && reg->precise)
1366 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1367 tnum_is_const(reg->var_off)) {
1368 /* reg->off should be 0 for SCALAR_VALUE */
1369 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1370 verbose(env, "%lld", reg->var_off.value + reg->off);
1372 const char *sep = "";
1374 verbose(env, "%s", reg_type_str(env, t));
1375 if (base_type(t) == PTR_TO_BTF_ID)
1376 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1379 * _a stands for append, was shortened to avoid multiline statements below.
1380 * This macro is used to output a comma separated list of attributes.
1382 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1385 verbose_a("id=%d", reg->id);
1386 if (reg->ref_obj_id)
1387 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1388 if (type_is_non_owning_ref(reg->type))
1389 verbose_a("%s", "non_own_ref");
1390 if (t != SCALAR_VALUE)
1391 verbose_a("off=%d", reg->off);
1392 if (type_is_pkt_pointer(t))
1393 verbose_a("r=%d", reg->range);
1394 else if (base_type(t) == CONST_PTR_TO_MAP ||
1395 base_type(t) == PTR_TO_MAP_KEY ||
1396 base_type(t) == PTR_TO_MAP_VALUE)
1397 verbose_a("ks=%d,vs=%d",
1398 reg->map_ptr->key_size,
1399 reg->map_ptr->value_size);
1400 if (tnum_is_const(reg->var_off)) {
1401 /* Typically an immediate SCALAR_VALUE, but
1402 * could be a pointer whose offset is too big
1405 verbose_a("imm=%llx", reg->var_off.value);
1407 if (reg->smin_value != reg->umin_value &&
1408 reg->smin_value != S64_MIN)
1409 verbose_a("smin=%lld", (long long)reg->smin_value);
1410 if (reg->smax_value != reg->umax_value &&
1411 reg->smax_value != S64_MAX)
1412 verbose_a("smax=%lld", (long long)reg->smax_value);
1413 if (reg->umin_value != 0)
1414 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1415 if (reg->umax_value != U64_MAX)
1416 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1417 if (!tnum_is_unknown(reg->var_off)) {
1420 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1421 verbose_a("var_off=%s", tn_buf);
1423 if (reg->s32_min_value != reg->smin_value &&
1424 reg->s32_min_value != S32_MIN)
1425 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1426 if (reg->s32_max_value != reg->smax_value &&
1427 reg->s32_max_value != S32_MAX)
1428 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1429 if (reg->u32_min_value != reg->umin_value &&
1430 reg->u32_min_value != U32_MIN)
1431 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1432 if (reg->u32_max_value != reg->umax_value &&
1433 reg->u32_max_value != U32_MAX)
1434 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1441 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1442 char types_buf[BPF_REG_SIZE + 1];
1446 for (j = 0; j < BPF_REG_SIZE; j++) {
1447 if (state->stack[i].slot_type[j] != STACK_INVALID)
1449 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1451 types_buf[BPF_REG_SIZE] = 0;
1454 if (!print_all && !stack_slot_scratched(env, i))
1456 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1458 reg = &state->stack[i].spilled_ptr;
1461 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1462 print_liveness(env, reg->live);
1463 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1464 if (t == SCALAR_VALUE && reg->precise)
1466 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1467 verbose(env, "%lld", reg->var_off.value + reg->off);
1470 i += BPF_DYNPTR_NR_SLOTS - 1;
1471 reg = &state->stack[i].spilled_ptr;
1473 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1474 print_liveness(env, reg->live);
1475 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1476 if (reg->ref_obj_id)
1477 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1480 /* only main slot has ref_obj_id set; skip others */
1481 reg = &state->stack[i].spilled_ptr;
1482 if (!reg->ref_obj_id)
1485 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1486 print_liveness(env, reg->live);
1487 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1488 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1489 reg->ref_obj_id, iter_state_str(reg->iter.state),
1495 reg = &state->stack[i].spilled_ptr;
1497 for (j = 0; j < BPF_REG_SIZE; j++)
1498 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1499 types_buf[BPF_REG_SIZE] = 0;
1501 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1502 print_liveness(env, reg->live);
1503 verbose(env, "=%s", types_buf);
1507 if (state->acquired_refs && state->refs[0].id) {
1508 verbose(env, " refs=%d", state->refs[0].id);
1509 for (i = 1; i < state->acquired_refs; i++)
1510 if (state->refs[i].id)
1511 verbose(env, ",%d", state->refs[i].id);
1513 if (state->in_callback_fn)
1514 verbose(env, " cb");
1515 if (state->in_async_callback_fn)
1516 verbose(env, " async_cb");
1519 mark_verifier_state_clean(env);
1522 static inline u32 vlog_alignment(u32 pos)
1524 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1525 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1528 static void print_insn_state(struct bpf_verifier_env *env,
1529 const struct bpf_func_state *state)
1531 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1532 /* remove new line character */
1533 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1534 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1536 verbose(env, "%d:", env->insn_idx);
1538 print_verifier_state(env, state, false);
1541 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1542 * small to hold src. This is different from krealloc since we don't want to preserve
1543 * the contents of dst.
1545 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1548 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1554 if (ZERO_OR_NULL_PTR(src))
1557 if (unlikely(check_mul_overflow(n, size, &bytes)))
1560 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1561 dst = krealloc(orig, alloc_bytes, flags);
1567 memcpy(dst, src, bytes);
1569 return dst ? dst : ZERO_SIZE_PTR;
1572 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1573 * small to hold new_n items. new items are zeroed out if the array grows.
1575 * Contrary to krealloc_array, does not free arr if new_n is zero.
1577 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1582 if (!new_n || old_n == new_n)
1585 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1586 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1594 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1597 return arr ? arr : ZERO_SIZE_PTR;
1600 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1602 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1603 sizeof(struct bpf_reference_state), GFP_KERNEL);
1607 dst->acquired_refs = src->acquired_refs;
1611 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1613 size_t n = src->allocated_stack / BPF_REG_SIZE;
1615 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1620 dst->allocated_stack = src->allocated_stack;
1624 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1626 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1627 sizeof(struct bpf_reference_state));
1631 state->acquired_refs = n;
1635 /* Possibly update state->allocated_stack to be at least size bytes. Also
1636 * possibly update the function's high-water mark in its bpf_subprog_info.
1638 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1640 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1645 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1649 state->allocated_stack = size;
1651 /* update known max for given subprogram */
1652 if (env->subprog_info[state->subprogno].stack_depth < size)
1653 env->subprog_info[state->subprogno].stack_depth = size;
1658 /* Acquire a pointer id from the env and update the state->refs to include
1659 * this new pointer reference.
1660 * On success, returns a valid pointer id to associate with the register
1661 * On failure, returns a negative errno.
1663 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1665 struct bpf_func_state *state = cur_func(env);
1666 int new_ofs = state->acquired_refs;
1669 err = resize_reference_state(state, state->acquired_refs + 1);
1673 state->refs[new_ofs].id = id;
1674 state->refs[new_ofs].insn_idx = insn_idx;
1675 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1680 /* release function corresponding to acquire_reference_state(). Idempotent. */
1681 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1685 last_idx = state->acquired_refs - 1;
1686 for (i = 0; i < state->acquired_refs; i++) {
1687 if (state->refs[i].id == ptr_id) {
1688 /* Cannot release caller references in callbacks */
1689 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1691 if (last_idx && i != last_idx)
1692 memcpy(&state->refs[i], &state->refs[last_idx],
1693 sizeof(*state->refs));
1694 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1695 state->acquired_refs--;
1702 static void free_func_state(struct bpf_func_state *state)
1707 kfree(state->stack);
1711 static void clear_jmp_history(struct bpf_verifier_state *state)
1713 kfree(state->jmp_history);
1714 state->jmp_history = NULL;
1715 state->jmp_history_cnt = 0;
1718 static void free_verifier_state(struct bpf_verifier_state *state,
1723 for (i = 0; i <= state->curframe; i++) {
1724 free_func_state(state->frame[i]);
1725 state->frame[i] = NULL;
1727 clear_jmp_history(state);
1732 /* copy verifier state from src to dst growing dst stack space
1733 * when necessary to accommodate larger src stack
1735 static int copy_func_state(struct bpf_func_state *dst,
1736 const struct bpf_func_state *src)
1740 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1741 err = copy_reference_state(dst, src);
1744 return copy_stack_state(dst, src);
1747 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1748 const struct bpf_verifier_state *src)
1750 struct bpf_func_state *dst;
1753 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1754 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1756 if (!dst_state->jmp_history)
1758 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1760 /* if dst has more stack frames then src frame, free them */
1761 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1762 free_func_state(dst_state->frame[i]);
1763 dst_state->frame[i] = NULL;
1765 dst_state->speculative = src->speculative;
1766 dst_state->active_rcu_lock = src->active_rcu_lock;
1767 dst_state->curframe = src->curframe;
1768 dst_state->active_lock.ptr = src->active_lock.ptr;
1769 dst_state->active_lock.id = src->active_lock.id;
1770 dst_state->branches = src->branches;
1771 dst_state->parent = src->parent;
1772 dst_state->first_insn_idx = src->first_insn_idx;
1773 dst_state->last_insn_idx = src->last_insn_idx;
1774 dst_state->dfs_depth = src->dfs_depth;
1775 dst_state->used_as_loop_entry = src->used_as_loop_entry;
1776 for (i = 0; i <= src->curframe; i++) {
1777 dst = dst_state->frame[i];
1779 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1782 dst_state->frame[i] = dst;
1784 err = copy_func_state(dst, src->frame[i]);
1791 static u32 state_htab_size(struct bpf_verifier_env *env)
1793 return env->prog->len;
1796 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1798 struct bpf_verifier_state *cur = env->cur_state;
1799 struct bpf_func_state *state = cur->frame[cur->curframe];
1801 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1804 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1808 if (a->curframe != b->curframe)
1811 for (fr = a->curframe; fr >= 0; fr--)
1812 if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1818 /* Open coded iterators allow back-edges in the state graph in order to
1819 * check unbounded loops that iterators.
1821 * In is_state_visited() it is necessary to know if explored states are
1822 * part of some loops in order to decide whether non-exact states
1823 * comparison could be used:
1824 * - non-exact states comparison establishes sub-state relation and uses
1825 * read and precision marks to do so, these marks are propagated from
1826 * children states and thus are not guaranteed to be final in a loop;
1827 * - exact states comparison just checks if current and explored states
1828 * are identical (and thus form a back-edge).
1830 * Paper "A New Algorithm for Identifying Loops in Decompilation"
1831 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1832 * algorithm for loop structure detection and gives an overview of
1833 * relevant terminology. It also has helpful illustrations.
1835 * [1] https://api.semanticscholar.org/CorpusID:15784067
1837 * We use a similar algorithm but because loop nested structure is
1838 * irrelevant for verifier ours is significantly simpler and resembles
1839 * strongly connected components algorithm from Sedgewick's textbook.
1841 * Define topmost loop entry as a first node of the loop traversed in a
1842 * depth first search starting from initial state. The goal of the loop
1843 * tracking algorithm is to associate topmost loop entries with states
1844 * derived from these entries.
1846 * For each step in the DFS states traversal algorithm needs to identify
1847 * the following situations:
1849 * initial initial initial
1852 * ... ... .---------> hdr
1855 * cur .-> succ | .------...
1858 * succ '-- cur | ... ...
1868 * (A) successor state of cur (B) successor state of cur or it's entry
1869 * not yet traversed are in current DFS path, thus cur and succ
1870 * are members of the same outermost loop
1878 * .------... .------...
1881 * .-> hdr ... ... ...
1884 * | succ <- cur succ <- cur
1891 * (C) successor state of cur is a part of some loop but this loop
1892 * does not include cur or successor state is not in a loop at all.
1894 * Algorithm could be described as the following python code:
1896 * traversed = set() # Set of traversed nodes
1897 * entries = {} # Mapping from node to loop entry
1898 * depths = {} # Depth level assigned to graph node
1899 * path = set() # Current DFS path
1901 * # Find outermost loop entry known for n
1902 * def get_loop_entry(n):
1903 * h = entries.get(n, None)
1904 * while h in entries and entries[h] != h:
1908 * # Update n's loop entry if h's outermost entry comes
1909 * # before n's outermost entry in current DFS path.
1910 * def update_loop_entry(n, h):
1911 * n1 = get_loop_entry(n) or n
1912 * h1 = get_loop_entry(h) or h
1913 * if h1 in path and depths[h1] <= depths[n1]:
1916 * def dfs(n, depth):
1920 * for succ in G.successors(n):
1921 * if succ not in traversed:
1922 * # Case A: explore succ and update cur's loop entry
1923 * # only if succ's entry is in current DFS path.
1924 * dfs(succ, depth + 1)
1925 * h = get_loop_entry(succ)
1926 * update_loop_entry(n, h)
1928 * # Case B or C depending on `h1 in path` check in update_loop_entry().
1929 * update_loop_entry(n, succ)
1932 * To adapt this algorithm for use with verifier:
1933 * - use st->branch == 0 as a signal that DFS of succ had been finished
1934 * and cur's loop entry has to be updated (case A), handle this in
1935 * update_branch_counts();
1936 * - use st->branch > 0 as a signal that st is in the current DFS path;
1937 * - handle cases B and C in is_state_visited();
1938 * - update topmost loop entry for intermediate states in get_loop_entry().
1940 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1942 struct bpf_verifier_state *topmost = st->loop_entry, *old;
1944 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1945 topmost = topmost->loop_entry;
1946 /* Update loop entries for intermediate states to avoid this
1947 * traversal in future get_loop_entry() calls.
1949 while (st && st->loop_entry != topmost) {
1950 old = st->loop_entry;
1951 st->loop_entry = topmost;
1957 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1959 struct bpf_verifier_state *cur1, *hdr1;
1961 cur1 = get_loop_entry(cur) ?: cur;
1962 hdr1 = get_loop_entry(hdr) ?: hdr;
1963 /* The head1->branches check decides between cases B and C in
1964 * comment for get_loop_entry(). If hdr1->branches == 0 then
1965 * head's topmost loop entry is not in current DFS path,
1966 * hence 'cur' and 'hdr' are not in the same loop and there is
1967 * no need to update cur->loop_entry.
1969 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1970 cur->loop_entry = hdr;
1971 hdr->used_as_loop_entry = true;
1975 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1978 u32 br = --st->branches;
1980 /* br == 0 signals that DFS exploration for 'st' is finished,
1981 * thus it is necessary to update parent's loop entry if it
1982 * turned out that st is a part of some loop.
1983 * This is a part of 'case A' in get_loop_entry() comment.
1985 if (br == 0 && st->parent && st->loop_entry)
1986 update_loop_entry(st->parent, st->loop_entry);
1988 /* WARN_ON(br > 1) technically makes sense here,
1989 * but see comment in push_stack(), hence:
1991 WARN_ONCE((int)br < 0,
1992 "BUG update_branch_counts:branches_to_explore=%d\n",
2000 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2001 int *insn_idx, bool pop_log)
2003 struct bpf_verifier_state *cur = env->cur_state;
2004 struct bpf_verifier_stack_elem *elem, *head = env->head;
2007 if (env->head == NULL)
2011 err = copy_verifier_state(cur, &head->st);
2016 bpf_vlog_reset(&env->log, head->log_pos);
2018 *insn_idx = head->insn_idx;
2020 *prev_insn_idx = head->prev_insn_idx;
2022 free_verifier_state(&head->st, false);
2029 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2030 int insn_idx, int prev_insn_idx,
2033 struct bpf_verifier_state *cur = env->cur_state;
2034 struct bpf_verifier_stack_elem *elem;
2037 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2041 elem->insn_idx = insn_idx;
2042 elem->prev_insn_idx = prev_insn_idx;
2043 elem->next = env->head;
2044 elem->log_pos = env->log.end_pos;
2047 err = copy_verifier_state(&elem->st, cur);
2050 elem->st.speculative |= speculative;
2051 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2052 verbose(env, "The sequence of %d jumps is too complex.\n",
2056 if (elem->st.parent) {
2057 ++elem->st.parent->branches;
2058 /* WARN_ON(branches > 2) technically makes sense here,
2060 * 1. speculative states will bump 'branches' for non-branch
2062 * 2. is_state_visited() heuristics may decide not to create
2063 * a new state for a sequence of branches and all such current
2064 * and cloned states will be pointing to a single parent state
2065 * which might have large 'branches' count.
2070 free_verifier_state(env->cur_state, true);
2071 env->cur_state = NULL;
2072 /* pop all elements and return */
2073 while (!pop_stack(env, NULL, NULL, false));
2077 #define CALLER_SAVED_REGS 6
2078 static const int caller_saved[CALLER_SAVED_REGS] = {
2079 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2082 /* This helper doesn't clear reg->id */
2083 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2085 reg->var_off = tnum_const(imm);
2086 reg->smin_value = (s64)imm;
2087 reg->smax_value = (s64)imm;
2088 reg->umin_value = imm;
2089 reg->umax_value = imm;
2091 reg->s32_min_value = (s32)imm;
2092 reg->s32_max_value = (s32)imm;
2093 reg->u32_min_value = (u32)imm;
2094 reg->u32_max_value = (u32)imm;
2097 /* Mark the unknown part of a register (variable offset or scalar value) as
2098 * known to have the value @imm.
2100 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2102 /* Clear off and union(map_ptr, range) */
2103 memset(((u8 *)reg) + sizeof(reg->type), 0,
2104 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2106 reg->ref_obj_id = 0;
2107 ___mark_reg_known(reg, imm);
2110 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2112 reg->var_off = tnum_const_subreg(reg->var_off, imm);
2113 reg->s32_min_value = (s32)imm;
2114 reg->s32_max_value = (s32)imm;
2115 reg->u32_min_value = (u32)imm;
2116 reg->u32_max_value = (u32)imm;
2119 /* Mark the 'variable offset' part of a register as zero. This should be
2120 * used only on registers holding a pointer type.
2122 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2124 __mark_reg_known(reg, 0);
2127 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
2129 __mark_reg_known(reg, 0);
2130 reg->type = SCALAR_VALUE;
2133 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2134 struct bpf_reg_state *regs, u32 regno)
2136 if (WARN_ON(regno >= MAX_BPF_REG)) {
2137 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2138 /* Something bad happened, let's kill all regs */
2139 for (regno = 0; regno < MAX_BPF_REG; regno++)
2140 __mark_reg_not_init(env, regs + regno);
2143 __mark_reg_known_zero(regs + regno);
2146 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2147 bool first_slot, int dynptr_id)
2149 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2150 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2151 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2153 __mark_reg_known_zero(reg);
2154 reg->type = CONST_PTR_TO_DYNPTR;
2155 /* Give each dynptr a unique id to uniquely associate slices to it. */
2156 reg->id = dynptr_id;
2157 reg->dynptr.type = type;
2158 reg->dynptr.first_slot = first_slot;
2161 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2163 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2164 const struct bpf_map *map = reg->map_ptr;
2166 if (map->inner_map_meta) {
2167 reg->type = CONST_PTR_TO_MAP;
2168 reg->map_ptr = map->inner_map_meta;
2169 /* transfer reg's id which is unique for every map_lookup_elem
2170 * as UID of the inner map.
2172 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2173 reg->map_uid = reg->id;
2174 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2175 reg->type = PTR_TO_XDP_SOCK;
2176 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2177 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2178 reg->type = PTR_TO_SOCKET;
2180 reg->type = PTR_TO_MAP_VALUE;
2185 reg->type &= ~PTR_MAYBE_NULL;
2188 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2189 struct btf_field_graph_root *ds_head)
2191 __mark_reg_known_zero(®s[regno]);
2192 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2193 regs[regno].btf = ds_head->btf;
2194 regs[regno].btf_id = ds_head->value_btf_id;
2195 regs[regno].off = ds_head->node_offset;
2198 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2200 return type_is_pkt_pointer(reg->type);
2203 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2205 return reg_is_pkt_pointer(reg) ||
2206 reg->type == PTR_TO_PACKET_END;
2209 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2211 return base_type(reg->type) == PTR_TO_MEM &&
2212 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2215 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2216 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2217 enum bpf_reg_type which)
2219 /* The register can already have a range from prior markings.
2220 * This is fine as long as it hasn't been advanced from its
2223 return reg->type == which &&
2226 tnum_equals_const(reg->var_off, 0);
2229 /* Reset the min/max bounds of a register */
2230 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2232 reg->smin_value = S64_MIN;
2233 reg->smax_value = S64_MAX;
2234 reg->umin_value = 0;
2235 reg->umax_value = U64_MAX;
2237 reg->s32_min_value = S32_MIN;
2238 reg->s32_max_value = S32_MAX;
2239 reg->u32_min_value = 0;
2240 reg->u32_max_value = U32_MAX;
2243 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2245 reg->smin_value = S64_MIN;
2246 reg->smax_value = S64_MAX;
2247 reg->umin_value = 0;
2248 reg->umax_value = U64_MAX;
2251 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2253 reg->s32_min_value = S32_MIN;
2254 reg->s32_max_value = S32_MAX;
2255 reg->u32_min_value = 0;
2256 reg->u32_max_value = U32_MAX;
2259 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2261 struct tnum var32_off = tnum_subreg(reg->var_off);
2263 /* min signed is max(sign bit) | min(other bits) */
2264 reg->s32_min_value = max_t(s32, reg->s32_min_value,
2265 var32_off.value | (var32_off.mask & S32_MIN));
2266 /* max signed is min(sign bit) | max(other bits) */
2267 reg->s32_max_value = min_t(s32, reg->s32_max_value,
2268 var32_off.value | (var32_off.mask & S32_MAX));
2269 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2270 reg->u32_max_value = min(reg->u32_max_value,
2271 (u32)(var32_off.value | var32_off.mask));
2274 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2276 /* min signed is max(sign bit) | min(other bits) */
2277 reg->smin_value = max_t(s64, reg->smin_value,
2278 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2279 /* max signed is min(sign bit) | max(other bits) */
2280 reg->smax_value = min_t(s64, reg->smax_value,
2281 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2282 reg->umin_value = max(reg->umin_value, reg->var_off.value);
2283 reg->umax_value = min(reg->umax_value,
2284 reg->var_off.value | reg->var_off.mask);
2287 static void __update_reg_bounds(struct bpf_reg_state *reg)
2289 __update_reg32_bounds(reg);
2290 __update_reg64_bounds(reg);
2293 /* Uses signed min/max values to inform unsigned, and vice-versa */
2294 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2296 /* Learn sign from signed bounds.
2297 * If we cannot cross the sign boundary, then signed and unsigned bounds
2298 * are the same, so combine. This works even in the negative case, e.g.
2299 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2301 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2302 reg->s32_min_value = reg->u32_min_value =
2303 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2304 reg->s32_max_value = reg->u32_max_value =
2305 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2308 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2309 * boundary, so we must be careful.
2311 if ((s32)reg->u32_max_value >= 0) {
2312 /* Positive. We can't learn anything from the smin, but smax
2313 * is positive, hence safe.
2315 reg->s32_min_value = reg->u32_min_value;
2316 reg->s32_max_value = reg->u32_max_value =
2317 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2318 } else if ((s32)reg->u32_min_value < 0) {
2319 /* Negative. We can't learn anything from the smax, but smin
2320 * is negative, hence safe.
2322 reg->s32_min_value = reg->u32_min_value =
2323 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2324 reg->s32_max_value = reg->u32_max_value;
2328 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2330 /* Learn sign from signed bounds.
2331 * If we cannot cross the sign boundary, then signed and unsigned bounds
2332 * are the same, so combine. This works even in the negative case, e.g.
2333 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2335 if (reg->smin_value >= 0 || reg->smax_value < 0) {
2336 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2338 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2342 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2343 * boundary, so we must be careful.
2345 if ((s64)reg->umax_value >= 0) {
2346 /* Positive. We can't learn anything from the smin, but smax
2347 * is positive, hence safe.
2349 reg->smin_value = reg->umin_value;
2350 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2352 } else if ((s64)reg->umin_value < 0) {
2353 /* Negative. We can't learn anything from the smax, but smin
2354 * is negative, hence safe.
2356 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2358 reg->smax_value = reg->umax_value;
2362 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2364 __reg32_deduce_bounds(reg);
2365 __reg64_deduce_bounds(reg);
2368 /* Attempts to improve var_off based on unsigned min/max information */
2369 static void __reg_bound_offset(struct bpf_reg_state *reg)
2371 struct tnum var64_off = tnum_intersect(reg->var_off,
2372 tnum_range(reg->umin_value,
2374 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2375 tnum_range(reg->u32_min_value,
2376 reg->u32_max_value));
2378 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2381 static void reg_bounds_sync(struct bpf_reg_state *reg)
2383 /* We might have learned new bounds from the var_off. */
2384 __update_reg_bounds(reg);
2385 /* We might have learned something about the sign bit. */
2386 __reg_deduce_bounds(reg);
2387 /* We might have learned some bits from the bounds. */
2388 __reg_bound_offset(reg);
2389 /* Intersecting with the old var_off might have improved our bounds
2390 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2391 * then new var_off is (0; 0x7f...fc) which improves our umax.
2393 __update_reg_bounds(reg);
2396 static bool __reg32_bound_s64(s32 a)
2398 return a >= 0 && a <= S32_MAX;
2401 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2403 reg->umin_value = reg->u32_min_value;
2404 reg->umax_value = reg->u32_max_value;
2406 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2407 * be positive otherwise set to worse case bounds and refine later
2410 if (__reg32_bound_s64(reg->s32_min_value) &&
2411 __reg32_bound_s64(reg->s32_max_value)) {
2412 reg->smin_value = reg->s32_min_value;
2413 reg->smax_value = reg->s32_max_value;
2415 reg->smin_value = 0;
2416 reg->smax_value = U32_MAX;
2420 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2422 /* special case when 64-bit register has upper 32-bit register
2423 * zeroed. Typically happens after zext or <<32, >>32 sequence
2424 * allowing us to use 32-bit bounds directly,
2426 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2427 __reg_assign_32_into_64(reg);
2429 /* Otherwise the best we can do is push lower 32bit known and
2430 * unknown bits into register (var_off set from jmp logic)
2431 * then learn as much as possible from the 64-bit tnum
2432 * known and unknown bits. The previous smin/smax bounds are
2433 * invalid here because of jmp32 compare so mark them unknown
2434 * so they do not impact tnum bounds calculation.
2436 __mark_reg64_unbounded(reg);
2438 reg_bounds_sync(reg);
2441 static bool __reg64_bound_s32(s64 a)
2443 return a >= S32_MIN && a <= S32_MAX;
2446 static bool __reg64_bound_u32(u64 a)
2448 return a >= U32_MIN && a <= U32_MAX;
2451 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2453 __mark_reg32_unbounded(reg);
2454 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2455 reg->s32_min_value = (s32)reg->smin_value;
2456 reg->s32_max_value = (s32)reg->smax_value;
2458 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2459 reg->u32_min_value = (u32)reg->umin_value;
2460 reg->u32_max_value = (u32)reg->umax_value;
2462 reg_bounds_sync(reg);
2465 /* Mark a register as having a completely unknown (scalar) value. */
2466 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2467 struct bpf_reg_state *reg)
2470 * Clear type, off, and union(map_ptr, range) and
2471 * padding between 'type' and union
2473 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2474 reg->type = SCALAR_VALUE;
2476 reg->ref_obj_id = 0;
2477 reg->var_off = tnum_unknown;
2479 reg->precise = !env->bpf_capable;
2480 __mark_reg_unbounded(reg);
2483 static void mark_reg_unknown(struct bpf_verifier_env *env,
2484 struct bpf_reg_state *regs, u32 regno)
2486 if (WARN_ON(regno >= MAX_BPF_REG)) {
2487 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2488 /* Something bad happened, let's kill all regs except FP */
2489 for (regno = 0; regno < BPF_REG_FP; regno++)
2490 __mark_reg_not_init(env, regs + regno);
2493 __mark_reg_unknown(env, regs + regno);
2496 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2497 struct bpf_reg_state *reg)
2499 __mark_reg_unknown(env, reg);
2500 reg->type = NOT_INIT;
2503 static void mark_reg_not_init(struct bpf_verifier_env *env,
2504 struct bpf_reg_state *regs, u32 regno)
2506 if (WARN_ON(regno >= MAX_BPF_REG)) {
2507 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2508 /* Something bad happened, let's kill all regs except FP */
2509 for (regno = 0; regno < BPF_REG_FP; regno++)
2510 __mark_reg_not_init(env, regs + regno);
2513 __mark_reg_not_init(env, regs + regno);
2516 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2517 struct bpf_reg_state *regs, u32 regno,
2518 enum bpf_reg_type reg_type,
2519 struct btf *btf, u32 btf_id,
2520 enum bpf_type_flag flag)
2522 if (reg_type == SCALAR_VALUE) {
2523 mark_reg_unknown(env, regs, regno);
2526 mark_reg_known_zero(env, regs, regno);
2527 regs[regno].type = PTR_TO_BTF_ID | flag;
2528 regs[regno].btf = btf;
2529 regs[regno].btf_id = btf_id;
2532 #define DEF_NOT_SUBREG (0)
2533 static void init_reg_state(struct bpf_verifier_env *env,
2534 struct bpf_func_state *state)
2536 struct bpf_reg_state *regs = state->regs;
2539 for (i = 0; i < MAX_BPF_REG; i++) {
2540 mark_reg_not_init(env, regs, i);
2541 regs[i].live = REG_LIVE_NONE;
2542 regs[i].parent = NULL;
2543 regs[i].subreg_def = DEF_NOT_SUBREG;
2547 regs[BPF_REG_FP].type = PTR_TO_STACK;
2548 mark_reg_known_zero(env, regs, BPF_REG_FP);
2549 regs[BPF_REG_FP].frameno = state->frameno;
2552 #define BPF_MAIN_FUNC (-1)
2553 static void init_func_state(struct bpf_verifier_env *env,
2554 struct bpf_func_state *state,
2555 int callsite, int frameno, int subprogno)
2557 state->callsite = callsite;
2558 state->frameno = frameno;
2559 state->subprogno = subprogno;
2560 state->callback_ret_range = tnum_range(0, 0);
2561 init_reg_state(env, state);
2562 mark_verifier_state_scratched(env);
2565 /* Similar to push_stack(), but for async callbacks */
2566 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2567 int insn_idx, int prev_insn_idx,
2570 struct bpf_verifier_stack_elem *elem;
2571 struct bpf_func_state *frame;
2573 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2577 elem->insn_idx = insn_idx;
2578 elem->prev_insn_idx = prev_insn_idx;
2579 elem->next = env->head;
2580 elem->log_pos = env->log.end_pos;
2583 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2585 "The sequence of %d jumps is too complex for async cb.\n",
2589 /* Unlike push_stack() do not copy_verifier_state().
2590 * The caller state doesn't matter.
2591 * This is async callback. It starts in a fresh stack.
2592 * Initialize it similar to do_check_common().
2594 elem->st.branches = 1;
2595 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2598 init_func_state(env, frame,
2599 BPF_MAIN_FUNC /* callsite */,
2600 0 /* frameno within this callchain */,
2601 subprog /* subprog number within this prog */);
2602 elem->st.frame[0] = frame;
2605 free_verifier_state(env->cur_state, true);
2606 env->cur_state = NULL;
2607 /* pop all elements and return */
2608 while (!pop_stack(env, NULL, NULL, false));
2614 SRC_OP, /* register is used as source operand */
2615 DST_OP, /* register is used as destination operand */
2616 DST_OP_NO_MARK /* same as above, check only, don't mark */
2619 static int cmp_subprogs(const void *a, const void *b)
2621 return ((struct bpf_subprog_info *)a)->start -
2622 ((struct bpf_subprog_info *)b)->start;
2625 static int find_subprog(struct bpf_verifier_env *env, int off)
2627 struct bpf_subprog_info *p;
2629 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2630 sizeof(env->subprog_info[0]), cmp_subprogs);
2633 return p - env->subprog_info;
2637 static int add_subprog(struct bpf_verifier_env *env, int off)
2639 int insn_cnt = env->prog->len;
2642 if (off >= insn_cnt || off < 0) {
2643 verbose(env, "call to invalid destination\n");
2646 ret = find_subprog(env, off);
2649 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2650 verbose(env, "too many subprograms\n");
2653 /* determine subprog starts. The end is one before the next starts */
2654 env->subprog_info[env->subprog_cnt++].start = off;
2655 sort(env->subprog_info, env->subprog_cnt,
2656 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2657 return env->subprog_cnt - 1;
2660 #define MAX_KFUNC_DESCS 256
2661 #define MAX_KFUNC_BTFS 256
2663 struct bpf_kfunc_desc {
2664 struct btf_func_model func_model;
2671 struct bpf_kfunc_btf {
2673 struct module *module;
2677 struct bpf_kfunc_desc_tab {
2678 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2679 * verification. JITs do lookups by bpf_insn, where func_id may not be
2680 * available, therefore at the end of verification do_misc_fixups()
2681 * sorts this by imm and offset.
2683 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2687 struct bpf_kfunc_btf_tab {
2688 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2692 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2694 const struct bpf_kfunc_desc *d0 = a;
2695 const struct bpf_kfunc_desc *d1 = b;
2697 /* func_id is not greater than BTF_MAX_TYPE */
2698 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2701 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2703 const struct bpf_kfunc_btf *d0 = a;
2704 const struct bpf_kfunc_btf *d1 = b;
2706 return d0->offset - d1->offset;
2709 static const struct bpf_kfunc_desc *
2710 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2712 struct bpf_kfunc_desc desc = {
2716 struct bpf_kfunc_desc_tab *tab;
2718 tab = prog->aux->kfunc_tab;
2719 return bsearch(&desc, tab->descs, tab->nr_descs,
2720 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2723 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2724 u16 btf_fd_idx, u8 **func_addr)
2726 const struct bpf_kfunc_desc *desc;
2728 desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2732 *func_addr = (u8 *)desc->addr;
2736 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2739 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2740 struct bpf_kfunc_btf_tab *tab;
2741 struct bpf_kfunc_btf *b;
2746 tab = env->prog->aux->kfunc_btf_tab;
2747 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2748 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2750 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2751 verbose(env, "too many different module BTFs\n");
2752 return ERR_PTR(-E2BIG);
2755 if (bpfptr_is_null(env->fd_array)) {
2756 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2757 return ERR_PTR(-EPROTO);
2760 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2761 offset * sizeof(btf_fd),
2763 return ERR_PTR(-EFAULT);
2765 btf = btf_get_by_fd(btf_fd);
2767 verbose(env, "invalid module BTF fd specified\n");
2771 if (!btf_is_module(btf)) {
2772 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2774 return ERR_PTR(-EINVAL);
2777 mod = btf_try_get_module(btf);
2780 return ERR_PTR(-ENXIO);
2783 b = &tab->descs[tab->nr_descs++];
2788 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2789 kfunc_btf_cmp_by_off, NULL);
2794 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2799 while (tab->nr_descs--) {
2800 module_put(tab->descs[tab->nr_descs].module);
2801 btf_put(tab->descs[tab->nr_descs].btf);
2806 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2810 /* In the future, this can be allowed to increase limit
2811 * of fd index into fd_array, interpreted as u16.
2813 verbose(env, "negative offset disallowed for kernel module function call\n");
2814 return ERR_PTR(-EINVAL);
2817 return __find_kfunc_desc_btf(env, offset);
2819 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2822 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2824 const struct btf_type *func, *func_proto;
2825 struct bpf_kfunc_btf_tab *btf_tab;
2826 struct bpf_kfunc_desc_tab *tab;
2827 struct bpf_prog_aux *prog_aux;
2828 struct bpf_kfunc_desc *desc;
2829 const char *func_name;
2830 struct btf *desc_btf;
2831 unsigned long call_imm;
2835 prog_aux = env->prog->aux;
2836 tab = prog_aux->kfunc_tab;
2837 btf_tab = prog_aux->kfunc_btf_tab;
2840 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2844 if (!env->prog->jit_requested) {
2845 verbose(env, "JIT is required for calling kernel function\n");
2849 if (!bpf_jit_supports_kfunc_call()) {
2850 verbose(env, "JIT does not support calling kernel function\n");
2854 if (!env->prog->gpl_compatible) {
2855 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2859 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2862 prog_aux->kfunc_tab = tab;
2865 /* func_id == 0 is always invalid, but instead of returning an error, be
2866 * conservative and wait until the code elimination pass before returning
2867 * error, so that invalid calls that get pruned out can be in BPF programs
2868 * loaded from userspace. It is also required that offset be untouched
2871 if (!func_id && !offset)
2874 if (!btf_tab && offset) {
2875 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2878 prog_aux->kfunc_btf_tab = btf_tab;
2881 desc_btf = find_kfunc_desc_btf(env, offset);
2882 if (IS_ERR(desc_btf)) {
2883 verbose(env, "failed to find BTF for kernel function\n");
2884 return PTR_ERR(desc_btf);
2887 if (find_kfunc_desc(env->prog, func_id, offset))
2890 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2891 verbose(env, "too many different kernel function calls\n");
2895 func = btf_type_by_id(desc_btf, func_id);
2896 if (!func || !btf_type_is_func(func)) {
2897 verbose(env, "kernel btf_id %u is not a function\n",
2901 func_proto = btf_type_by_id(desc_btf, func->type);
2902 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2903 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2908 func_name = btf_name_by_offset(desc_btf, func->name_off);
2909 addr = kallsyms_lookup_name(func_name);
2911 verbose(env, "cannot find address for kernel function %s\n",
2915 specialize_kfunc(env, func_id, offset, &addr);
2917 if (bpf_jit_supports_far_kfunc_call()) {
2920 call_imm = BPF_CALL_IMM(addr);
2921 /* Check whether the relative offset overflows desc->imm */
2922 if ((unsigned long)(s32)call_imm != call_imm) {
2923 verbose(env, "address of kernel function %s is out of range\n",
2929 if (bpf_dev_bound_kfunc_id(func_id)) {
2930 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2935 desc = &tab->descs[tab->nr_descs++];
2936 desc->func_id = func_id;
2937 desc->imm = call_imm;
2938 desc->offset = offset;
2940 err = btf_distill_func_proto(&env->log, desc_btf,
2941 func_proto, func_name,
2944 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2945 kfunc_desc_cmp_by_id_off, NULL);
2949 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2951 const struct bpf_kfunc_desc *d0 = a;
2952 const struct bpf_kfunc_desc *d1 = b;
2954 if (d0->imm != d1->imm)
2955 return d0->imm < d1->imm ? -1 : 1;
2956 if (d0->offset != d1->offset)
2957 return d0->offset < d1->offset ? -1 : 1;
2961 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2963 struct bpf_kfunc_desc_tab *tab;
2965 tab = prog->aux->kfunc_tab;
2969 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2970 kfunc_desc_cmp_by_imm_off, NULL);
2973 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2975 return !!prog->aux->kfunc_tab;
2978 const struct btf_func_model *
2979 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2980 const struct bpf_insn *insn)
2982 const struct bpf_kfunc_desc desc = {
2984 .offset = insn->off,
2986 const struct bpf_kfunc_desc *res;
2987 struct bpf_kfunc_desc_tab *tab;
2989 tab = prog->aux->kfunc_tab;
2990 res = bsearch(&desc, tab->descs, tab->nr_descs,
2991 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2993 return res ? &res->func_model : NULL;
2996 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2998 struct bpf_subprog_info *subprog = env->subprog_info;
2999 struct bpf_insn *insn = env->prog->insnsi;
3000 int i, ret, insn_cnt = env->prog->len;
3002 /* Add entry function. */
3003 ret = add_subprog(env, 0);
3007 for (i = 0; i < insn_cnt; i++, insn++) {
3008 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3009 !bpf_pseudo_kfunc_call(insn))
3012 if (!env->bpf_capable) {
3013 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3017 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3018 ret = add_subprog(env, i + insn->imm + 1);
3020 ret = add_kfunc_call(env, insn->imm, insn->off);
3026 /* Add a fake 'exit' subprog which could simplify subprog iteration
3027 * logic. 'subprog_cnt' should not be increased.
3029 subprog[env->subprog_cnt].start = insn_cnt;
3031 if (env->log.level & BPF_LOG_LEVEL2)
3032 for (i = 0; i < env->subprog_cnt; i++)
3033 verbose(env, "func#%d @%d\n", i, subprog[i].start);
3038 static int check_subprogs(struct bpf_verifier_env *env)
3040 int i, subprog_start, subprog_end, off, cur_subprog = 0;
3041 struct bpf_subprog_info *subprog = env->subprog_info;
3042 struct bpf_insn *insn = env->prog->insnsi;
3043 int insn_cnt = env->prog->len;
3045 /* now check that all jumps are within the same subprog */
3046 subprog_start = subprog[cur_subprog].start;
3047 subprog_end = subprog[cur_subprog + 1].start;
3048 for (i = 0; i < insn_cnt; i++) {
3049 u8 code = insn[i].code;
3051 if (code == (BPF_JMP | BPF_CALL) &&
3052 insn[i].src_reg == 0 &&
3053 insn[i].imm == BPF_FUNC_tail_call)
3054 subprog[cur_subprog].has_tail_call = true;
3055 if (BPF_CLASS(code) == BPF_LD &&
3056 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3057 subprog[cur_subprog].has_ld_abs = true;
3058 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3060 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3062 if (code == (BPF_JMP32 | BPF_JA))
3063 off = i + insn[i].imm + 1;
3065 off = i + insn[i].off + 1;
3066 if (off < subprog_start || off >= subprog_end) {
3067 verbose(env, "jump out of range from insn %d to %d\n", i, off);
3071 if (i == subprog_end - 1) {
3072 /* to avoid fall-through from one subprog into another
3073 * the last insn of the subprog should be either exit
3074 * or unconditional jump back
3076 if (code != (BPF_JMP | BPF_EXIT) &&
3077 code != (BPF_JMP32 | BPF_JA) &&
3078 code != (BPF_JMP | BPF_JA)) {
3079 verbose(env, "last insn is not an exit or jmp\n");
3082 subprog_start = subprog_end;
3084 if (cur_subprog < env->subprog_cnt)
3085 subprog_end = subprog[cur_subprog + 1].start;
3091 /* Parentage chain of this register (or stack slot) should take care of all
3092 * issues like callee-saved registers, stack slot allocation time, etc.
3094 static int mark_reg_read(struct bpf_verifier_env *env,
3095 const struct bpf_reg_state *state,
3096 struct bpf_reg_state *parent, u8 flag)
3098 bool writes = parent == state->parent; /* Observe write marks */
3102 /* if read wasn't screened by an earlier write ... */
3103 if (writes && state->live & REG_LIVE_WRITTEN)
3105 if (parent->live & REG_LIVE_DONE) {
3106 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3107 reg_type_str(env, parent->type),
3108 parent->var_off.value, parent->off);
3111 /* The first condition is more likely to be true than the
3112 * second, checked it first.
3114 if ((parent->live & REG_LIVE_READ) == flag ||
3115 parent->live & REG_LIVE_READ64)
3116 /* The parentage chain never changes and
3117 * this parent was already marked as LIVE_READ.
3118 * There is no need to keep walking the chain again and
3119 * keep re-marking all parents as LIVE_READ.
3120 * This case happens when the same register is read
3121 * multiple times without writes into it in-between.
3122 * Also, if parent has the stronger REG_LIVE_READ64 set,
3123 * then no need to set the weak REG_LIVE_READ32.
3126 /* ... then we depend on parent's value */
3127 parent->live |= flag;
3128 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3129 if (flag == REG_LIVE_READ64)
3130 parent->live &= ~REG_LIVE_READ32;
3132 parent = state->parent;
3137 if (env->longest_mark_read_walk < cnt)
3138 env->longest_mark_read_walk = cnt;
3142 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3144 struct bpf_func_state *state = func(env, reg);
3147 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
3148 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3151 if (reg->type == CONST_PTR_TO_DYNPTR)
3153 spi = dynptr_get_spi(env, reg);
3156 /* Caller ensures dynptr is valid and initialized, which means spi is in
3157 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3160 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3161 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3164 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3165 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3168 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3169 int spi, int nr_slots)
3171 struct bpf_func_state *state = func(env, reg);
3174 for (i = 0; i < nr_slots; i++) {
3175 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3177 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3181 mark_stack_slot_scratched(env, spi - i);
3187 /* This function is supposed to be used by the following 32-bit optimization
3188 * code only. It returns TRUE if the source or destination register operates
3189 * on 64-bit, otherwise return FALSE.
3191 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3192 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3197 class = BPF_CLASS(code);
3199 if (class == BPF_JMP) {
3200 /* BPF_EXIT for "main" will reach here. Return TRUE
3205 if (op == BPF_CALL) {
3206 /* BPF to BPF call will reach here because of marking
3207 * caller saved clobber with DST_OP_NO_MARK for which we
3208 * don't care the register def because they are anyway
3209 * marked as NOT_INIT already.
3211 if (insn->src_reg == BPF_PSEUDO_CALL)
3213 /* Helper call will reach here because of arg type
3214 * check, conservatively return TRUE.
3223 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3226 if (class == BPF_ALU64 || class == BPF_JMP ||
3227 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3230 if (class == BPF_ALU || class == BPF_JMP32)
3233 if (class == BPF_LDX) {
3235 return BPF_SIZE(code) == BPF_DW;
3236 /* LDX source must be ptr. */
3240 if (class == BPF_STX) {
3241 /* BPF_STX (including atomic variants) has multiple source
3242 * operands, one of which is a ptr. Check whether the caller is
3245 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3247 return BPF_SIZE(code) == BPF_DW;
3250 if (class == BPF_LD) {
3251 u8 mode = BPF_MODE(code);
3254 if (mode == BPF_IMM)
3257 /* Both LD_IND and LD_ABS return 32-bit data. */
3261 /* Implicit ctx ptr. */
3262 if (regno == BPF_REG_6)
3265 /* Explicit source could be any width. */
3269 if (class == BPF_ST)
3270 /* The only source register for BPF_ST is a ptr. */
3273 /* Conservatively return true at default. */
3277 /* Return the regno defined by the insn, or -1. */
3278 static int insn_def_regno(const struct bpf_insn *insn)
3280 switch (BPF_CLASS(insn->code)) {
3286 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3287 (insn->imm & BPF_FETCH)) {
3288 if (insn->imm == BPF_CMPXCHG)
3291 return insn->src_reg;
3296 return insn->dst_reg;
3300 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3301 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3303 int dst_reg = insn_def_regno(insn);
3308 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3311 static void mark_insn_zext(struct bpf_verifier_env *env,
3312 struct bpf_reg_state *reg)
3314 s32 def_idx = reg->subreg_def;
3316 if (def_idx == DEF_NOT_SUBREG)
3319 env->insn_aux_data[def_idx - 1].zext_dst = true;
3320 /* The dst will be zero extended, so won't be sub-register anymore. */
3321 reg->subreg_def = DEF_NOT_SUBREG;
3324 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3325 enum reg_arg_type t)
3327 struct bpf_verifier_state *vstate = env->cur_state;
3328 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3329 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3330 struct bpf_reg_state *reg, *regs = state->regs;
3333 if (regno >= MAX_BPF_REG) {
3334 verbose(env, "R%d is invalid\n", regno);
3338 mark_reg_scratched(env, regno);
3341 rw64 = is_reg64(env, insn, regno, reg, t);
3343 /* check whether register used as source operand can be read */
3344 if (reg->type == NOT_INIT) {
3345 verbose(env, "R%d !read_ok\n", regno);
3348 /* We don't need to worry about FP liveness because it's read-only */
3349 if (regno == BPF_REG_FP)
3353 mark_insn_zext(env, reg);
3355 return mark_reg_read(env, reg, reg->parent,
3356 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3358 /* check whether register used as dest operand can be written to */
3359 if (regno == BPF_REG_FP) {
3360 verbose(env, "frame pointer is read only\n");
3363 reg->live |= REG_LIVE_WRITTEN;
3364 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3366 mark_reg_unknown(env, regs, regno);
3371 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3373 env->insn_aux_data[idx].jmp_point = true;
3376 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3378 return env->insn_aux_data[insn_idx].jmp_point;
3381 /* for any branch, call, exit record the history of jmps in the given state */
3382 static int push_jmp_history(struct bpf_verifier_env *env,
3383 struct bpf_verifier_state *cur)
3385 u32 cnt = cur->jmp_history_cnt;
3386 struct bpf_idx_pair *p;
3389 if (!is_jmp_point(env, env->insn_idx))
3393 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3394 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3397 p[cnt - 1].idx = env->insn_idx;
3398 p[cnt - 1].prev_idx = env->prev_insn_idx;
3399 cur->jmp_history = p;
3400 cur->jmp_history_cnt = cnt;
3404 /* Backtrack one insn at a time. If idx is not at the top of recorded
3405 * history then previous instruction came from straight line execution.
3406 * Return -ENOENT if we exhausted all instructions within given state.
3408 * It's legal to have a bit of a looping with the same starting and ending
3409 * insn index within the same state, e.g.: 3->4->5->3, so just because current
3410 * instruction index is the same as state's first_idx doesn't mean we are
3411 * done. If there is still some jump history left, we should keep going. We
3412 * need to take into account that we might have a jump history between given
3413 * state's parent and itself, due to checkpointing. In this case, we'll have
3414 * history entry recording a jump from last instruction of parent state and
3415 * first instruction of given state.
3417 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3422 if (i == st->first_insn_idx) {
3425 if (cnt == 1 && st->jmp_history[0].idx == i)
3429 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3430 i = st->jmp_history[cnt - 1].prev_idx;
3438 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3440 const struct btf_type *func;
3441 struct btf *desc_btf;
3443 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3446 desc_btf = find_kfunc_desc_btf(data, insn->off);
3447 if (IS_ERR(desc_btf))
3450 func = btf_type_by_id(desc_btf, insn->imm);
3451 return btf_name_by_offset(desc_btf, func->name_off);
3454 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3459 static inline void bt_reset(struct backtrack_state *bt)
3461 struct bpf_verifier_env *env = bt->env;
3463 memset(bt, 0, sizeof(*bt));
3467 static inline u32 bt_empty(struct backtrack_state *bt)
3472 for (i = 0; i <= bt->frame; i++)
3473 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3478 static inline int bt_subprog_enter(struct backtrack_state *bt)
3480 if (bt->frame == MAX_CALL_FRAMES - 1) {
3481 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3482 WARN_ONCE(1, "verifier backtracking bug");
3489 static inline int bt_subprog_exit(struct backtrack_state *bt)
3491 if (bt->frame == 0) {
3492 verbose(bt->env, "BUG subprog exit from frame 0\n");
3493 WARN_ONCE(1, "verifier backtracking bug");
3500 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3502 bt->reg_masks[frame] |= 1 << reg;
3505 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3507 bt->reg_masks[frame] &= ~(1 << reg);
3510 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3512 bt_set_frame_reg(bt, bt->frame, reg);
3515 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3517 bt_clear_frame_reg(bt, bt->frame, reg);
3520 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3522 bt->stack_masks[frame] |= 1ull << slot;
3525 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3527 bt->stack_masks[frame] &= ~(1ull << slot);
3530 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3532 bt_set_frame_slot(bt, bt->frame, slot);
3535 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3537 bt_clear_frame_slot(bt, bt->frame, slot);
3540 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3542 return bt->reg_masks[frame];
3545 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3547 return bt->reg_masks[bt->frame];
3550 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3552 return bt->stack_masks[frame];
3555 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3557 return bt->stack_masks[bt->frame];
3560 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3562 return bt->reg_masks[bt->frame] & (1 << reg);
3565 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3567 return bt->stack_masks[bt->frame] & (1ull << slot);
3570 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3571 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3573 DECLARE_BITMAP(mask, 64);
3579 bitmap_from_u64(mask, reg_mask);
3580 for_each_set_bit(i, mask, 32) {
3581 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3589 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3590 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3592 DECLARE_BITMAP(mask, 64);
3598 bitmap_from_u64(mask, stack_mask);
3599 for_each_set_bit(i, mask, 64) {
3600 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3609 /* For given verifier state backtrack_insn() is called from the last insn to
3610 * the first insn. Its purpose is to compute a bitmask of registers and
3611 * stack slots that needs precision in the parent verifier state.
3613 * @idx is an index of the instruction we are currently processing;
3614 * @subseq_idx is an index of the subsequent instruction that:
3615 * - *would be* executed next, if jump history is viewed in forward order;
3616 * - *was* processed previously during backtracking.
3618 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3619 struct backtrack_state *bt)
3621 const struct bpf_insn_cbs cbs = {
3622 .cb_call = disasm_kfunc_name,
3623 .cb_print = verbose,
3624 .private_data = env,
3626 struct bpf_insn *insn = env->prog->insnsi + idx;
3627 u8 class = BPF_CLASS(insn->code);
3628 u8 opcode = BPF_OP(insn->code);
3629 u8 mode = BPF_MODE(insn->code);
3630 u32 dreg = insn->dst_reg;
3631 u32 sreg = insn->src_reg;
3634 if (insn->code == 0)
3636 if (env->log.level & BPF_LOG_LEVEL2) {
3637 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3638 verbose(env, "mark_precise: frame%d: regs=%s ",
3639 bt->frame, env->tmp_str_buf);
3640 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3641 verbose(env, "stack=%s before ", env->tmp_str_buf);
3642 verbose(env, "%d: ", idx);
3643 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3646 if (class == BPF_ALU || class == BPF_ALU64) {
3647 if (!bt_is_reg_set(bt, dreg))
3649 if (opcode == BPF_END || opcode == BPF_NEG) {
3650 /* sreg is reserved and unused
3651 * dreg still need precision before this insn
3654 } else if (opcode == BPF_MOV) {
3655 if (BPF_SRC(insn->code) == BPF_X) {
3656 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3657 * dreg needs precision after this insn
3658 * sreg needs precision before this insn
3660 bt_clear_reg(bt, dreg);
3661 bt_set_reg(bt, sreg);
3664 * dreg needs precision after this insn.
3665 * Corresponding register is already marked
3666 * as precise=true in this verifier state.
3667 * No further markings in parent are necessary
3669 bt_clear_reg(bt, dreg);
3672 if (BPF_SRC(insn->code) == BPF_X) {
3674 * both dreg and sreg need precision
3677 bt_set_reg(bt, sreg);
3679 * dreg still needs precision before this insn
3682 } else if (class == BPF_LDX) {
3683 if (!bt_is_reg_set(bt, dreg))
3685 bt_clear_reg(bt, dreg);
3687 /* scalars can only be spilled into stack w/o losing precision.
3688 * Load from any other memory can be zero extended.
3689 * The desire to keep that precision is already indicated
3690 * by 'precise' mark in corresponding register of this state.
3691 * No further tracking necessary.
3693 if (insn->src_reg != BPF_REG_FP)
3696 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3697 * that [fp - off] slot contains scalar that needs to be
3698 * tracked with precision
3700 spi = (-insn->off - 1) / BPF_REG_SIZE;
3702 verbose(env, "BUG spi %d\n", spi);
3703 WARN_ONCE(1, "verifier backtracking bug");
3706 bt_set_slot(bt, spi);
3707 } else if (class == BPF_STX || class == BPF_ST) {
3708 if (bt_is_reg_set(bt, dreg))
3709 /* stx & st shouldn't be using _scalar_ dst_reg
3710 * to access memory. It means backtracking
3711 * encountered a case of pointer subtraction.
3714 /* scalars can only be spilled into stack */
3715 if (insn->dst_reg != BPF_REG_FP)
3717 spi = (-insn->off - 1) / BPF_REG_SIZE;
3719 verbose(env, "BUG spi %d\n", spi);
3720 WARN_ONCE(1, "verifier backtracking bug");
3723 if (!bt_is_slot_set(bt, spi))
3725 bt_clear_slot(bt, spi);
3726 if (class == BPF_STX)
3727 bt_set_reg(bt, sreg);
3728 } else if (class == BPF_JMP || class == BPF_JMP32) {
3729 if (bpf_pseudo_call(insn)) {
3730 int subprog_insn_idx, subprog;
3732 subprog_insn_idx = idx + insn->imm + 1;
3733 subprog = find_subprog(env, subprog_insn_idx);
3737 if (subprog_is_global(env, subprog)) {
3738 /* check that jump history doesn't have any
3739 * extra instructions from subprog; the next
3740 * instruction after call to global subprog
3741 * should be literally next instruction in
3744 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3745 /* r1-r5 are invalidated after subprog call,
3746 * so for global func call it shouldn't be set
3749 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3750 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3751 WARN_ONCE(1, "verifier backtracking bug");
3754 /* global subprog always sets R0 */
3755 bt_clear_reg(bt, BPF_REG_0);
3758 /* static subprog call instruction, which
3759 * means that we are exiting current subprog,
3760 * so only r1-r5 could be still requested as
3761 * precise, r0 and r6-r10 or any stack slot in
3762 * the current frame should be zero by now
3764 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3765 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3766 WARN_ONCE(1, "verifier backtracking bug");
3769 /* we don't track register spills perfectly,
3770 * so fallback to force-precise instead of failing */
3771 if (bt_stack_mask(bt) != 0)
3773 /* propagate r1-r5 to the caller */
3774 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3775 if (bt_is_reg_set(bt, i)) {
3776 bt_clear_reg(bt, i);
3777 bt_set_frame_reg(bt, bt->frame - 1, i);
3780 if (bt_subprog_exit(bt))
3784 } else if ((bpf_helper_call(insn) &&
3785 is_callback_calling_function(insn->imm) &&
3786 !is_async_callback_calling_function(insn->imm)) ||
3787 (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3788 /* callback-calling helper or kfunc call, which means
3789 * we are exiting from subprog, but unlike the subprog
3790 * call handling above, we shouldn't propagate
3791 * precision of r1-r5 (if any requested), as they are
3792 * not actually arguments passed directly to callback
3795 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3796 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3797 WARN_ONCE(1, "verifier backtracking bug");
3800 if (bt_stack_mask(bt) != 0)
3802 /* clear r1-r5 in callback subprog's mask */
3803 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3804 bt_clear_reg(bt, i);
3805 if (bt_subprog_exit(bt))
3808 } else if (opcode == BPF_CALL) {
3809 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3810 * catch this error later. Make backtracking conservative
3813 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3815 /* regular helper call sets R0 */
3816 bt_clear_reg(bt, BPF_REG_0);
3817 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3818 /* if backtracing was looking for registers R1-R5
3819 * they should have been found already.
3821 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3822 WARN_ONCE(1, "verifier backtracking bug");
3825 } else if (opcode == BPF_EXIT) {
3828 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3829 /* if backtracing was looking for registers R1-R5
3830 * they should have been found already.
3832 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3833 WARN_ONCE(1, "verifier backtracking bug");
3837 /* BPF_EXIT in subprog or callback always returns
3838 * right after the call instruction, so by checking
3839 * whether the instruction at subseq_idx-1 is subprog
3840 * call or not we can distinguish actual exit from
3841 * *subprog* from exit from *callback*. In the former
3842 * case, we need to propagate r0 precision, if
3843 * necessary. In the former we never do that.
3845 r0_precise = subseq_idx - 1 >= 0 &&
3846 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3847 bt_is_reg_set(bt, BPF_REG_0);
3849 bt_clear_reg(bt, BPF_REG_0);
3850 if (bt_subprog_enter(bt))
3854 bt_set_reg(bt, BPF_REG_0);
3855 /* r6-r9 and stack slots will stay set in caller frame
3856 * bitmasks until we return back from callee(s)
3859 } else if (BPF_SRC(insn->code) == BPF_X) {
3860 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3863 * Both dreg and sreg need precision before
3864 * this insn. If only sreg was marked precise
3865 * before it would be equally necessary to
3866 * propagate it to dreg.
3868 bt_set_reg(bt, dreg);
3869 bt_set_reg(bt, sreg);
3870 /* else dreg <cond> K
3871 * Only dreg still needs precision before
3872 * this insn, so for the K-based conditional
3873 * there is nothing new to be marked.
3876 } else if (class == BPF_LD) {
3877 if (!bt_is_reg_set(bt, dreg))
3879 bt_clear_reg(bt, dreg);
3880 /* It's ld_imm64 or ld_abs or ld_ind.
3881 * For ld_imm64 no further tracking of precision
3882 * into parent is necessary
3884 if (mode == BPF_IND || mode == BPF_ABS)
3885 /* to be analyzed */
3891 /* the scalar precision tracking algorithm:
3892 * . at the start all registers have precise=false.
3893 * . scalar ranges are tracked as normal through alu and jmp insns.
3894 * . once precise value of the scalar register is used in:
3895 * . ptr + scalar alu
3896 * . if (scalar cond K|scalar)
3897 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3898 * backtrack through the verifier states and mark all registers and
3899 * stack slots with spilled constants that these scalar regisers
3900 * should be precise.
3901 * . during state pruning two registers (or spilled stack slots)
3902 * are equivalent if both are not precise.
3904 * Note the verifier cannot simply walk register parentage chain,
3905 * since many different registers and stack slots could have been
3906 * used to compute single precise scalar.
3908 * The approach of starting with precise=true for all registers and then
3909 * backtrack to mark a register as not precise when the verifier detects
3910 * that program doesn't care about specific value (e.g., when helper
3911 * takes register as ARG_ANYTHING parameter) is not safe.
3913 * It's ok to walk single parentage chain of the verifier states.
3914 * It's possible that this backtracking will go all the way till 1st insn.
3915 * All other branches will be explored for needing precision later.
3917 * The backtracking needs to deal with cases like:
3918 * 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)
3921 * if r5 > 0x79f goto pc+7
3922 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3925 * call bpf_perf_event_output#25
3926 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3930 * call foo // uses callee's r6 inside to compute r0
3934 * to track above reg_mask/stack_mask needs to be independent for each frame.
3936 * Also if parent's curframe > frame where backtracking started,
3937 * the verifier need to mark registers in both frames, otherwise callees
3938 * may incorrectly prune callers. This is similar to
3939 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3941 * For now backtracking falls back into conservative marking.
3943 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3944 struct bpf_verifier_state *st)
3946 struct bpf_func_state *func;
3947 struct bpf_reg_state *reg;
3950 if (env->log.level & BPF_LOG_LEVEL2) {
3951 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3955 /* big hammer: mark all scalars precise in this path.
3956 * pop_stack may still get !precise scalars.
3957 * We also skip current state and go straight to first parent state,
3958 * because precision markings in current non-checkpointed state are
3959 * not needed. See why in the comment in __mark_chain_precision below.
3961 for (st = st->parent; st; st = st->parent) {
3962 for (i = 0; i <= st->curframe; i++) {
3963 func = st->frame[i];
3964 for (j = 0; j < BPF_REG_FP; j++) {
3965 reg = &func->regs[j];
3966 if (reg->type != SCALAR_VALUE || reg->precise)
3968 reg->precise = true;
3969 if (env->log.level & BPF_LOG_LEVEL2) {
3970 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3974 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3975 if (!is_spilled_reg(&func->stack[j]))
3977 reg = &func->stack[j].spilled_ptr;
3978 if (reg->type != SCALAR_VALUE || reg->precise)
3980 reg->precise = true;
3981 if (env->log.level & BPF_LOG_LEVEL2) {
3982 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3990 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3992 struct bpf_func_state *func;
3993 struct bpf_reg_state *reg;
3996 for (i = 0; i <= st->curframe; i++) {
3997 func = st->frame[i];
3998 for (j = 0; j < BPF_REG_FP; j++) {
3999 reg = &func->regs[j];
4000 if (reg->type != SCALAR_VALUE)
4002 reg->precise = false;
4004 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4005 if (!is_spilled_reg(&func->stack[j]))
4007 reg = &func->stack[j].spilled_ptr;
4008 if (reg->type != SCALAR_VALUE)
4010 reg->precise = false;
4015 static bool idset_contains(struct bpf_idset *s, u32 id)
4019 for (i = 0; i < s->count; ++i)
4020 if (s->ids[i] == id)
4026 static int idset_push(struct bpf_idset *s, u32 id)
4028 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4030 s->ids[s->count++] = id;
4034 static void idset_reset(struct bpf_idset *s)
4039 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4040 * Mark all registers with these IDs as precise.
4042 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4044 struct bpf_idset *precise_ids = &env->idset_scratch;
4045 struct backtrack_state *bt = &env->bt;
4046 struct bpf_func_state *func;
4047 struct bpf_reg_state *reg;
4048 DECLARE_BITMAP(mask, 64);
4051 idset_reset(precise_ids);
4053 for (fr = bt->frame; fr >= 0; fr--) {
4054 func = st->frame[fr];
4056 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4057 for_each_set_bit(i, mask, 32) {
4058 reg = &func->regs[i];
4059 if (!reg->id || reg->type != SCALAR_VALUE)
4061 if (idset_push(precise_ids, reg->id))
4065 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4066 for_each_set_bit(i, mask, 64) {
4067 if (i >= func->allocated_stack / BPF_REG_SIZE)
4069 if (!is_spilled_scalar_reg(&func->stack[i]))
4071 reg = &func->stack[i].spilled_ptr;
4074 if (idset_push(precise_ids, reg->id))
4079 for (fr = 0; fr <= st->curframe; ++fr) {
4080 func = st->frame[fr];
4082 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4083 reg = &func->regs[i];
4086 if (!idset_contains(precise_ids, reg->id))
4088 bt_set_frame_reg(bt, fr, i);
4090 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4091 if (!is_spilled_scalar_reg(&func->stack[i]))
4093 reg = &func->stack[i].spilled_ptr;
4096 if (!idset_contains(precise_ids, reg->id))
4098 bt_set_frame_slot(bt, fr, i);
4106 * __mark_chain_precision() backtracks BPF program instruction sequence and
4107 * chain of verifier states making sure that register *regno* (if regno >= 0)
4108 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4109 * SCALARS, as well as any other registers and slots that contribute to
4110 * a tracked state of given registers/stack slots, depending on specific BPF
4111 * assembly instructions (see backtrack_insns() for exact instruction handling
4112 * logic). This backtracking relies on recorded jmp_history and is able to
4113 * traverse entire chain of parent states. This process ends only when all the
4114 * necessary registers/slots and their transitive dependencies are marked as
4117 * One important and subtle aspect is that precise marks *do not matter* in
4118 * the currently verified state (current state). It is important to understand
4119 * why this is the case.
4121 * First, note that current state is the state that is not yet "checkpointed",
4122 * i.e., it is not yet put into env->explored_states, and it has no children
4123 * states as well. It's ephemeral, and can end up either a) being discarded if
4124 * compatible explored state is found at some point or BPF_EXIT instruction is
4125 * reached or b) checkpointed and put into env->explored_states, branching out
4126 * into one or more children states.
4128 * In the former case, precise markings in current state are completely
4129 * ignored by state comparison code (see regsafe() for details). Only
4130 * checkpointed ("old") state precise markings are important, and if old
4131 * state's register/slot is precise, regsafe() assumes current state's
4132 * register/slot as precise and checks value ranges exactly and precisely. If
4133 * states turn out to be compatible, current state's necessary precise
4134 * markings and any required parent states' precise markings are enforced
4135 * after the fact with propagate_precision() logic, after the fact. But it's
4136 * important to realize that in this case, even after marking current state
4137 * registers/slots as precise, we immediately discard current state. So what
4138 * actually matters is any of the precise markings propagated into current
4139 * state's parent states, which are always checkpointed (due to b) case above).
4140 * As such, for scenario a) it doesn't matter if current state has precise
4141 * markings set or not.
4143 * Now, for the scenario b), checkpointing and forking into child(ren)
4144 * state(s). Note that before current state gets to checkpointing step, any
4145 * processed instruction always assumes precise SCALAR register/slot
4146 * knowledge: if precise value or range is useful to prune jump branch, BPF
4147 * verifier takes this opportunity enthusiastically. Similarly, when
4148 * register's value is used to calculate offset or memory address, exact
4149 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4150 * what we mentioned above about state comparison ignoring precise markings
4151 * during state comparison, BPF verifier ignores and also assumes precise
4152 * markings *at will* during instruction verification process. But as verifier
4153 * assumes precision, it also propagates any precision dependencies across
4154 * parent states, which are not yet finalized, so can be further restricted
4155 * based on new knowledge gained from restrictions enforced by their children
4156 * states. This is so that once those parent states are finalized, i.e., when
4157 * they have no more active children state, state comparison logic in
4158 * is_state_visited() would enforce strict and precise SCALAR ranges, if
4159 * required for correctness.
4161 * To build a bit more intuition, note also that once a state is checkpointed,
4162 * the path we took to get to that state is not important. This is crucial
4163 * property for state pruning. When state is checkpointed and finalized at
4164 * some instruction index, it can be correctly and safely used to "short
4165 * circuit" any *compatible* state that reaches exactly the same instruction
4166 * index. I.e., if we jumped to that instruction from a completely different
4167 * code path than original finalized state was derived from, it doesn't
4168 * matter, current state can be discarded because from that instruction
4169 * forward having a compatible state will ensure we will safely reach the
4170 * exit. States describe preconditions for further exploration, but completely
4171 * forget the history of how we got here.
4173 * This also means that even if we needed precise SCALAR range to get to
4174 * finalized state, but from that point forward *that same* SCALAR register is
4175 * never used in a precise context (i.e., it's precise value is not needed for
4176 * correctness), it's correct and safe to mark such register as "imprecise"
4177 * (i.e., precise marking set to false). This is what we rely on when we do
4178 * not set precise marking in current state. If no child state requires
4179 * precision for any given SCALAR register, it's safe to dictate that it can
4180 * be imprecise. If any child state does require this register to be precise,
4181 * we'll mark it precise later retroactively during precise markings
4182 * propagation from child state to parent states.
4184 * Skipping precise marking setting in current state is a mild version of
4185 * relying on the above observation. But we can utilize this property even
4186 * more aggressively by proactively forgetting any precise marking in the
4187 * current state (which we inherited from the parent state), right before we
4188 * checkpoint it and branch off into new child state. This is done by
4189 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4190 * finalized states which help in short circuiting more future states.
4192 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4194 struct backtrack_state *bt = &env->bt;
4195 struct bpf_verifier_state *st = env->cur_state;
4196 int first_idx = st->first_insn_idx;
4197 int last_idx = env->insn_idx;
4198 int subseq_idx = -1;
4199 struct bpf_func_state *func;
4200 struct bpf_reg_state *reg;
4201 bool skip_first = true;
4204 if (!env->bpf_capable)
4207 /* set frame number from which we are starting to backtrack */
4208 bt_init(bt, env->cur_state->curframe);
4210 /* Do sanity checks against current state of register and/or stack
4211 * slot, but don't set precise flag in current state, as precision
4212 * tracking in the current state is unnecessary.
4214 func = st->frame[bt->frame];
4216 reg = &func->regs[regno];
4217 if (reg->type != SCALAR_VALUE) {
4218 WARN_ONCE(1, "backtracing misuse");
4221 bt_set_reg(bt, regno);
4228 DECLARE_BITMAP(mask, 64);
4229 u32 history = st->jmp_history_cnt;
4231 if (env->log.level & BPF_LOG_LEVEL2) {
4232 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4233 bt->frame, last_idx, first_idx, subseq_idx);
4236 /* If some register with scalar ID is marked as precise,
4237 * make sure that all registers sharing this ID are also precise.
4238 * This is needed to estimate effect of find_equal_scalars().
4239 * Do this at the last instruction of each state,
4240 * bpf_reg_state::id fields are valid for these instructions.
4242 * Allows to track precision in situation like below:
4244 * r2 = unknown value
4248 * r1 = r2 // r1 and r2 now share the same ID
4250 * --- state #1 {r1.id = A, r2.id = A} ---
4252 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4254 * --- state #2 {r1.id = A, r2.id = A} ---
4256 * r3 += r1 // need to mark both r1 and r2
4258 if (mark_precise_scalar_ids(env, st))
4262 /* we are at the entry into subprog, which
4263 * is expected for global funcs, but only if
4264 * requested precise registers are R1-R5
4265 * (which are global func's input arguments)
4267 if (st->curframe == 0 &&
4268 st->frame[0]->subprogno > 0 &&
4269 st->frame[0]->callsite == BPF_MAIN_FUNC &&
4270 bt_stack_mask(bt) == 0 &&
4271 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4272 bitmap_from_u64(mask, bt_reg_mask(bt));
4273 for_each_set_bit(i, mask, 32) {
4274 reg = &st->frame[0]->regs[i];
4275 bt_clear_reg(bt, i);
4276 if (reg->type == SCALAR_VALUE)
4277 reg->precise = true;
4282 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4283 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4284 WARN_ONCE(1, "verifier backtracking bug");
4288 for (i = last_idx;;) {
4293 err = backtrack_insn(env, i, subseq_idx, bt);
4295 if (err == -ENOTSUPP) {
4296 mark_all_scalars_precise(env, env->cur_state);
4303 /* Found assignment(s) into tracked register in this state.
4304 * Since this state is already marked, just return.
4305 * Nothing to be tracked further in the parent state.
4309 i = get_prev_insn_idx(st, i, &history);
4312 if (i >= env->prog->len) {
4313 /* This can happen if backtracking reached insn 0
4314 * and there are still reg_mask or stack_mask
4316 * It means the backtracking missed the spot where
4317 * particular register was initialized with a constant.
4319 verbose(env, "BUG backtracking idx %d\n", i);
4320 WARN_ONCE(1, "verifier backtracking bug");
4328 for (fr = bt->frame; fr >= 0; fr--) {
4329 func = st->frame[fr];
4330 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4331 for_each_set_bit(i, mask, 32) {
4332 reg = &func->regs[i];
4333 if (reg->type != SCALAR_VALUE) {
4334 bt_clear_frame_reg(bt, fr, i);
4338 bt_clear_frame_reg(bt, fr, i);
4340 reg->precise = true;
4343 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4344 for_each_set_bit(i, mask, 64) {
4345 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4346 /* the sequence of instructions:
4348 * 3: (7b) *(u64 *)(r3 -8) = r0
4349 * 4: (79) r4 = *(u64 *)(r10 -8)
4350 * doesn't contain jmps. It's backtracked
4351 * as a single block.
4352 * During backtracking insn 3 is not recognized as
4353 * stack access, so at the end of backtracking
4354 * stack slot fp-8 is still marked in stack_mask.
4355 * However the parent state may not have accessed
4356 * fp-8 and it's "unallocated" stack space.
4357 * In such case fallback to conservative.
4359 mark_all_scalars_precise(env, env->cur_state);
4364 if (!is_spilled_scalar_reg(&func->stack[i])) {
4365 bt_clear_frame_slot(bt, fr, i);
4368 reg = &func->stack[i].spilled_ptr;
4370 bt_clear_frame_slot(bt, fr, i);
4372 reg->precise = true;
4374 if (env->log.level & BPF_LOG_LEVEL2) {
4375 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4376 bt_frame_reg_mask(bt, fr));
4377 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4378 fr, env->tmp_str_buf);
4379 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4380 bt_frame_stack_mask(bt, fr));
4381 verbose(env, "stack=%s: ", env->tmp_str_buf);
4382 print_verifier_state(env, func, true);
4389 subseq_idx = first_idx;
4390 last_idx = st->last_insn_idx;
4391 first_idx = st->first_insn_idx;
4394 /* if we still have requested precise regs or slots, we missed
4395 * something (e.g., stack access through non-r10 register), so
4396 * fallback to marking all precise
4398 if (!bt_empty(bt)) {
4399 mark_all_scalars_precise(env, env->cur_state);
4406 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4408 return __mark_chain_precision(env, regno);
4411 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4412 * desired reg and stack masks across all relevant frames
4414 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4416 return __mark_chain_precision(env, -1);
4419 static bool is_spillable_regtype(enum bpf_reg_type type)
4421 switch (base_type(type)) {
4422 case PTR_TO_MAP_VALUE:
4426 case PTR_TO_PACKET_META:
4427 case PTR_TO_PACKET_END:
4428 case PTR_TO_FLOW_KEYS:
4429 case CONST_PTR_TO_MAP:
4431 case PTR_TO_SOCK_COMMON:
4432 case PTR_TO_TCP_SOCK:
4433 case PTR_TO_XDP_SOCK:
4438 case PTR_TO_MAP_KEY:
4445 /* Does this register contain a constant zero? */
4446 static bool register_is_null(struct bpf_reg_state *reg)
4448 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4451 static bool register_is_const(struct bpf_reg_state *reg)
4453 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4456 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4458 return tnum_is_unknown(reg->var_off) &&
4459 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4460 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4461 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4462 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4465 static bool register_is_bounded(struct bpf_reg_state *reg)
4467 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4470 static bool __is_pointer_value(bool allow_ptr_leaks,
4471 const struct bpf_reg_state *reg)
4473 if (allow_ptr_leaks)
4476 return reg->type != SCALAR_VALUE;
4479 /* Copy src state preserving dst->parent and dst->live fields */
4480 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4482 struct bpf_reg_state *parent = dst->parent;
4483 enum bpf_reg_liveness live = dst->live;
4486 dst->parent = parent;
4490 static void save_register_state(struct bpf_func_state *state,
4491 int spi, struct bpf_reg_state *reg,
4496 copy_register_state(&state->stack[spi].spilled_ptr, reg);
4497 if (size == BPF_REG_SIZE)
4498 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4500 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4501 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4503 /* size < 8 bytes spill */
4505 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4508 static bool is_bpf_st_mem(struct bpf_insn *insn)
4510 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4513 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4514 * stack boundary and alignment are checked in check_mem_access()
4516 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4517 /* stack frame we're writing to */
4518 struct bpf_func_state *state,
4519 int off, int size, int value_regno,
4522 struct bpf_func_state *cur; /* state of the current function */
4523 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4524 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4525 struct bpf_reg_state *reg = NULL;
4526 u32 dst_reg = insn->dst_reg;
4528 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4529 * so it's aligned access and [off, off + size) are within stack limits
4531 if (!env->allow_ptr_leaks &&
4532 is_spilled_reg(&state->stack[spi]) &&
4533 size != BPF_REG_SIZE) {
4534 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4538 cur = env->cur_state->frame[env->cur_state->curframe];
4539 if (value_regno >= 0)
4540 reg = &cur->regs[value_regno];
4541 if (!env->bypass_spec_v4) {
4542 bool sanitize = reg && is_spillable_regtype(reg->type);
4544 for (i = 0; i < size; i++) {
4545 u8 type = state->stack[spi].slot_type[i];
4547 if (type != STACK_MISC && type != STACK_ZERO) {
4554 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4557 err = destroy_if_dynptr_stack_slot(env, state, spi);
4561 mark_stack_slot_scratched(env, spi);
4562 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4563 !register_is_null(reg) && env->bpf_capable) {
4564 if (dst_reg != BPF_REG_FP) {
4565 /* The backtracking logic can only recognize explicit
4566 * stack slot address like [fp - 8]. Other spill of
4567 * scalar via different register has to be conservative.
4568 * Backtrack from here and mark all registers as precise
4569 * that contributed into 'reg' being a constant.
4571 err = mark_chain_precision(env, value_regno);
4575 save_register_state(state, spi, reg, size);
4576 /* Break the relation on a narrowing spill. */
4577 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4578 state->stack[spi].spilled_ptr.id = 0;
4579 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4580 insn->imm != 0 && env->bpf_capable) {
4581 struct bpf_reg_state fake_reg = {};
4583 __mark_reg_known(&fake_reg, insn->imm);
4584 fake_reg.type = SCALAR_VALUE;
4585 save_register_state(state, spi, &fake_reg, size);
4586 } else if (reg && is_spillable_regtype(reg->type)) {
4587 /* register containing pointer is being spilled into stack */
4588 if (size != BPF_REG_SIZE) {
4589 verbose_linfo(env, insn_idx, "; ");
4590 verbose(env, "invalid size of register spill\n");
4593 if (state != cur && reg->type == PTR_TO_STACK) {
4594 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4597 save_register_state(state, spi, reg, size);
4599 u8 type = STACK_MISC;
4601 /* regular write of data into stack destroys any spilled ptr */
4602 state->stack[spi].spilled_ptr.type = NOT_INIT;
4603 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4604 if (is_stack_slot_special(&state->stack[spi]))
4605 for (i = 0; i < BPF_REG_SIZE; i++)
4606 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4608 /* only mark the slot as written if all 8 bytes were written
4609 * otherwise read propagation may incorrectly stop too soon
4610 * when stack slots are partially written.
4611 * This heuristic means that read propagation will be
4612 * conservative, since it will add reg_live_read marks
4613 * to stack slots all the way to first state when programs
4614 * writes+reads less than 8 bytes
4616 if (size == BPF_REG_SIZE)
4617 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4619 /* when we zero initialize stack slots mark them as such */
4620 if ((reg && register_is_null(reg)) ||
4621 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4622 /* backtracking doesn't work for STACK_ZERO yet. */
4623 err = mark_chain_precision(env, value_regno);
4629 /* Mark slots affected by this stack write. */
4630 for (i = 0; i < size; i++)
4631 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4637 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4638 * known to contain a variable offset.
4639 * This function checks whether the write is permitted and conservatively
4640 * tracks the effects of the write, considering that each stack slot in the
4641 * dynamic range is potentially written to.
4643 * 'off' includes 'regno->off'.
4644 * 'value_regno' can be -1, meaning that an unknown value is being written to
4647 * Spilled pointers in range are not marked as written because we don't know
4648 * what's going to be actually written. This means that read propagation for
4649 * future reads cannot be terminated by this write.
4651 * For privileged programs, uninitialized stack slots are considered
4652 * initialized by this write (even though we don't know exactly what offsets
4653 * are going to be written to). The idea is that we don't want the verifier to
4654 * reject future reads that access slots written to through variable offsets.
4656 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4657 /* func where register points to */
4658 struct bpf_func_state *state,
4659 int ptr_regno, int off, int size,
4660 int value_regno, int insn_idx)
4662 struct bpf_func_state *cur; /* state of the current function */
4663 int min_off, max_off;
4665 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4666 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4667 bool writing_zero = false;
4668 /* set if the fact that we're writing a zero is used to let any
4669 * stack slots remain STACK_ZERO
4671 bool zero_used = false;
4673 cur = env->cur_state->frame[env->cur_state->curframe];
4674 ptr_reg = &cur->regs[ptr_regno];
4675 min_off = ptr_reg->smin_value + off;
4676 max_off = ptr_reg->smax_value + off + size;
4677 if (value_regno >= 0)
4678 value_reg = &cur->regs[value_regno];
4679 if ((value_reg && register_is_null(value_reg)) ||
4680 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4681 writing_zero = true;
4683 for (i = min_off; i < max_off; i++) {
4687 err = destroy_if_dynptr_stack_slot(env, state, spi);
4692 /* Variable offset writes destroy any spilled pointers in range. */
4693 for (i = min_off; i < max_off; i++) {
4694 u8 new_type, *stype;
4698 spi = slot / BPF_REG_SIZE;
4699 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4700 mark_stack_slot_scratched(env, spi);
4702 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4703 /* Reject the write if range we may write to has not
4704 * been initialized beforehand. If we didn't reject
4705 * here, the ptr status would be erased below (even
4706 * though not all slots are actually overwritten),
4707 * possibly opening the door to leaks.
4709 * We do however catch STACK_INVALID case below, and
4710 * only allow reading possibly uninitialized memory
4711 * later for CAP_PERFMON, as the write may not happen to
4714 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4719 /* Erase all spilled pointers. */
4720 state->stack[spi].spilled_ptr.type = NOT_INIT;
4722 /* Update the slot type. */
4723 new_type = STACK_MISC;
4724 if (writing_zero && *stype == STACK_ZERO) {
4725 new_type = STACK_ZERO;
4728 /* If the slot is STACK_INVALID, we check whether it's OK to
4729 * pretend that it will be initialized by this write. The slot
4730 * might not actually be written to, and so if we mark it as
4731 * initialized future reads might leak uninitialized memory.
4732 * For privileged programs, we will accept such reads to slots
4733 * that may or may not be written because, if we're reject
4734 * them, the error would be too confusing.
4736 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4737 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4744 /* backtracking doesn't work for STACK_ZERO yet. */
4745 err = mark_chain_precision(env, value_regno);
4752 /* When register 'dst_regno' is assigned some values from stack[min_off,
4753 * max_off), we set the register's type according to the types of the
4754 * respective stack slots. If all the stack values are known to be zeros, then
4755 * so is the destination reg. Otherwise, the register is considered to be
4756 * SCALAR. This function does not deal with register filling; the caller must
4757 * ensure that all spilled registers in the stack range have been marked as
4760 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4761 /* func where src register points to */
4762 struct bpf_func_state *ptr_state,
4763 int min_off, int max_off, int dst_regno)
4765 struct bpf_verifier_state *vstate = env->cur_state;
4766 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4771 for (i = min_off; i < max_off; i++) {
4773 spi = slot / BPF_REG_SIZE;
4774 mark_stack_slot_scratched(env, spi);
4775 stype = ptr_state->stack[spi].slot_type;
4776 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4780 if (zeros == max_off - min_off) {
4781 /* any access_size read into register is zero extended,
4782 * so the whole register == const_zero
4784 __mark_reg_const_zero(&state->regs[dst_regno]);
4785 /* backtracking doesn't support STACK_ZERO yet,
4786 * so mark it precise here, so that later
4787 * backtracking can stop here.
4788 * Backtracking may not need this if this register
4789 * doesn't participate in pointer adjustment.
4790 * Forward propagation of precise flag is not
4791 * necessary either. This mark is only to stop
4792 * backtracking. Any register that contributed
4793 * to const 0 was marked precise before spill.
4795 state->regs[dst_regno].precise = true;
4797 /* have read misc data from the stack */
4798 mark_reg_unknown(env, state->regs, dst_regno);
4800 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4803 /* Read the stack at 'off' and put the results into the register indicated by
4804 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4807 * 'dst_regno' can be -1, meaning that the read value is not going to a
4810 * The access is assumed to be within the current stack bounds.
4812 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4813 /* func where src register points to */
4814 struct bpf_func_state *reg_state,
4815 int off, int size, int dst_regno)
4817 struct bpf_verifier_state *vstate = env->cur_state;
4818 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4819 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4820 struct bpf_reg_state *reg;
4823 stype = reg_state->stack[spi].slot_type;
4824 reg = ®_state->stack[spi].spilled_ptr;
4826 mark_stack_slot_scratched(env, spi);
4828 if (is_spilled_reg(®_state->stack[spi])) {
4831 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4834 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4835 if (reg->type != SCALAR_VALUE) {
4836 verbose_linfo(env, env->insn_idx, "; ");
4837 verbose(env, "invalid size of register fill\n");
4841 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4845 if (!(off % BPF_REG_SIZE) && size == spill_size) {
4846 /* The earlier check_reg_arg() has decided the
4847 * subreg_def for this insn. Save it first.
4849 s32 subreg_def = state->regs[dst_regno].subreg_def;
4851 copy_register_state(&state->regs[dst_regno], reg);
4852 state->regs[dst_regno].subreg_def = subreg_def;
4854 for (i = 0; i < size; i++) {
4855 type = stype[(slot - i) % BPF_REG_SIZE];
4856 if (type == STACK_SPILL)
4858 if (type == STACK_MISC)
4860 if (type == STACK_INVALID && env->allow_uninit_stack)
4862 verbose(env, "invalid read from stack off %d+%d size %d\n",
4866 mark_reg_unknown(env, state->regs, dst_regno);
4868 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4872 if (dst_regno >= 0) {
4873 /* restore register state from stack */
4874 copy_register_state(&state->regs[dst_regno], reg);
4875 /* mark reg as written since spilled pointer state likely
4876 * has its liveness marks cleared by is_state_visited()
4877 * which resets stack/reg liveness for state transitions
4879 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4880 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4881 /* If dst_regno==-1, the caller is asking us whether
4882 * it is acceptable to use this value as a SCALAR_VALUE
4884 * We must not allow unprivileged callers to do that
4885 * with spilled pointers.
4887 verbose(env, "leaking pointer from stack off %d\n",
4891 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4893 for (i = 0; i < size; i++) {
4894 type = stype[(slot - i) % BPF_REG_SIZE];
4895 if (type == STACK_MISC)
4897 if (type == STACK_ZERO)
4899 if (type == STACK_INVALID && env->allow_uninit_stack)
4901 verbose(env, "invalid read from stack off %d+%d size %d\n",
4905 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4907 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4912 enum bpf_access_src {
4913 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4914 ACCESS_HELPER = 2, /* the access is performed by a helper */
4917 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4918 int regno, int off, int access_size,
4919 bool zero_size_allowed,
4920 enum bpf_access_src type,
4921 struct bpf_call_arg_meta *meta);
4923 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4925 return cur_regs(env) + regno;
4928 /* Read the stack at 'ptr_regno + off' and put the result into the register
4930 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4931 * but not its variable offset.
4932 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4934 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4935 * filling registers (i.e. reads of spilled register cannot be detected when
4936 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4937 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4938 * offset; for a fixed offset check_stack_read_fixed_off should be used
4941 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4942 int ptr_regno, int off, int size, int dst_regno)
4944 /* The state of the source register. */
4945 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4946 struct bpf_func_state *ptr_state = func(env, reg);
4948 int min_off, max_off;
4950 /* Note that we pass a NULL meta, so raw access will not be permitted.
4952 err = check_stack_range_initialized(env, ptr_regno, off, size,
4953 false, ACCESS_DIRECT, NULL);
4957 min_off = reg->smin_value + off;
4958 max_off = reg->smax_value + off;
4959 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4963 /* check_stack_read dispatches to check_stack_read_fixed_off or
4964 * check_stack_read_var_off.
4966 * The caller must ensure that the offset falls within the allocated stack
4969 * 'dst_regno' is a register which will receive the value from the stack. It
4970 * can be -1, meaning that the read value is not going to a register.
4972 static int check_stack_read(struct bpf_verifier_env *env,
4973 int ptr_regno, int off, int size,
4976 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4977 struct bpf_func_state *state = func(env, reg);
4979 /* Some accesses are only permitted with a static offset. */
4980 bool var_off = !tnum_is_const(reg->var_off);
4982 /* The offset is required to be static when reads don't go to a
4983 * register, in order to not leak pointers (see
4984 * check_stack_read_fixed_off).
4986 if (dst_regno < 0 && var_off) {
4989 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4990 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4994 /* Variable offset is prohibited for unprivileged mode for simplicity
4995 * since it requires corresponding support in Spectre masking for stack
4996 * ALU. See also retrieve_ptr_limit(). The check in
4997 * check_stack_access_for_ptr_arithmetic() called by
4998 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4999 * with variable offsets, therefore no check is required here. Further,
5000 * just checking it here would be insufficient as speculative stack
5001 * writes could still lead to unsafe speculative behaviour.
5004 off += reg->var_off.value;
5005 err = check_stack_read_fixed_off(env, state, off, size,
5008 /* Variable offset stack reads need more conservative handling
5009 * than fixed offset ones. Note that dst_regno >= 0 on this
5012 err = check_stack_read_var_off(env, ptr_regno, off, size,
5019 /* check_stack_write dispatches to check_stack_write_fixed_off or
5020 * check_stack_write_var_off.
5022 * 'ptr_regno' is the register used as a pointer into the stack.
5023 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5024 * 'value_regno' is the register whose value we're writing to the stack. It can
5025 * be -1, meaning that we're not writing from a register.
5027 * The caller must ensure that the offset falls within the maximum stack size.
5029 static int check_stack_write(struct bpf_verifier_env *env,
5030 int ptr_regno, int off, int size,
5031 int value_regno, int insn_idx)
5033 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5034 struct bpf_func_state *state = func(env, reg);
5037 if (tnum_is_const(reg->var_off)) {
5038 off += reg->var_off.value;
5039 err = check_stack_write_fixed_off(env, state, off, size,
5040 value_regno, insn_idx);
5042 /* Variable offset stack reads need more conservative handling
5043 * than fixed offset ones.
5045 err = check_stack_write_var_off(env, state,
5046 ptr_regno, off, size,
5047 value_regno, insn_idx);
5052 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5053 int off, int size, enum bpf_access_type type)
5055 struct bpf_reg_state *regs = cur_regs(env);
5056 struct bpf_map *map = regs[regno].map_ptr;
5057 u32 cap = bpf_map_flags_to_cap(map);
5059 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5060 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5061 map->value_size, off, size);
5065 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5066 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5067 map->value_size, off, size);
5074 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5075 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5076 int off, int size, u32 mem_size,
5077 bool zero_size_allowed)
5079 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5080 struct bpf_reg_state *reg;
5082 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5085 reg = &cur_regs(env)[regno];
5086 switch (reg->type) {
5087 case PTR_TO_MAP_KEY:
5088 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5089 mem_size, off, size);
5091 case PTR_TO_MAP_VALUE:
5092 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5093 mem_size, off, size);
5096 case PTR_TO_PACKET_META:
5097 case PTR_TO_PACKET_END:
5098 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5099 off, size, regno, reg->id, off, mem_size);
5103 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5104 mem_size, off, size);
5110 /* check read/write into a memory region with possible variable offset */
5111 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5112 int off, int size, u32 mem_size,
5113 bool zero_size_allowed)
5115 struct bpf_verifier_state *vstate = env->cur_state;
5116 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5117 struct bpf_reg_state *reg = &state->regs[regno];
5120 /* We may have adjusted the register pointing to memory region, so we
5121 * need to try adding each of min_value and max_value to off
5122 * to make sure our theoretical access will be safe.
5124 * The minimum value is only important with signed
5125 * comparisons where we can't assume the floor of a
5126 * value is 0. If we are using signed variables for our
5127 * index'es we need to make sure that whatever we use
5128 * will have a set floor within our range.
5130 if (reg->smin_value < 0 &&
5131 (reg->smin_value == S64_MIN ||
5132 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5133 reg->smin_value + off < 0)) {
5134 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5138 err = __check_mem_access(env, regno, reg->smin_value + off, size,
5139 mem_size, zero_size_allowed);
5141 verbose(env, "R%d min value is outside of the allowed memory range\n",
5146 /* If we haven't set a max value then we need to bail since we can't be
5147 * sure we won't do bad things.
5148 * If reg->umax_value + off could overflow, treat that as unbounded too.
5150 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5151 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5155 err = __check_mem_access(env, regno, reg->umax_value + off, size,
5156 mem_size, zero_size_allowed);
5158 verbose(env, "R%d max value is outside of the allowed memory range\n",
5166 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5167 const struct bpf_reg_state *reg, int regno,
5170 /* Access to this pointer-typed register or passing it to a helper
5171 * is only allowed in its original, unmodified form.
5175 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5176 reg_type_str(env, reg->type), regno, reg->off);
5180 if (!fixed_off_ok && reg->off) {
5181 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5182 reg_type_str(env, reg->type), regno, reg->off);
5186 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5189 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5190 verbose(env, "variable %s access var_off=%s disallowed\n",
5191 reg_type_str(env, reg->type), tn_buf);
5198 int check_ptr_off_reg(struct bpf_verifier_env *env,
5199 const struct bpf_reg_state *reg, int regno)
5201 return __check_ptr_off_reg(env, reg, regno, false);
5204 static int map_kptr_match_type(struct bpf_verifier_env *env,
5205 struct btf_field *kptr_field,
5206 struct bpf_reg_state *reg, u32 regno)
5208 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5210 const char *reg_name = "";
5212 if (btf_is_kernel(reg->btf)) {
5213 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5215 /* Only unreferenced case accepts untrusted pointers */
5216 if (kptr_field->type == BPF_KPTR_UNREF)
5217 perm_flags |= PTR_UNTRUSTED;
5219 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5222 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5225 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5226 reg_name = btf_type_name(reg->btf, reg->btf_id);
5228 /* For ref_ptr case, release function check should ensure we get one
5229 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5230 * normal store of unreferenced kptr, we must ensure var_off is zero.
5231 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5232 * reg->off and reg->ref_obj_id are not needed here.
5234 if (__check_ptr_off_reg(env, reg, regno, true))
5237 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5238 * we also need to take into account the reg->off.
5240 * We want to support cases like:
5248 * v = func(); // PTR_TO_BTF_ID
5249 * val->foo = v; // reg->off is zero, btf and btf_id match type
5250 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5251 * // first member type of struct after comparison fails
5252 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5255 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5256 * is zero. We must also ensure that btf_struct_ids_match does not walk
5257 * the struct to match type against first member of struct, i.e. reject
5258 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5259 * strict mode to true for type match.
5261 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5262 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5263 kptr_field->type == BPF_KPTR_REF))
5267 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5268 reg_type_str(env, reg->type), reg_name);
5269 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5270 if (kptr_field->type == BPF_KPTR_UNREF)
5271 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5278 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5279 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5281 static bool in_rcu_cs(struct bpf_verifier_env *env)
5283 return env->cur_state->active_rcu_lock ||
5284 env->cur_state->active_lock.ptr ||
5285 !env->prog->aux->sleepable;
5288 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5289 BTF_SET_START(rcu_protected_types)
5290 BTF_ID(struct, prog_test_ref_kfunc)
5291 BTF_ID(struct, cgroup)
5292 BTF_ID(struct, bpf_cpumask)
5293 BTF_ID(struct, task_struct)
5294 BTF_SET_END(rcu_protected_types)
5296 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5298 if (!btf_is_kernel(btf))
5300 return btf_id_set_contains(&rcu_protected_types, btf_id);
5303 static bool rcu_safe_kptr(const struct btf_field *field)
5305 const struct btf_field_kptr *kptr = &field->kptr;
5307 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5310 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5311 int value_regno, int insn_idx,
5312 struct btf_field *kptr_field)
5314 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5315 int class = BPF_CLASS(insn->code);
5316 struct bpf_reg_state *val_reg;
5318 /* Things we already checked for in check_map_access and caller:
5319 * - Reject cases where variable offset may touch kptr
5320 * - size of access (must be BPF_DW)
5321 * - tnum_is_const(reg->var_off)
5322 * - kptr_field->offset == off + reg->var_off.value
5324 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5325 if (BPF_MODE(insn->code) != BPF_MEM) {
5326 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5330 /* We only allow loading referenced kptr, since it will be marked as
5331 * untrusted, similar to unreferenced kptr.
5333 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5334 verbose(env, "store to referenced kptr disallowed\n");
5338 if (class == BPF_LDX) {
5339 val_reg = reg_state(env, value_regno);
5340 /* We can simply mark the value_regno receiving the pointer
5341 * value from map as PTR_TO_BTF_ID, with the correct type.
5343 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5344 kptr_field->kptr.btf_id,
5345 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5346 PTR_MAYBE_NULL | MEM_RCU :
5347 PTR_MAYBE_NULL | PTR_UNTRUSTED);
5348 /* For mark_ptr_or_null_reg */
5349 val_reg->id = ++env->id_gen;
5350 } else if (class == BPF_STX) {
5351 val_reg = reg_state(env, value_regno);
5352 if (!register_is_null(val_reg) &&
5353 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5355 } else if (class == BPF_ST) {
5357 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5358 kptr_field->offset);
5362 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5368 /* check read/write into a map element with possible variable offset */
5369 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5370 int off, int size, bool zero_size_allowed,
5371 enum bpf_access_src src)
5373 struct bpf_verifier_state *vstate = env->cur_state;
5374 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5375 struct bpf_reg_state *reg = &state->regs[regno];
5376 struct bpf_map *map = reg->map_ptr;
5377 struct btf_record *rec;
5380 err = check_mem_region_access(env, regno, off, size, map->value_size,
5385 if (IS_ERR_OR_NULL(map->record))
5388 for (i = 0; i < rec->cnt; i++) {
5389 struct btf_field *field = &rec->fields[i];
5390 u32 p = field->offset;
5392 /* If any part of a field can be touched by load/store, reject
5393 * this program. To check that [x1, x2) overlaps with [y1, y2),
5394 * it is sufficient to check x1 < y2 && y1 < x2.
5396 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5397 p < reg->umax_value + off + size) {
5398 switch (field->type) {
5399 case BPF_KPTR_UNREF:
5401 if (src != ACCESS_DIRECT) {
5402 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5405 if (!tnum_is_const(reg->var_off)) {
5406 verbose(env, "kptr access cannot have variable offset\n");
5409 if (p != off + reg->var_off.value) {
5410 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5411 p, off + reg->var_off.value);
5414 if (size != bpf_size_to_bytes(BPF_DW)) {
5415 verbose(env, "kptr access size must be BPF_DW\n");
5420 verbose(env, "%s cannot be accessed directly by load/store\n",
5421 btf_field_type_name(field->type));
5429 #define MAX_PACKET_OFF 0xffff
5431 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5432 const struct bpf_call_arg_meta *meta,
5433 enum bpf_access_type t)
5435 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5437 switch (prog_type) {
5438 /* Program types only with direct read access go here! */
5439 case BPF_PROG_TYPE_LWT_IN:
5440 case BPF_PROG_TYPE_LWT_OUT:
5441 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5442 case BPF_PROG_TYPE_SK_REUSEPORT:
5443 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5444 case BPF_PROG_TYPE_CGROUP_SKB:
5449 /* Program types with direct read + write access go here! */
5450 case BPF_PROG_TYPE_SCHED_CLS:
5451 case BPF_PROG_TYPE_SCHED_ACT:
5452 case BPF_PROG_TYPE_XDP:
5453 case BPF_PROG_TYPE_LWT_XMIT:
5454 case BPF_PROG_TYPE_SK_SKB:
5455 case BPF_PROG_TYPE_SK_MSG:
5457 return meta->pkt_access;
5459 env->seen_direct_write = true;
5462 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5464 env->seen_direct_write = true;
5473 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5474 int size, bool zero_size_allowed)
5476 struct bpf_reg_state *regs = cur_regs(env);
5477 struct bpf_reg_state *reg = ®s[regno];
5480 /* We may have added a variable offset to the packet pointer; but any
5481 * reg->range we have comes after that. We are only checking the fixed
5485 /* We don't allow negative numbers, because we aren't tracking enough
5486 * detail to prove they're safe.
5488 if (reg->smin_value < 0) {
5489 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5494 err = reg->range < 0 ? -EINVAL :
5495 __check_mem_access(env, regno, off, size, reg->range,
5498 verbose(env, "R%d offset is outside of the packet\n", regno);
5502 /* __check_mem_access has made sure "off + size - 1" is within u16.
5503 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5504 * otherwise find_good_pkt_pointers would have refused to set range info
5505 * that __check_mem_access would have rejected this pkt access.
5506 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5508 env->prog->aux->max_pkt_offset =
5509 max_t(u32, env->prog->aux->max_pkt_offset,
5510 off + reg->umax_value + size - 1);
5515 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
5516 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5517 enum bpf_access_type t, enum bpf_reg_type *reg_type,
5518 struct btf **btf, u32 *btf_id)
5520 struct bpf_insn_access_aux info = {
5521 .reg_type = *reg_type,
5525 if (env->ops->is_valid_access &&
5526 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5527 /* A non zero info.ctx_field_size indicates that this field is a
5528 * candidate for later verifier transformation to load the whole
5529 * field and then apply a mask when accessed with a narrower
5530 * access than actual ctx access size. A zero info.ctx_field_size
5531 * will only allow for whole field access and rejects any other
5532 * type of narrower access.
5534 *reg_type = info.reg_type;
5536 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5538 *btf_id = info.btf_id;
5540 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5542 /* remember the offset of last byte accessed in ctx */
5543 if (env->prog->aux->max_ctx_offset < off + size)
5544 env->prog->aux->max_ctx_offset = off + size;
5548 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5552 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5555 if (size < 0 || off < 0 ||
5556 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5557 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5564 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5565 u32 regno, int off, int size,
5566 enum bpf_access_type t)
5568 struct bpf_reg_state *regs = cur_regs(env);
5569 struct bpf_reg_state *reg = ®s[regno];
5570 struct bpf_insn_access_aux info = {};
5573 if (reg->smin_value < 0) {
5574 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5579 switch (reg->type) {
5580 case PTR_TO_SOCK_COMMON:
5581 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5584 valid = bpf_sock_is_valid_access(off, size, t, &info);
5586 case PTR_TO_TCP_SOCK:
5587 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5589 case PTR_TO_XDP_SOCK:
5590 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5598 env->insn_aux_data[insn_idx].ctx_field_size =
5599 info.ctx_field_size;
5603 verbose(env, "R%d invalid %s access off=%d size=%d\n",
5604 regno, reg_type_str(env, reg->type), off, size);
5609 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5611 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5614 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5616 const struct bpf_reg_state *reg = reg_state(env, regno);
5618 return reg->type == PTR_TO_CTX;
5621 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5623 const struct bpf_reg_state *reg = reg_state(env, regno);
5625 return type_is_sk_pointer(reg->type);
5628 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5630 const struct bpf_reg_state *reg = reg_state(env, regno);
5632 return type_is_pkt_pointer(reg->type);
5635 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5637 const struct bpf_reg_state *reg = reg_state(env, regno);
5639 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5640 return reg->type == PTR_TO_FLOW_KEYS;
5643 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5645 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5646 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5647 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5649 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5652 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5654 /* A referenced register is always trusted. */
5655 if (reg->ref_obj_id)
5658 /* Types listed in the reg2btf_ids are always trusted */
5659 if (reg2btf_ids[base_type(reg->type)])
5662 /* If a register is not referenced, it is trusted if it has the
5663 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5664 * other type modifiers may be safe, but we elect to take an opt-in
5665 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5668 * Eventually, we should make PTR_TRUSTED the single source of truth
5669 * for whether a register is trusted.
5671 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5672 !bpf_type_has_unsafe_modifiers(reg->type);
5675 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5677 return reg->type & MEM_RCU;
5680 static void clear_trusted_flags(enum bpf_type_flag *flag)
5682 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5685 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5686 const struct bpf_reg_state *reg,
5687 int off, int size, bool strict)
5689 struct tnum reg_off;
5692 /* Byte size accesses are always allowed. */
5693 if (!strict || size == 1)
5696 /* For platforms that do not have a Kconfig enabling
5697 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5698 * NET_IP_ALIGN is universally set to '2'. And on platforms
5699 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5700 * to this code only in strict mode where we want to emulate
5701 * the NET_IP_ALIGN==2 checking. Therefore use an
5702 * unconditional IP align value of '2'.
5706 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5707 if (!tnum_is_aligned(reg_off, size)) {
5710 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5712 "misaligned packet access off %d+%s+%d+%d size %d\n",
5713 ip_align, tn_buf, reg->off, off, size);
5720 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5721 const struct bpf_reg_state *reg,
5722 const char *pointer_desc,
5723 int off, int size, bool strict)
5725 struct tnum reg_off;
5727 /* Byte size accesses are always allowed. */
5728 if (!strict || size == 1)
5731 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5732 if (!tnum_is_aligned(reg_off, size)) {
5735 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5736 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5737 pointer_desc, tn_buf, reg->off, off, size);
5744 static int check_ptr_alignment(struct bpf_verifier_env *env,
5745 const struct bpf_reg_state *reg, int off,
5746 int size, bool strict_alignment_once)
5748 bool strict = env->strict_alignment || strict_alignment_once;
5749 const char *pointer_desc = "";
5751 switch (reg->type) {
5753 case PTR_TO_PACKET_META:
5754 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5755 * right in front, treat it the very same way.
5757 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5758 case PTR_TO_FLOW_KEYS:
5759 pointer_desc = "flow keys ";
5761 case PTR_TO_MAP_KEY:
5762 pointer_desc = "key ";
5764 case PTR_TO_MAP_VALUE:
5765 pointer_desc = "value ";
5768 pointer_desc = "context ";
5771 pointer_desc = "stack ";
5772 /* The stack spill tracking logic in check_stack_write_fixed_off()
5773 * and check_stack_read_fixed_off() relies on stack accesses being
5779 pointer_desc = "sock ";
5781 case PTR_TO_SOCK_COMMON:
5782 pointer_desc = "sock_common ";
5784 case PTR_TO_TCP_SOCK:
5785 pointer_desc = "tcp_sock ";
5787 case PTR_TO_XDP_SOCK:
5788 pointer_desc = "xdp_sock ";
5793 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5797 /* starting from main bpf function walk all instructions of the function
5798 * and recursively walk all callees that given function can call.
5799 * Ignore jump and exit insns.
5800 * Since recursion is prevented by check_cfg() this algorithm
5801 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5803 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5805 struct bpf_subprog_info *subprog = env->subprog_info;
5806 struct bpf_insn *insn = env->prog->insnsi;
5807 int depth = 0, frame = 0, i, subprog_end;
5808 bool tail_call_reachable = false;
5809 int ret_insn[MAX_CALL_FRAMES];
5810 int ret_prog[MAX_CALL_FRAMES];
5813 i = subprog[idx].start;
5815 /* protect against potential stack overflow that might happen when
5816 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5817 * depth for such case down to 256 so that the worst case scenario
5818 * would result in 8k stack size (32 which is tailcall limit * 256 =
5821 * To get the idea what might happen, see an example:
5822 * func1 -> sub rsp, 128
5823 * subfunc1 -> sub rsp, 256
5824 * tailcall1 -> add rsp, 256
5825 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5826 * subfunc2 -> sub rsp, 64
5827 * subfunc22 -> sub rsp, 128
5828 * tailcall2 -> add rsp, 128
5829 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5831 * tailcall will unwind the current stack frame but it will not get rid
5832 * of caller's stack as shown on the example above.
5834 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5836 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5840 /* round up to 32-bytes, since this is granularity
5841 * of interpreter stack size
5843 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5844 if (depth > MAX_BPF_STACK) {
5845 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5850 subprog_end = subprog[idx + 1].start;
5851 for (; i < subprog_end; i++) {
5852 int next_insn, sidx;
5854 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5856 /* remember insn and function to return to */
5857 ret_insn[frame] = i + 1;
5858 ret_prog[frame] = idx;
5860 /* find the callee */
5861 next_insn = i + insn[i].imm + 1;
5862 sidx = find_subprog(env, next_insn);
5864 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5868 if (subprog[sidx].is_async_cb) {
5869 if (subprog[sidx].has_tail_call) {
5870 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5873 /* async callbacks don't increase bpf prog stack size unless called directly */
5874 if (!bpf_pseudo_call(insn + i))
5880 if (subprog[idx].has_tail_call)
5881 tail_call_reachable = true;
5884 if (frame >= MAX_CALL_FRAMES) {
5885 verbose(env, "the call stack of %d frames is too deep !\n",
5891 /* if tail call got detected across bpf2bpf calls then mark each of the
5892 * currently present subprog frames as tail call reachable subprogs;
5893 * this info will be utilized by JIT so that we will be preserving the
5894 * tail call counter throughout bpf2bpf calls combined with tailcalls
5896 if (tail_call_reachable)
5897 for (j = 0; j < frame; j++)
5898 subprog[ret_prog[j]].tail_call_reachable = true;
5899 if (subprog[0].tail_call_reachable)
5900 env->prog->aux->tail_call_reachable = true;
5902 /* end of for() loop means the last insn of the 'subprog'
5903 * was reached. Doesn't matter whether it was JA or EXIT
5907 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5909 i = ret_insn[frame];
5910 idx = ret_prog[frame];
5914 static int check_max_stack_depth(struct bpf_verifier_env *env)
5916 struct bpf_subprog_info *si = env->subprog_info;
5919 for (int i = 0; i < env->subprog_cnt; i++) {
5920 if (!i || si[i].is_async_cb) {
5921 ret = check_max_stack_depth_subprog(env, i);
5930 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5931 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5932 const struct bpf_insn *insn, int idx)
5934 int start = idx + insn->imm + 1, subprog;
5936 subprog = find_subprog(env, start);
5938 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5942 return env->subprog_info[subprog].stack_depth;
5946 static int __check_buffer_access(struct bpf_verifier_env *env,
5947 const char *buf_info,
5948 const struct bpf_reg_state *reg,
5949 int regno, int off, int size)
5953 "R%d invalid %s buffer access: off=%d, size=%d\n",
5954 regno, buf_info, off, size);
5957 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5960 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5962 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5963 regno, off, tn_buf);
5970 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5971 const struct bpf_reg_state *reg,
5972 int regno, int off, int size)
5976 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5980 if (off + size > env->prog->aux->max_tp_access)
5981 env->prog->aux->max_tp_access = off + size;
5986 static int check_buffer_access(struct bpf_verifier_env *env,
5987 const struct bpf_reg_state *reg,
5988 int regno, int off, int size,
5989 bool zero_size_allowed,
5992 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5995 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5999 if (off + size > *max_access)
6000 *max_access = off + size;
6005 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6006 static void zext_32_to_64(struct bpf_reg_state *reg)
6008 reg->var_off = tnum_subreg(reg->var_off);
6009 __reg_assign_32_into_64(reg);
6012 /* truncate register to smaller size (in bytes)
6013 * must be called with size < BPF_REG_SIZE
6015 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6019 /* clear high bits in bit representation */
6020 reg->var_off = tnum_cast(reg->var_off, size);
6022 /* fix arithmetic bounds */
6023 mask = ((u64)1 << (size * 8)) - 1;
6024 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6025 reg->umin_value &= mask;
6026 reg->umax_value &= mask;
6028 reg->umin_value = 0;
6029 reg->umax_value = mask;
6031 reg->smin_value = reg->umin_value;
6032 reg->smax_value = reg->umax_value;
6034 /* If size is smaller than 32bit register the 32bit register
6035 * values are also truncated so we push 64-bit bounds into
6036 * 32-bit bounds. Above were truncated < 32-bits already.
6040 __reg_combine_64_into_32(reg);
6043 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6046 reg->smin_value = reg->s32_min_value = S8_MIN;
6047 reg->smax_value = reg->s32_max_value = S8_MAX;
6048 } else if (size == 2) {
6049 reg->smin_value = reg->s32_min_value = S16_MIN;
6050 reg->smax_value = reg->s32_max_value = S16_MAX;
6053 reg->smin_value = reg->s32_min_value = S32_MIN;
6054 reg->smax_value = reg->s32_max_value = S32_MAX;
6056 reg->umin_value = reg->u32_min_value = 0;
6057 reg->umax_value = U64_MAX;
6058 reg->u32_max_value = U32_MAX;
6059 reg->var_off = tnum_unknown;
6062 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6064 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6065 u64 top_smax_value, top_smin_value;
6066 u64 num_bits = size * 8;
6068 if (tnum_is_const(reg->var_off)) {
6069 u64_cval = reg->var_off.value;
6071 reg->var_off = tnum_const((s8)u64_cval);
6073 reg->var_off = tnum_const((s16)u64_cval);
6076 reg->var_off = tnum_const((s32)u64_cval);
6078 u64_cval = reg->var_off.value;
6079 reg->smax_value = reg->smin_value = u64_cval;
6080 reg->umax_value = reg->umin_value = u64_cval;
6081 reg->s32_max_value = reg->s32_min_value = u64_cval;
6082 reg->u32_max_value = reg->u32_min_value = u64_cval;
6086 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6087 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6089 if (top_smax_value != top_smin_value)
6092 /* find the s64_min and s64_min after sign extension */
6094 init_s64_max = (s8)reg->smax_value;
6095 init_s64_min = (s8)reg->smin_value;
6096 } else if (size == 2) {
6097 init_s64_max = (s16)reg->smax_value;
6098 init_s64_min = (s16)reg->smin_value;
6100 init_s64_max = (s32)reg->smax_value;
6101 init_s64_min = (s32)reg->smin_value;
6104 s64_max = max(init_s64_max, init_s64_min);
6105 s64_min = min(init_s64_max, init_s64_min);
6107 /* both of s64_max/s64_min positive or negative */
6108 if ((s64_max >= 0) == (s64_min >= 0)) {
6109 reg->smin_value = reg->s32_min_value = s64_min;
6110 reg->smax_value = reg->s32_max_value = s64_max;
6111 reg->umin_value = reg->u32_min_value = s64_min;
6112 reg->umax_value = reg->u32_max_value = s64_max;
6113 reg->var_off = tnum_range(s64_min, s64_max);
6118 set_sext64_default_val(reg, size);
6121 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6124 reg->s32_min_value = S8_MIN;
6125 reg->s32_max_value = S8_MAX;
6128 reg->s32_min_value = S16_MIN;
6129 reg->s32_max_value = S16_MAX;
6131 reg->u32_min_value = 0;
6132 reg->u32_max_value = U32_MAX;
6135 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6137 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6138 u32 top_smax_value, top_smin_value;
6139 u32 num_bits = size * 8;
6141 if (tnum_is_const(reg->var_off)) {
6142 u32_val = reg->var_off.value;
6144 reg->var_off = tnum_const((s8)u32_val);
6146 reg->var_off = tnum_const((s16)u32_val);
6148 u32_val = reg->var_off.value;
6149 reg->s32_min_value = reg->s32_max_value = u32_val;
6150 reg->u32_min_value = reg->u32_max_value = u32_val;
6154 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6155 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6157 if (top_smax_value != top_smin_value)
6160 /* find the s32_min and s32_min after sign extension */
6162 init_s32_max = (s8)reg->s32_max_value;
6163 init_s32_min = (s8)reg->s32_min_value;
6166 init_s32_max = (s16)reg->s32_max_value;
6167 init_s32_min = (s16)reg->s32_min_value;
6169 s32_max = max(init_s32_max, init_s32_min);
6170 s32_min = min(init_s32_max, init_s32_min);
6172 if ((s32_min >= 0) == (s32_max >= 0)) {
6173 reg->s32_min_value = s32_min;
6174 reg->s32_max_value = s32_max;
6175 reg->u32_min_value = (u32)s32_min;
6176 reg->u32_max_value = (u32)s32_max;
6181 set_sext32_default_val(reg, size);
6184 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6186 /* A map is considered read-only if the following condition are true:
6188 * 1) BPF program side cannot change any of the map content. The
6189 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6190 * and was set at map creation time.
6191 * 2) The map value(s) have been initialized from user space by a
6192 * loader and then "frozen", such that no new map update/delete
6193 * operations from syscall side are possible for the rest of
6194 * the map's lifetime from that point onwards.
6195 * 3) Any parallel/pending map update/delete operations from syscall
6196 * side have been completed. Only after that point, it's safe to
6197 * assume that map value(s) are immutable.
6199 return (map->map_flags & BPF_F_RDONLY_PROG) &&
6200 READ_ONCE(map->frozen) &&
6201 !bpf_map_write_active(map);
6204 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6211 err = map->ops->map_direct_value_addr(map, &addr, off);
6214 ptr = (void *)(long)addr + off;
6218 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6221 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6224 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6235 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
6236 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6237 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
6240 * Allow list few fields as RCU trusted or full trusted.
6241 * This logic doesn't allow mix tagging and will be removed once GCC supports
6245 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6246 BTF_TYPE_SAFE_RCU(struct task_struct) {
6247 const cpumask_t *cpus_ptr;
6248 struct css_set __rcu *cgroups;
6249 struct task_struct __rcu *real_parent;
6250 struct task_struct *group_leader;
6253 BTF_TYPE_SAFE_RCU(struct cgroup) {
6254 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6255 struct kernfs_node *kn;
6258 BTF_TYPE_SAFE_RCU(struct css_set) {
6259 struct cgroup *dfl_cgrp;
6262 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6263 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6264 struct file __rcu *exe_file;
6267 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6268 * because bpf prog accessible sockets are SOCK_RCU_FREE.
6270 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6274 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6278 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6279 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6280 struct seq_file *seq;
6283 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6284 struct bpf_iter_meta *meta;
6285 struct task_struct *task;
6288 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6292 BTF_TYPE_SAFE_TRUSTED(struct file) {
6293 struct inode *f_inode;
6296 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6297 /* no negative dentry-s in places where bpf can see it */
6298 struct inode *d_inode;
6301 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6305 static bool type_is_rcu(struct bpf_verifier_env *env,
6306 struct bpf_reg_state *reg,
6307 const char *field_name, u32 btf_id)
6309 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6310 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6311 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6313 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6316 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6317 struct bpf_reg_state *reg,
6318 const char *field_name, u32 btf_id)
6320 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6321 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6322 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6324 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6327 static bool type_is_trusted(struct bpf_verifier_env *env,
6328 struct bpf_reg_state *reg,
6329 const char *field_name, u32 btf_id)
6331 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6332 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6333 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6334 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6335 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6336 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6338 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6341 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6342 struct bpf_reg_state *regs,
6343 int regno, int off, int size,
6344 enum bpf_access_type atype,
6347 struct bpf_reg_state *reg = regs + regno;
6348 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6349 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6350 const char *field_name = NULL;
6351 enum bpf_type_flag flag = 0;
6355 if (!env->allow_ptr_leaks) {
6357 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6361 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6363 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6369 "R%d is ptr_%s invalid negative access: off=%d\n",
6373 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6376 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6378 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6379 regno, tname, off, tn_buf);
6383 if (reg->type & MEM_USER) {
6385 "R%d is ptr_%s access user memory: off=%d\n",
6390 if (reg->type & MEM_PERCPU) {
6392 "R%d is ptr_%s access percpu memory: off=%d\n",
6397 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6398 if (!btf_is_kernel(reg->btf)) {
6399 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6402 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6404 /* Writes are permitted with default btf_struct_access for
6405 * program allocated objects (which always have ref_obj_id > 0),
6406 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6408 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6409 verbose(env, "only read is supported\n");
6413 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6415 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6419 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6425 if (ret != PTR_TO_BTF_ID) {
6428 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6429 /* If this is an untrusted pointer, all pointers formed by walking it
6430 * also inherit the untrusted flag.
6432 flag = PTR_UNTRUSTED;
6434 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6435 /* By default any pointer obtained from walking a trusted pointer is no
6436 * longer trusted, unless the field being accessed has explicitly been
6437 * marked as inheriting its parent's state of trust (either full or RCU).
6439 * 'cgroups' pointer is untrusted if task->cgroups dereference
6440 * happened in a sleepable program outside of bpf_rcu_read_lock()
6441 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6442 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6444 * A regular RCU-protected pointer with __rcu tag can also be deemed
6445 * trusted if we are in an RCU CS. Such pointer can be NULL.
6447 if (type_is_trusted(env, reg, field_name, btf_id)) {
6448 flag |= PTR_TRUSTED;
6449 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6450 if (type_is_rcu(env, reg, field_name, btf_id)) {
6451 /* ignore __rcu tag and mark it MEM_RCU */
6453 } else if (flag & MEM_RCU ||
6454 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6455 /* __rcu tagged pointers can be NULL */
6456 flag |= MEM_RCU | PTR_MAYBE_NULL;
6458 /* We always trust them */
6459 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6460 flag & PTR_UNTRUSTED)
6461 flag &= ~PTR_UNTRUSTED;
6462 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6465 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6466 clear_trusted_flags(&flag);
6470 * If not in RCU CS or MEM_RCU pointer can be NULL then
6471 * aggressively mark as untrusted otherwise such
6472 * pointers will be plain PTR_TO_BTF_ID without flags
6473 * and will be allowed to be passed into helpers for
6476 flag = PTR_UNTRUSTED;
6479 /* Old compat. Deprecated */
6480 clear_trusted_flags(&flag);
6483 if (atype == BPF_READ && value_regno >= 0)
6484 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6489 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6490 struct bpf_reg_state *regs,
6491 int regno, int off, int size,
6492 enum bpf_access_type atype,
6495 struct bpf_reg_state *reg = regs + regno;
6496 struct bpf_map *map = reg->map_ptr;
6497 struct bpf_reg_state map_reg;
6498 enum bpf_type_flag flag = 0;
6499 const struct btf_type *t;
6505 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6509 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6510 verbose(env, "map_ptr access not supported for map type %d\n",
6515 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6516 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6518 if (!env->allow_ptr_leaks) {
6520 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6526 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6531 if (atype != BPF_READ) {
6532 verbose(env, "only read from %s is supported\n", tname);
6536 /* Simulate access to a PTR_TO_BTF_ID */
6537 memset(&map_reg, 0, sizeof(map_reg));
6538 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6539 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6543 if (value_regno >= 0)
6544 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6549 /* Check that the stack access at the given offset is within bounds. The
6550 * maximum valid offset is -1.
6552 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6553 * -state->allocated_stack for reads.
6555 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6557 struct bpf_func_state *state,
6558 enum bpf_access_type t)
6562 if (t == BPF_WRITE || env->allow_uninit_stack)
6563 min_valid_off = -MAX_BPF_STACK;
6565 min_valid_off = -state->allocated_stack;
6567 if (off < min_valid_off || off > -1)
6572 /* Check that the stack access at 'regno + off' falls within the maximum stack
6575 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6577 static int check_stack_access_within_bounds(
6578 struct bpf_verifier_env *env,
6579 int regno, int off, int access_size,
6580 enum bpf_access_src src, enum bpf_access_type type)
6582 struct bpf_reg_state *regs = cur_regs(env);
6583 struct bpf_reg_state *reg = regs + regno;
6584 struct bpf_func_state *state = func(env, reg);
6585 s64 min_off, max_off;
6589 if (src == ACCESS_HELPER)
6590 /* We don't know if helpers are reading or writing (or both). */
6591 err_extra = " indirect access to";
6592 else if (type == BPF_READ)
6593 err_extra = " read from";
6595 err_extra = " write to";
6597 if (tnum_is_const(reg->var_off)) {
6598 min_off = (s64)reg->var_off.value + off;
6599 max_off = min_off + access_size;
6601 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6602 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6603 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6607 min_off = reg->smin_value + off;
6608 max_off = reg->smax_value + off + access_size;
6611 err = check_stack_slot_within_bounds(env, min_off, state, type);
6612 if (!err && max_off > 0)
6613 err = -EINVAL; /* out of stack access into non-negative offsets */
6616 if (tnum_is_const(reg->var_off)) {
6617 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6618 err_extra, regno, off, access_size);
6622 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6623 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6624 err_extra, regno, tn_buf, access_size);
6629 return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE));
6632 /* check whether memory at (regno + off) is accessible for t = (read | write)
6633 * if t==write, value_regno is a register which value is stored into memory
6634 * if t==read, value_regno is a register which will receive the value from memory
6635 * if t==write && value_regno==-1, some unknown value is stored into memory
6636 * if t==read && value_regno==-1, don't care what we read from memory
6638 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6639 int off, int bpf_size, enum bpf_access_type t,
6640 int value_regno, bool strict_alignment_once, bool is_ldsx)
6642 struct bpf_reg_state *regs = cur_regs(env);
6643 struct bpf_reg_state *reg = regs + regno;
6646 size = bpf_size_to_bytes(bpf_size);
6650 /* alignment checks will add in reg->off themselves */
6651 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6655 /* for access checks, reg->off is just part of off */
6658 if (reg->type == PTR_TO_MAP_KEY) {
6659 if (t == BPF_WRITE) {
6660 verbose(env, "write to change key R%d not allowed\n", regno);
6664 err = check_mem_region_access(env, regno, off, size,
6665 reg->map_ptr->key_size, false);
6668 if (value_regno >= 0)
6669 mark_reg_unknown(env, regs, value_regno);
6670 } else if (reg->type == PTR_TO_MAP_VALUE) {
6671 struct btf_field *kptr_field = NULL;
6673 if (t == BPF_WRITE && value_regno >= 0 &&
6674 is_pointer_value(env, value_regno)) {
6675 verbose(env, "R%d leaks addr into map\n", value_regno);
6678 err = check_map_access_type(env, regno, off, size, t);
6681 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6684 if (tnum_is_const(reg->var_off))
6685 kptr_field = btf_record_find(reg->map_ptr->record,
6686 off + reg->var_off.value, BPF_KPTR);
6688 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6689 } else if (t == BPF_READ && value_regno >= 0) {
6690 struct bpf_map *map = reg->map_ptr;
6692 /* if map is read-only, track its contents as scalars */
6693 if (tnum_is_const(reg->var_off) &&
6694 bpf_map_is_rdonly(map) &&
6695 map->ops->map_direct_value_addr) {
6696 int map_off = off + reg->var_off.value;
6699 err = bpf_map_direct_read(map, map_off, size,
6704 regs[value_regno].type = SCALAR_VALUE;
6705 __mark_reg_known(®s[value_regno], val);
6707 mark_reg_unknown(env, regs, value_regno);
6710 } else if (base_type(reg->type) == PTR_TO_MEM) {
6711 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6713 if (type_may_be_null(reg->type)) {
6714 verbose(env, "R%d invalid mem access '%s'\n", regno,
6715 reg_type_str(env, reg->type));
6719 if (t == BPF_WRITE && rdonly_mem) {
6720 verbose(env, "R%d cannot write into %s\n",
6721 regno, reg_type_str(env, reg->type));
6725 if (t == BPF_WRITE && value_regno >= 0 &&
6726 is_pointer_value(env, value_regno)) {
6727 verbose(env, "R%d leaks addr into mem\n", value_regno);
6731 err = check_mem_region_access(env, regno, off, size,
6732 reg->mem_size, false);
6733 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6734 mark_reg_unknown(env, regs, value_regno);
6735 } else if (reg->type == PTR_TO_CTX) {
6736 enum bpf_reg_type reg_type = SCALAR_VALUE;
6737 struct btf *btf = NULL;
6740 if (t == BPF_WRITE && value_regno >= 0 &&
6741 is_pointer_value(env, value_regno)) {
6742 verbose(env, "R%d leaks addr into ctx\n", value_regno);
6746 err = check_ptr_off_reg(env, reg, regno);
6750 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
6753 verbose_linfo(env, insn_idx, "; ");
6754 if (!err && t == BPF_READ && value_regno >= 0) {
6755 /* ctx access returns either a scalar, or a
6756 * PTR_TO_PACKET[_META,_END]. In the latter
6757 * case, we know the offset is zero.
6759 if (reg_type == SCALAR_VALUE) {
6760 mark_reg_unknown(env, regs, value_regno);
6762 mark_reg_known_zero(env, regs,
6764 if (type_may_be_null(reg_type))
6765 regs[value_regno].id = ++env->id_gen;
6766 /* A load of ctx field could have different
6767 * actual load size with the one encoded in the
6768 * insn. When the dst is PTR, it is for sure not
6771 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6772 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6773 regs[value_regno].btf = btf;
6774 regs[value_regno].btf_id = btf_id;
6777 regs[value_regno].type = reg_type;
6780 } else if (reg->type == PTR_TO_STACK) {
6781 /* Basic bounds checks. */
6782 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6787 err = check_stack_read(env, regno, off, size,
6790 err = check_stack_write(env, regno, off, size,
6791 value_regno, insn_idx);
6792 } else if (reg_is_pkt_pointer(reg)) {
6793 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6794 verbose(env, "cannot write into packet\n");
6797 if (t == BPF_WRITE && value_regno >= 0 &&
6798 is_pointer_value(env, value_regno)) {
6799 verbose(env, "R%d leaks addr into packet\n",
6803 err = check_packet_access(env, regno, off, size, false);
6804 if (!err && t == BPF_READ && value_regno >= 0)
6805 mark_reg_unknown(env, regs, value_regno);
6806 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6807 if (t == BPF_WRITE && value_regno >= 0 &&
6808 is_pointer_value(env, value_regno)) {
6809 verbose(env, "R%d leaks addr into flow keys\n",
6814 err = check_flow_keys_access(env, off, size);
6815 if (!err && t == BPF_READ && value_regno >= 0)
6816 mark_reg_unknown(env, regs, value_regno);
6817 } else if (type_is_sk_pointer(reg->type)) {
6818 if (t == BPF_WRITE) {
6819 verbose(env, "R%d cannot write into %s\n",
6820 regno, reg_type_str(env, reg->type));
6823 err = check_sock_access(env, insn_idx, regno, off, size, t);
6824 if (!err && value_regno >= 0)
6825 mark_reg_unknown(env, regs, value_regno);
6826 } else if (reg->type == PTR_TO_TP_BUFFER) {
6827 err = check_tp_buffer_access(env, reg, regno, off, size);
6828 if (!err && t == BPF_READ && value_regno >= 0)
6829 mark_reg_unknown(env, regs, value_regno);
6830 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6831 !type_may_be_null(reg->type)) {
6832 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6834 } else if (reg->type == CONST_PTR_TO_MAP) {
6835 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6837 } else if (base_type(reg->type) == PTR_TO_BUF) {
6838 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6842 if (t == BPF_WRITE) {
6843 verbose(env, "R%d cannot write into %s\n",
6844 regno, reg_type_str(env, reg->type));
6847 max_access = &env->prog->aux->max_rdonly_access;
6849 max_access = &env->prog->aux->max_rdwr_access;
6852 err = check_buffer_access(env, reg, regno, off, size, false,
6855 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6856 mark_reg_unknown(env, regs, value_regno);
6858 verbose(env, "R%d invalid mem access '%s'\n", regno,
6859 reg_type_str(env, reg->type));
6863 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6864 regs[value_regno].type == SCALAR_VALUE) {
6866 /* b/h/w load zero-extends, mark upper bits as known 0 */
6867 coerce_reg_to_size(®s[value_regno], size);
6869 coerce_reg_to_size_sx(®s[value_regno], size);
6874 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6879 switch (insn->imm) {
6881 case BPF_ADD | BPF_FETCH:
6883 case BPF_AND | BPF_FETCH:
6885 case BPF_OR | BPF_FETCH:
6887 case BPF_XOR | BPF_FETCH:
6892 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6896 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6897 verbose(env, "invalid atomic operand size\n");
6901 /* check src1 operand */
6902 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6906 /* check src2 operand */
6907 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6911 if (insn->imm == BPF_CMPXCHG) {
6912 /* Check comparison of R0 with memory location */
6913 const u32 aux_reg = BPF_REG_0;
6915 err = check_reg_arg(env, aux_reg, SRC_OP);
6919 if (is_pointer_value(env, aux_reg)) {
6920 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6925 if (is_pointer_value(env, insn->src_reg)) {
6926 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6930 if (is_ctx_reg(env, insn->dst_reg) ||
6931 is_pkt_reg(env, insn->dst_reg) ||
6932 is_flow_key_reg(env, insn->dst_reg) ||
6933 is_sk_reg(env, insn->dst_reg)) {
6934 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6936 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6940 if (insn->imm & BPF_FETCH) {
6941 if (insn->imm == BPF_CMPXCHG)
6942 load_reg = BPF_REG_0;
6944 load_reg = insn->src_reg;
6946 /* check and record load of old value */
6947 err = check_reg_arg(env, load_reg, DST_OP);
6951 /* This instruction accesses a memory location but doesn't
6952 * actually load it into a register.
6957 /* Check whether we can read the memory, with second call for fetch
6958 * case to simulate the register fill.
6960 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6961 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6962 if (!err && load_reg >= 0)
6963 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6964 BPF_SIZE(insn->code), BPF_READ, load_reg,
6969 /* Check whether we can write into the same memory. */
6970 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6971 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6978 /* When register 'regno' is used to read the stack (either directly or through
6979 * a helper function) make sure that it's within stack boundary and, depending
6980 * on the access type and privileges, that all elements of the stack are
6983 * 'off' includes 'regno->off', but not its dynamic part (if any).
6985 * All registers that have been spilled on the stack in the slots within the
6986 * read offsets are marked as read.
6988 static int check_stack_range_initialized(
6989 struct bpf_verifier_env *env, int regno, int off,
6990 int access_size, bool zero_size_allowed,
6991 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6993 struct bpf_reg_state *reg = reg_state(env, regno);
6994 struct bpf_func_state *state = func(env, reg);
6995 int err, min_off, max_off, i, j, slot, spi;
6996 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6997 enum bpf_access_type bounds_check_type;
6998 /* Some accesses can write anything into the stack, others are
7001 bool clobber = false;
7003 if (access_size == 0 && !zero_size_allowed) {
7004 verbose(env, "invalid zero-sized read\n");
7008 if (type == ACCESS_HELPER) {
7009 /* The bounds checks for writes are more permissive than for
7010 * reads. However, if raw_mode is not set, we'll do extra
7013 bounds_check_type = BPF_WRITE;
7016 bounds_check_type = BPF_READ;
7018 err = check_stack_access_within_bounds(env, regno, off, access_size,
7019 type, bounds_check_type);
7024 if (tnum_is_const(reg->var_off)) {
7025 min_off = max_off = reg->var_off.value + off;
7027 /* Variable offset is prohibited for unprivileged mode for
7028 * simplicity since it requires corresponding support in
7029 * Spectre masking for stack ALU.
7030 * See also retrieve_ptr_limit().
7032 if (!env->bypass_spec_v1) {
7035 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7036 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7037 regno, err_extra, tn_buf);
7040 /* Only initialized buffer on stack is allowed to be accessed
7041 * with variable offset. With uninitialized buffer it's hard to
7042 * guarantee that whole memory is marked as initialized on
7043 * helper return since specific bounds are unknown what may
7044 * cause uninitialized stack leaking.
7046 if (meta && meta->raw_mode)
7049 min_off = reg->smin_value + off;
7050 max_off = reg->smax_value + off;
7053 if (meta && meta->raw_mode) {
7054 /* Ensure we won't be overwriting dynptrs when simulating byte
7055 * by byte access in check_helper_call using meta.access_size.
7056 * This would be a problem if we have a helper in the future
7059 * helper(uninit_mem, len, dynptr)
7061 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7062 * may end up writing to dynptr itself when touching memory from
7063 * arg 1. This can be relaxed on a case by case basis for known
7064 * safe cases, but reject due to the possibilitiy of aliasing by
7067 for (i = min_off; i < max_off + access_size; i++) {
7068 int stack_off = -i - 1;
7071 /* raw_mode may write past allocated_stack */
7072 if (state->allocated_stack <= stack_off)
7074 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7075 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7079 meta->access_size = access_size;
7080 meta->regno = regno;
7084 for (i = min_off; i < max_off + access_size; i++) {
7088 spi = slot / BPF_REG_SIZE;
7089 if (state->allocated_stack <= slot) {
7090 verbose(env, "verifier bug: allocated_stack too small");
7094 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7095 if (*stype == STACK_MISC)
7097 if ((*stype == STACK_ZERO) ||
7098 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7100 /* helper can write anything into the stack */
7101 *stype = STACK_MISC;
7106 if (is_spilled_reg(&state->stack[spi]) &&
7107 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7108 env->allow_ptr_leaks)) {
7110 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7111 for (j = 0; j < BPF_REG_SIZE; j++)
7112 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7117 if (tnum_is_const(reg->var_off)) {
7118 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7119 err_extra, regno, min_off, i - min_off, access_size);
7123 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7124 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7125 err_extra, regno, tn_buf, i - min_off, access_size);
7129 /* reading any byte out of 8-byte 'spill_slot' will cause
7130 * the whole slot to be marked as 'read'
7132 mark_reg_read(env, &state->stack[spi].spilled_ptr,
7133 state->stack[spi].spilled_ptr.parent,
7135 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7136 * be sure that whether stack slot is written to or not. Hence,
7137 * we must still conservatively propagate reads upwards even if
7138 * helper may write to the entire memory range.
7144 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7145 int access_size, bool zero_size_allowed,
7146 struct bpf_call_arg_meta *meta)
7148 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7151 switch (base_type(reg->type)) {
7153 case PTR_TO_PACKET_META:
7154 return check_packet_access(env, regno, reg->off, access_size,
7156 case PTR_TO_MAP_KEY:
7157 if (meta && meta->raw_mode) {
7158 verbose(env, "R%d cannot write into %s\n", regno,
7159 reg_type_str(env, reg->type));
7162 return check_mem_region_access(env, regno, reg->off, access_size,
7163 reg->map_ptr->key_size, false);
7164 case PTR_TO_MAP_VALUE:
7165 if (check_map_access_type(env, regno, reg->off, access_size,
7166 meta && meta->raw_mode ? BPF_WRITE :
7169 return check_map_access(env, regno, reg->off, access_size,
7170 zero_size_allowed, ACCESS_HELPER);
7172 if (type_is_rdonly_mem(reg->type)) {
7173 if (meta && meta->raw_mode) {
7174 verbose(env, "R%d cannot write into %s\n", regno,
7175 reg_type_str(env, reg->type));
7179 return check_mem_region_access(env, regno, reg->off,
7180 access_size, reg->mem_size,
7183 if (type_is_rdonly_mem(reg->type)) {
7184 if (meta && meta->raw_mode) {
7185 verbose(env, "R%d cannot write into %s\n", regno,
7186 reg_type_str(env, reg->type));
7190 max_access = &env->prog->aux->max_rdonly_access;
7192 max_access = &env->prog->aux->max_rdwr_access;
7194 return check_buffer_access(env, reg, regno, reg->off,
7195 access_size, zero_size_allowed,
7198 return check_stack_range_initialized(
7200 regno, reg->off, access_size,
7201 zero_size_allowed, ACCESS_HELPER, meta);
7203 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7204 access_size, BPF_READ, -1);
7206 /* in case the function doesn't know how to access the context,
7207 * (because we are in a program of type SYSCALL for example), we
7208 * can not statically check its size.
7209 * Dynamically check it now.
7211 if (!env->ops->convert_ctx_access) {
7212 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7213 int offset = access_size - 1;
7215 /* Allow zero-byte read from PTR_TO_CTX */
7216 if (access_size == 0)
7217 return zero_size_allowed ? 0 : -EACCES;
7219 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7220 atype, -1, false, false);
7224 default: /* scalar_value or invalid ptr */
7225 /* Allow zero-byte read from NULL, regardless of pointer type */
7226 if (zero_size_allowed && access_size == 0 &&
7227 register_is_null(reg))
7230 verbose(env, "R%d type=%s ", regno,
7231 reg_type_str(env, reg->type));
7232 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7237 static int check_mem_size_reg(struct bpf_verifier_env *env,
7238 struct bpf_reg_state *reg, u32 regno,
7239 bool zero_size_allowed,
7240 struct bpf_call_arg_meta *meta)
7244 /* This is used to refine r0 return value bounds for helpers
7245 * that enforce this value as an upper bound on return values.
7246 * See do_refine_retval_range() for helpers that can refine
7247 * the return value. C type of helper is u32 so we pull register
7248 * bound from umax_value however, if negative verifier errors
7249 * out. Only upper bounds can be learned because retval is an
7250 * int type and negative retvals are allowed.
7252 meta->msize_max_value = reg->umax_value;
7254 /* The register is SCALAR_VALUE; the access check
7255 * happens using its boundaries.
7257 if (!tnum_is_const(reg->var_off))
7258 /* For unprivileged variable accesses, disable raw
7259 * mode so that the program is required to
7260 * initialize all the memory that the helper could
7261 * just partially fill up.
7265 if (reg->smin_value < 0) {
7266 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7271 if (reg->umin_value == 0) {
7272 err = check_helper_mem_access(env, regno - 1, 0,
7279 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7280 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7284 err = check_helper_mem_access(env, regno - 1,
7286 zero_size_allowed, meta);
7288 err = mark_chain_precision(env, regno);
7292 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7293 u32 regno, u32 mem_size)
7295 bool may_be_null = type_may_be_null(reg->type);
7296 struct bpf_reg_state saved_reg;
7297 struct bpf_call_arg_meta meta;
7300 if (register_is_null(reg))
7303 memset(&meta, 0, sizeof(meta));
7304 /* Assuming that the register contains a value check if the memory
7305 * access is safe. Temporarily save and restore the register's state as
7306 * the conversion shouldn't be visible to a caller.
7310 mark_ptr_not_null_reg(reg);
7313 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7314 /* Check access for BPF_WRITE */
7315 meta.raw_mode = true;
7316 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7324 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7327 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7328 bool may_be_null = type_may_be_null(mem_reg->type);
7329 struct bpf_reg_state saved_reg;
7330 struct bpf_call_arg_meta meta;
7333 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7335 memset(&meta, 0, sizeof(meta));
7338 saved_reg = *mem_reg;
7339 mark_ptr_not_null_reg(mem_reg);
7342 err = check_mem_size_reg(env, reg, regno, true, &meta);
7343 /* Check access for BPF_WRITE */
7344 meta.raw_mode = true;
7345 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7348 *mem_reg = saved_reg;
7352 /* Implementation details:
7353 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7354 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7355 * Two bpf_map_lookups (even with the same key) will have different reg->id.
7356 * Two separate bpf_obj_new will also have different reg->id.
7357 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7358 * clears reg->id after value_or_null->value transition, since the verifier only
7359 * cares about the range of access to valid map value pointer and doesn't care
7360 * about actual address of the map element.
7361 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7362 * reg->id > 0 after value_or_null->value transition. By doing so
7363 * two bpf_map_lookups will be considered two different pointers that
7364 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7365 * returned from bpf_obj_new.
7366 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7368 * Since only one bpf_spin_lock is allowed the checks are simpler than
7369 * reg_is_refcounted() logic. The verifier needs to remember only
7370 * one spin_lock instead of array of acquired_refs.
7371 * cur_state->active_lock remembers which map value element or allocated
7372 * object got locked and clears it after bpf_spin_unlock.
7374 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7377 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7378 struct bpf_verifier_state *cur = env->cur_state;
7379 bool is_const = tnum_is_const(reg->var_off);
7380 u64 val = reg->var_off.value;
7381 struct bpf_map *map = NULL;
7382 struct btf *btf = NULL;
7383 struct btf_record *rec;
7387 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7391 if (reg->type == PTR_TO_MAP_VALUE) {
7395 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7403 rec = reg_btf_record(reg);
7404 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7405 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7406 map ? map->name : "kptr");
7409 if (rec->spin_lock_off != val + reg->off) {
7410 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7411 val + reg->off, rec->spin_lock_off);
7415 if (cur->active_lock.ptr) {
7417 "Locking two bpf_spin_locks are not allowed\n");
7421 cur->active_lock.ptr = map;
7423 cur->active_lock.ptr = btf;
7424 cur->active_lock.id = reg->id;
7433 if (!cur->active_lock.ptr) {
7434 verbose(env, "bpf_spin_unlock without taking a lock\n");
7437 if (cur->active_lock.ptr != ptr ||
7438 cur->active_lock.id != reg->id) {
7439 verbose(env, "bpf_spin_unlock of different lock\n");
7443 invalidate_non_owning_refs(env);
7445 cur->active_lock.ptr = NULL;
7446 cur->active_lock.id = 0;
7451 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7452 struct bpf_call_arg_meta *meta)
7454 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7455 bool is_const = tnum_is_const(reg->var_off);
7456 struct bpf_map *map = reg->map_ptr;
7457 u64 val = reg->var_off.value;
7461 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7466 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7470 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7471 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7474 if (map->record->timer_off != val + reg->off) {
7475 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7476 val + reg->off, map->record->timer_off);
7479 if (meta->map_ptr) {
7480 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7483 meta->map_uid = reg->map_uid;
7484 meta->map_ptr = map;
7488 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7489 struct bpf_call_arg_meta *meta)
7491 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7492 struct bpf_map *map_ptr = reg->map_ptr;
7493 struct btf_field *kptr_field;
7496 if (!tnum_is_const(reg->var_off)) {
7498 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7502 if (!map_ptr->btf) {
7503 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7507 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7508 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7512 meta->map_ptr = map_ptr;
7513 kptr_off = reg->off + reg->var_off.value;
7514 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7516 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7519 if (kptr_field->type != BPF_KPTR_REF) {
7520 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7523 meta->kptr_field = kptr_field;
7527 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7528 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7530 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7531 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7532 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7534 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7535 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7536 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7537 * mutate the view of the dynptr and also possibly destroy it. In the latter
7538 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7539 * memory that dynptr points to.
7541 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7542 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7543 * readonly dynptr view yet, hence only the first case is tracked and checked.
7545 * This is consistent with how C applies the const modifier to a struct object,
7546 * where the pointer itself inside bpf_dynptr becomes const but not what it
7549 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7550 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7552 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7553 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7555 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7558 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7559 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7561 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7562 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7566 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7567 * constructing a mutable bpf_dynptr object.
7569 * Currently, this is only possible with PTR_TO_STACK
7570 * pointing to a region of at least 16 bytes which doesn't
7571 * contain an existing bpf_dynptr.
7573 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7574 * mutated or destroyed. However, the memory it points to
7577 * None - Points to a initialized dynptr that can be mutated and
7578 * destroyed, including mutation of the memory it points
7581 if (arg_type & MEM_UNINIT) {
7584 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7585 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7589 /* we write BPF_DW bits (8 bytes) at a time */
7590 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7591 err = check_mem_access(env, insn_idx, regno,
7592 i, BPF_DW, BPF_WRITE, -1, false, false);
7597 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7598 } else /* MEM_RDONLY and None case from above */ {
7599 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7600 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7601 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7605 if (!is_dynptr_reg_valid_init(env, reg)) {
7607 "Expected an initialized dynptr as arg #%d\n",
7612 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7613 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7615 "Expected a dynptr of type %s as arg #%d\n",
7616 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7620 err = mark_dynptr_read(env, reg);
7625 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7627 struct bpf_func_state *state = func(env, reg);
7629 return state->stack[spi].spilled_ptr.ref_obj_id;
7632 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7634 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7637 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7639 return meta->kfunc_flags & KF_ITER_NEW;
7642 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7644 return meta->kfunc_flags & KF_ITER_NEXT;
7647 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7649 return meta->kfunc_flags & KF_ITER_DESTROY;
7652 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7654 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7655 * kfunc is iter state pointer
7657 return arg == 0 && is_iter_kfunc(meta);
7660 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7661 struct bpf_kfunc_call_arg_meta *meta)
7663 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7664 const struct btf_type *t;
7665 const struct btf_param *arg;
7666 int spi, err, i, nr_slots;
7669 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7670 arg = &btf_params(meta->func_proto)[0];
7671 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7672 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7673 nr_slots = t->size / BPF_REG_SIZE;
7675 if (is_iter_new_kfunc(meta)) {
7676 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7677 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7678 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7679 iter_type_str(meta->btf, btf_id), regno);
7683 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7684 err = check_mem_access(env, insn_idx, regno,
7685 i, BPF_DW, BPF_WRITE, -1, false, false);
7690 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7694 /* iter_next() or iter_destroy() expect initialized iter state*/
7695 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7696 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7697 iter_type_str(meta->btf, btf_id), regno);
7701 spi = iter_get_spi(env, reg, nr_slots);
7705 err = mark_iter_read(env, reg, spi, nr_slots);
7709 /* remember meta->iter info for process_iter_next_call() */
7710 meta->iter.spi = spi;
7711 meta->iter.frameno = reg->frameno;
7712 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7714 if (is_iter_destroy_kfunc(meta)) {
7715 err = unmark_stack_slots_iter(env, reg, nr_slots);
7724 /* Look for a previous loop entry at insn_idx: nearest parent state
7725 * stopped at insn_idx with callsites matching those in cur->frame.
7727 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7728 struct bpf_verifier_state *cur,
7731 struct bpf_verifier_state_list *sl;
7732 struct bpf_verifier_state *st;
7734 /* Explored states are pushed in stack order, most recent states come first */
7735 sl = *explored_state(env, insn_idx);
7736 for (; sl; sl = sl->next) {
7737 /* If st->branches != 0 state is a part of current DFS verification path,
7738 * hence cur & st for a loop.
7741 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7742 st->dfs_depth < cur->dfs_depth)
7749 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7750 static bool regs_exact(const struct bpf_reg_state *rold,
7751 const struct bpf_reg_state *rcur,
7752 struct bpf_idmap *idmap);
7754 static void maybe_widen_reg(struct bpf_verifier_env *env,
7755 struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7756 struct bpf_idmap *idmap)
7758 if (rold->type != SCALAR_VALUE)
7760 if (rold->type != rcur->type)
7762 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7764 __mark_reg_unknown(env, rcur);
7767 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7768 struct bpf_verifier_state *old,
7769 struct bpf_verifier_state *cur)
7771 struct bpf_func_state *fold, *fcur;
7774 reset_idmap_scratch(env);
7775 for (fr = old->curframe; fr >= 0; fr--) {
7776 fold = old->frame[fr];
7777 fcur = cur->frame[fr];
7779 for (i = 0; i < MAX_BPF_REG; i++)
7780 maybe_widen_reg(env,
7783 &env->idmap_scratch);
7785 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7786 if (!is_spilled_reg(&fold->stack[i]) ||
7787 !is_spilled_reg(&fcur->stack[i]))
7790 maybe_widen_reg(env,
7791 &fold->stack[i].spilled_ptr,
7792 &fcur->stack[i].spilled_ptr,
7793 &env->idmap_scratch);
7799 /* process_iter_next_call() is called when verifier gets to iterator's next
7800 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7801 * to it as just "iter_next()" in comments below.
7803 * BPF verifier relies on a crucial contract for any iter_next()
7804 * implementation: it should *eventually* return NULL, and once that happens
7805 * it should keep returning NULL. That is, once iterator exhausts elements to
7806 * iterate, it should never reset or spuriously return new elements.
7808 * With the assumption of such contract, process_iter_next_call() simulates
7809 * a fork in the verifier state to validate loop logic correctness and safety
7810 * without having to simulate infinite amount of iterations.
7812 * In current state, we first assume that iter_next() returned NULL and
7813 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7814 * conditions we should not form an infinite loop and should eventually reach
7817 * Besides that, we also fork current state and enqueue it for later
7818 * verification. In a forked state we keep iterator state as ACTIVE
7819 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7820 * also bump iteration depth to prevent erroneous infinite loop detection
7821 * later on (see iter_active_depths_differ() comment for details). In this
7822 * state we assume that we'll eventually loop back to another iter_next()
7823 * calls (it could be in exactly same location or in some other instruction,
7824 * it doesn't matter, we don't make any unnecessary assumptions about this,
7825 * everything revolves around iterator state in a stack slot, not which
7826 * instruction is calling iter_next()). When that happens, we either will come
7827 * to iter_next() with equivalent state and can conclude that next iteration
7828 * will proceed in exactly the same way as we just verified, so it's safe to
7829 * assume that loop converges. If not, we'll go on another iteration
7830 * simulation with a different input state, until all possible starting states
7831 * are validated or we reach maximum number of instructions limit.
7833 * This way, we will either exhaustively discover all possible input states
7834 * that iterator loop can start with and eventually will converge, or we'll
7835 * effectively regress into bounded loop simulation logic and either reach
7836 * maximum number of instructions if loop is not provably convergent, or there
7837 * is some statically known limit on number of iterations (e.g., if there is
7838 * an explicit `if n > 100 then break;` statement somewhere in the loop).
7840 * Iteration convergence logic in is_state_visited() relies on exact
7841 * states comparison, which ignores read and precision marks.
7842 * This is necessary because read and precision marks are not finalized
7843 * while in the loop. Exact comparison might preclude convergence for
7844 * simple programs like below:
7847 * while(iter_next(&it))
7850 * At each iteration step i++ would produce a new distinct state and
7851 * eventually instruction processing limit would be reached.
7853 * To avoid such behavior speculatively forget (widen) range for
7854 * imprecise scalar registers, if those registers were not precise at the
7855 * end of the previous iteration and do not match exactly.
7857 * This is a conservative heuristic that allows to verify wide range of programs,
7858 * however it precludes verification of programs that conjure an
7859 * imprecise value on the first loop iteration and use it as precise on a second.
7860 * For example, the following safe program would fail to verify:
7862 * struct bpf_num_iter it;
7865 * bpf_iter_num_new(&it, 0, 10);
7866 * while (bpf_iter_num_next(&it)) {
7869 * i = 7; // Because i changed verifier would forget
7870 * // it's range on second loop entry.
7872 * arr[i] = 42; // This would fail to verify.
7875 * bpf_iter_num_destroy(&it);
7877 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7878 struct bpf_kfunc_call_arg_meta *meta)
7880 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7881 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7882 struct bpf_reg_state *cur_iter, *queued_iter;
7883 int iter_frameno = meta->iter.frameno;
7884 int iter_spi = meta->iter.spi;
7886 BTF_TYPE_EMIT(struct bpf_iter);
7888 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7890 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7891 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7892 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7893 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7897 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7898 /* Because iter_next() call is a checkpoint is_state_visitied()
7899 * should guarantee parent state with same call sites and insn_idx.
7901 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7902 !same_callsites(cur_st->parent, cur_st)) {
7903 verbose(env, "bug: bad parent state for iter next call");
7906 /* Note cur_st->parent in the call below, it is necessary to skip
7907 * checkpoint created for cur_st by is_state_visited()
7908 * right at this instruction.
7910 prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7911 /* branch out active iter state */
7912 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7916 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7917 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7918 queued_iter->iter.depth++;
7920 widen_imprecise_scalars(env, prev_st, queued_st);
7922 queued_fr = queued_st->frame[queued_st->curframe];
7923 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7926 /* switch to DRAINED state, but keep the depth unchanged */
7927 /* mark current iter state as drained and assume returned NULL */
7928 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7929 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7934 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7936 return type == ARG_CONST_SIZE ||
7937 type == ARG_CONST_SIZE_OR_ZERO;
7940 static bool arg_type_is_release(enum bpf_arg_type type)
7942 return type & OBJ_RELEASE;
7945 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7947 return base_type(type) == ARG_PTR_TO_DYNPTR;
7950 static int int_ptr_type_to_size(enum bpf_arg_type type)
7952 if (type == ARG_PTR_TO_INT)
7954 else if (type == ARG_PTR_TO_LONG)
7960 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7961 const struct bpf_call_arg_meta *meta,
7962 enum bpf_arg_type *arg_type)
7964 if (!meta->map_ptr) {
7965 /* kernel subsystem misconfigured verifier */
7966 verbose(env, "invalid map_ptr to access map->type\n");
7970 switch (meta->map_ptr->map_type) {
7971 case BPF_MAP_TYPE_SOCKMAP:
7972 case BPF_MAP_TYPE_SOCKHASH:
7973 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7974 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7976 verbose(env, "invalid arg_type for sockmap/sockhash\n");
7980 case BPF_MAP_TYPE_BLOOM_FILTER:
7981 if (meta->func_id == BPF_FUNC_map_peek_elem)
7982 *arg_type = ARG_PTR_TO_MAP_VALUE;
7990 struct bpf_reg_types {
7991 const enum bpf_reg_type types[10];
7995 static const struct bpf_reg_types sock_types = {
8005 static const struct bpf_reg_types btf_id_sock_common_types = {
8012 PTR_TO_BTF_ID | PTR_TRUSTED,
8014 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8018 static const struct bpf_reg_types mem_types = {
8026 PTR_TO_MEM | MEM_RINGBUF,
8028 PTR_TO_BTF_ID | PTR_TRUSTED,
8032 static const struct bpf_reg_types int_ptr_types = {
8042 static const struct bpf_reg_types spin_lock_types = {
8045 PTR_TO_BTF_ID | MEM_ALLOC,
8049 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8050 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8051 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8052 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8053 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8054 static const struct bpf_reg_types btf_ptr_types = {
8057 PTR_TO_BTF_ID | PTR_TRUSTED,
8058 PTR_TO_BTF_ID | MEM_RCU,
8061 static const struct bpf_reg_types percpu_btf_ptr_types = {
8063 PTR_TO_BTF_ID | MEM_PERCPU,
8064 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8067 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8068 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8069 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8070 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8071 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8072 static const struct bpf_reg_types dynptr_types = {
8075 CONST_PTR_TO_DYNPTR,
8079 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8080 [ARG_PTR_TO_MAP_KEY] = &mem_types,
8081 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
8082 [ARG_CONST_SIZE] = &scalar_types,
8083 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
8084 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
8085 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
8086 [ARG_PTR_TO_CTX] = &context_types,
8087 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
8089 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
8091 [ARG_PTR_TO_SOCKET] = &fullsock_types,
8092 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
8093 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
8094 [ARG_PTR_TO_MEM] = &mem_types,
8095 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
8096 [ARG_PTR_TO_INT] = &int_ptr_types,
8097 [ARG_PTR_TO_LONG] = &int_ptr_types,
8098 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
8099 [ARG_PTR_TO_FUNC] = &func_ptr_types,
8100 [ARG_PTR_TO_STACK] = &stack_ptr_types,
8101 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
8102 [ARG_PTR_TO_TIMER] = &timer_types,
8103 [ARG_PTR_TO_KPTR] = &kptr_types,
8104 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
8107 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8108 enum bpf_arg_type arg_type,
8109 const u32 *arg_btf_id,
8110 struct bpf_call_arg_meta *meta)
8112 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8113 enum bpf_reg_type expected, type = reg->type;
8114 const struct bpf_reg_types *compatible;
8117 compatible = compatible_reg_types[base_type(arg_type)];
8119 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8123 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8124 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8126 * Same for MAYBE_NULL:
8128 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8129 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8131 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8133 * Therefore we fold these flags depending on the arg_type before comparison.
8135 if (arg_type & MEM_RDONLY)
8136 type &= ~MEM_RDONLY;
8137 if (arg_type & PTR_MAYBE_NULL)
8138 type &= ~PTR_MAYBE_NULL;
8139 if (base_type(arg_type) == ARG_PTR_TO_MEM)
8140 type &= ~DYNPTR_TYPE_FLAG_MASK;
8142 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
8145 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8146 expected = compatible->types[i];
8147 if (expected == NOT_INIT)
8150 if (type == expected)
8154 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8155 for (j = 0; j + 1 < i; j++)
8156 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8157 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8161 if (base_type(reg->type) != PTR_TO_BTF_ID)
8164 if (compatible == &mem_types) {
8165 if (!(arg_type & MEM_RDONLY)) {
8167 "%s() may write into memory pointed by R%d type=%s\n",
8168 func_id_name(meta->func_id),
8169 regno, reg_type_str(env, reg->type));
8175 switch ((int)reg->type) {
8177 case PTR_TO_BTF_ID | PTR_TRUSTED:
8178 case PTR_TO_BTF_ID | MEM_RCU:
8179 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8180 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8182 /* For bpf_sk_release, it needs to match against first member
8183 * 'struct sock_common', hence make an exception for it. This
8184 * allows bpf_sk_release to work for multiple socket types.
8186 bool strict_type_match = arg_type_is_release(arg_type) &&
8187 meta->func_id != BPF_FUNC_sk_release;
8189 if (type_may_be_null(reg->type) &&
8190 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8191 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8196 if (!compatible->btf_id) {
8197 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8200 arg_btf_id = compatible->btf_id;
8203 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8204 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8207 if (arg_btf_id == BPF_PTR_POISON) {
8208 verbose(env, "verifier internal error:");
8209 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8214 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8215 btf_vmlinux, *arg_btf_id,
8216 strict_type_match)) {
8217 verbose(env, "R%d is of type %s but %s is expected\n",
8218 regno, btf_type_name(reg->btf, reg->btf_id),
8219 btf_type_name(btf_vmlinux, *arg_btf_id));
8225 case PTR_TO_BTF_ID | MEM_ALLOC:
8226 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8227 meta->func_id != BPF_FUNC_kptr_xchg) {
8228 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8231 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8232 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8236 case PTR_TO_BTF_ID | MEM_PERCPU:
8237 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8238 /* Handled by helper specific checks */
8241 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8247 static struct btf_field *
8248 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8250 struct btf_field *field;
8251 struct btf_record *rec;
8253 rec = reg_btf_record(reg);
8257 field = btf_record_find(rec, off, fields);
8264 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8265 const struct bpf_reg_state *reg, int regno,
8266 enum bpf_arg_type arg_type)
8268 u32 type = reg->type;
8270 /* When referenced register is passed to release function, its fixed
8273 * We will check arg_type_is_release reg has ref_obj_id when storing
8274 * meta->release_regno.
8276 if (arg_type_is_release(arg_type)) {
8277 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8278 * may not directly point to the object being released, but to
8279 * dynptr pointing to such object, which might be at some offset
8280 * on the stack. In that case, we simply to fallback to the
8283 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8286 /* Doing check_ptr_off_reg check for the offset will catch this
8287 * because fixed_off_ok is false, but checking here allows us
8288 * to give the user a better error message.
8291 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8295 return __check_ptr_off_reg(env, reg, regno, false);
8299 /* Pointer types where both fixed and variable offset is explicitly allowed: */
8302 case PTR_TO_PACKET_META:
8303 case PTR_TO_MAP_KEY:
8304 case PTR_TO_MAP_VALUE:
8306 case PTR_TO_MEM | MEM_RDONLY:
8307 case PTR_TO_MEM | MEM_RINGBUF:
8309 case PTR_TO_BUF | MEM_RDONLY:
8312 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8316 case PTR_TO_BTF_ID | MEM_ALLOC:
8317 case PTR_TO_BTF_ID | PTR_TRUSTED:
8318 case PTR_TO_BTF_ID | MEM_RCU:
8319 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8320 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8321 /* When referenced PTR_TO_BTF_ID is passed to release function,
8322 * its fixed offset must be 0. In the other cases, fixed offset
8323 * can be non-zero. This was already checked above. So pass
8324 * fixed_off_ok as true to allow fixed offset for all other
8325 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8326 * still need to do checks instead of returning.
8328 return __check_ptr_off_reg(env, reg, regno, true);
8330 return __check_ptr_off_reg(env, reg, regno, false);
8334 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8335 const struct bpf_func_proto *fn,
8336 struct bpf_reg_state *regs)
8338 struct bpf_reg_state *state = NULL;
8341 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8342 if (arg_type_is_dynptr(fn->arg_type[i])) {
8344 verbose(env, "verifier internal error: multiple dynptr args\n");
8347 state = ®s[BPF_REG_1 + i];
8351 verbose(env, "verifier internal error: no dynptr arg found\n");
8356 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8358 struct bpf_func_state *state = func(env, reg);
8361 if (reg->type == CONST_PTR_TO_DYNPTR)
8363 spi = dynptr_get_spi(env, reg);
8366 return state->stack[spi].spilled_ptr.id;
8369 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8371 struct bpf_func_state *state = func(env, reg);
8374 if (reg->type == CONST_PTR_TO_DYNPTR)
8375 return reg->ref_obj_id;
8376 spi = dynptr_get_spi(env, reg);
8379 return state->stack[spi].spilled_ptr.ref_obj_id;
8382 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8383 struct bpf_reg_state *reg)
8385 struct bpf_func_state *state = func(env, reg);
8388 if (reg->type == CONST_PTR_TO_DYNPTR)
8389 return reg->dynptr.type;
8391 spi = __get_spi(reg->off);
8393 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8394 return BPF_DYNPTR_TYPE_INVALID;
8397 return state->stack[spi].spilled_ptr.dynptr.type;
8400 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8401 struct bpf_call_arg_meta *meta,
8402 const struct bpf_func_proto *fn,
8405 u32 regno = BPF_REG_1 + arg;
8406 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8407 enum bpf_arg_type arg_type = fn->arg_type[arg];
8408 enum bpf_reg_type type = reg->type;
8409 u32 *arg_btf_id = NULL;
8412 if (arg_type == ARG_DONTCARE)
8415 err = check_reg_arg(env, regno, SRC_OP);
8419 if (arg_type == ARG_ANYTHING) {
8420 if (is_pointer_value(env, regno)) {
8421 verbose(env, "R%d leaks addr into helper function\n",
8428 if (type_is_pkt_pointer(type) &&
8429 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8430 verbose(env, "helper access to the packet is not allowed\n");
8434 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8435 err = resolve_map_arg_type(env, meta, &arg_type);
8440 if (register_is_null(reg) && type_may_be_null(arg_type))
8441 /* A NULL register has a SCALAR_VALUE type, so skip
8444 goto skip_type_check;
8446 /* arg_btf_id and arg_size are in a union. */
8447 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8448 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8449 arg_btf_id = fn->arg_btf_id[arg];
8451 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8455 err = check_func_arg_reg_off(env, reg, regno, arg_type);
8460 if (arg_type_is_release(arg_type)) {
8461 if (arg_type_is_dynptr(arg_type)) {
8462 struct bpf_func_state *state = func(env, reg);
8465 /* Only dynptr created on stack can be released, thus
8466 * the get_spi and stack state checks for spilled_ptr
8467 * should only be done before process_dynptr_func for
8470 if (reg->type == PTR_TO_STACK) {
8471 spi = dynptr_get_spi(env, reg);
8472 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8473 verbose(env, "arg %d is an unacquired reference\n", regno);
8477 verbose(env, "cannot release unowned const bpf_dynptr\n");
8480 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8481 verbose(env, "R%d must be referenced when passed to release function\n",
8485 if (meta->release_regno) {
8486 verbose(env, "verifier internal error: more than one release argument\n");
8489 meta->release_regno = regno;
8492 if (reg->ref_obj_id) {
8493 if (meta->ref_obj_id) {
8494 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8495 regno, reg->ref_obj_id,
8499 meta->ref_obj_id = reg->ref_obj_id;
8502 switch (base_type(arg_type)) {
8503 case ARG_CONST_MAP_PTR:
8504 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8505 if (meta->map_ptr) {
8506 /* Use map_uid (which is unique id of inner map) to reject:
8507 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8508 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8509 * if (inner_map1 && inner_map2) {
8510 * timer = bpf_map_lookup_elem(inner_map1);
8512 * // mismatch would have been allowed
8513 * bpf_timer_init(timer, inner_map2);
8516 * Comparing map_ptr is enough to distinguish normal and outer maps.
8518 if (meta->map_ptr != reg->map_ptr ||
8519 meta->map_uid != reg->map_uid) {
8521 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8522 meta->map_uid, reg->map_uid);
8526 meta->map_ptr = reg->map_ptr;
8527 meta->map_uid = reg->map_uid;
8529 case ARG_PTR_TO_MAP_KEY:
8530 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8531 * check that [key, key + map->key_size) are within
8532 * stack limits and initialized
8534 if (!meta->map_ptr) {
8535 /* in function declaration map_ptr must come before
8536 * map_key, so that it's verified and known before
8537 * we have to check map_key here. Otherwise it means
8538 * that kernel subsystem misconfigured verifier
8540 verbose(env, "invalid map_ptr to access map->key\n");
8543 err = check_helper_mem_access(env, regno,
8544 meta->map_ptr->key_size, false,
8547 case ARG_PTR_TO_MAP_VALUE:
8548 if (type_may_be_null(arg_type) && register_is_null(reg))
8551 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8552 * check [value, value + map->value_size) validity
8554 if (!meta->map_ptr) {
8555 /* kernel subsystem misconfigured verifier */
8556 verbose(env, "invalid map_ptr to access map->value\n");
8559 meta->raw_mode = arg_type & MEM_UNINIT;
8560 err = check_helper_mem_access(env, regno,
8561 meta->map_ptr->value_size, false,
8564 case ARG_PTR_TO_PERCPU_BTF_ID:
8566 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8569 meta->ret_btf = reg->btf;
8570 meta->ret_btf_id = reg->btf_id;
8572 case ARG_PTR_TO_SPIN_LOCK:
8573 if (in_rbtree_lock_required_cb(env)) {
8574 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8577 if (meta->func_id == BPF_FUNC_spin_lock) {
8578 err = process_spin_lock(env, regno, true);
8581 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8582 err = process_spin_lock(env, regno, false);
8586 verbose(env, "verifier internal error\n");
8590 case ARG_PTR_TO_TIMER:
8591 err = process_timer_func(env, regno, meta);
8595 case ARG_PTR_TO_FUNC:
8596 meta->subprogno = reg->subprogno;
8598 case ARG_PTR_TO_MEM:
8599 /* The access to this pointer is only checked when we hit the
8600 * next is_mem_size argument below.
8602 meta->raw_mode = arg_type & MEM_UNINIT;
8603 if (arg_type & MEM_FIXED_SIZE) {
8604 err = check_helper_mem_access(env, regno,
8605 fn->arg_size[arg], false,
8609 case ARG_CONST_SIZE:
8610 err = check_mem_size_reg(env, reg, regno, false, meta);
8612 case ARG_CONST_SIZE_OR_ZERO:
8613 err = check_mem_size_reg(env, reg, regno, true, meta);
8615 case ARG_PTR_TO_DYNPTR:
8616 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8620 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8621 if (!tnum_is_const(reg->var_off)) {
8622 verbose(env, "R%d is not a known constant'\n",
8626 meta->mem_size = reg->var_off.value;
8627 err = mark_chain_precision(env, regno);
8631 case ARG_PTR_TO_INT:
8632 case ARG_PTR_TO_LONG:
8634 int size = int_ptr_type_to_size(arg_type);
8636 err = check_helper_mem_access(env, regno, size, false, meta);
8639 err = check_ptr_alignment(env, reg, 0, size, true);
8642 case ARG_PTR_TO_CONST_STR:
8644 struct bpf_map *map = reg->map_ptr;
8649 if (!bpf_map_is_rdonly(map)) {
8650 verbose(env, "R%d does not point to a readonly map'\n", regno);
8654 if (!tnum_is_const(reg->var_off)) {
8655 verbose(env, "R%d is not a constant address'\n", regno);
8659 if (!map->ops->map_direct_value_addr) {
8660 verbose(env, "no direct value access support for this map type\n");
8664 err = check_map_access(env, regno, reg->off,
8665 map->value_size - reg->off, false,
8670 map_off = reg->off + reg->var_off.value;
8671 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8673 verbose(env, "direct value access on string failed\n");
8677 str_ptr = (char *)(long)(map_addr);
8678 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8679 verbose(env, "string is not zero-terminated\n");
8684 case ARG_PTR_TO_KPTR:
8685 err = process_kptr_func(env, regno, meta);
8694 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8696 enum bpf_attach_type eatype = env->prog->expected_attach_type;
8697 enum bpf_prog_type type = resolve_prog_type(env->prog);
8699 if (func_id != BPF_FUNC_map_update_elem)
8702 /* It's not possible to get access to a locked struct sock in these
8703 * contexts, so updating is safe.
8706 case BPF_PROG_TYPE_TRACING:
8707 if (eatype == BPF_TRACE_ITER)
8710 case BPF_PROG_TYPE_SOCKET_FILTER:
8711 case BPF_PROG_TYPE_SCHED_CLS:
8712 case BPF_PROG_TYPE_SCHED_ACT:
8713 case BPF_PROG_TYPE_XDP:
8714 case BPF_PROG_TYPE_SK_REUSEPORT:
8715 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8716 case BPF_PROG_TYPE_SK_LOOKUP:
8722 verbose(env, "cannot update sockmap in this context\n");
8726 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8728 return env->prog->jit_requested &&
8729 bpf_jit_supports_subprog_tailcalls();
8732 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8733 struct bpf_map *map, int func_id)
8738 /* We need a two way check, first is from map perspective ... */
8739 switch (map->map_type) {
8740 case BPF_MAP_TYPE_PROG_ARRAY:
8741 if (func_id != BPF_FUNC_tail_call)
8744 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8745 if (func_id != BPF_FUNC_perf_event_read &&
8746 func_id != BPF_FUNC_perf_event_output &&
8747 func_id != BPF_FUNC_skb_output &&
8748 func_id != BPF_FUNC_perf_event_read_value &&
8749 func_id != BPF_FUNC_xdp_output)
8752 case BPF_MAP_TYPE_RINGBUF:
8753 if (func_id != BPF_FUNC_ringbuf_output &&
8754 func_id != BPF_FUNC_ringbuf_reserve &&
8755 func_id != BPF_FUNC_ringbuf_query &&
8756 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8757 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8758 func_id != BPF_FUNC_ringbuf_discard_dynptr)
8761 case BPF_MAP_TYPE_USER_RINGBUF:
8762 if (func_id != BPF_FUNC_user_ringbuf_drain)
8765 case BPF_MAP_TYPE_STACK_TRACE:
8766 if (func_id != BPF_FUNC_get_stackid)
8769 case BPF_MAP_TYPE_CGROUP_ARRAY:
8770 if (func_id != BPF_FUNC_skb_under_cgroup &&
8771 func_id != BPF_FUNC_current_task_under_cgroup)
8774 case BPF_MAP_TYPE_CGROUP_STORAGE:
8775 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8776 if (func_id != BPF_FUNC_get_local_storage)
8779 case BPF_MAP_TYPE_DEVMAP:
8780 case BPF_MAP_TYPE_DEVMAP_HASH:
8781 if (func_id != BPF_FUNC_redirect_map &&
8782 func_id != BPF_FUNC_map_lookup_elem)
8785 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8788 case BPF_MAP_TYPE_CPUMAP:
8789 if (func_id != BPF_FUNC_redirect_map)
8792 case BPF_MAP_TYPE_XSKMAP:
8793 if (func_id != BPF_FUNC_redirect_map &&
8794 func_id != BPF_FUNC_map_lookup_elem)
8797 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8798 case BPF_MAP_TYPE_HASH_OF_MAPS:
8799 if (func_id != BPF_FUNC_map_lookup_elem)
8802 case BPF_MAP_TYPE_SOCKMAP:
8803 if (func_id != BPF_FUNC_sk_redirect_map &&
8804 func_id != BPF_FUNC_sock_map_update &&
8805 func_id != BPF_FUNC_map_delete_elem &&
8806 func_id != BPF_FUNC_msg_redirect_map &&
8807 func_id != BPF_FUNC_sk_select_reuseport &&
8808 func_id != BPF_FUNC_map_lookup_elem &&
8809 !may_update_sockmap(env, func_id))
8812 case BPF_MAP_TYPE_SOCKHASH:
8813 if (func_id != BPF_FUNC_sk_redirect_hash &&
8814 func_id != BPF_FUNC_sock_hash_update &&
8815 func_id != BPF_FUNC_map_delete_elem &&
8816 func_id != BPF_FUNC_msg_redirect_hash &&
8817 func_id != BPF_FUNC_sk_select_reuseport &&
8818 func_id != BPF_FUNC_map_lookup_elem &&
8819 !may_update_sockmap(env, func_id))
8822 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8823 if (func_id != BPF_FUNC_sk_select_reuseport)
8826 case BPF_MAP_TYPE_QUEUE:
8827 case BPF_MAP_TYPE_STACK:
8828 if (func_id != BPF_FUNC_map_peek_elem &&
8829 func_id != BPF_FUNC_map_pop_elem &&
8830 func_id != BPF_FUNC_map_push_elem)
8833 case BPF_MAP_TYPE_SK_STORAGE:
8834 if (func_id != BPF_FUNC_sk_storage_get &&
8835 func_id != BPF_FUNC_sk_storage_delete &&
8836 func_id != BPF_FUNC_kptr_xchg)
8839 case BPF_MAP_TYPE_INODE_STORAGE:
8840 if (func_id != BPF_FUNC_inode_storage_get &&
8841 func_id != BPF_FUNC_inode_storage_delete &&
8842 func_id != BPF_FUNC_kptr_xchg)
8845 case BPF_MAP_TYPE_TASK_STORAGE:
8846 if (func_id != BPF_FUNC_task_storage_get &&
8847 func_id != BPF_FUNC_task_storage_delete &&
8848 func_id != BPF_FUNC_kptr_xchg)
8851 case BPF_MAP_TYPE_CGRP_STORAGE:
8852 if (func_id != BPF_FUNC_cgrp_storage_get &&
8853 func_id != BPF_FUNC_cgrp_storage_delete &&
8854 func_id != BPF_FUNC_kptr_xchg)
8857 case BPF_MAP_TYPE_BLOOM_FILTER:
8858 if (func_id != BPF_FUNC_map_peek_elem &&
8859 func_id != BPF_FUNC_map_push_elem)
8866 /* ... and second from the function itself. */
8868 case BPF_FUNC_tail_call:
8869 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8871 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8872 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8876 case BPF_FUNC_perf_event_read:
8877 case BPF_FUNC_perf_event_output:
8878 case BPF_FUNC_perf_event_read_value:
8879 case BPF_FUNC_skb_output:
8880 case BPF_FUNC_xdp_output:
8881 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8884 case BPF_FUNC_ringbuf_output:
8885 case BPF_FUNC_ringbuf_reserve:
8886 case BPF_FUNC_ringbuf_query:
8887 case BPF_FUNC_ringbuf_reserve_dynptr:
8888 case BPF_FUNC_ringbuf_submit_dynptr:
8889 case BPF_FUNC_ringbuf_discard_dynptr:
8890 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8893 case BPF_FUNC_user_ringbuf_drain:
8894 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8897 case BPF_FUNC_get_stackid:
8898 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8901 case BPF_FUNC_current_task_under_cgroup:
8902 case BPF_FUNC_skb_under_cgroup:
8903 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8906 case BPF_FUNC_redirect_map:
8907 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8908 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8909 map->map_type != BPF_MAP_TYPE_CPUMAP &&
8910 map->map_type != BPF_MAP_TYPE_XSKMAP)
8913 case BPF_FUNC_sk_redirect_map:
8914 case BPF_FUNC_msg_redirect_map:
8915 case BPF_FUNC_sock_map_update:
8916 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8919 case BPF_FUNC_sk_redirect_hash:
8920 case BPF_FUNC_msg_redirect_hash:
8921 case BPF_FUNC_sock_hash_update:
8922 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8925 case BPF_FUNC_get_local_storage:
8926 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8927 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8930 case BPF_FUNC_sk_select_reuseport:
8931 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8932 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8933 map->map_type != BPF_MAP_TYPE_SOCKHASH)
8936 case BPF_FUNC_map_pop_elem:
8937 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8938 map->map_type != BPF_MAP_TYPE_STACK)
8941 case BPF_FUNC_map_peek_elem:
8942 case BPF_FUNC_map_push_elem:
8943 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8944 map->map_type != BPF_MAP_TYPE_STACK &&
8945 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8948 case BPF_FUNC_map_lookup_percpu_elem:
8949 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8950 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8951 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8954 case BPF_FUNC_sk_storage_get:
8955 case BPF_FUNC_sk_storage_delete:
8956 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8959 case BPF_FUNC_inode_storage_get:
8960 case BPF_FUNC_inode_storage_delete:
8961 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8964 case BPF_FUNC_task_storage_get:
8965 case BPF_FUNC_task_storage_delete:
8966 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8969 case BPF_FUNC_cgrp_storage_get:
8970 case BPF_FUNC_cgrp_storage_delete:
8971 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8980 verbose(env, "cannot pass map_type %d into func %s#%d\n",
8981 map->map_type, func_id_name(func_id), func_id);
8985 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8989 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8991 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8993 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8995 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8997 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9000 /* We only support one arg being in raw mode at the moment,
9001 * which is sufficient for the helper functions we have
9007 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9009 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9010 bool has_size = fn->arg_size[arg] != 0;
9011 bool is_next_size = false;
9013 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9014 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9016 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9017 return is_next_size;
9019 return has_size == is_next_size || is_next_size == is_fixed;
9022 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9024 /* bpf_xxx(..., buf, len) call will access 'len'
9025 * bytes from memory 'buf'. Both arg types need
9026 * to be paired, so make sure there's no buggy
9027 * helper function specification.
9029 if (arg_type_is_mem_size(fn->arg1_type) ||
9030 check_args_pair_invalid(fn, 0) ||
9031 check_args_pair_invalid(fn, 1) ||
9032 check_args_pair_invalid(fn, 2) ||
9033 check_args_pair_invalid(fn, 3) ||
9034 check_args_pair_invalid(fn, 4))
9040 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9044 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9045 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9046 return !!fn->arg_btf_id[i];
9047 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9048 return fn->arg_btf_id[i] == BPF_PTR_POISON;
9049 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9050 /* arg_btf_id and arg_size are in a union. */
9051 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9052 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9059 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9061 return check_raw_mode_ok(fn) &&
9062 check_arg_pair_ok(fn) &&
9063 check_btf_id_ok(fn) ? 0 : -EINVAL;
9066 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9067 * are now invalid, so turn them into unknown SCALAR_VALUE.
9069 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9070 * since these slices point to packet data.
9072 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9074 struct bpf_func_state *state;
9075 struct bpf_reg_state *reg;
9077 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9078 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9079 mark_reg_invalid(env, reg);
9085 BEYOND_PKT_END = -2,
9088 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9090 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9091 struct bpf_reg_state *reg = &state->regs[regn];
9093 if (reg->type != PTR_TO_PACKET)
9094 /* PTR_TO_PACKET_META is not supported yet */
9097 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9098 * How far beyond pkt_end it goes is unknown.
9099 * if (!range_open) it's the case of pkt >= pkt_end
9100 * if (range_open) it's the case of pkt > pkt_end
9101 * hence this pointer is at least 1 byte bigger than pkt_end
9104 reg->range = BEYOND_PKT_END;
9106 reg->range = AT_PKT_END;
9109 /* The pointer with the specified id has released its reference to kernel
9110 * resources. Identify all copies of the same pointer and clear the reference.
9112 static int release_reference(struct bpf_verifier_env *env,
9115 struct bpf_func_state *state;
9116 struct bpf_reg_state *reg;
9119 err = release_reference_state(cur_func(env), ref_obj_id);
9123 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9124 if (reg->ref_obj_id == ref_obj_id)
9125 mark_reg_invalid(env, reg);
9131 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9133 struct bpf_func_state *unused;
9134 struct bpf_reg_state *reg;
9136 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9137 if (type_is_non_owning_ref(reg->type))
9138 mark_reg_invalid(env, reg);
9142 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9143 struct bpf_reg_state *regs)
9147 /* after the call registers r0 - r5 were scratched */
9148 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9149 mark_reg_not_init(env, regs, caller_saved[i]);
9150 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9154 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9155 struct bpf_func_state *caller,
9156 struct bpf_func_state *callee,
9159 static int set_callee_state(struct bpf_verifier_env *env,
9160 struct bpf_func_state *caller,
9161 struct bpf_func_state *callee, int insn_idx);
9163 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9164 int *insn_idx, int subprog,
9165 set_callee_state_fn set_callee_state_cb)
9167 struct bpf_verifier_state *state = env->cur_state;
9168 struct bpf_func_state *caller, *callee;
9171 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9172 verbose(env, "the call stack of %d frames is too deep\n",
9173 state->curframe + 2);
9177 caller = state->frame[state->curframe];
9178 if (state->frame[state->curframe + 1]) {
9179 verbose(env, "verifier bug. Frame %d already allocated\n",
9180 state->curframe + 1);
9184 err = btf_check_subprog_call(env, subprog, caller->regs);
9187 if (subprog_is_global(env, subprog)) {
9189 verbose(env, "Caller passes invalid args into func#%d\n",
9193 if (env->log.level & BPF_LOG_LEVEL)
9195 "Func#%d is global and valid. Skipping.\n",
9197 clear_caller_saved_regs(env, caller->regs);
9199 /* All global functions return a 64-bit SCALAR_VALUE */
9200 mark_reg_unknown(env, caller->regs, BPF_REG_0);
9201 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9203 /* continue with next insn after call */
9208 /* set_callee_state is used for direct subprog calls, but we are
9209 * interested in validating only BPF helpers that can call subprogs as
9212 if (set_callee_state_cb != set_callee_state) {
9213 if (bpf_pseudo_kfunc_call(insn) &&
9214 !is_callback_calling_kfunc(insn->imm)) {
9215 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9216 func_id_name(insn->imm), insn->imm);
9218 } else if (!bpf_pseudo_kfunc_call(insn) &&
9219 !is_callback_calling_function(insn->imm)) { /* helper */
9220 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9221 func_id_name(insn->imm), insn->imm);
9226 if (insn->code == (BPF_JMP | BPF_CALL) &&
9227 insn->src_reg == 0 &&
9228 insn->imm == BPF_FUNC_timer_set_callback) {
9229 struct bpf_verifier_state *async_cb;
9231 /* there is no real recursion here. timer callbacks are async */
9232 env->subprog_info[subprog].is_async_cb = true;
9233 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9234 *insn_idx, subprog);
9237 callee = async_cb->frame[0];
9238 callee->async_entry_cnt = caller->async_entry_cnt + 1;
9240 /* Convert bpf_timer_set_callback() args into timer callback args */
9241 err = set_callee_state_cb(env, caller, callee, *insn_idx);
9245 clear_caller_saved_regs(env, caller->regs);
9246 mark_reg_unknown(env, caller->regs, BPF_REG_0);
9247 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9248 /* continue with next insn after call */
9252 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9255 state->frame[state->curframe + 1] = callee;
9257 /* callee cannot access r0, r6 - r9 for reading and has to write
9258 * into its own stack before reading from it.
9259 * callee can read/write into caller's stack
9261 init_func_state(env, callee,
9262 /* remember the callsite, it will be used by bpf_exit */
9263 *insn_idx /* callsite */,
9264 state->curframe + 1 /* frameno within this callchain */,
9265 subprog /* subprog number within this prog */);
9267 /* Transfer references to the callee */
9268 err = copy_reference_state(callee, caller);
9272 err = set_callee_state_cb(env, caller, callee, *insn_idx);
9276 clear_caller_saved_regs(env, caller->regs);
9278 /* only increment it after check_reg_arg() finished */
9281 /* and go analyze first insn of the callee */
9282 *insn_idx = env->subprog_info[subprog].start - 1;
9284 if (env->log.level & BPF_LOG_LEVEL) {
9285 verbose(env, "caller:\n");
9286 print_verifier_state(env, caller, true);
9287 verbose(env, "callee:\n");
9288 print_verifier_state(env, callee, true);
9293 free_func_state(callee);
9294 state->frame[state->curframe + 1] = NULL;
9298 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9299 struct bpf_func_state *caller,
9300 struct bpf_func_state *callee)
9302 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9303 * void *callback_ctx, u64 flags);
9304 * callback_fn(struct bpf_map *map, void *key, void *value,
9305 * void *callback_ctx);
9307 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9309 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9310 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9311 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9313 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9314 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9315 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9317 /* pointer to stack or null */
9318 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9321 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9325 static int set_callee_state(struct bpf_verifier_env *env,
9326 struct bpf_func_state *caller,
9327 struct bpf_func_state *callee, int insn_idx)
9331 /* copy r1 - r5 args that callee can access. The copy includes parent
9332 * pointers, which connects us up to the liveness chain
9334 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9335 callee->regs[i] = caller->regs[i];
9339 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9342 int subprog, target_insn;
9344 target_insn = *insn_idx + insn->imm + 1;
9345 subprog = find_subprog(env, target_insn);
9347 verbose(env, "verifier bug. No program starts at insn %d\n",
9352 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
9355 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9356 struct bpf_func_state *caller,
9357 struct bpf_func_state *callee,
9360 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9361 struct bpf_map *map;
9364 if (bpf_map_ptr_poisoned(insn_aux)) {
9365 verbose(env, "tail_call abusing map_ptr\n");
9369 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9370 if (!map->ops->map_set_for_each_callback_args ||
9371 !map->ops->map_for_each_callback) {
9372 verbose(env, "callback function not allowed for map\n");
9376 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9380 callee->in_callback_fn = true;
9381 callee->callback_ret_range = tnum_range(0, 1);
9385 static int set_loop_callback_state(struct bpf_verifier_env *env,
9386 struct bpf_func_state *caller,
9387 struct bpf_func_state *callee,
9390 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9392 * callback_fn(u32 index, void *callback_ctx);
9394 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9395 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9398 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9399 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9400 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9402 callee->in_callback_fn = true;
9403 callee->callback_ret_range = tnum_range(0, 1);
9407 static int set_timer_callback_state(struct bpf_verifier_env *env,
9408 struct bpf_func_state *caller,
9409 struct bpf_func_state *callee,
9412 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9414 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9415 * callback_fn(struct bpf_map *map, void *key, void *value);
9417 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9418 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9419 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9421 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9422 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9423 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9425 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9426 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9427 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9430 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9431 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9432 callee->in_async_callback_fn = true;
9433 callee->callback_ret_range = tnum_range(0, 1);
9437 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9438 struct bpf_func_state *caller,
9439 struct bpf_func_state *callee,
9442 /* bpf_find_vma(struct task_struct *task, u64 addr,
9443 * void *callback_fn, void *callback_ctx, u64 flags)
9444 * (callback_fn)(struct task_struct *task,
9445 * struct vm_area_struct *vma, void *callback_ctx);
9447 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9449 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9450 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9451 callee->regs[BPF_REG_2].btf = btf_vmlinux;
9452 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9454 /* pointer to stack or null */
9455 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9458 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9459 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9460 callee->in_callback_fn = true;
9461 callee->callback_ret_range = tnum_range(0, 1);
9465 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9466 struct bpf_func_state *caller,
9467 struct bpf_func_state *callee,
9470 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9471 * callback_ctx, u64 flags);
9472 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9474 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9475 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9476 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9479 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9480 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9481 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9483 callee->in_callback_fn = true;
9484 callee->callback_ret_range = tnum_range(0, 1);
9488 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9489 struct bpf_func_state *caller,
9490 struct bpf_func_state *callee,
9493 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9494 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9496 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9497 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9498 * by this point, so look at 'root'
9500 struct btf_field *field;
9502 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9504 if (!field || !field->graph_root.value_btf_id)
9507 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9508 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9509 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9510 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9512 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9513 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9514 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9515 callee->in_callback_fn = true;
9516 callee->callback_ret_range = tnum_range(0, 1);
9520 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9522 /* Are we currently verifying the callback for a rbtree helper that must
9523 * be called with lock held? If so, no need to complain about unreleased
9526 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9528 struct bpf_verifier_state *state = env->cur_state;
9529 struct bpf_insn *insn = env->prog->insnsi;
9530 struct bpf_func_state *callee;
9533 if (!state->curframe)
9536 callee = state->frame[state->curframe];
9538 if (!callee->in_callback_fn)
9541 kfunc_btf_id = insn[callee->callsite].imm;
9542 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9545 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9547 struct bpf_verifier_state *state = env->cur_state;
9548 struct bpf_func_state *caller, *callee;
9549 struct bpf_reg_state *r0;
9552 callee = state->frame[state->curframe];
9553 r0 = &callee->regs[BPF_REG_0];
9554 if (r0->type == PTR_TO_STACK) {
9555 /* technically it's ok to return caller's stack pointer
9556 * (or caller's caller's pointer) back to the caller,
9557 * since these pointers are valid. Only current stack
9558 * pointer will be invalid as soon as function exits,
9559 * but let's be conservative
9561 verbose(env, "cannot return stack pointer to the caller\n");
9565 caller = state->frame[state->curframe - 1];
9566 if (callee->in_callback_fn) {
9567 /* enforce R0 return value range [0, 1]. */
9568 struct tnum range = callee->callback_ret_range;
9570 if (r0->type != SCALAR_VALUE) {
9571 verbose(env, "R0 not a scalar value\n");
9575 /* we are going to rely on register's precise value */
9576 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9577 err = err ?: mark_chain_precision(env, BPF_REG_0);
9581 if (!tnum_in(range, r0->var_off)) {
9582 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9586 /* return to the caller whatever r0 had in the callee */
9587 caller->regs[BPF_REG_0] = *r0;
9590 /* callback_fn frame should have released its own additions to parent's
9591 * reference state at this point, or check_reference_leak would
9592 * complain, hence it must be the same as the caller. There is no need
9595 if (!callee->in_callback_fn) {
9596 /* Transfer references to the caller */
9597 err = copy_reference_state(caller, callee);
9602 *insn_idx = callee->callsite + 1;
9603 if (env->log.level & BPF_LOG_LEVEL) {
9604 verbose(env, "returning from callee:\n");
9605 print_verifier_state(env, callee, true);
9606 verbose(env, "to caller at %d:\n", *insn_idx);
9607 print_verifier_state(env, caller, true);
9609 /* clear everything in the callee */
9610 free_func_state(callee);
9611 state->frame[state->curframe--] = NULL;
9615 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9617 struct bpf_call_arg_meta *meta)
9619 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
9621 if (ret_type != RET_INTEGER)
9625 case BPF_FUNC_get_stack:
9626 case BPF_FUNC_get_task_stack:
9627 case BPF_FUNC_probe_read_str:
9628 case BPF_FUNC_probe_read_kernel_str:
9629 case BPF_FUNC_probe_read_user_str:
9630 ret_reg->smax_value = meta->msize_max_value;
9631 ret_reg->s32_max_value = meta->msize_max_value;
9632 ret_reg->smin_value = -MAX_ERRNO;
9633 ret_reg->s32_min_value = -MAX_ERRNO;
9634 reg_bounds_sync(ret_reg);
9636 case BPF_FUNC_get_smp_processor_id:
9637 ret_reg->umax_value = nr_cpu_ids - 1;
9638 ret_reg->u32_max_value = nr_cpu_ids - 1;
9639 ret_reg->smax_value = nr_cpu_ids - 1;
9640 ret_reg->s32_max_value = nr_cpu_ids - 1;
9641 ret_reg->umin_value = 0;
9642 ret_reg->u32_min_value = 0;
9643 ret_reg->smin_value = 0;
9644 ret_reg->s32_min_value = 0;
9645 reg_bounds_sync(ret_reg);
9651 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9652 int func_id, int insn_idx)
9654 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9655 struct bpf_map *map = meta->map_ptr;
9657 if (func_id != BPF_FUNC_tail_call &&
9658 func_id != BPF_FUNC_map_lookup_elem &&
9659 func_id != BPF_FUNC_map_update_elem &&
9660 func_id != BPF_FUNC_map_delete_elem &&
9661 func_id != BPF_FUNC_map_push_elem &&
9662 func_id != BPF_FUNC_map_pop_elem &&
9663 func_id != BPF_FUNC_map_peek_elem &&
9664 func_id != BPF_FUNC_for_each_map_elem &&
9665 func_id != BPF_FUNC_redirect_map &&
9666 func_id != BPF_FUNC_map_lookup_percpu_elem)
9670 verbose(env, "kernel subsystem misconfigured verifier\n");
9674 /* In case of read-only, some additional restrictions
9675 * need to be applied in order to prevent altering the
9676 * state of the map from program side.
9678 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9679 (func_id == BPF_FUNC_map_delete_elem ||
9680 func_id == BPF_FUNC_map_update_elem ||
9681 func_id == BPF_FUNC_map_push_elem ||
9682 func_id == BPF_FUNC_map_pop_elem)) {
9683 verbose(env, "write into map forbidden\n");
9687 if (!BPF_MAP_PTR(aux->map_ptr_state))
9688 bpf_map_ptr_store(aux, meta->map_ptr,
9689 !meta->map_ptr->bypass_spec_v1);
9690 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9691 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9692 !meta->map_ptr->bypass_spec_v1);
9697 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9698 int func_id, int insn_idx)
9700 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9701 struct bpf_reg_state *regs = cur_regs(env), *reg;
9702 struct bpf_map *map = meta->map_ptr;
9706 if (func_id != BPF_FUNC_tail_call)
9708 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9709 verbose(env, "kernel subsystem misconfigured verifier\n");
9713 reg = ®s[BPF_REG_3];
9714 val = reg->var_off.value;
9715 max = map->max_entries;
9717 if (!(register_is_const(reg) && val < max)) {
9718 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9722 err = mark_chain_precision(env, BPF_REG_3);
9725 if (bpf_map_key_unseen(aux))
9726 bpf_map_key_store(aux, val);
9727 else if (!bpf_map_key_poisoned(aux) &&
9728 bpf_map_key_immediate(aux) != val)
9729 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9733 static int check_reference_leak(struct bpf_verifier_env *env)
9735 struct bpf_func_state *state = cur_func(env);
9736 bool refs_lingering = false;
9739 if (state->frameno && !state->in_callback_fn)
9742 for (i = 0; i < state->acquired_refs; i++) {
9743 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9745 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9746 state->refs[i].id, state->refs[i].insn_idx);
9747 refs_lingering = true;
9749 return refs_lingering ? -EINVAL : 0;
9752 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9753 struct bpf_reg_state *regs)
9755 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
9756 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
9757 struct bpf_map *fmt_map = fmt_reg->map_ptr;
9758 struct bpf_bprintf_data data = {};
9759 int err, fmt_map_off, num_args;
9763 /* data must be an array of u64 */
9764 if (data_len_reg->var_off.value % 8)
9766 num_args = data_len_reg->var_off.value / 8;
9768 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9769 * and map_direct_value_addr is set.
9771 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9772 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9775 verbose(env, "verifier bug\n");
9778 fmt = (char *)(long)fmt_addr + fmt_map_off;
9780 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9781 * can focus on validating the format specifiers.
9783 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9785 verbose(env, "Invalid format string\n");
9790 static int check_get_func_ip(struct bpf_verifier_env *env)
9792 enum bpf_prog_type type = resolve_prog_type(env->prog);
9793 int func_id = BPF_FUNC_get_func_ip;
9795 if (type == BPF_PROG_TYPE_TRACING) {
9796 if (!bpf_prog_has_trampoline(env->prog)) {
9797 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9798 func_id_name(func_id), func_id);
9802 } else if (type == BPF_PROG_TYPE_KPROBE) {
9806 verbose(env, "func %s#%d not supported for program type %d\n",
9807 func_id_name(func_id), func_id, type);
9811 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9813 return &env->insn_aux_data[env->insn_idx];
9816 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9818 struct bpf_reg_state *regs = cur_regs(env);
9819 struct bpf_reg_state *reg = ®s[BPF_REG_4];
9820 bool reg_is_null = register_is_null(reg);
9823 mark_chain_precision(env, BPF_REG_4);
9828 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9830 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9832 if (!state->initialized) {
9833 state->initialized = 1;
9834 state->fit_for_inline = loop_flag_is_zero(env);
9835 state->callback_subprogno = subprogno;
9839 if (!state->fit_for_inline)
9842 state->fit_for_inline = (loop_flag_is_zero(env) &&
9843 state->callback_subprogno == subprogno);
9846 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9849 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9850 const struct bpf_func_proto *fn = NULL;
9851 enum bpf_return_type ret_type;
9852 enum bpf_type_flag ret_flag;
9853 struct bpf_reg_state *regs;
9854 struct bpf_call_arg_meta meta;
9855 int insn_idx = *insn_idx_p;
9857 int i, err, func_id;
9859 /* find function prototype */
9860 func_id = insn->imm;
9861 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9862 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9867 if (env->ops->get_func_proto)
9868 fn = env->ops->get_func_proto(func_id, env->prog);
9870 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9875 /* eBPF programs must be GPL compatible to use GPL-ed functions */
9876 if (!env->prog->gpl_compatible && fn->gpl_only) {
9877 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9881 if (fn->allowed && !fn->allowed(env->prog)) {
9882 verbose(env, "helper call is not allowed in probe\n");
9886 if (!env->prog->aux->sleepable && fn->might_sleep) {
9887 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9891 /* With LD_ABS/IND some JITs save/restore skb from r1. */
9892 changes_data = bpf_helper_changes_pkt_data(fn->func);
9893 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9894 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9895 func_id_name(func_id), func_id);
9899 memset(&meta, 0, sizeof(meta));
9900 meta.pkt_access = fn->pkt_access;
9902 err = check_func_proto(fn, func_id);
9904 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9905 func_id_name(func_id), func_id);
9909 if (env->cur_state->active_rcu_lock) {
9910 if (fn->might_sleep) {
9911 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9912 func_id_name(func_id), func_id);
9916 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9917 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9920 meta.func_id = func_id;
9922 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9923 err = check_func_arg(env, i, &meta, fn, insn_idx);
9928 err = record_func_map(env, &meta, func_id, insn_idx);
9932 err = record_func_key(env, &meta, func_id, insn_idx);
9936 /* Mark slots with STACK_MISC in case of raw mode, stack offset
9937 * is inferred from register state.
9939 for (i = 0; i < meta.access_size; i++) {
9940 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9941 BPF_WRITE, -1, false, false);
9946 regs = cur_regs(env);
9948 if (meta.release_regno) {
9950 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9951 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9952 * is safe to do directly.
9954 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9955 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9956 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9959 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
9960 } else if (meta.ref_obj_id) {
9961 err = release_reference(env, meta.ref_obj_id);
9962 } else if (register_is_null(®s[meta.release_regno])) {
9963 /* meta.ref_obj_id can only be 0 if register that is meant to be
9964 * released is NULL, which must be > R0.
9969 verbose(env, "func %s#%d reference has not been acquired before\n",
9970 func_id_name(func_id), func_id);
9976 case BPF_FUNC_tail_call:
9977 err = check_reference_leak(env);
9979 verbose(env, "tail_call would lead to reference leak\n");
9983 case BPF_FUNC_get_local_storage:
9984 /* check that flags argument in get_local_storage(map, flags) is 0,
9985 * this is required because get_local_storage() can't return an error.
9987 if (!register_is_null(®s[BPF_REG_2])) {
9988 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9992 case BPF_FUNC_for_each_map_elem:
9993 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9994 set_map_elem_callback_state);
9996 case BPF_FUNC_timer_set_callback:
9997 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9998 set_timer_callback_state);
10000 case BPF_FUNC_find_vma:
10001 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10002 set_find_vma_callback_state);
10004 case BPF_FUNC_snprintf:
10005 err = check_bpf_snprintf_call(env, regs);
10007 case BPF_FUNC_loop:
10008 update_loop_inline_state(env, meta.subprogno);
10009 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10010 set_loop_callback_state);
10012 case BPF_FUNC_dynptr_from_mem:
10013 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10014 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10015 reg_type_str(env, regs[BPF_REG_1].type));
10019 case BPF_FUNC_set_retval:
10020 if (prog_type == BPF_PROG_TYPE_LSM &&
10021 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10022 if (!env->prog->aux->attach_func_proto->type) {
10023 /* Make sure programs that attach to void
10024 * hooks don't try to modify return value.
10026 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10031 case BPF_FUNC_dynptr_data:
10033 struct bpf_reg_state *reg;
10034 int id, ref_obj_id;
10036 reg = get_dynptr_arg_reg(env, fn, regs);
10041 if (meta.dynptr_id) {
10042 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10045 if (meta.ref_obj_id) {
10046 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10050 id = dynptr_id(env, reg);
10052 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10056 ref_obj_id = dynptr_ref_obj_id(env, reg);
10057 if (ref_obj_id < 0) {
10058 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10062 meta.dynptr_id = id;
10063 meta.ref_obj_id = ref_obj_id;
10067 case BPF_FUNC_dynptr_write:
10069 enum bpf_dynptr_type dynptr_type;
10070 struct bpf_reg_state *reg;
10072 reg = get_dynptr_arg_reg(env, fn, regs);
10076 dynptr_type = dynptr_get_type(env, reg);
10077 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10080 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10081 /* this will trigger clear_all_pkt_pointers(), which will
10082 * invalidate all dynptr slices associated with the skb
10084 changes_data = true;
10088 case BPF_FUNC_user_ringbuf_drain:
10089 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10090 set_user_ringbuf_callback_state);
10097 /* reset caller saved regs */
10098 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10099 mark_reg_not_init(env, regs, caller_saved[i]);
10100 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10103 /* helper call returns 64-bit value. */
10104 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10106 /* update return register (already marked as written above) */
10107 ret_type = fn->ret_type;
10108 ret_flag = type_flag(ret_type);
10110 switch (base_type(ret_type)) {
10112 /* sets type to SCALAR_VALUE */
10113 mark_reg_unknown(env, regs, BPF_REG_0);
10116 regs[BPF_REG_0].type = NOT_INIT;
10118 case RET_PTR_TO_MAP_VALUE:
10119 /* There is no offset yet applied, variable or fixed */
10120 mark_reg_known_zero(env, regs, BPF_REG_0);
10121 /* remember map_ptr, so that check_map_access()
10122 * can check 'value_size' boundary of memory access
10123 * to map element returned from bpf_map_lookup_elem()
10125 if (meta.map_ptr == NULL) {
10127 "kernel subsystem misconfigured verifier\n");
10130 regs[BPF_REG_0].map_ptr = meta.map_ptr;
10131 regs[BPF_REG_0].map_uid = meta.map_uid;
10132 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10133 if (!type_may_be_null(ret_type) &&
10134 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10135 regs[BPF_REG_0].id = ++env->id_gen;
10138 case RET_PTR_TO_SOCKET:
10139 mark_reg_known_zero(env, regs, BPF_REG_0);
10140 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10142 case RET_PTR_TO_SOCK_COMMON:
10143 mark_reg_known_zero(env, regs, BPF_REG_0);
10144 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10146 case RET_PTR_TO_TCP_SOCK:
10147 mark_reg_known_zero(env, regs, BPF_REG_0);
10148 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10150 case RET_PTR_TO_MEM:
10151 mark_reg_known_zero(env, regs, BPF_REG_0);
10152 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10153 regs[BPF_REG_0].mem_size = meta.mem_size;
10155 case RET_PTR_TO_MEM_OR_BTF_ID:
10157 const struct btf_type *t;
10159 mark_reg_known_zero(env, regs, BPF_REG_0);
10160 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10161 if (!btf_type_is_struct(t)) {
10163 const struct btf_type *ret;
10166 /* resolve the type size of ksym. */
10167 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10169 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10170 verbose(env, "unable to resolve the size of type '%s': %ld\n",
10171 tname, PTR_ERR(ret));
10174 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10175 regs[BPF_REG_0].mem_size = tsize;
10177 /* MEM_RDONLY may be carried from ret_flag, but it
10178 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10179 * it will confuse the check of PTR_TO_BTF_ID in
10180 * check_mem_access().
10182 ret_flag &= ~MEM_RDONLY;
10184 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10185 regs[BPF_REG_0].btf = meta.ret_btf;
10186 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10190 case RET_PTR_TO_BTF_ID:
10192 struct btf *ret_btf;
10195 mark_reg_known_zero(env, regs, BPF_REG_0);
10196 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10197 if (func_id == BPF_FUNC_kptr_xchg) {
10198 ret_btf = meta.kptr_field->kptr.btf;
10199 ret_btf_id = meta.kptr_field->kptr.btf_id;
10200 if (!btf_is_kernel(ret_btf))
10201 regs[BPF_REG_0].type |= MEM_ALLOC;
10203 if (fn->ret_btf_id == BPF_PTR_POISON) {
10204 verbose(env, "verifier internal error:");
10205 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10206 func_id_name(func_id));
10209 ret_btf = btf_vmlinux;
10210 ret_btf_id = *fn->ret_btf_id;
10212 if (ret_btf_id == 0) {
10213 verbose(env, "invalid return type %u of func %s#%d\n",
10214 base_type(ret_type), func_id_name(func_id),
10218 regs[BPF_REG_0].btf = ret_btf;
10219 regs[BPF_REG_0].btf_id = ret_btf_id;
10223 verbose(env, "unknown return type %u of func %s#%d\n",
10224 base_type(ret_type), func_id_name(func_id), func_id);
10228 if (type_may_be_null(regs[BPF_REG_0].type))
10229 regs[BPF_REG_0].id = ++env->id_gen;
10231 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10232 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10233 func_id_name(func_id), func_id);
10237 if (is_dynptr_ref_function(func_id))
10238 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10240 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10241 /* For release_reference() */
10242 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10243 } else if (is_acquire_function(func_id, meta.map_ptr)) {
10244 int id = acquire_reference_state(env, insn_idx);
10248 /* For mark_ptr_or_null_reg() */
10249 regs[BPF_REG_0].id = id;
10250 /* For release_reference() */
10251 regs[BPF_REG_0].ref_obj_id = id;
10254 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10256 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10260 if ((func_id == BPF_FUNC_get_stack ||
10261 func_id == BPF_FUNC_get_task_stack) &&
10262 !env->prog->has_callchain_buf) {
10263 const char *err_str;
10265 #ifdef CONFIG_PERF_EVENTS
10266 err = get_callchain_buffers(sysctl_perf_event_max_stack);
10267 err_str = "cannot get callchain buffer for func %s#%d\n";
10270 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10273 verbose(env, err_str, func_id_name(func_id), func_id);
10277 env->prog->has_callchain_buf = true;
10280 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10281 env->prog->call_get_stack = true;
10283 if (func_id == BPF_FUNC_get_func_ip) {
10284 if (check_get_func_ip(env))
10286 env->prog->call_get_func_ip = true;
10290 clear_all_pkt_pointers(env);
10294 /* mark_btf_func_reg_size() is used when the reg size is determined by
10295 * the BTF func_proto's return value size and argument.
10297 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10300 struct bpf_reg_state *reg = &cur_regs(env)[regno];
10302 if (regno == BPF_REG_0) {
10303 /* Function return value */
10304 reg->live |= REG_LIVE_WRITTEN;
10305 reg->subreg_def = reg_size == sizeof(u64) ?
10306 DEF_NOT_SUBREG : env->insn_idx + 1;
10308 /* Function argument */
10309 if (reg_size == sizeof(u64)) {
10310 mark_insn_zext(env, reg);
10311 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10313 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10318 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10320 return meta->kfunc_flags & KF_ACQUIRE;
10323 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10325 return meta->kfunc_flags & KF_RELEASE;
10328 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10330 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10333 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10335 return meta->kfunc_flags & KF_SLEEPABLE;
10338 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10340 return meta->kfunc_flags & KF_DESTRUCTIVE;
10343 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10345 return meta->kfunc_flags & KF_RCU;
10348 static bool __kfunc_param_match_suffix(const struct btf *btf,
10349 const struct btf_param *arg,
10350 const char *suffix)
10352 int suffix_len = strlen(suffix), len;
10353 const char *param_name;
10355 /* In the future, this can be ported to use BTF tagging */
10356 param_name = btf_name_by_offset(btf, arg->name_off);
10357 if (str_is_empty(param_name))
10359 len = strlen(param_name);
10360 if (len < suffix_len)
10362 param_name += len - suffix_len;
10363 return !strncmp(param_name, suffix, suffix_len);
10366 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10367 const struct btf_param *arg,
10368 const struct bpf_reg_state *reg)
10370 const struct btf_type *t;
10372 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10373 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10376 return __kfunc_param_match_suffix(btf, arg, "__sz");
10379 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10380 const struct btf_param *arg,
10381 const struct bpf_reg_state *reg)
10383 const struct btf_type *t;
10385 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10386 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10389 return __kfunc_param_match_suffix(btf, arg, "__szk");
10392 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10394 return __kfunc_param_match_suffix(btf, arg, "__opt");
10397 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10399 return __kfunc_param_match_suffix(btf, arg, "__k");
10402 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10404 return __kfunc_param_match_suffix(btf, arg, "__ign");
10407 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10409 return __kfunc_param_match_suffix(btf, arg, "__alloc");
10412 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10414 return __kfunc_param_match_suffix(btf, arg, "__uninit");
10417 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10419 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10422 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10423 const struct btf_param *arg,
10426 int len, target_len = strlen(name);
10427 const char *param_name;
10429 param_name = btf_name_by_offset(btf, arg->name_off);
10430 if (str_is_empty(param_name))
10432 len = strlen(param_name);
10433 if (len != target_len)
10435 if (strcmp(param_name, name))
10443 KF_ARG_LIST_HEAD_ID,
10444 KF_ARG_LIST_NODE_ID,
10449 BTF_ID_LIST(kf_arg_btf_ids)
10450 BTF_ID(struct, bpf_dynptr_kern)
10451 BTF_ID(struct, bpf_list_head)
10452 BTF_ID(struct, bpf_list_node)
10453 BTF_ID(struct, bpf_rb_root)
10454 BTF_ID(struct, bpf_rb_node)
10456 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10457 const struct btf_param *arg, int type)
10459 const struct btf_type *t;
10462 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10465 if (!btf_type_is_ptr(t))
10467 t = btf_type_skip_modifiers(btf, t->type, &res_id);
10470 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10473 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10475 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10478 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10480 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10483 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10485 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10488 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10490 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10493 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10495 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10498 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10499 const struct btf_param *arg)
10501 const struct btf_type *t;
10503 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10510 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10511 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10512 const struct btf *btf,
10513 const struct btf_type *t, int rec)
10515 const struct btf_type *member_type;
10516 const struct btf_member *member;
10519 if (!btf_type_is_struct(t))
10522 for_each_member(i, t, member) {
10523 const struct btf_array *array;
10525 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10526 if (btf_type_is_struct(member_type)) {
10528 verbose(env, "max struct nesting depth exceeded\n");
10531 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10535 if (btf_type_is_array(member_type)) {
10536 array = btf_array(member_type);
10537 if (!array->nelems)
10539 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10540 if (!btf_type_is_scalar(member_type))
10544 if (!btf_type_is_scalar(member_type))
10550 enum kfunc_ptr_arg_type {
10552 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10553 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10554 KF_ARG_PTR_TO_DYNPTR,
10555 KF_ARG_PTR_TO_ITER,
10556 KF_ARG_PTR_TO_LIST_HEAD,
10557 KF_ARG_PTR_TO_LIST_NODE,
10558 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
10560 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
10561 KF_ARG_PTR_TO_CALLBACK,
10562 KF_ARG_PTR_TO_RB_ROOT,
10563 KF_ARG_PTR_TO_RB_NODE,
10566 enum special_kfunc_type {
10567 KF_bpf_obj_new_impl,
10568 KF_bpf_obj_drop_impl,
10569 KF_bpf_refcount_acquire_impl,
10570 KF_bpf_list_push_front_impl,
10571 KF_bpf_list_push_back_impl,
10572 KF_bpf_list_pop_front,
10573 KF_bpf_list_pop_back,
10574 KF_bpf_cast_to_kern_ctx,
10575 KF_bpf_rdonly_cast,
10576 KF_bpf_rcu_read_lock,
10577 KF_bpf_rcu_read_unlock,
10578 KF_bpf_rbtree_remove,
10579 KF_bpf_rbtree_add_impl,
10580 KF_bpf_rbtree_first,
10581 KF_bpf_dynptr_from_skb,
10582 KF_bpf_dynptr_from_xdp,
10583 KF_bpf_dynptr_slice,
10584 KF_bpf_dynptr_slice_rdwr,
10585 KF_bpf_dynptr_clone,
10588 BTF_SET_START(special_kfunc_set)
10589 BTF_ID(func, bpf_obj_new_impl)
10590 BTF_ID(func, bpf_obj_drop_impl)
10591 BTF_ID(func, bpf_refcount_acquire_impl)
10592 BTF_ID(func, bpf_list_push_front_impl)
10593 BTF_ID(func, bpf_list_push_back_impl)
10594 BTF_ID(func, bpf_list_pop_front)
10595 BTF_ID(func, bpf_list_pop_back)
10596 BTF_ID(func, bpf_cast_to_kern_ctx)
10597 BTF_ID(func, bpf_rdonly_cast)
10598 BTF_ID(func, bpf_rbtree_remove)
10599 BTF_ID(func, bpf_rbtree_add_impl)
10600 BTF_ID(func, bpf_rbtree_first)
10601 BTF_ID(func, bpf_dynptr_from_skb)
10602 BTF_ID(func, bpf_dynptr_from_xdp)
10603 BTF_ID(func, bpf_dynptr_slice)
10604 BTF_ID(func, bpf_dynptr_slice_rdwr)
10605 BTF_ID(func, bpf_dynptr_clone)
10606 BTF_SET_END(special_kfunc_set)
10608 BTF_ID_LIST(special_kfunc_list)
10609 BTF_ID(func, bpf_obj_new_impl)
10610 BTF_ID(func, bpf_obj_drop_impl)
10611 BTF_ID(func, bpf_refcount_acquire_impl)
10612 BTF_ID(func, bpf_list_push_front_impl)
10613 BTF_ID(func, bpf_list_push_back_impl)
10614 BTF_ID(func, bpf_list_pop_front)
10615 BTF_ID(func, bpf_list_pop_back)
10616 BTF_ID(func, bpf_cast_to_kern_ctx)
10617 BTF_ID(func, bpf_rdonly_cast)
10618 BTF_ID(func, bpf_rcu_read_lock)
10619 BTF_ID(func, bpf_rcu_read_unlock)
10620 BTF_ID(func, bpf_rbtree_remove)
10621 BTF_ID(func, bpf_rbtree_add_impl)
10622 BTF_ID(func, bpf_rbtree_first)
10623 BTF_ID(func, bpf_dynptr_from_skb)
10624 BTF_ID(func, bpf_dynptr_from_xdp)
10625 BTF_ID(func, bpf_dynptr_slice)
10626 BTF_ID(func, bpf_dynptr_slice_rdwr)
10627 BTF_ID(func, bpf_dynptr_clone)
10629 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10631 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10632 meta->arg_owning_ref) {
10636 return meta->kfunc_flags & KF_RET_NULL;
10639 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10641 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10644 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10646 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10649 static enum kfunc_ptr_arg_type
10650 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10651 struct bpf_kfunc_call_arg_meta *meta,
10652 const struct btf_type *t, const struct btf_type *ref_t,
10653 const char *ref_tname, const struct btf_param *args,
10654 int argno, int nargs)
10656 u32 regno = argno + 1;
10657 struct bpf_reg_state *regs = cur_regs(env);
10658 struct bpf_reg_state *reg = ®s[regno];
10659 bool arg_mem_size = false;
10661 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10662 return KF_ARG_PTR_TO_CTX;
10664 /* In this function, we verify the kfunc's BTF as per the argument type,
10665 * leaving the rest of the verification with respect to the register
10666 * type to our caller. When a set of conditions hold in the BTF type of
10667 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10669 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10670 return KF_ARG_PTR_TO_CTX;
10672 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10673 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10675 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10676 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10678 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10679 return KF_ARG_PTR_TO_DYNPTR;
10681 if (is_kfunc_arg_iter(meta, argno))
10682 return KF_ARG_PTR_TO_ITER;
10684 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10685 return KF_ARG_PTR_TO_LIST_HEAD;
10687 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10688 return KF_ARG_PTR_TO_LIST_NODE;
10690 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10691 return KF_ARG_PTR_TO_RB_ROOT;
10693 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10694 return KF_ARG_PTR_TO_RB_NODE;
10696 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10697 if (!btf_type_is_struct(ref_t)) {
10698 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10699 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10702 return KF_ARG_PTR_TO_BTF_ID;
10705 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10706 return KF_ARG_PTR_TO_CALLBACK;
10709 if (argno + 1 < nargs &&
10710 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
10711 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
10712 arg_mem_size = true;
10714 /* This is the catch all argument type of register types supported by
10715 * check_helper_mem_access. However, we only allow when argument type is
10716 * pointer to scalar, or struct composed (recursively) of scalars. When
10717 * arg_mem_size is true, the pointer can be void *.
10719 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10720 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10721 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10722 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10725 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10728 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10729 struct bpf_reg_state *reg,
10730 const struct btf_type *ref_t,
10731 const char *ref_tname, u32 ref_id,
10732 struct bpf_kfunc_call_arg_meta *meta,
10735 const struct btf_type *reg_ref_t;
10736 bool strict_type_match = false;
10737 const struct btf *reg_btf;
10738 const char *reg_ref_tname;
10741 if (base_type(reg->type) == PTR_TO_BTF_ID) {
10742 reg_btf = reg->btf;
10743 reg_ref_id = reg->btf_id;
10745 reg_btf = btf_vmlinux;
10746 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10749 /* Enforce strict type matching for calls to kfuncs that are acquiring
10750 * or releasing a reference, or are no-cast aliases. We do _not_
10751 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10752 * as we want to enable BPF programs to pass types that are bitwise
10753 * equivalent without forcing them to explicitly cast with something
10754 * like bpf_cast_to_kern_ctx().
10756 * For example, say we had a type like the following:
10758 * struct bpf_cpumask {
10759 * cpumask_t cpumask;
10760 * refcount_t usage;
10763 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10764 * to a struct cpumask, so it would be safe to pass a struct
10765 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10767 * The philosophy here is similar to how we allow scalars of different
10768 * types to be passed to kfuncs as long as the size is the same. The
10769 * only difference here is that we're simply allowing
10770 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10773 if (is_kfunc_acquire(meta) ||
10774 (is_kfunc_release(meta) && reg->ref_obj_id) ||
10775 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10776 strict_type_match = true;
10778 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10780 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
10781 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10782 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10783 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10784 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10785 btf_type_str(reg_ref_t), reg_ref_tname);
10791 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10793 struct bpf_verifier_state *state = env->cur_state;
10794 struct btf_record *rec = reg_btf_record(reg);
10796 if (!state->active_lock.ptr) {
10797 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10801 if (type_flag(reg->type) & NON_OWN_REF) {
10802 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10806 reg->type |= NON_OWN_REF;
10807 if (rec->refcount_off >= 0)
10808 reg->type |= MEM_RCU;
10813 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10815 struct bpf_func_state *state, *unused;
10816 struct bpf_reg_state *reg;
10819 state = cur_func(env);
10822 verbose(env, "verifier internal error: ref_obj_id is zero for "
10823 "owning -> non-owning conversion\n");
10827 for (i = 0; i < state->acquired_refs; i++) {
10828 if (state->refs[i].id != ref_obj_id)
10831 /* Clear ref_obj_id here so release_reference doesn't clobber
10834 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10835 if (reg->ref_obj_id == ref_obj_id) {
10836 reg->ref_obj_id = 0;
10837 ref_set_non_owning(env, reg);
10843 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10847 /* Implementation details:
10849 * Each register points to some region of memory, which we define as an
10850 * allocation. Each allocation may embed a bpf_spin_lock which protects any
10851 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10852 * allocation. The lock and the data it protects are colocated in the same
10855 * Hence, everytime a register holds a pointer value pointing to such
10856 * allocation, the verifier preserves a unique reg->id for it.
10858 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10859 * bpf_spin_lock is called.
10861 * To enable this, lock state in the verifier captures two values:
10862 * active_lock.ptr = Register's type specific pointer
10863 * active_lock.id = A unique ID for each register pointer value
10865 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10866 * supported register types.
10868 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10869 * allocated objects is the reg->btf pointer.
10871 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10872 * can establish the provenance of the map value statically for each distinct
10873 * lookup into such maps. They always contain a single map value hence unique
10874 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10876 * So, in case of global variables, they use array maps with max_entries = 1,
10877 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10878 * into the same map value as max_entries is 1, as described above).
10880 * In case of inner map lookups, the inner map pointer has same map_ptr as the
10881 * outer map pointer (in verifier context), but each lookup into an inner map
10882 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10883 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10884 * will get different reg->id assigned to each lookup, hence different
10887 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10888 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10889 * returned from bpf_obj_new. Each allocation receives a new reg->id.
10891 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10896 switch ((int)reg->type) {
10897 case PTR_TO_MAP_VALUE:
10898 ptr = reg->map_ptr;
10900 case PTR_TO_BTF_ID | MEM_ALLOC:
10904 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10909 if (!env->cur_state->active_lock.ptr)
10911 if (env->cur_state->active_lock.ptr != ptr ||
10912 env->cur_state->active_lock.id != id) {
10913 verbose(env, "held lock and object are not in the same allocation\n");
10919 static bool is_bpf_list_api_kfunc(u32 btf_id)
10921 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10922 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10923 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10924 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10927 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10929 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10930 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10931 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10934 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10936 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10937 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10940 static bool is_callback_calling_kfunc(u32 btf_id)
10942 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10945 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10947 return is_bpf_rbtree_api_kfunc(btf_id);
10950 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10951 enum btf_field_type head_field_type,
10956 switch (head_field_type) {
10957 case BPF_LIST_HEAD:
10958 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10961 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10964 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10965 btf_field_type_name(head_field_type));
10970 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10971 btf_field_type_name(head_field_type));
10975 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10976 enum btf_field_type node_field_type,
10981 switch (node_field_type) {
10982 case BPF_LIST_NODE:
10983 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10984 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10987 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10988 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10991 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10992 btf_field_type_name(node_field_type));
10997 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10998 btf_field_type_name(node_field_type));
11003 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11004 struct bpf_reg_state *reg, u32 regno,
11005 struct bpf_kfunc_call_arg_meta *meta,
11006 enum btf_field_type head_field_type,
11007 struct btf_field **head_field)
11009 const char *head_type_name;
11010 struct btf_field *field;
11011 struct btf_record *rec;
11014 if (meta->btf != btf_vmlinux) {
11015 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11019 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11022 head_type_name = btf_field_type_name(head_field_type);
11023 if (!tnum_is_const(reg->var_off)) {
11025 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11026 regno, head_type_name);
11030 rec = reg_btf_record(reg);
11031 head_off = reg->off + reg->var_off.value;
11032 field = btf_record_find(rec, head_off, head_field_type);
11034 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11038 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11039 if (check_reg_allocation_locked(env, reg)) {
11040 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11041 rec->spin_lock_off, head_type_name);
11046 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11049 *head_field = field;
11053 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11054 struct bpf_reg_state *reg, u32 regno,
11055 struct bpf_kfunc_call_arg_meta *meta)
11057 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11058 &meta->arg_list_head.field);
11061 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11062 struct bpf_reg_state *reg, u32 regno,
11063 struct bpf_kfunc_call_arg_meta *meta)
11065 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11066 &meta->arg_rbtree_root.field);
11070 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11071 struct bpf_reg_state *reg, u32 regno,
11072 struct bpf_kfunc_call_arg_meta *meta,
11073 enum btf_field_type head_field_type,
11074 enum btf_field_type node_field_type,
11075 struct btf_field **node_field)
11077 const char *node_type_name;
11078 const struct btf_type *et, *t;
11079 struct btf_field *field;
11082 if (meta->btf != btf_vmlinux) {
11083 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11087 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11090 node_type_name = btf_field_type_name(node_field_type);
11091 if (!tnum_is_const(reg->var_off)) {
11093 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11094 regno, node_type_name);
11098 node_off = reg->off + reg->var_off.value;
11099 field = reg_find_field_offset(reg, node_off, node_field_type);
11100 if (!field || field->offset != node_off) {
11101 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11105 field = *node_field;
11107 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11108 t = btf_type_by_id(reg->btf, reg->btf_id);
11109 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11110 field->graph_root.value_btf_id, true)) {
11111 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11112 "in struct %s, but arg is at offset=%d in struct %s\n",
11113 btf_field_type_name(head_field_type),
11114 btf_field_type_name(node_field_type),
11115 field->graph_root.node_offset,
11116 btf_name_by_offset(field->graph_root.btf, et->name_off),
11117 node_off, btf_name_by_offset(reg->btf, t->name_off));
11120 meta->arg_btf = reg->btf;
11121 meta->arg_btf_id = reg->btf_id;
11123 if (node_off != field->graph_root.node_offset) {
11124 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11125 node_off, btf_field_type_name(node_field_type),
11126 field->graph_root.node_offset,
11127 btf_name_by_offset(field->graph_root.btf, et->name_off));
11134 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11135 struct bpf_reg_state *reg, u32 regno,
11136 struct bpf_kfunc_call_arg_meta *meta)
11138 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11139 BPF_LIST_HEAD, BPF_LIST_NODE,
11140 &meta->arg_list_head.field);
11143 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11144 struct bpf_reg_state *reg, u32 regno,
11145 struct bpf_kfunc_call_arg_meta *meta)
11147 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11148 BPF_RB_ROOT, BPF_RB_NODE,
11149 &meta->arg_rbtree_root.field);
11152 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11155 const char *func_name = meta->func_name, *ref_tname;
11156 const struct btf *btf = meta->btf;
11157 const struct btf_param *args;
11158 struct btf_record *rec;
11162 args = (const struct btf_param *)(meta->func_proto + 1);
11163 nargs = btf_type_vlen(meta->func_proto);
11164 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11165 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11166 MAX_BPF_FUNC_REG_ARGS);
11170 /* Check that BTF function arguments match actual types that the
11173 for (i = 0; i < nargs; i++) {
11174 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
11175 const struct btf_type *t, *ref_t, *resolve_ret;
11176 enum bpf_arg_type arg_type = ARG_DONTCARE;
11177 u32 regno = i + 1, ref_id, type_size;
11178 bool is_ret_buf_sz = false;
11181 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11183 if (is_kfunc_arg_ignore(btf, &args[i]))
11186 if (btf_type_is_scalar(t)) {
11187 if (reg->type != SCALAR_VALUE) {
11188 verbose(env, "R%d is not a scalar\n", regno);
11192 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11193 if (meta->arg_constant.found) {
11194 verbose(env, "verifier internal error: only one constant argument permitted\n");
11197 if (!tnum_is_const(reg->var_off)) {
11198 verbose(env, "R%d must be a known constant\n", regno);
11201 ret = mark_chain_precision(env, regno);
11204 meta->arg_constant.found = true;
11205 meta->arg_constant.value = reg->var_off.value;
11206 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11207 meta->r0_rdonly = true;
11208 is_ret_buf_sz = true;
11209 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11210 is_ret_buf_sz = true;
11213 if (is_ret_buf_sz) {
11214 if (meta->r0_size) {
11215 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11219 if (!tnum_is_const(reg->var_off)) {
11220 verbose(env, "R%d is not a const\n", regno);
11224 meta->r0_size = reg->var_off.value;
11225 ret = mark_chain_precision(env, regno);
11232 if (!btf_type_is_ptr(t)) {
11233 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11237 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11238 (register_is_null(reg) || type_may_be_null(reg->type))) {
11239 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11243 if (reg->ref_obj_id) {
11244 if (is_kfunc_release(meta) && meta->ref_obj_id) {
11245 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11246 regno, reg->ref_obj_id,
11250 meta->ref_obj_id = reg->ref_obj_id;
11251 if (is_kfunc_release(meta))
11252 meta->release_regno = regno;
11255 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11256 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11258 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11259 if (kf_arg_type < 0)
11260 return kf_arg_type;
11262 switch (kf_arg_type) {
11263 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11264 case KF_ARG_PTR_TO_BTF_ID:
11265 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11268 if (!is_trusted_reg(reg)) {
11269 if (!is_kfunc_rcu(meta)) {
11270 verbose(env, "R%d must be referenced or trusted\n", regno);
11273 if (!is_rcu_reg(reg)) {
11274 verbose(env, "R%d must be a rcu pointer\n", regno);
11280 case KF_ARG_PTR_TO_CTX:
11281 /* Trusted arguments have the same offset checks as release arguments */
11282 arg_type |= OBJ_RELEASE;
11284 case KF_ARG_PTR_TO_DYNPTR:
11285 case KF_ARG_PTR_TO_ITER:
11286 case KF_ARG_PTR_TO_LIST_HEAD:
11287 case KF_ARG_PTR_TO_LIST_NODE:
11288 case KF_ARG_PTR_TO_RB_ROOT:
11289 case KF_ARG_PTR_TO_RB_NODE:
11290 case KF_ARG_PTR_TO_MEM:
11291 case KF_ARG_PTR_TO_MEM_SIZE:
11292 case KF_ARG_PTR_TO_CALLBACK:
11293 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11294 /* Trusted by default */
11301 if (is_kfunc_release(meta) && reg->ref_obj_id)
11302 arg_type |= OBJ_RELEASE;
11303 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11307 switch (kf_arg_type) {
11308 case KF_ARG_PTR_TO_CTX:
11309 if (reg->type != PTR_TO_CTX) {
11310 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11314 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11315 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11318 meta->ret_btf_id = ret;
11321 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11322 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11323 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11326 if (!reg->ref_obj_id) {
11327 verbose(env, "allocated object must be referenced\n");
11330 if (meta->btf == btf_vmlinux &&
11331 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11332 meta->arg_btf = reg->btf;
11333 meta->arg_btf_id = reg->btf_id;
11336 case KF_ARG_PTR_TO_DYNPTR:
11338 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11339 int clone_ref_obj_id = 0;
11341 if (reg->type != PTR_TO_STACK &&
11342 reg->type != CONST_PTR_TO_DYNPTR) {
11343 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11347 if (reg->type == CONST_PTR_TO_DYNPTR)
11348 dynptr_arg_type |= MEM_RDONLY;
11350 if (is_kfunc_arg_uninit(btf, &args[i]))
11351 dynptr_arg_type |= MEM_UNINIT;
11353 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11354 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11355 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11356 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11357 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11358 (dynptr_arg_type & MEM_UNINIT)) {
11359 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11361 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11362 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11366 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11367 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11368 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11369 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11374 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11378 if (!(dynptr_arg_type & MEM_UNINIT)) {
11379 int id = dynptr_id(env, reg);
11382 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11385 meta->initialized_dynptr.id = id;
11386 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11387 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11392 case KF_ARG_PTR_TO_ITER:
11393 ret = process_iter_arg(env, regno, insn_idx, meta);
11397 case KF_ARG_PTR_TO_LIST_HEAD:
11398 if (reg->type != PTR_TO_MAP_VALUE &&
11399 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11400 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11403 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11404 verbose(env, "allocated object must be referenced\n");
11407 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11411 case KF_ARG_PTR_TO_RB_ROOT:
11412 if (reg->type != PTR_TO_MAP_VALUE &&
11413 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11414 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11417 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11418 verbose(env, "allocated object must be referenced\n");
11421 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11425 case KF_ARG_PTR_TO_LIST_NODE:
11426 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11427 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11430 if (!reg->ref_obj_id) {
11431 verbose(env, "allocated object must be referenced\n");
11434 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11438 case KF_ARG_PTR_TO_RB_NODE:
11439 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11440 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11441 verbose(env, "rbtree_remove node input must be non-owning ref\n");
11444 if (in_rbtree_lock_required_cb(env)) {
11445 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11449 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11450 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11453 if (!reg->ref_obj_id) {
11454 verbose(env, "allocated object must be referenced\n");
11459 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11463 case KF_ARG_PTR_TO_BTF_ID:
11464 /* Only base_type is checked, further checks are done here */
11465 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11466 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11467 !reg2btf_ids[base_type(reg->type)]) {
11468 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11469 verbose(env, "expected %s or socket\n",
11470 reg_type_str(env, base_type(reg->type) |
11471 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11474 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11478 case KF_ARG_PTR_TO_MEM:
11479 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11480 if (IS_ERR(resolve_ret)) {
11481 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11482 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11485 ret = check_mem_reg(env, reg, regno, type_size);
11489 case KF_ARG_PTR_TO_MEM_SIZE:
11491 struct bpf_reg_state *buff_reg = ®s[regno];
11492 const struct btf_param *buff_arg = &args[i];
11493 struct bpf_reg_state *size_reg = ®s[regno + 1];
11494 const struct btf_param *size_arg = &args[i + 1];
11496 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11497 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11499 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11504 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11505 if (meta->arg_constant.found) {
11506 verbose(env, "verifier internal error: only one constant argument permitted\n");
11509 if (!tnum_is_const(size_reg->var_off)) {
11510 verbose(env, "R%d must be a known constant\n", regno + 1);
11513 meta->arg_constant.found = true;
11514 meta->arg_constant.value = size_reg->var_off.value;
11517 /* Skip next '__sz' or '__szk' argument */
11521 case KF_ARG_PTR_TO_CALLBACK:
11522 if (reg->type != PTR_TO_FUNC) {
11523 verbose(env, "arg%d expected pointer to func\n", i);
11526 meta->subprogno = reg->subprogno;
11528 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11529 if (!type_is_ptr_alloc_obj(reg->type)) {
11530 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11533 if (!type_is_non_owning_ref(reg->type))
11534 meta->arg_owning_ref = true;
11536 rec = reg_btf_record(reg);
11538 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11542 if (rec->refcount_off < 0) {
11543 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11547 meta->arg_btf = reg->btf;
11548 meta->arg_btf_id = reg->btf_id;
11553 if (is_kfunc_release(meta) && !meta->release_regno) {
11554 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11562 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11563 struct bpf_insn *insn,
11564 struct bpf_kfunc_call_arg_meta *meta,
11565 const char **kfunc_name)
11567 const struct btf_type *func, *func_proto;
11568 u32 func_id, *kfunc_flags;
11569 const char *func_name;
11570 struct btf *desc_btf;
11573 *kfunc_name = NULL;
11578 desc_btf = find_kfunc_desc_btf(env, insn->off);
11579 if (IS_ERR(desc_btf))
11580 return PTR_ERR(desc_btf);
11582 func_id = insn->imm;
11583 func = btf_type_by_id(desc_btf, func_id);
11584 func_name = btf_name_by_offset(desc_btf, func->name_off);
11586 *kfunc_name = func_name;
11587 func_proto = btf_type_by_id(desc_btf, func->type);
11589 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11590 if (!kfunc_flags) {
11594 memset(meta, 0, sizeof(*meta));
11595 meta->btf = desc_btf;
11596 meta->func_id = func_id;
11597 meta->kfunc_flags = *kfunc_flags;
11598 meta->func_proto = func_proto;
11599 meta->func_name = func_name;
11604 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11607 const struct btf_type *t, *ptr_type;
11608 u32 i, nargs, ptr_type_id, release_ref_obj_id;
11609 struct bpf_reg_state *regs = cur_regs(env);
11610 const char *func_name, *ptr_type_name;
11611 bool sleepable, rcu_lock, rcu_unlock;
11612 struct bpf_kfunc_call_arg_meta meta;
11613 struct bpf_insn_aux_data *insn_aux;
11614 int err, insn_idx = *insn_idx_p;
11615 const struct btf_param *args;
11616 const struct btf_type *ret_t;
11617 struct btf *desc_btf;
11619 /* skip for now, but return error when we find this in fixup_kfunc_call */
11623 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11624 if (err == -EACCES && func_name)
11625 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11628 desc_btf = meta.btf;
11629 insn_aux = &env->insn_aux_data[insn_idx];
11631 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11633 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11634 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11638 sleepable = is_kfunc_sleepable(&meta);
11639 if (sleepable && !env->prog->aux->sleepable) {
11640 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11644 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11645 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11647 if (env->cur_state->active_rcu_lock) {
11648 struct bpf_func_state *state;
11649 struct bpf_reg_state *reg;
11651 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11652 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11657 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11659 } else if (rcu_unlock) {
11660 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11661 if (reg->type & MEM_RCU) {
11662 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11663 reg->type |= PTR_UNTRUSTED;
11666 env->cur_state->active_rcu_lock = false;
11667 } else if (sleepable) {
11668 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11671 } else if (rcu_lock) {
11672 env->cur_state->active_rcu_lock = true;
11673 } else if (rcu_unlock) {
11674 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11678 /* Check the arguments */
11679 err = check_kfunc_args(env, &meta, insn_idx);
11682 /* In case of release function, we get register number of refcounted
11683 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11685 if (meta.release_regno) {
11686 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11688 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11689 func_name, meta.func_id);
11694 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11695 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11696 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11697 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11698 insn_aux->insert_off = regs[BPF_REG_2].off;
11699 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11700 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11702 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11703 func_name, meta.func_id);
11707 err = release_reference(env, release_ref_obj_id);
11709 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11710 func_name, meta.func_id);
11715 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11716 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11717 set_rbtree_add_callback_state);
11719 verbose(env, "kfunc %s#%d failed callback verification\n",
11720 func_name, meta.func_id);
11725 for (i = 0; i < CALLER_SAVED_REGS; i++)
11726 mark_reg_not_init(env, regs, caller_saved[i]);
11728 /* Check return type */
11729 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11731 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11732 /* Only exception is bpf_obj_new_impl */
11733 if (meta.btf != btf_vmlinux ||
11734 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11735 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11736 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11741 if (btf_type_is_scalar(t)) {
11742 mark_reg_unknown(env, regs, BPF_REG_0);
11743 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11744 } else if (btf_type_is_ptr(t)) {
11745 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11747 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11748 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11749 struct btf *ret_btf;
11752 if (unlikely(!bpf_global_ma_set))
11755 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11756 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11760 ret_btf = env->prog->aux->btf;
11761 ret_btf_id = meta.arg_constant.value;
11763 /* This may be NULL due to user not supplying a BTF */
11765 verbose(env, "bpf_obj_new requires prog BTF\n");
11769 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11770 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11771 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11775 mark_reg_known_zero(env, regs, BPF_REG_0);
11776 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11777 regs[BPF_REG_0].btf = ret_btf;
11778 regs[BPF_REG_0].btf_id = ret_btf_id;
11780 insn_aux->obj_new_size = ret_t->size;
11781 insn_aux->kptr_struct_meta =
11782 btf_find_struct_meta(ret_btf, ret_btf_id);
11783 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11784 mark_reg_known_zero(env, regs, BPF_REG_0);
11785 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11786 regs[BPF_REG_0].btf = meta.arg_btf;
11787 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11789 insn_aux->kptr_struct_meta =
11790 btf_find_struct_meta(meta.arg_btf,
11792 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11793 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11794 struct btf_field *field = meta.arg_list_head.field;
11796 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11797 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11798 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11799 struct btf_field *field = meta.arg_rbtree_root.field;
11801 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11802 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11803 mark_reg_known_zero(env, regs, BPF_REG_0);
11804 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11805 regs[BPF_REG_0].btf = desc_btf;
11806 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11807 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11808 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11809 if (!ret_t || !btf_type_is_struct(ret_t)) {
11811 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11815 mark_reg_known_zero(env, regs, BPF_REG_0);
11816 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11817 regs[BPF_REG_0].btf = desc_btf;
11818 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11819 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11820 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11821 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11823 mark_reg_known_zero(env, regs, BPF_REG_0);
11825 if (!meta.arg_constant.found) {
11826 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11830 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11832 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11833 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11835 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11836 regs[BPF_REG_0].type |= MEM_RDONLY;
11838 /* this will set env->seen_direct_write to true */
11839 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11840 verbose(env, "the prog does not allow writes to packet data\n");
11845 if (!meta.initialized_dynptr.id) {
11846 verbose(env, "verifier internal error: no dynptr id\n");
11849 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11851 /* we don't need to set BPF_REG_0's ref obj id
11852 * because packet slices are not refcounted (see
11853 * dynptr_type_refcounted)
11856 verbose(env, "kernel function %s unhandled dynamic return type\n",
11860 } else if (!__btf_type_is_struct(ptr_type)) {
11861 if (!meta.r0_size) {
11864 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11866 meta.r0_rdonly = true;
11869 if (!meta.r0_size) {
11870 ptr_type_name = btf_name_by_offset(desc_btf,
11871 ptr_type->name_off);
11873 "kernel function %s returns pointer type %s %s is not supported\n",
11875 btf_type_str(ptr_type),
11880 mark_reg_known_zero(env, regs, BPF_REG_0);
11881 regs[BPF_REG_0].type = PTR_TO_MEM;
11882 regs[BPF_REG_0].mem_size = meta.r0_size;
11884 if (meta.r0_rdonly)
11885 regs[BPF_REG_0].type |= MEM_RDONLY;
11887 /* Ensures we don't access the memory after a release_reference() */
11888 if (meta.ref_obj_id)
11889 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11891 mark_reg_known_zero(env, regs, BPF_REG_0);
11892 regs[BPF_REG_0].btf = desc_btf;
11893 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11894 regs[BPF_REG_0].btf_id = ptr_type_id;
11897 if (is_kfunc_ret_null(&meta)) {
11898 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11899 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11900 regs[BPF_REG_0].id = ++env->id_gen;
11902 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11903 if (is_kfunc_acquire(&meta)) {
11904 int id = acquire_reference_state(env, insn_idx);
11908 if (is_kfunc_ret_null(&meta))
11909 regs[BPF_REG_0].id = id;
11910 regs[BPF_REG_0].ref_obj_id = id;
11911 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11912 ref_set_non_owning(env, ®s[BPF_REG_0]);
11915 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
11916 regs[BPF_REG_0].id = ++env->id_gen;
11917 } else if (btf_type_is_void(t)) {
11918 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11919 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11920 insn_aux->kptr_struct_meta =
11921 btf_find_struct_meta(meta.arg_btf,
11927 nargs = btf_type_vlen(meta.func_proto);
11928 args = (const struct btf_param *)(meta.func_proto + 1);
11929 for (i = 0; i < nargs; i++) {
11932 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11933 if (btf_type_is_ptr(t))
11934 mark_btf_func_reg_size(env, regno, sizeof(void *));
11936 /* scalar. ensured by btf_check_kfunc_arg_match() */
11937 mark_btf_func_reg_size(env, regno, t->size);
11940 if (is_iter_next_kfunc(&meta)) {
11941 err = process_iter_next_call(env, insn_idx, &meta);
11949 static bool signed_add_overflows(s64 a, s64 b)
11951 /* Do the add in u64, where overflow is well-defined */
11952 s64 res = (s64)((u64)a + (u64)b);
11959 static bool signed_add32_overflows(s32 a, s32 b)
11961 /* Do the add in u32, where overflow is well-defined */
11962 s32 res = (s32)((u32)a + (u32)b);
11969 static bool signed_sub_overflows(s64 a, s64 b)
11971 /* Do the sub in u64, where overflow is well-defined */
11972 s64 res = (s64)((u64)a - (u64)b);
11979 static bool signed_sub32_overflows(s32 a, s32 b)
11981 /* Do the sub in u32, where overflow is well-defined */
11982 s32 res = (s32)((u32)a - (u32)b);
11989 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11990 const struct bpf_reg_state *reg,
11991 enum bpf_reg_type type)
11993 bool known = tnum_is_const(reg->var_off);
11994 s64 val = reg->var_off.value;
11995 s64 smin = reg->smin_value;
11997 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11998 verbose(env, "math between %s pointer and %lld is not allowed\n",
11999 reg_type_str(env, type), val);
12003 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12004 verbose(env, "%s pointer offset %d is not allowed\n",
12005 reg_type_str(env, type), reg->off);
12009 if (smin == S64_MIN) {
12010 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12011 reg_type_str(env, type));
12015 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12016 verbose(env, "value %lld makes %s pointer be out of bounds\n",
12017 smin, reg_type_str(env, type));
12025 REASON_BOUNDS = -1,
12032 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12033 u32 *alu_limit, bool mask_to_left)
12035 u32 max = 0, ptr_limit = 0;
12037 switch (ptr_reg->type) {
12039 /* Offset 0 is out-of-bounds, but acceptable start for the
12040 * left direction, see BPF_REG_FP. Also, unknown scalar
12041 * offset where we would need to deal with min/max bounds is
12042 * currently prohibited for unprivileged.
12044 max = MAX_BPF_STACK + mask_to_left;
12045 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12047 case PTR_TO_MAP_VALUE:
12048 max = ptr_reg->map_ptr->value_size;
12049 ptr_limit = (mask_to_left ?
12050 ptr_reg->smin_value :
12051 ptr_reg->umax_value) + ptr_reg->off;
12054 return REASON_TYPE;
12057 if (ptr_limit >= max)
12058 return REASON_LIMIT;
12059 *alu_limit = ptr_limit;
12063 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12064 const struct bpf_insn *insn)
12066 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12069 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12070 u32 alu_state, u32 alu_limit)
12072 /* If we arrived here from different branches with different
12073 * state or limits to sanitize, then this won't work.
12075 if (aux->alu_state &&
12076 (aux->alu_state != alu_state ||
12077 aux->alu_limit != alu_limit))
12078 return REASON_PATHS;
12080 /* Corresponding fixup done in do_misc_fixups(). */
12081 aux->alu_state = alu_state;
12082 aux->alu_limit = alu_limit;
12086 static int sanitize_val_alu(struct bpf_verifier_env *env,
12087 struct bpf_insn *insn)
12089 struct bpf_insn_aux_data *aux = cur_aux(env);
12091 if (can_skip_alu_sanitation(env, insn))
12094 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12097 static bool sanitize_needed(u8 opcode)
12099 return opcode == BPF_ADD || opcode == BPF_SUB;
12102 struct bpf_sanitize_info {
12103 struct bpf_insn_aux_data aux;
12107 static struct bpf_verifier_state *
12108 sanitize_speculative_path(struct bpf_verifier_env *env,
12109 const struct bpf_insn *insn,
12110 u32 next_idx, u32 curr_idx)
12112 struct bpf_verifier_state *branch;
12113 struct bpf_reg_state *regs;
12115 branch = push_stack(env, next_idx, curr_idx, true);
12116 if (branch && insn) {
12117 regs = branch->frame[branch->curframe]->regs;
12118 if (BPF_SRC(insn->code) == BPF_K) {
12119 mark_reg_unknown(env, regs, insn->dst_reg);
12120 } else if (BPF_SRC(insn->code) == BPF_X) {
12121 mark_reg_unknown(env, regs, insn->dst_reg);
12122 mark_reg_unknown(env, regs, insn->src_reg);
12128 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12129 struct bpf_insn *insn,
12130 const struct bpf_reg_state *ptr_reg,
12131 const struct bpf_reg_state *off_reg,
12132 struct bpf_reg_state *dst_reg,
12133 struct bpf_sanitize_info *info,
12134 const bool commit_window)
12136 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12137 struct bpf_verifier_state *vstate = env->cur_state;
12138 bool off_is_imm = tnum_is_const(off_reg->var_off);
12139 bool off_is_neg = off_reg->smin_value < 0;
12140 bool ptr_is_dst_reg = ptr_reg == dst_reg;
12141 u8 opcode = BPF_OP(insn->code);
12142 u32 alu_state, alu_limit;
12143 struct bpf_reg_state tmp;
12147 if (can_skip_alu_sanitation(env, insn))
12150 /* We already marked aux for masking from non-speculative
12151 * paths, thus we got here in the first place. We only care
12152 * to explore bad access from here.
12154 if (vstate->speculative)
12157 if (!commit_window) {
12158 if (!tnum_is_const(off_reg->var_off) &&
12159 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12160 return REASON_BOUNDS;
12162 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
12163 (opcode == BPF_SUB && !off_is_neg);
12166 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12170 if (commit_window) {
12171 /* In commit phase we narrow the masking window based on
12172 * the observed pointer move after the simulated operation.
12174 alu_state = info->aux.alu_state;
12175 alu_limit = abs(info->aux.alu_limit - alu_limit);
12177 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12178 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12179 alu_state |= ptr_is_dst_reg ?
12180 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12182 /* Limit pruning on unknown scalars to enable deep search for
12183 * potential masking differences from other program paths.
12186 env->explore_alu_limits = true;
12189 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12193 /* If we're in commit phase, we're done here given we already
12194 * pushed the truncated dst_reg into the speculative verification
12197 * Also, when register is a known constant, we rewrite register-based
12198 * operation to immediate-based, and thus do not need masking (and as
12199 * a consequence, do not need to simulate the zero-truncation either).
12201 if (commit_window || off_is_imm)
12204 /* Simulate and find potential out-of-bounds access under
12205 * speculative execution from truncation as a result of
12206 * masking when off was not within expected range. If off
12207 * sits in dst, then we temporarily need to move ptr there
12208 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12209 * for cases where we use K-based arithmetic in one direction
12210 * and truncated reg-based in the other in order to explore
12213 if (!ptr_is_dst_reg) {
12215 copy_register_state(dst_reg, ptr_reg);
12217 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12219 if (!ptr_is_dst_reg && ret)
12221 return !ret ? REASON_STACK : 0;
12224 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12226 struct bpf_verifier_state *vstate = env->cur_state;
12228 /* If we simulate paths under speculation, we don't update the
12229 * insn as 'seen' such that when we verify unreachable paths in
12230 * the non-speculative domain, sanitize_dead_code() can still
12231 * rewrite/sanitize them.
12233 if (!vstate->speculative)
12234 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12237 static int sanitize_err(struct bpf_verifier_env *env,
12238 const struct bpf_insn *insn, int reason,
12239 const struct bpf_reg_state *off_reg,
12240 const struct bpf_reg_state *dst_reg)
12242 static const char *err = "pointer arithmetic with it prohibited for !root";
12243 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12244 u32 dst = insn->dst_reg, src = insn->src_reg;
12247 case REASON_BOUNDS:
12248 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12249 off_reg == dst_reg ? dst : src, err);
12252 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12253 off_reg == dst_reg ? src : dst, err);
12256 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12260 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12264 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12268 verbose(env, "verifier internal error: unknown reason (%d)\n",
12276 /* check that stack access falls within stack limits and that 'reg' doesn't
12277 * have a variable offset.
12279 * Variable offset is prohibited for unprivileged mode for simplicity since it
12280 * requires corresponding support in Spectre masking for stack ALU. See also
12281 * retrieve_ptr_limit().
12284 * 'off' includes 'reg->off'.
12286 static int check_stack_access_for_ptr_arithmetic(
12287 struct bpf_verifier_env *env,
12289 const struct bpf_reg_state *reg,
12292 if (!tnum_is_const(reg->var_off)) {
12295 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12296 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12297 regno, tn_buf, off);
12301 if (off >= 0 || off < -MAX_BPF_STACK) {
12302 verbose(env, "R%d stack pointer arithmetic goes out of range, "
12303 "prohibited for !root; off=%d\n", regno, off);
12310 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12311 const struct bpf_insn *insn,
12312 const struct bpf_reg_state *dst_reg)
12314 u32 dst = insn->dst_reg;
12316 /* For unprivileged we require that resulting offset must be in bounds
12317 * in order to be able to sanitize access later on.
12319 if (env->bypass_spec_v1)
12322 switch (dst_reg->type) {
12324 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12325 dst_reg->off + dst_reg->var_off.value))
12328 case PTR_TO_MAP_VALUE:
12329 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12330 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12331 "prohibited for !root\n", dst);
12342 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12343 * Caller should also handle BPF_MOV case separately.
12344 * If we return -EACCES, caller may want to try again treating pointer as a
12345 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
12347 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12348 struct bpf_insn *insn,
12349 const struct bpf_reg_state *ptr_reg,
12350 const struct bpf_reg_state *off_reg)
12352 struct bpf_verifier_state *vstate = env->cur_state;
12353 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12354 struct bpf_reg_state *regs = state->regs, *dst_reg;
12355 bool known = tnum_is_const(off_reg->var_off);
12356 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12357 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12358 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12359 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12360 struct bpf_sanitize_info info = {};
12361 u8 opcode = BPF_OP(insn->code);
12362 u32 dst = insn->dst_reg;
12365 dst_reg = ®s[dst];
12367 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12368 smin_val > smax_val || umin_val > umax_val) {
12369 /* Taint dst register if offset had invalid bounds derived from
12370 * e.g. dead branches.
12372 __mark_reg_unknown(env, dst_reg);
12376 if (BPF_CLASS(insn->code) != BPF_ALU64) {
12377 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12378 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12379 __mark_reg_unknown(env, dst_reg);
12384 "R%d 32-bit pointer arithmetic prohibited\n",
12389 if (ptr_reg->type & PTR_MAYBE_NULL) {
12390 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12391 dst, reg_type_str(env, ptr_reg->type));
12395 switch (base_type(ptr_reg->type)) {
12396 case PTR_TO_FLOW_KEYS:
12400 case CONST_PTR_TO_MAP:
12401 /* smin_val represents the known value */
12402 if (known && smin_val == 0 && opcode == BPF_ADD)
12405 case PTR_TO_PACKET_END:
12406 case PTR_TO_SOCKET:
12407 case PTR_TO_SOCK_COMMON:
12408 case PTR_TO_TCP_SOCK:
12409 case PTR_TO_XDP_SOCK:
12410 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12411 dst, reg_type_str(env, ptr_reg->type));
12417 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12418 * The id may be overwritten later if we create a new variable offset.
12420 dst_reg->type = ptr_reg->type;
12421 dst_reg->id = ptr_reg->id;
12423 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12424 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12427 /* pointer types do not carry 32-bit bounds at the moment. */
12428 __mark_reg32_unbounded(dst_reg);
12430 if (sanitize_needed(opcode)) {
12431 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12434 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12439 /* We can take a fixed offset as long as it doesn't overflow
12440 * the s32 'off' field
12442 if (known && (ptr_reg->off + smin_val ==
12443 (s64)(s32)(ptr_reg->off + smin_val))) {
12444 /* pointer += K. Accumulate it into fixed offset */
12445 dst_reg->smin_value = smin_ptr;
12446 dst_reg->smax_value = smax_ptr;
12447 dst_reg->umin_value = umin_ptr;
12448 dst_reg->umax_value = umax_ptr;
12449 dst_reg->var_off = ptr_reg->var_off;
12450 dst_reg->off = ptr_reg->off + smin_val;
12451 dst_reg->raw = ptr_reg->raw;
12454 /* A new variable offset is created. Note that off_reg->off
12455 * == 0, since it's a scalar.
12456 * dst_reg gets the pointer type and since some positive
12457 * integer value was added to the pointer, give it a new 'id'
12458 * if it's a PTR_TO_PACKET.
12459 * this creates a new 'base' pointer, off_reg (variable) gets
12460 * added into the variable offset, and we copy the fixed offset
12463 if (signed_add_overflows(smin_ptr, smin_val) ||
12464 signed_add_overflows(smax_ptr, smax_val)) {
12465 dst_reg->smin_value = S64_MIN;
12466 dst_reg->smax_value = S64_MAX;
12468 dst_reg->smin_value = smin_ptr + smin_val;
12469 dst_reg->smax_value = smax_ptr + smax_val;
12471 if (umin_ptr + umin_val < umin_ptr ||
12472 umax_ptr + umax_val < umax_ptr) {
12473 dst_reg->umin_value = 0;
12474 dst_reg->umax_value = U64_MAX;
12476 dst_reg->umin_value = umin_ptr + umin_val;
12477 dst_reg->umax_value = umax_ptr + umax_val;
12479 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12480 dst_reg->off = ptr_reg->off;
12481 dst_reg->raw = ptr_reg->raw;
12482 if (reg_is_pkt_pointer(ptr_reg)) {
12483 dst_reg->id = ++env->id_gen;
12484 /* something was added to pkt_ptr, set range to zero */
12485 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12489 if (dst_reg == off_reg) {
12490 /* scalar -= pointer. Creates an unknown scalar */
12491 verbose(env, "R%d tried to subtract pointer from scalar\n",
12495 /* We don't allow subtraction from FP, because (according to
12496 * test_verifier.c test "invalid fp arithmetic", JITs might not
12497 * be able to deal with it.
12499 if (ptr_reg->type == PTR_TO_STACK) {
12500 verbose(env, "R%d subtraction from stack pointer prohibited\n",
12504 if (known && (ptr_reg->off - smin_val ==
12505 (s64)(s32)(ptr_reg->off - smin_val))) {
12506 /* pointer -= K. Subtract it from fixed offset */
12507 dst_reg->smin_value = smin_ptr;
12508 dst_reg->smax_value = smax_ptr;
12509 dst_reg->umin_value = umin_ptr;
12510 dst_reg->umax_value = umax_ptr;
12511 dst_reg->var_off = ptr_reg->var_off;
12512 dst_reg->id = ptr_reg->id;
12513 dst_reg->off = ptr_reg->off - smin_val;
12514 dst_reg->raw = ptr_reg->raw;
12517 /* A new variable offset is created. If the subtrahend is known
12518 * nonnegative, then any reg->range we had before is still good.
12520 if (signed_sub_overflows(smin_ptr, smax_val) ||
12521 signed_sub_overflows(smax_ptr, smin_val)) {
12522 /* Overflow possible, we know nothing */
12523 dst_reg->smin_value = S64_MIN;
12524 dst_reg->smax_value = S64_MAX;
12526 dst_reg->smin_value = smin_ptr - smax_val;
12527 dst_reg->smax_value = smax_ptr - smin_val;
12529 if (umin_ptr < umax_val) {
12530 /* Overflow possible, we know nothing */
12531 dst_reg->umin_value = 0;
12532 dst_reg->umax_value = U64_MAX;
12534 /* Cannot overflow (as long as bounds are consistent) */
12535 dst_reg->umin_value = umin_ptr - umax_val;
12536 dst_reg->umax_value = umax_ptr - umin_val;
12538 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12539 dst_reg->off = ptr_reg->off;
12540 dst_reg->raw = ptr_reg->raw;
12541 if (reg_is_pkt_pointer(ptr_reg)) {
12542 dst_reg->id = ++env->id_gen;
12543 /* something was added to pkt_ptr, set range to zero */
12545 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12551 /* bitwise ops on pointers are troublesome, prohibit. */
12552 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12553 dst, bpf_alu_string[opcode >> 4]);
12556 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12557 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12558 dst, bpf_alu_string[opcode >> 4]);
12562 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12564 reg_bounds_sync(dst_reg);
12565 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12567 if (sanitize_needed(opcode)) {
12568 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12571 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12577 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12578 struct bpf_reg_state *src_reg)
12580 s32 smin_val = src_reg->s32_min_value;
12581 s32 smax_val = src_reg->s32_max_value;
12582 u32 umin_val = src_reg->u32_min_value;
12583 u32 umax_val = src_reg->u32_max_value;
12585 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12586 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12587 dst_reg->s32_min_value = S32_MIN;
12588 dst_reg->s32_max_value = S32_MAX;
12590 dst_reg->s32_min_value += smin_val;
12591 dst_reg->s32_max_value += smax_val;
12593 if (dst_reg->u32_min_value + umin_val < umin_val ||
12594 dst_reg->u32_max_value + umax_val < umax_val) {
12595 dst_reg->u32_min_value = 0;
12596 dst_reg->u32_max_value = U32_MAX;
12598 dst_reg->u32_min_value += umin_val;
12599 dst_reg->u32_max_value += umax_val;
12603 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12604 struct bpf_reg_state *src_reg)
12606 s64 smin_val = src_reg->smin_value;
12607 s64 smax_val = src_reg->smax_value;
12608 u64 umin_val = src_reg->umin_value;
12609 u64 umax_val = src_reg->umax_value;
12611 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12612 signed_add_overflows(dst_reg->smax_value, smax_val)) {
12613 dst_reg->smin_value = S64_MIN;
12614 dst_reg->smax_value = S64_MAX;
12616 dst_reg->smin_value += smin_val;
12617 dst_reg->smax_value += smax_val;
12619 if (dst_reg->umin_value + umin_val < umin_val ||
12620 dst_reg->umax_value + umax_val < umax_val) {
12621 dst_reg->umin_value = 0;
12622 dst_reg->umax_value = U64_MAX;
12624 dst_reg->umin_value += umin_val;
12625 dst_reg->umax_value += umax_val;
12629 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12630 struct bpf_reg_state *src_reg)
12632 s32 smin_val = src_reg->s32_min_value;
12633 s32 smax_val = src_reg->s32_max_value;
12634 u32 umin_val = src_reg->u32_min_value;
12635 u32 umax_val = src_reg->u32_max_value;
12637 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12638 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12639 /* Overflow possible, we know nothing */
12640 dst_reg->s32_min_value = S32_MIN;
12641 dst_reg->s32_max_value = S32_MAX;
12643 dst_reg->s32_min_value -= smax_val;
12644 dst_reg->s32_max_value -= smin_val;
12646 if (dst_reg->u32_min_value < umax_val) {
12647 /* Overflow possible, we know nothing */
12648 dst_reg->u32_min_value = 0;
12649 dst_reg->u32_max_value = U32_MAX;
12651 /* Cannot overflow (as long as bounds are consistent) */
12652 dst_reg->u32_min_value -= umax_val;
12653 dst_reg->u32_max_value -= umin_val;
12657 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12658 struct bpf_reg_state *src_reg)
12660 s64 smin_val = src_reg->smin_value;
12661 s64 smax_val = src_reg->smax_value;
12662 u64 umin_val = src_reg->umin_value;
12663 u64 umax_val = src_reg->umax_value;
12665 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12666 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12667 /* Overflow possible, we know nothing */
12668 dst_reg->smin_value = S64_MIN;
12669 dst_reg->smax_value = S64_MAX;
12671 dst_reg->smin_value -= smax_val;
12672 dst_reg->smax_value -= smin_val;
12674 if (dst_reg->umin_value < umax_val) {
12675 /* Overflow possible, we know nothing */
12676 dst_reg->umin_value = 0;
12677 dst_reg->umax_value = U64_MAX;
12679 /* Cannot overflow (as long as bounds are consistent) */
12680 dst_reg->umin_value -= umax_val;
12681 dst_reg->umax_value -= umin_val;
12685 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12686 struct bpf_reg_state *src_reg)
12688 s32 smin_val = src_reg->s32_min_value;
12689 u32 umin_val = src_reg->u32_min_value;
12690 u32 umax_val = src_reg->u32_max_value;
12692 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12693 /* Ain't nobody got time to multiply that sign */
12694 __mark_reg32_unbounded(dst_reg);
12697 /* Both values are positive, so we can work with unsigned and
12698 * copy the result to signed (unless it exceeds S32_MAX).
12700 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12701 /* Potential overflow, we know nothing */
12702 __mark_reg32_unbounded(dst_reg);
12705 dst_reg->u32_min_value *= umin_val;
12706 dst_reg->u32_max_value *= umax_val;
12707 if (dst_reg->u32_max_value > S32_MAX) {
12708 /* Overflow possible, we know nothing */
12709 dst_reg->s32_min_value = S32_MIN;
12710 dst_reg->s32_max_value = S32_MAX;
12712 dst_reg->s32_min_value = dst_reg->u32_min_value;
12713 dst_reg->s32_max_value = dst_reg->u32_max_value;
12717 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12718 struct bpf_reg_state *src_reg)
12720 s64 smin_val = src_reg->smin_value;
12721 u64 umin_val = src_reg->umin_value;
12722 u64 umax_val = src_reg->umax_value;
12724 if (smin_val < 0 || dst_reg->smin_value < 0) {
12725 /* Ain't nobody got time to multiply that sign */
12726 __mark_reg64_unbounded(dst_reg);
12729 /* Both values are positive, so we can work with unsigned and
12730 * copy the result to signed (unless it exceeds S64_MAX).
12732 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12733 /* Potential overflow, we know nothing */
12734 __mark_reg64_unbounded(dst_reg);
12737 dst_reg->umin_value *= umin_val;
12738 dst_reg->umax_value *= umax_val;
12739 if (dst_reg->umax_value > S64_MAX) {
12740 /* Overflow possible, we know nothing */
12741 dst_reg->smin_value = S64_MIN;
12742 dst_reg->smax_value = S64_MAX;
12744 dst_reg->smin_value = dst_reg->umin_value;
12745 dst_reg->smax_value = dst_reg->umax_value;
12749 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12750 struct bpf_reg_state *src_reg)
12752 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12753 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12754 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12755 s32 smin_val = src_reg->s32_min_value;
12756 u32 umax_val = src_reg->u32_max_value;
12758 if (src_known && dst_known) {
12759 __mark_reg32_known(dst_reg, var32_off.value);
12763 /* We get our minimum from the var_off, since that's inherently
12764 * bitwise. Our maximum is the minimum of the operands' maxima.
12766 dst_reg->u32_min_value = var32_off.value;
12767 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12768 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12769 /* Lose signed bounds when ANDing negative numbers,
12770 * ain't nobody got time for that.
12772 dst_reg->s32_min_value = S32_MIN;
12773 dst_reg->s32_max_value = S32_MAX;
12775 /* ANDing two positives gives a positive, so safe to
12776 * cast result into s64.
12778 dst_reg->s32_min_value = dst_reg->u32_min_value;
12779 dst_reg->s32_max_value = dst_reg->u32_max_value;
12783 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12784 struct bpf_reg_state *src_reg)
12786 bool src_known = tnum_is_const(src_reg->var_off);
12787 bool dst_known = tnum_is_const(dst_reg->var_off);
12788 s64 smin_val = src_reg->smin_value;
12789 u64 umax_val = src_reg->umax_value;
12791 if (src_known && dst_known) {
12792 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12796 /* We get our minimum from the var_off, since that's inherently
12797 * bitwise. Our maximum is the minimum of the operands' maxima.
12799 dst_reg->umin_value = dst_reg->var_off.value;
12800 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12801 if (dst_reg->smin_value < 0 || smin_val < 0) {
12802 /* Lose signed bounds when ANDing negative numbers,
12803 * ain't nobody got time for that.
12805 dst_reg->smin_value = S64_MIN;
12806 dst_reg->smax_value = S64_MAX;
12808 /* ANDing two positives gives a positive, so safe to
12809 * cast result into s64.
12811 dst_reg->smin_value = dst_reg->umin_value;
12812 dst_reg->smax_value = dst_reg->umax_value;
12814 /* We may learn something more from the var_off */
12815 __update_reg_bounds(dst_reg);
12818 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12819 struct bpf_reg_state *src_reg)
12821 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12822 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12823 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12824 s32 smin_val = src_reg->s32_min_value;
12825 u32 umin_val = src_reg->u32_min_value;
12827 if (src_known && dst_known) {
12828 __mark_reg32_known(dst_reg, var32_off.value);
12832 /* We get our maximum from the var_off, and our minimum is the
12833 * maximum of the operands' minima
12835 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12836 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12837 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12838 /* Lose signed bounds when ORing negative numbers,
12839 * ain't nobody got time for that.
12841 dst_reg->s32_min_value = S32_MIN;
12842 dst_reg->s32_max_value = S32_MAX;
12844 /* ORing two positives gives a positive, so safe to
12845 * cast result into s64.
12847 dst_reg->s32_min_value = dst_reg->u32_min_value;
12848 dst_reg->s32_max_value = dst_reg->u32_max_value;
12852 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12853 struct bpf_reg_state *src_reg)
12855 bool src_known = tnum_is_const(src_reg->var_off);
12856 bool dst_known = tnum_is_const(dst_reg->var_off);
12857 s64 smin_val = src_reg->smin_value;
12858 u64 umin_val = src_reg->umin_value;
12860 if (src_known && dst_known) {
12861 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12865 /* We get our maximum from the var_off, and our minimum is the
12866 * maximum of the operands' minima
12868 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12869 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12870 if (dst_reg->smin_value < 0 || smin_val < 0) {
12871 /* Lose signed bounds when ORing negative numbers,
12872 * ain't nobody got time for that.
12874 dst_reg->smin_value = S64_MIN;
12875 dst_reg->smax_value = S64_MAX;
12877 /* ORing two positives gives a positive, so safe to
12878 * cast result into s64.
12880 dst_reg->smin_value = dst_reg->umin_value;
12881 dst_reg->smax_value = dst_reg->umax_value;
12883 /* We may learn something more from the var_off */
12884 __update_reg_bounds(dst_reg);
12887 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12888 struct bpf_reg_state *src_reg)
12890 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12891 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12892 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12893 s32 smin_val = src_reg->s32_min_value;
12895 if (src_known && dst_known) {
12896 __mark_reg32_known(dst_reg, var32_off.value);
12900 /* We get both minimum and maximum from the var32_off. */
12901 dst_reg->u32_min_value = var32_off.value;
12902 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12904 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12905 /* XORing two positive sign numbers gives a positive,
12906 * so safe to cast u32 result into s32.
12908 dst_reg->s32_min_value = dst_reg->u32_min_value;
12909 dst_reg->s32_max_value = dst_reg->u32_max_value;
12911 dst_reg->s32_min_value = S32_MIN;
12912 dst_reg->s32_max_value = S32_MAX;
12916 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12917 struct bpf_reg_state *src_reg)
12919 bool src_known = tnum_is_const(src_reg->var_off);
12920 bool dst_known = tnum_is_const(dst_reg->var_off);
12921 s64 smin_val = src_reg->smin_value;
12923 if (src_known && dst_known) {
12924 /* dst_reg->var_off.value has been updated earlier */
12925 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12929 /* We get both minimum and maximum from the var_off. */
12930 dst_reg->umin_value = dst_reg->var_off.value;
12931 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12933 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12934 /* XORing two positive sign numbers gives a positive,
12935 * so safe to cast u64 result into s64.
12937 dst_reg->smin_value = dst_reg->umin_value;
12938 dst_reg->smax_value = dst_reg->umax_value;
12940 dst_reg->smin_value = S64_MIN;
12941 dst_reg->smax_value = S64_MAX;
12944 __update_reg_bounds(dst_reg);
12947 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12948 u64 umin_val, u64 umax_val)
12950 /* We lose all sign bit information (except what we can pick
12953 dst_reg->s32_min_value = S32_MIN;
12954 dst_reg->s32_max_value = S32_MAX;
12955 /* If we might shift our top bit out, then we know nothing */
12956 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12957 dst_reg->u32_min_value = 0;
12958 dst_reg->u32_max_value = U32_MAX;
12960 dst_reg->u32_min_value <<= umin_val;
12961 dst_reg->u32_max_value <<= umax_val;
12965 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12966 struct bpf_reg_state *src_reg)
12968 u32 umax_val = src_reg->u32_max_value;
12969 u32 umin_val = src_reg->u32_min_value;
12970 /* u32 alu operation will zext upper bits */
12971 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12973 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12974 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12975 /* Not required but being careful mark reg64 bounds as unknown so
12976 * that we are forced to pick them up from tnum and zext later and
12977 * if some path skips this step we are still safe.
12979 __mark_reg64_unbounded(dst_reg);
12980 __update_reg32_bounds(dst_reg);
12983 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12984 u64 umin_val, u64 umax_val)
12986 /* Special case <<32 because it is a common compiler pattern to sign
12987 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12988 * positive we know this shift will also be positive so we can track
12989 * bounds correctly. Otherwise we lose all sign bit information except
12990 * what we can pick up from var_off. Perhaps we can generalize this
12991 * later to shifts of any length.
12993 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12994 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12996 dst_reg->smax_value = S64_MAX;
12998 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12999 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13001 dst_reg->smin_value = S64_MIN;
13003 /* If we might shift our top bit out, then we know nothing */
13004 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13005 dst_reg->umin_value = 0;
13006 dst_reg->umax_value = U64_MAX;
13008 dst_reg->umin_value <<= umin_val;
13009 dst_reg->umax_value <<= umax_val;
13013 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13014 struct bpf_reg_state *src_reg)
13016 u64 umax_val = src_reg->umax_value;
13017 u64 umin_val = src_reg->umin_value;
13019 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
13020 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13021 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13023 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13024 /* We may learn something more from the var_off */
13025 __update_reg_bounds(dst_reg);
13028 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13029 struct bpf_reg_state *src_reg)
13031 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13032 u32 umax_val = src_reg->u32_max_value;
13033 u32 umin_val = src_reg->u32_min_value;
13035 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13036 * be negative, then either:
13037 * 1) src_reg might be zero, so the sign bit of the result is
13038 * unknown, so we lose our signed bounds
13039 * 2) it's known negative, thus the unsigned bounds capture the
13041 * 3) the signed bounds cross zero, so they tell us nothing
13043 * If the value in dst_reg is known nonnegative, then again the
13044 * unsigned bounds capture the signed bounds.
13045 * Thus, in all cases it suffices to blow away our signed bounds
13046 * and rely on inferring new ones from the unsigned bounds and
13047 * var_off of the result.
13049 dst_reg->s32_min_value = S32_MIN;
13050 dst_reg->s32_max_value = S32_MAX;
13052 dst_reg->var_off = tnum_rshift(subreg, umin_val);
13053 dst_reg->u32_min_value >>= umax_val;
13054 dst_reg->u32_max_value >>= umin_val;
13056 __mark_reg64_unbounded(dst_reg);
13057 __update_reg32_bounds(dst_reg);
13060 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13061 struct bpf_reg_state *src_reg)
13063 u64 umax_val = src_reg->umax_value;
13064 u64 umin_val = src_reg->umin_value;
13066 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13067 * be negative, then either:
13068 * 1) src_reg might be zero, so the sign bit of the result is
13069 * unknown, so we lose our signed bounds
13070 * 2) it's known negative, thus the unsigned bounds capture the
13072 * 3) the signed bounds cross zero, so they tell us nothing
13074 * If the value in dst_reg is known nonnegative, then again the
13075 * unsigned bounds capture the signed bounds.
13076 * Thus, in all cases it suffices to blow away our signed bounds
13077 * and rely on inferring new ones from the unsigned bounds and
13078 * var_off of the result.
13080 dst_reg->smin_value = S64_MIN;
13081 dst_reg->smax_value = S64_MAX;
13082 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13083 dst_reg->umin_value >>= umax_val;
13084 dst_reg->umax_value >>= umin_val;
13086 /* Its not easy to operate on alu32 bounds here because it depends
13087 * on bits being shifted in. Take easy way out and mark unbounded
13088 * so we can recalculate later from tnum.
13090 __mark_reg32_unbounded(dst_reg);
13091 __update_reg_bounds(dst_reg);
13094 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13095 struct bpf_reg_state *src_reg)
13097 u64 umin_val = src_reg->u32_min_value;
13099 /* Upon reaching here, src_known is true and
13100 * umax_val is equal to umin_val.
13102 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13103 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13105 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13107 /* blow away the dst_reg umin_value/umax_value and rely on
13108 * dst_reg var_off to refine the result.
13110 dst_reg->u32_min_value = 0;
13111 dst_reg->u32_max_value = U32_MAX;
13113 __mark_reg64_unbounded(dst_reg);
13114 __update_reg32_bounds(dst_reg);
13117 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13118 struct bpf_reg_state *src_reg)
13120 u64 umin_val = src_reg->umin_value;
13122 /* Upon reaching here, src_known is true and umax_val is equal
13125 dst_reg->smin_value >>= umin_val;
13126 dst_reg->smax_value >>= umin_val;
13128 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13130 /* blow away the dst_reg umin_value/umax_value and rely on
13131 * dst_reg var_off to refine the result.
13133 dst_reg->umin_value = 0;
13134 dst_reg->umax_value = U64_MAX;
13136 /* Its not easy to operate on alu32 bounds here because it depends
13137 * on bits being shifted in from upper 32-bits. Take easy way out
13138 * and mark unbounded so we can recalculate later from tnum.
13140 __mark_reg32_unbounded(dst_reg);
13141 __update_reg_bounds(dst_reg);
13144 /* WARNING: This function does calculations on 64-bit values, but the actual
13145 * execution may occur on 32-bit values. Therefore, things like bitshifts
13146 * need extra checks in the 32-bit case.
13148 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13149 struct bpf_insn *insn,
13150 struct bpf_reg_state *dst_reg,
13151 struct bpf_reg_state src_reg)
13153 struct bpf_reg_state *regs = cur_regs(env);
13154 u8 opcode = BPF_OP(insn->code);
13156 s64 smin_val, smax_val;
13157 u64 umin_val, umax_val;
13158 s32 s32_min_val, s32_max_val;
13159 u32 u32_min_val, u32_max_val;
13160 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13161 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13164 smin_val = src_reg.smin_value;
13165 smax_val = src_reg.smax_value;
13166 umin_val = src_reg.umin_value;
13167 umax_val = src_reg.umax_value;
13169 s32_min_val = src_reg.s32_min_value;
13170 s32_max_val = src_reg.s32_max_value;
13171 u32_min_val = src_reg.u32_min_value;
13172 u32_max_val = src_reg.u32_max_value;
13175 src_known = tnum_subreg_is_const(src_reg.var_off);
13177 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13178 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13179 /* Taint dst register if offset had invalid bounds
13180 * derived from e.g. dead branches.
13182 __mark_reg_unknown(env, dst_reg);
13186 src_known = tnum_is_const(src_reg.var_off);
13188 (smin_val != smax_val || umin_val != umax_val)) ||
13189 smin_val > smax_val || umin_val > umax_val) {
13190 /* Taint dst register if offset had invalid bounds
13191 * derived from e.g. dead branches.
13193 __mark_reg_unknown(env, dst_reg);
13199 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13200 __mark_reg_unknown(env, dst_reg);
13204 if (sanitize_needed(opcode)) {
13205 ret = sanitize_val_alu(env, insn);
13207 return sanitize_err(env, insn, ret, NULL, NULL);
13210 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13211 * There are two classes of instructions: The first class we track both
13212 * alu32 and alu64 sign/unsigned bounds independently this provides the
13213 * greatest amount of precision when alu operations are mixed with jmp32
13214 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13215 * and BPF_OR. This is possible because these ops have fairly easy to
13216 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13217 * See alu32 verifier tests for examples. The second class of
13218 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13219 * with regards to tracking sign/unsigned bounds because the bits may
13220 * cross subreg boundaries in the alu64 case. When this happens we mark
13221 * the reg unbounded in the subreg bound space and use the resulting
13222 * tnum to calculate an approximation of the sign/unsigned bounds.
13226 scalar32_min_max_add(dst_reg, &src_reg);
13227 scalar_min_max_add(dst_reg, &src_reg);
13228 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13231 scalar32_min_max_sub(dst_reg, &src_reg);
13232 scalar_min_max_sub(dst_reg, &src_reg);
13233 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13236 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13237 scalar32_min_max_mul(dst_reg, &src_reg);
13238 scalar_min_max_mul(dst_reg, &src_reg);
13241 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13242 scalar32_min_max_and(dst_reg, &src_reg);
13243 scalar_min_max_and(dst_reg, &src_reg);
13246 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13247 scalar32_min_max_or(dst_reg, &src_reg);
13248 scalar_min_max_or(dst_reg, &src_reg);
13251 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13252 scalar32_min_max_xor(dst_reg, &src_reg);
13253 scalar_min_max_xor(dst_reg, &src_reg);
13256 if (umax_val >= insn_bitness) {
13257 /* Shifts greater than 31 or 63 are undefined.
13258 * This includes shifts by a negative number.
13260 mark_reg_unknown(env, regs, insn->dst_reg);
13264 scalar32_min_max_lsh(dst_reg, &src_reg);
13266 scalar_min_max_lsh(dst_reg, &src_reg);
13269 if (umax_val >= insn_bitness) {
13270 /* Shifts greater than 31 or 63 are undefined.
13271 * This includes shifts by a negative number.
13273 mark_reg_unknown(env, regs, insn->dst_reg);
13277 scalar32_min_max_rsh(dst_reg, &src_reg);
13279 scalar_min_max_rsh(dst_reg, &src_reg);
13282 if (umax_val >= insn_bitness) {
13283 /* Shifts greater than 31 or 63 are undefined.
13284 * This includes shifts by a negative number.
13286 mark_reg_unknown(env, regs, insn->dst_reg);
13290 scalar32_min_max_arsh(dst_reg, &src_reg);
13292 scalar_min_max_arsh(dst_reg, &src_reg);
13295 mark_reg_unknown(env, regs, insn->dst_reg);
13299 /* ALU32 ops are zero extended into 64bit register */
13301 zext_32_to_64(dst_reg);
13302 reg_bounds_sync(dst_reg);
13306 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13309 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13310 struct bpf_insn *insn)
13312 struct bpf_verifier_state *vstate = env->cur_state;
13313 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13314 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13315 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13316 u8 opcode = BPF_OP(insn->code);
13319 dst_reg = ®s[insn->dst_reg];
13321 if (dst_reg->type != SCALAR_VALUE)
13324 /* Make sure ID is cleared otherwise dst_reg min/max could be
13325 * incorrectly propagated into other registers by find_equal_scalars()
13328 if (BPF_SRC(insn->code) == BPF_X) {
13329 src_reg = ®s[insn->src_reg];
13330 if (src_reg->type != SCALAR_VALUE) {
13331 if (dst_reg->type != SCALAR_VALUE) {
13332 /* Combining two pointers by any ALU op yields
13333 * an arbitrary scalar. Disallow all math except
13334 * pointer subtraction
13336 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13337 mark_reg_unknown(env, regs, insn->dst_reg);
13340 verbose(env, "R%d pointer %s pointer prohibited\n",
13342 bpf_alu_string[opcode >> 4]);
13345 /* scalar += pointer
13346 * This is legal, but we have to reverse our
13347 * src/dest handling in computing the range
13349 err = mark_chain_precision(env, insn->dst_reg);
13352 return adjust_ptr_min_max_vals(env, insn,
13355 } else if (ptr_reg) {
13356 /* pointer += scalar */
13357 err = mark_chain_precision(env, insn->src_reg);
13360 return adjust_ptr_min_max_vals(env, insn,
13362 } else if (dst_reg->precise) {
13363 /* if dst_reg is precise, src_reg should be precise as well */
13364 err = mark_chain_precision(env, insn->src_reg);
13369 /* Pretend the src is a reg with a known value, since we only
13370 * need to be able to read from this state.
13372 off_reg.type = SCALAR_VALUE;
13373 __mark_reg_known(&off_reg, insn->imm);
13374 src_reg = &off_reg;
13375 if (ptr_reg) /* pointer += K */
13376 return adjust_ptr_min_max_vals(env, insn,
13380 /* Got here implies adding two SCALAR_VALUEs */
13381 if (WARN_ON_ONCE(ptr_reg)) {
13382 print_verifier_state(env, state, true);
13383 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13386 if (WARN_ON(!src_reg)) {
13387 print_verifier_state(env, state, true);
13388 verbose(env, "verifier internal error: no src_reg\n");
13391 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13394 /* check validity of 32-bit and 64-bit arithmetic operations */
13395 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13397 struct bpf_reg_state *regs = cur_regs(env);
13398 u8 opcode = BPF_OP(insn->code);
13401 if (opcode == BPF_END || opcode == BPF_NEG) {
13402 if (opcode == BPF_NEG) {
13403 if (BPF_SRC(insn->code) != BPF_K ||
13404 insn->src_reg != BPF_REG_0 ||
13405 insn->off != 0 || insn->imm != 0) {
13406 verbose(env, "BPF_NEG uses reserved fields\n");
13410 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13411 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13412 (BPF_CLASS(insn->code) == BPF_ALU64 &&
13413 BPF_SRC(insn->code) != BPF_TO_LE)) {
13414 verbose(env, "BPF_END uses reserved fields\n");
13419 /* check src operand */
13420 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13424 if (is_pointer_value(env, insn->dst_reg)) {
13425 verbose(env, "R%d pointer arithmetic prohibited\n",
13430 /* check dest operand */
13431 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13435 } else if (opcode == BPF_MOV) {
13437 if (BPF_SRC(insn->code) == BPF_X) {
13438 if (insn->imm != 0) {
13439 verbose(env, "BPF_MOV uses reserved fields\n");
13443 if (BPF_CLASS(insn->code) == BPF_ALU) {
13444 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13445 verbose(env, "BPF_MOV uses reserved fields\n");
13449 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13451 verbose(env, "BPF_MOV uses reserved fields\n");
13456 /* check src operand */
13457 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13461 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13462 verbose(env, "BPF_MOV uses reserved fields\n");
13467 /* check dest operand, mark as required later */
13468 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13472 if (BPF_SRC(insn->code) == BPF_X) {
13473 struct bpf_reg_state *src_reg = regs + insn->src_reg;
13474 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13475 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13476 !tnum_is_const(src_reg->var_off);
13478 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13479 if (insn->off == 0) {
13481 * copy register state to dest reg
13484 /* Assign src and dst registers the same ID
13485 * that will be used by find_equal_scalars()
13486 * to propagate min/max range.
13488 src_reg->id = ++env->id_gen;
13489 copy_register_state(dst_reg, src_reg);
13490 dst_reg->live |= REG_LIVE_WRITTEN;
13491 dst_reg->subreg_def = DEF_NOT_SUBREG;
13493 /* case: R1 = (s8, s16 s32)R2 */
13494 if (is_pointer_value(env, insn->src_reg)) {
13496 "R%d sign-extension part of pointer\n",
13499 } else if (src_reg->type == SCALAR_VALUE) {
13502 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13503 if (no_sext && need_id)
13504 src_reg->id = ++env->id_gen;
13505 copy_register_state(dst_reg, src_reg);
13508 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13509 dst_reg->live |= REG_LIVE_WRITTEN;
13510 dst_reg->subreg_def = DEF_NOT_SUBREG;
13512 mark_reg_unknown(env, regs, insn->dst_reg);
13516 /* R1 = (u32) R2 */
13517 if (is_pointer_value(env, insn->src_reg)) {
13519 "R%d partial copy of pointer\n",
13522 } else if (src_reg->type == SCALAR_VALUE) {
13523 if (insn->off == 0) {
13524 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13526 if (is_src_reg_u32 && need_id)
13527 src_reg->id = ++env->id_gen;
13528 copy_register_state(dst_reg, src_reg);
13529 /* Make sure ID is cleared if src_reg is not in u32
13530 * range otherwise dst_reg min/max could be incorrectly
13531 * propagated into src_reg by find_equal_scalars()
13533 if (!is_src_reg_u32)
13535 dst_reg->live |= REG_LIVE_WRITTEN;
13536 dst_reg->subreg_def = env->insn_idx + 1;
13538 /* case: W1 = (s8, s16)W2 */
13539 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13541 if (no_sext && need_id)
13542 src_reg->id = ++env->id_gen;
13543 copy_register_state(dst_reg, src_reg);
13546 dst_reg->live |= REG_LIVE_WRITTEN;
13547 dst_reg->subreg_def = env->insn_idx + 1;
13548 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13551 mark_reg_unknown(env, regs,
13554 zext_32_to_64(dst_reg);
13555 reg_bounds_sync(dst_reg);
13559 * remember the value we stored into this reg
13561 /* clear any state __mark_reg_known doesn't set */
13562 mark_reg_unknown(env, regs, insn->dst_reg);
13563 regs[insn->dst_reg].type = SCALAR_VALUE;
13564 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13565 __mark_reg_known(regs + insn->dst_reg,
13568 __mark_reg_known(regs + insn->dst_reg,
13573 } else if (opcode > BPF_END) {
13574 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13577 } else { /* all other ALU ops: and, sub, xor, add, ... */
13579 if (BPF_SRC(insn->code) == BPF_X) {
13580 if (insn->imm != 0 || insn->off > 1 ||
13581 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13582 verbose(env, "BPF_ALU uses reserved fields\n");
13585 /* check src1 operand */
13586 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13590 if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13591 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13592 verbose(env, "BPF_ALU uses reserved fields\n");
13597 /* check src2 operand */
13598 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13602 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13603 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13604 verbose(env, "div by zero\n");
13608 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13609 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13610 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13612 if (insn->imm < 0 || insn->imm >= size) {
13613 verbose(env, "invalid shift %d\n", insn->imm);
13618 /* check dest operand */
13619 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13623 return adjust_reg_min_max_vals(env, insn);
13629 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13630 struct bpf_reg_state *dst_reg,
13631 enum bpf_reg_type type,
13632 bool range_right_open)
13634 struct bpf_func_state *state;
13635 struct bpf_reg_state *reg;
13638 if (dst_reg->off < 0 ||
13639 (dst_reg->off == 0 && range_right_open))
13640 /* This doesn't give us any range */
13643 if (dst_reg->umax_value > MAX_PACKET_OFF ||
13644 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13645 /* Risk of overflow. For instance, ptr + (1<<63) may be less
13646 * than pkt_end, but that's because it's also less than pkt.
13650 new_range = dst_reg->off;
13651 if (range_right_open)
13654 /* Examples for register markings:
13656 * pkt_data in dst register:
13660 * if (r2 > pkt_end) goto <handle exception>
13665 * if (r2 < pkt_end) goto <access okay>
13666 * <handle exception>
13669 * r2 == dst_reg, pkt_end == src_reg
13670 * r2=pkt(id=n,off=8,r=0)
13671 * r3=pkt(id=n,off=0,r=0)
13673 * pkt_data in src register:
13677 * if (pkt_end >= r2) goto <access okay>
13678 * <handle exception>
13682 * if (pkt_end <= r2) goto <handle exception>
13686 * pkt_end == dst_reg, r2 == src_reg
13687 * r2=pkt(id=n,off=8,r=0)
13688 * r3=pkt(id=n,off=0,r=0)
13690 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13691 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13692 * and [r3, r3 + 8-1) respectively is safe to access depending on
13696 /* If our ids match, then we must have the same max_value. And we
13697 * don't care about the other reg's fixed offset, since if it's too big
13698 * the range won't allow anything.
13699 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13701 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13702 if (reg->type == type && reg->id == dst_reg->id)
13703 /* keep the maximum range already checked */
13704 reg->range = max(reg->range, new_range);
13708 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13710 struct tnum subreg = tnum_subreg(reg->var_off);
13711 s32 sval = (s32)val;
13715 if (tnum_is_const(subreg))
13716 return !!tnum_equals_const(subreg, val);
13717 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13721 if (tnum_is_const(subreg))
13722 return !tnum_equals_const(subreg, val);
13723 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13727 if ((~subreg.mask & subreg.value) & val)
13729 if (!((subreg.mask | subreg.value) & val))
13733 if (reg->u32_min_value > val)
13735 else if (reg->u32_max_value <= val)
13739 if (reg->s32_min_value > sval)
13741 else if (reg->s32_max_value <= sval)
13745 if (reg->u32_max_value < val)
13747 else if (reg->u32_min_value >= val)
13751 if (reg->s32_max_value < sval)
13753 else if (reg->s32_min_value >= sval)
13757 if (reg->u32_min_value >= val)
13759 else if (reg->u32_max_value < val)
13763 if (reg->s32_min_value >= sval)
13765 else if (reg->s32_max_value < sval)
13769 if (reg->u32_max_value <= val)
13771 else if (reg->u32_min_value > val)
13775 if (reg->s32_max_value <= sval)
13777 else if (reg->s32_min_value > sval)
13786 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13788 s64 sval = (s64)val;
13792 if (tnum_is_const(reg->var_off))
13793 return !!tnum_equals_const(reg->var_off, val);
13794 else if (val < reg->umin_value || val > reg->umax_value)
13798 if (tnum_is_const(reg->var_off))
13799 return !tnum_equals_const(reg->var_off, val);
13800 else if (val < reg->umin_value || val > reg->umax_value)
13804 if ((~reg->var_off.mask & reg->var_off.value) & val)
13806 if (!((reg->var_off.mask | reg->var_off.value) & val))
13810 if (reg->umin_value > val)
13812 else if (reg->umax_value <= val)
13816 if (reg->smin_value > sval)
13818 else if (reg->smax_value <= sval)
13822 if (reg->umax_value < val)
13824 else if (reg->umin_value >= val)
13828 if (reg->smax_value < sval)
13830 else if (reg->smin_value >= sval)
13834 if (reg->umin_value >= val)
13836 else if (reg->umax_value < val)
13840 if (reg->smin_value >= sval)
13842 else if (reg->smax_value < sval)
13846 if (reg->umax_value <= val)
13848 else if (reg->umin_value > val)
13852 if (reg->smax_value <= sval)
13854 else if (reg->smin_value > sval)
13862 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13864 * 1 - branch will be taken and "goto target" will be executed
13865 * 0 - branch will not be taken and fall-through to next insn
13866 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13869 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13872 if (__is_pointer_value(false, reg)) {
13873 if (!reg_not_null(reg))
13876 /* If pointer is valid tests against zero will fail so we can
13877 * use this to direct branch taken.
13893 return is_branch32_taken(reg, val, opcode);
13894 return is_branch64_taken(reg, val, opcode);
13897 static int flip_opcode(u32 opcode)
13899 /* How can we transform "a <op> b" into "b <op> a"? */
13900 static const u8 opcode_flip[16] = {
13901 /* these stay the same */
13902 [BPF_JEQ >> 4] = BPF_JEQ,
13903 [BPF_JNE >> 4] = BPF_JNE,
13904 [BPF_JSET >> 4] = BPF_JSET,
13905 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13906 [BPF_JGE >> 4] = BPF_JLE,
13907 [BPF_JGT >> 4] = BPF_JLT,
13908 [BPF_JLE >> 4] = BPF_JGE,
13909 [BPF_JLT >> 4] = BPF_JGT,
13910 [BPF_JSGE >> 4] = BPF_JSLE,
13911 [BPF_JSGT >> 4] = BPF_JSLT,
13912 [BPF_JSLE >> 4] = BPF_JSGE,
13913 [BPF_JSLT >> 4] = BPF_JSGT
13915 return opcode_flip[opcode >> 4];
13918 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13919 struct bpf_reg_state *src_reg,
13922 struct bpf_reg_state *pkt;
13924 if (src_reg->type == PTR_TO_PACKET_END) {
13926 } else if (dst_reg->type == PTR_TO_PACKET_END) {
13928 opcode = flip_opcode(opcode);
13933 if (pkt->range >= 0)
13938 /* pkt <= pkt_end */
13941 /* pkt > pkt_end */
13942 if (pkt->range == BEYOND_PKT_END)
13943 /* pkt has at last one extra byte beyond pkt_end */
13944 return opcode == BPF_JGT;
13947 /* pkt < pkt_end */
13950 /* pkt >= pkt_end */
13951 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13952 return opcode == BPF_JGE;
13958 /* Adjusts the register min/max values in the case that the dst_reg is the
13959 * variable register that we are working on, and src_reg is a constant or we're
13960 * simply doing a BPF_K check.
13961 * In JEQ/JNE cases we also adjust the var_off values.
13963 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13964 struct bpf_reg_state *false_reg,
13965 u64 val, u32 val32,
13966 u8 opcode, bool is_jmp32)
13968 struct tnum false_32off = tnum_subreg(false_reg->var_off);
13969 struct tnum false_64off = false_reg->var_off;
13970 struct tnum true_32off = tnum_subreg(true_reg->var_off);
13971 struct tnum true_64off = true_reg->var_off;
13972 s64 sval = (s64)val;
13973 s32 sval32 = (s32)val32;
13975 /* If the dst_reg is a pointer, we can't learn anything about its
13976 * variable offset from the compare (unless src_reg were a pointer into
13977 * the same object, but we don't bother with that.
13978 * Since false_reg and true_reg have the same type by construction, we
13979 * only need to check one of them for pointerness.
13981 if (__is_pointer_value(false, false_reg))
13985 /* JEQ/JNE comparison doesn't change the register equivalence.
13988 * if (r1 == 42) goto label;
13990 * label: // here both r1 and r2 are known to be 42.
13992 * Hence when marking register as known preserve it's ID.
13996 __mark_reg32_known(true_reg, val32);
13997 true_32off = tnum_subreg(true_reg->var_off);
13999 ___mark_reg_known(true_reg, val);
14000 true_64off = true_reg->var_off;
14005 __mark_reg32_known(false_reg, val32);
14006 false_32off = tnum_subreg(false_reg->var_off);
14008 ___mark_reg_known(false_reg, val);
14009 false_64off = false_reg->var_off;
14014 false_32off = tnum_and(false_32off, tnum_const(~val32));
14015 if (is_power_of_2(val32))
14016 true_32off = tnum_or(true_32off,
14017 tnum_const(val32));
14019 false_64off = tnum_and(false_64off, tnum_const(~val));
14020 if (is_power_of_2(val))
14021 true_64off = tnum_or(true_64off,
14029 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
14030 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14032 false_reg->u32_max_value = min(false_reg->u32_max_value,
14034 true_reg->u32_min_value = max(true_reg->u32_min_value,
14037 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
14038 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14040 false_reg->umax_value = min(false_reg->umax_value, false_umax);
14041 true_reg->umin_value = max(true_reg->umin_value, true_umin);
14049 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
14050 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14052 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14053 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14055 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
14056 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14058 false_reg->smax_value = min(false_reg->smax_value, false_smax);
14059 true_reg->smin_value = max(true_reg->smin_value, true_smin);
14067 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
14068 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14070 false_reg->u32_min_value = max(false_reg->u32_min_value,
14072 true_reg->u32_max_value = min(true_reg->u32_max_value,
14075 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
14076 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14078 false_reg->umin_value = max(false_reg->umin_value, false_umin);
14079 true_reg->umax_value = min(true_reg->umax_value, true_umax);
14087 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
14088 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14090 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14091 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14093 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
14094 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14096 false_reg->smin_value = max(false_reg->smin_value, false_smin);
14097 true_reg->smax_value = min(true_reg->smax_value, true_smax);
14106 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14107 tnum_subreg(false_32off));
14108 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14109 tnum_subreg(true_32off));
14110 __reg_combine_32_into_64(false_reg);
14111 __reg_combine_32_into_64(true_reg);
14113 false_reg->var_off = false_64off;
14114 true_reg->var_off = true_64off;
14115 __reg_combine_64_into_32(false_reg);
14116 __reg_combine_64_into_32(true_reg);
14120 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14121 * the variable reg.
14123 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14124 struct bpf_reg_state *false_reg,
14125 u64 val, u32 val32,
14126 u8 opcode, bool is_jmp32)
14128 opcode = flip_opcode(opcode);
14129 /* This uses zero as "not present in table"; luckily the zero opcode,
14130 * BPF_JA, can't get here.
14133 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14136 /* Regs are known to be equal, so intersect their min/max/var_off */
14137 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14138 struct bpf_reg_state *dst_reg)
14140 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14141 dst_reg->umin_value);
14142 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14143 dst_reg->umax_value);
14144 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14145 dst_reg->smin_value);
14146 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14147 dst_reg->smax_value);
14148 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14150 reg_bounds_sync(src_reg);
14151 reg_bounds_sync(dst_reg);
14154 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14155 struct bpf_reg_state *true_dst,
14156 struct bpf_reg_state *false_src,
14157 struct bpf_reg_state *false_dst,
14162 __reg_combine_min_max(true_src, true_dst);
14165 __reg_combine_min_max(false_src, false_dst);
14170 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14171 struct bpf_reg_state *reg, u32 id,
14174 if (type_may_be_null(reg->type) && reg->id == id &&
14175 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14176 /* Old offset (both fixed and variable parts) should have been
14177 * known-zero, because we don't allow pointer arithmetic on
14178 * pointers that might be NULL. If we see this happening, don't
14179 * convert the register.
14181 * But in some cases, some helpers that return local kptrs
14182 * advance offset for the returned pointer. In those cases, it
14183 * is fine to expect to see reg->off.
14185 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14187 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14188 WARN_ON_ONCE(reg->off))
14192 reg->type = SCALAR_VALUE;
14193 /* We don't need id and ref_obj_id from this point
14194 * onwards anymore, thus we should better reset it,
14195 * so that state pruning has chances to take effect.
14198 reg->ref_obj_id = 0;
14203 mark_ptr_not_null_reg(reg);
14205 if (!reg_may_point_to_spin_lock(reg)) {
14206 /* For not-NULL ptr, reg->ref_obj_id will be reset
14207 * in release_reference().
14209 * reg->id is still used by spin_lock ptr. Other
14210 * than spin_lock ptr type, reg->id can be reset.
14217 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14218 * be folded together at some point.
14220 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14223 struct bpf_func_state *state = vstate->frame[vstate->curframe];
14224 struct bpf_reg_state *regs = state->regs, *reg;
14225 u32 ref_obj_id = regs[regno].ref_obj_id;
14226 u32 id = regs[regno].id;
14228 if (ref_obj_id && ref_obj_id == id && is_null)
14229 /* regs[regno] is in the " == NULL" branch.
14230 * No one could have freed the reference state before
14231 * doing the NULL check.
14233 WARN_ON_ONCE(release_reference_state(state, id));
14235 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14236 mark_ptr_or_null_reg(state, reg, id, is_null);
14240 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14241 struct bpf_reg_state *dst_reg,
14242 struct bpf_reg_state *src_reg,
14243 struct bpf_verifier_state *this_branch,
14244 struct bpf_verifier_state *other_branch)
14246 if (BPF_SRC(insn->code) != BPF_X)
14249 /* Pointers are always 64-bit. */
14250 if (BPF_CLASS(insn->code) == BPF_JMP32)
14253 switch (BPF_OP(insn->code)) {
14255 if ((dst_reg->type == PTR_TO_PACKET &&
14256 src_reg->type == PTR_TO_PACKET_END) ||
14257 (dst_reg->type == PTR_TO_PACKET_META &&
14258 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14259 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14260 find_good_pkt_pointers(this_branch, dst_reg,
14261 dst_reg->type, false);
14262 mark_pkt_end(other_branch, insn->dst_reg, true);
14263 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14264 src_reg->type == PTR_TO_PACKET) ||
14265 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14266 src_reg->type == PTR_TO_PACKET_META)) {
14267 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
14268 find_good_pkt_pointers(other_branch, src_reg,
14269 src_reg->type, true);
14270 mark_pkt_end(this_branch, insn->src_reg, false);
14276 if ((dst_reg->type == PTR_TO_PACKET &&
14277 src_reg->type == PTR_TO_PACKET_END) ||
14278 (dst_reg->type == PTR_TO_PACKET_META &&
14279 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14280 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14281 find_good_pkt_pointers(other_branch, dst_reg,
14282 dst_reg->type, true);
14283 mark_pkt_end(this_branch, insn->dst_reg, false);
14284 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14285 src_reg->type == PTR_TO_PACKET) ||
14286 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14287 src_reg->type == PTR_TO_PACKET_META)) {
14288 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
14289 find_good_pkt_pointers(this_branch, src_reg,
14290 src_reg->type, false);
14291 mark_pkt_end(other_branch, insn->src_reg, true);
14297 if ((dst_reg->type == PTR_TO_PACKET &&
14298 src_reg->type == PTR_TO_PACKET_END) ||
14299 (dst_reg->type == PTR_TO_PACKET_META &&
14300 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14301 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14302 find_good_pkt_pointers(this_branch, dst_reg,
14303 dst_reg->type, true);
14304 mark_pkt_end(other_branch, insn->dst_reg, false);
14305 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14306 src_reg->type == PTR_TO_PACKET) ||
14307 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14308 src_reg->type == PTR_TO_PACKET_META)) {
14309 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14310 find_good_pkt_pointers(other_branch, src_reg,
14311 src_reg->type, false);
14312 mark_pkt_end(this_branch, insn->src_reg, true);
14318 if ((dst_reg->type == PTR_TO_PACKET &&
14319 src_reg->type == PTR_TO_PACKET_END) ||
14320 (dst_reg->type == PTR_TO_PACKET_META &&
14321 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14322 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14323 find_good_pkt_pointers(other_branch, dst_reg,
14324 dst_reg->type, false);
14325 mark_pkt_end(this_branch, insn->dst_reg, true);
14326 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14327 src_reg->type == PTR_TO_PACKET) ||
14328 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14329 src_reg->type == PTR_TO_PACKET_META)) {
14330 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14331 find_good_pkt_pointers(this_branch, src_reg,
14332 src_reg->type, true);
14333 mark_pkt_end(other_branch, insn->src_reg, false);
14345 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14346 struct bpf_reg_state *known_reg)
14348 struct bpf_func_state *state;
14349 struct bpf_reg_state *reg;
14351 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14352 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14353 copy_register_state(reg, known_reg);
14357 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14358 struct bpf_insn *insn, int *insn_idx)
14360 struct bpf_verifier_state *this_branch = env->cur_state;
14361 struct bpf_verifier_state *other_branch;
14362 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14363 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14364 struct bpf_reg_state *eq_branch_regs;
14365 u8 opcode = BPF_OP(insn->code);
14370 /* Only conditional jumps are expected to reach here. */
14371 if (opcode == BPF_JA || opcode > BPF_JSLE) {
14372 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14376 /* check src2 operand */
14377 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14381 dst_reg = ®s[insn->dst_reg];
14382 if (BPF_SRC(insn->code) == BPF_X) {
14383 if (insn->imm != 0) {
14384 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14388 /* check src1 operand */
14389 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14393 src_reg = ®s[insn->src_reg];
14394 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14395 is_pointer_value(env, insn->src_reg)) {
14396 verbose(env, "R%d pointer comparison prohibited\n",
14401 if (insn->src_reg != BPF_REG_0) {
14402 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14407 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14409 if (BPF_SRC(insn->code) == BPF_K) {
14410 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14411 } else if (src_reg->type == SCALAR_VALUE &&
14412 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14413 pred = is_branch_taken(dst_reg,
14414 tnum_subreg(src_reg->var_off).value,
14417 } else if (src_reg->type == SCALAR_VALUE &&
14418 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14419 pred = is_branch_taken(dst_reg,
14420 src_reg->var_off.value,
14423 } else if (dst_reg->type == SCALAR_VALUE &&
14424 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14425 pred = is_branch_taken(src_reg,
14426 tnum_subreg(dst_reg->var_off).value,
14427 flip_opcode(opcode),
14429 } else if (dst_reg->type == SCALAR_VALUE &&
14430 !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14431 pred = is_branch_taken(src_reg,
14432 dst_reg->var_off.value,
14433 flip_opcode(opcode),
14435 } else if (reg_is_pkt_pointer_any(dst_reg) &&
14436 reg_is_pkt_pointer_any(src_reg) &&
14438 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14442 /* If we get here with a dst_reg pointer type it is because
14443 * above is_branch_taken() special cased the 0 comparison.
14445 if (!__is_pointer_value(false, dst_reg))
14446 err = mark_chain_precision(env, insn->dst_reg);
14447 if (BPF_SRC(insn->code) == BPF_X && !err &&
14448 !__is_pointer_value(false, src_reg))
14449 err = mark_chain_precision(env, insn->src_reg);
14455 /* Only follow the goto, ignore fall-through. If needed, push
14456 * the fall-through branch for simulation under speculative
14459 if (!env->bypass_spec_v1 &&
14460 !sanitize_speculative_path(env, insn, *insn_idx + 1,
14463 if (env->log.level & BPF_LOG_LEVEL)
14464 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14465 *insn_idx += insn->off;
14467 } else if (pred == 0) {
14468 /* Only follow the fall-through branch, since that's where the
14469 * program will go. If needed, push the goto branch for
14470 * simulation under speculative execution.
14472 if (!env->bypass_spec_v1 &&
14473 !sanitize_speculative_path(env, insn,
14474 *insn_idx + insn->off + 1,
14477 if (env->log.level & BPF_LOG_LEVEL)
14478 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14482 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14486 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14488 /* detect if we are comparing against a constant value so we can adjust
14489 * our min/max values for our dst register.
14490 * this is only legit if both are scalars (or pointers to the same
14491 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14492 * because otherwise the different base pointers mean the offsets aren't
14495 if (BPF_SRC(insn->code) == BPF_X) {
14496 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
14498 if (dst_reg->type == SCALAR_VALUE &&
14499 src_reg->type == SCALAR_VALUE) {
14500 if (tnum_is_const(src_reg->var_off) ||
14502 tnum_is_const(tnum_subreg(src_reg->var_off))))
14503 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14505 src_reg->var_off.value,
14506 tnum_subreg(src_reg->var_off).value,
14508 else if (tnum_is_const(dst_reg->var_off) ||
14510 tnum_is_const(tnum_subreg(dst_reg->var_off))))
14511 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14513 dst_reg->var_off.value,
14514 tnum_subreg(dst_reg->var_off).value,
14516 else if (!is_jmp32 &&
14517 (opcode == BPF_JEQ || opcode == BPF_JNE))
14518 /* Comparing for equality, we can combine knowledge */
14519 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14520 &other_branch_regs[insn->dst_reg],
14521 src_reg, dst_reg, opcode);
14523 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14524 find_equal_scalars(this_branch, src_reg);
14525 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14529 } else if (dst_reg->type == SCALAR_VALUE) {
14530 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14531 dst_reg, insn->imm, (u32)insn->imm,
14535 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14536 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14537 find_equal_scalars(this_branch, dst_reg);
14538 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14541 /* if one pointer register is compared to another pointer
14542 * register check if PTR_MAYBE_NULL could be lifted.
14543 * E.g. register A - maybe null
14544 * register B - not null
14545 * for JNE A, B, ... - A is not null in the false branch;
14546 * for JEQ A, B, ... - A is not null in the true branch.
14548 * Since PTR_TO_BTF_ID points to a kernel struct that does
14549 * not need to be null checked by the BPF program, i.e.,
14550 * could be null even without PTR_MAYBE_NULL marking, so
14551 * only propagate nullness when neither reg is that type.
14553 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14554 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14555 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14556 base_type(src_reg->type) != PTR_TO_BTF_ID &&
14557 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14558 eq_branch_regs = NULL;
14561 eq_branch_regs = other_branch_regs;
14564 eq_branch_regs = regs;
14570 if (eq_branch_regs) {
14571 if (type_may_be_null(src_reg->type))
14572 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14574 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14578 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14579 * NOTE: these optimizations below are related with pointer comparison
14580 * which will never be JMP32.
14582 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14583 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14584 type_may_be_null(dst_reg->type)) {
14585 /* Mark all identical registers in each branch as either
14586 * safe or unknown depending R == 0 or R != 0 conditional.
14588 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14589 opcode == BPF_JNE);
14590 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14591 opcode == BPF_JEQ);
14592 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
14593 this_branch, other_branch) &&
14594 is_pointer_value(env, insn->dst_reg)) {
14595 verbose(env, "R%d pointer comparison prohibited\n",
14599 if (env->log.level & BPF_LOG_LEVEL)
14600 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14604 /* verify BPF_LD_IMM64 instruction */
14605 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14607 struct bpf_insn_aux_data *aux = cur_aux(env);
14608 struct bpf_reg_state *regs = cur_regs(env);
14609 struct bpf_reg_state *dst_reg;
14610 struct bpf_map *map;
14613 if (BPF_SIZE(insn->code) != BPF_DW) {
14614 verbose(env, "invalid BPF_LD_IMM insn\n");
14617 if (insn->off != 0) {
14618 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14622 err = check_reg_arg(env, insn->dst_reg, DST_OP);
14626 dst_reg = ®s[insn->dst_reg];
14627 if (insn->src_reg == 0) {
14628 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14630 dst_reg->type = SCALAR_VALUE;
14631 __mark_reg_known(®s[insn->dst_reg], imm);
14635 /* All special src_reg cases are listed below. From this point onwards
14636 * we either succeed and assign a corresponding dst_reg->type after
14637 * zeroing the offset, or fail and reject the program.
14639 mark_reg_known_zero(env, regs, insn->dst_reg);
14641 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14642 dst_reg->type = aux->btf_var.reg_type;
14643 switch (base_type(dst_reg->type)) {
14645 dst_reg->mem_size = aux->btf_var.mem_size;
14647 case PTR_TO_BTF_ID:
14648 dst_reg->btf = aux->btf_var.btf;
14649 dst_reg->btf_id = aux->btf_var.btf_id;
14652 verbose(env, "bpf verifier is misconfigured\n");
14658 if (insn->src_reg == BPF_PSEUDO_FUNC) {
14659 struct bpf_prog_aux *aux = env->prog->aux;
14660 u32 subprogno = find_subprog(env,
14661 env->insn_idx + insn->imm + 1);
14663 if (!aux->func_info) {
14664 verbose(env, "missing btf func_info\n");
14667 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14668 verbose(env, "callback function not static\n");
14672 dst_reg->type = PTR_TO_FUNC;
14673 dst_reg->subprogno = subprogno;
14677 map = env->used_maps[aux->map_index];
14678 dst_reg->map_ptr = map;
14680 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14681 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14682 dst_reg->type = PTR_TO_MAP_VALUE;
14683 dst_reg->off = aux->map_off;
14684 WARN_ON_ONCE(map->max_entries != 1);
14685 /* We want reg->id to be same (0) as map_value is not distinct */
14686 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14687 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14688 dst_reg->type = CONST_PTR_TO_MAP;
14690 verbose(env, "bpf verifier is misconfigured\n");
14697 static bool may_access_skb(enum bpf_prog_type type)
14700 case BPF_PROG_TYPE_SOCKET_FILTER:
14701 case BPF_PROG_TYPE_SCHED_CLS:
14702 case BPF_PROG_TYPE_SCHED_ACT:
14709 /* verify safety of LD_ABS|LD_IND instructions:
14710 * - they can only appear in the programs where ctx == skb
14711 * - since they are wrappers of function calls, they scratch R1-R5 registers,
14712 * preserve R6-R9, and store return value into R0
14715 * ctx == skb == R6 == CTX
14718 * SRC == any register
14719 * IMM == 32-bit immediate
14722 * R0 - 8/16/32-bit skb data converted to cpu endianness
14724 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14726 struct bpf_reg_state *regs = cur_regs(env);
14727 static const int ctx_reg = BPF_REG_6;
14728 u8 mode = BPF_MODE(insn->code);
14731 if (!may_access_skb(resolve_prog_type(env->prog))) {
14732 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14736 if (!env->ops->gen_ld_abs) {
14737 verbose(env, "bpf verifier is misconfigured\n");
14741 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14742 BPF_SIZE(insn->code) == BPF_DW ||
14743 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14744 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14748 /* check whether implicit source operand (register R6) is readable */
14749 err = check_reg_arg(env, ctx_reg, SRC_OP);
14753 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14754 * gen_ld_abs() may terminate the program at runtime, leading to
14757 err = check_reference_leak(env);
14759 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14763 if (env->cur_state->active_lock.ptr) {
14764 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14768 if (env->cur_state->active_rcu_lock) {
14769 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14773 if (regs[ctx_reg].type != PTR_TO_CTX) {
14775 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14779 if (mode == BPF_IND) {
14780 /* check explicit source operand */
14781 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14786 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
14790 /* reset caller saved regs to unreadable */
14791 for (i = 0; i < CALLER_SAVED_REGS; i++) {
14792 mark_reg_not_init(env, regs, caller_saved[i]);
14793 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14796 /* mark destination R0 register as readable, since it contains
14797 * the value fetched from the packet.
14798 * Already marked as written above.
14800 mark_reg_unknown(env, regs, BPF_REG_0);
14801 /* ld_abs load up to 32-bit skb data. */
14802 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14806 static int check_return_code(struct bpf_verifier_env *env)
14808 struct tnum enforce_attach_type_range = tnum_unknown;
14809 const struct bpf_prog *prog = env->prog;
14810 struct bpf_reg_state *reg;
14811 struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14812 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14814 struct bpf_func_state *frame = env->cur_state->frame[0];
14815 const bool is_subprog = frame->subprogno;
14817 /* LSM and struct_ops func-ptr's return type could be "void" */
14819 switch (prog_type) {
14820 case BPF_PROG_TYPE_LSM:
14821 if (prog->expected_attach_type == BPF_LSM_CGROUP)
14822 /* See below, can be 0 or 0-1 depending on hook. */
14825 case BPF_PROG_TYPE_STRUCT_OPS:
14826 if (!prog->aux->attach_func_proto->type)
14834 /* eBPF calling convention is such that R0 is used
14835 * to return the value from eBPF program.
14836 * Make sure that it's readable at this time
14837 * of bpf_exit, which means that program wrote
14838 * something into it earlier
14840 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14844 if (is_pointer_value(env, BPF_REG_0)) {
14845 verbose(env, "R0 leaks addr as return value\n");
14849 reg = cur_regs(env) + BPF_REG_0;
14851 if (frame->in_async_callback_fn) {
14852 /* enforce return zero from async callbacks like timer */
14853 if (reg->type != SCALAR_VALUE) {
14854 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14855 reg_type_str(env, reg->type));
14859 if (!tnum_in(const_0, reg->var_off)) {
14860 verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14867 if (reg->type != SCALAR_VALUE) {
14868 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14869 reg_type_str(env, reg->type));
14875 switch (prog_type) {
14876 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14877 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14878 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14879 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14880 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14881 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14882 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14883 range = tnum_range(1, 1);
14884 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14885 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14886 range = tnum_range(0, 3);
14888 case BPF_PROG_TYPE_CGROUP_SKB:
14889 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14890 range = tnum_range(0, 3);
14891 enforce_attach_type_range = tnum_range(2, 3);
14894 case BPF_PROG_TYPE_CGROUP_SOCK:
14895 case BPF_PROG_TYPE_SOCK_OPS:
14896 case BPF_PROG_TYPE_CGROUP_DEVICE:
14897 case BPF_PROG_TYPE_CGROUP_SYSCTL:
14898 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14900 case BPF_PROG_TYPE_RAW_TRACEPOINT:
14901 if (!env->prog->aux->attach_btf_id)
14903 range = tnum_const(0);
14905 case BPF_PROG_TYPE_TRACING:
14906 switch (env->prog->expected_attach_type) {
14907 case BPF_TRACE_FENTRY:
14908 case BPF_TRACE_FEXIT:
14909 range = tnum_const(0);
14911 case BPF_TRACE_RAW_TP:
14912 case BPF_MODIFY_RETURN:
14914 case BPF_TRACE_ITER:
14920 case BPF_PROG_TYPE_SK_LOOKUP:
14921 range = tnum_range(SK_DROP, SK_PASS);
14924 case BPF_PROG_TYPE_LSM:
14925 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14926 /* Regular BPF_PROG_TYPE_LSM programs can return
14931 if (!env->prog->aux->attach_func_proto->type) {
14932 /* Make sure programs that attach to void
14933 * hooks don't try to modify return value.
14935 range = tnum_range(1, 1);
14939 case BPF_PROG_TYPE_NETFILTER:
14940 range = tnum_range(NF_DROP, NF_ACCEPT);
14942 case BPF_PROG_TYPE_EXT:
14943 /* freplace program can return anything as its return value
14944 * depends on the to-be-replaced kernel func or bpf program.
14950 if (reg->type != SCALAR_VALUE) {
14951 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14952 reg_type_str(env, reg->type));
14956 if (!tnum_in(range, reg->var_off)) {
14957 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14958 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14959 prog_type == BPF_PROG_TYPE_LSM &&
14960 !prog->aux->attach_func_proto->type)
14961 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14965 if (!tnum_is_unknown(enforce_attach_type_range) &&
14966 tnum_in(enforce_attach_type_range, reg->var_off))
14967 env->prog->enforce_expected_attach_type = 1;
14971 /* non-recursive DFS pseudo code
14972 * 1 procedure DFS-iterative(G,v):
14973 * 2 label v as discovered
14974 * 3 let S be a stack
14976 * 5 while S is not empty
14978 * 7 if t is what we're looking for:
14980 * 9 for all edges e in G.adjacentEdges(t) do
14981 * 10 if edge e is already labelled
14982 * 11 continue with the next edge
14983 * 12 w <- G.adjacentVertex(t,e)
14984 * 13 if vertex w is not discovered and not explored
14985 * 14 label e as tree-edge
14986 * 15 label w as discovered
14989 * 18 else if vertex w is discovered
14990 * 19 label e as back-edge
14992 * 21 // vertex w is explored
14993 * 22 label e as forward- or cross-edge
14994 * 23 label t as explored
14998 * 0x10 - discovered
14999 * 0x11 - discovered and fall-through edge labelled
15000 * 0x12 - discovered and fall-through and branch edges labelled
15011 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15013 env->insn_aux_data[idx].prune_point = true;
15016 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15018 return env->insn_aux_data[insn_idx].prune_point;
15021 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15023 env->insn_aux_data[idx].force_checkpoint = true;
15026 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15028 return env->insn_aux_data[insn_idx].force_checkpoint;
15033 DONE_EXPLORING = 0,
15034 KEEP_EXPLORING = 1,
15037 /* t, w, e - match pseudo-code above:
15038 * t - index of current instruction
15039 * w - next instruction
15042 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15044 int *insn_stack = env->cfg.insn_stack;
15045 int *insn_state = env->cfg.insn_state;
15047 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15048 return DONE_EXPLORING;
15050 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15051 return DONE_EXPLORING;
15053 if (w < 0 || w >= env->prog->len) {
15054 verbose_linfo(env, t, "%d: ", t);
15055 verbose(env, "jump out of range from insn %d to %d\n", t, w);
15060 /* mark branch target for state pruning */
15061 mark_prune_point(env, w);
15062 mark_jmp_point(env, w);
15065 if (insn_state[w] == 0) {
15067 insn_state[t] = DISCOVERED | e;
15068 insn_state[w] = DISCOVERED;
15069 if (env->cfg.cur_stack >= env->prog->len)
15071 insn_stack[env->cfg.cur_stack++] = w;
15072 return KEEP_EXPLORING;
15073 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15074 if (env->bpf_capable)
15075 return DONE_EXPLORING;
15076 verbose_linfo(env, t, "%d: ", t);
15077 verbose_linfo(env, w, "%d: ", w);
15078 verbose(env, "back-edge from insn %d to %d\n", t, w);
15080 } else if (insn_state[w] == EXPLORED) {
15081 /* forward- or cross-edge */
15082 insn_state[t] = DISCOVERED | e;
15084 verbose(env, "insn state internal bug\n");
15087 return DONE_EXPLORING;
15090 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15091 struct bpf_verifier_env *env,
15096 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15097 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15101 mark_prune_point(env, t + insn_sz);
15102 /* when we exit from subprog, we need to record non-linear history */
15103 mark_jmp_point(env, t + insn_sz);
15105 if (visit_callee) {
15106 mark_prune_point(env, t);
15107 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15112 /* Visits the instruction at index t and returns one of the following:
15113 * < 0 - an error occurred
15114 * DONE_EXPLORING - the instruction was fully explored
15115 * KEEP_EXPLORING - there is still work to be done before it is fully explored
15117 static int visit_insn(int t, struct bpf_verifier_env *env)
15119 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15120 int ret, off, insn_sz;
15122 if (bpf_pseudo_func(insn))
15123 return visit_func_call_insn(t, insns, env, true);
15125 /* All non-branch instructions have a single fall-through edge. */
15126 if (BPF_CLASS(insn->code) != BPF_JMP &&
15127 BPF_CLASS(insn->code) != BPF_JMP32) {
15128 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15129 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15132 switch (BPF_OP(insn->code)) {
15134 return DONE_EXPLORING;
15137 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15138 /* Mark this call insn as a prune point to trigger
15139 * is_state_visited() check before call itself is
15140 * processed by __check_func_call(). Otherwise new
15141 * async state will be pushed for further exploration.
15143 mark_prune_point(env, t);
15144 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15145 struct bpf_kfunc_call_arg_meta meta;
15147 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15148 if (ret == 0 && is_iter_next_kfunc(&meta)) {
15149 mark_prune_point(env, t);
15150 /* Checking and saving state checkpoints at iter_next() call
15151 * is crucial for fast convergence of open-coded iterator loop
15152 * logic, so we need to force it. If we don't do that,
15153 * is_state_visited() might skip saving a checkpoint, causing
15154 * unnecessarily long sequence of not checkpointed
15155 * instructions and jumps, leading to exhaustion of jump
15156 * history buffer, and potentially other undesired outcomes.
15157 * It is expected that with correct open-coded iterators
15158 * convergence will happen quickly, so we don't run a risk of
15159 * exhausting memory.
15161 mark_force_checkpoint(env, t);
15164 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15167 if (BPF_SRC(insn->code) != BPF_K)
15170 if (BPF_CLASS(insn->code) == BPF_JMP)
15175 /* unconditional jump with single edge */
15176 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15180 mark_prune_point(env, t + off + 1);
15181 mark_jmp_point(env, t + off + 1);
15186 /* conditional jump with two edges */
15187 mark_prune_point(env, t);
15189 ret = push_insn(t, t + 1, FALLTHROUGH, env);
15193 return push_insn(t, t + insn->off + 1, BRANCH, env);
15197 /* non-recursive depth-first-search to detect loops in BPF program
15198 * loop == back-edge in directed graph
15200 static int check_cfg(struct bpf_verifier_env *env)
15202 int insn_cnt = env->prog->len;
15203 int *insn_stack, *insn_state;
15207 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15211 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15213 kvfree(insn_state);
15217 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15218 insn_stack[0] = 0; /* 0 is the first instruction */
15219 env->cfg.cur_stack = 1;
15221 while (env->cfg.cur_stack > 0) {
15222 int t = insn_stack[env->cfg.cur_stack - 1];
15224 ret = visit_insn(t, env);
15226 case DONE_EXPLORING:
15227 insn_state[t] = EXPLORED;
15228 env->cfg.cur_stack--;
15230 case KEEP_EXPLORING:
15234 verbose(env, "visit_insn internal bug\n");
15241 if (env->cfg.cur_stack < 0) {
15242 verbose(env, "pop stack internal bug\n");
15247 for (i = 0; i < insn_cnt; i++) {
15248 struct bpf_insn *insn = &env->prog->insnsi[i];
15250 if (insn_state[i] != EXPLORED) {
15251 verbose(env, "unreachable insn %d\n", i);
15255 if (bpf_is_ldimm64(insn)) {
15256 if (insn_state[i + 1] != 0) {
15257 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15261 i++; /* skip second half of ldimm64 */
15264 ret = 0; /* cfg looks good */
15267 kvfree(insn_state);
15268 kvfree(insn_stack);
15269 env->cfg.insn_state = env->cfg.insn_stack = NULL;
15273 static int check_abnormal_return(struct bpf_verifier_env *env)
15277 for (i = 1; i < env->subprog_cnt; i++) {
15278 if (env->subprog_info[i].has_ld_abs) {
15279 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15282 if (env->subprog_info[i].has_tail_call) {
15283 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15290 /* The minimum supported BTF func info size */
15291 #define MIN_BPF_FUNCINFO_SIZE 8
15292 #define MAX_FUNCINFO_REC_SIZE 252
15294 static int check_btf_func(struct bpf_verifier_env *env,
15295 const union bpf_attr *attr,
15298 const struct btf_type *type, *func_proto, *ret_type;
15299 u32 i, nfuncs, urec_size, min_size;
15300 u32 krec_size = sizeof(struct bpf_func_info);
15301 struct bpf_func_info *krecord;
15302 struct bpf_func_info_aux *info_aux = NULL;
15303 struct bpf_prog *prog;
15304 const struct btf *btf;
15306 u32 prev_offset = 0;
15307 bool scalar_return;
15310 nfuncs = attr->func_info_cnt;
15312 if (check_abnormal_return(env))
15317 if (nfuncs != env->subprog_cnt) {
15318 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15322 urec_size = attr->func_info_rec_size;
15323 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15324 urec_size > MAX_FUNCINFO_REC_SIZE ||
15325 urec_size % sizeof(u32)) {
15326 verbose(env, "invalid func info rec size %u\n", urec_size);
15331 btf = prog->aux->btf;
15333 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15334 min_size = min_t(u32, krec_size, urec_size);
15336 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15339 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15343 for (i = 0; i < nfuncs; i++) {
15344 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15346 if (ret == -E2BIG) {
15347 verbose(env, "nonzero tailing record in func info");
15348 /* set the size kernel expects so loader can zero
15349 * out the rest of the record.
15351 if (copy_to_bpfptr_offset(uattr,
15352 offsetof(union bpf_attr, func_info_rec_size),
15353 &min_size, sizeof(min_size)))
15359 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15364 /* check insn_off */
15367 if (krecord[i].insn_off) {
15369 "nonzero insn_off %u for the first func info record",
15370 krecord[i].insn_off);
15373 } else if (krecord[i].insn_off <= prev_offset) {
15375 "same or smaller insn offset (%u) than previous func info record (%u)",
15376 krecord[i].insn_off, prev_offset);
15380 if (env->subprog_info[i].start != krecord[i].insn_off) {
15381 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15385 /* check type_id */
15386 type = btf_type_by_id(btf, krecord[i].type_id);
15387 if (!type || !btf_type_is_func(type)) {
15388 verbose(env, "invalid type id %d in func info",
15389 krecord[i].type_id);
15392 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15394 func_proto = btf_type_by_id(btf, type->type);
15395 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15396 /* btf_func_check() already verified it during BTF load */
15398 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15400 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15401 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15402 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15405 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15406 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15410 prev_offset = krecord[i].insn_off;
15411 bpfptr_add(&urecord, urec_size);
15414 prog->aux->func_info = krecord;
15415 prog->aux->func_info_cnt = nfuncs;
15416 prog->aux->func_info_aux = info_aux;
15425 static void adjust_btf_func(struct bpf_verifier_env *env)
15427 struct bpf_prog_aux *aux = env->prog->aux;
15430 if (!aux->func_info)
15433 for (i = 0; i < env->subprog_cnt; i++)
15434 aux->func_info[i].insn_off = env->subprog_info[i].start;
15437 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
15438 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
15440 static int check_btf_line(struct bpf_verifier_env *env,
15441 const union bpf_attr *attr,
15444 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15445 struct bpf_subprog_info *sub;
15446 struct bpf_line_info *linfo;
15447 struct bpf_prog *prog;
15448 const struct btf *btf;
15452 nr_linfo = attr->line_info_cnt;
15455 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15458 rec_size = attr->line_info_rec_size;
15459 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15460 rec_size > MAX_LINEINFO_REC_SIZE ||
15461 rec_size & (sizeof(u32) - 1))
15464 /* Need to zero it in case the userspace may
15465 * pass in a smaller bpf_line_info object.
15467 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15468 GFP_KERNEL | __GFP_NOWARN);
15473 btf = prog->aux->btf;
15476 sub = env->subprog_info;
15477 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15478 expected_size = sizeof(struct bpf_line_info);
15479 ncopy = min_t(u32, expected_size, rec_size);
15480 for (i = 0; i < nr_linfo; i++) {
15481 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15483 if (err == -E2BIG) {
15484 verbose(env, "nonzero tailing record in line_info");
15485 if (copy_to_bpfptr_offset(uattr,
15486 offsetof(union bpf_attr, line_info_rec_size),
15487 &expected_size, sizeof(expected_size)))
15493 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15499 * Check insn_off to ensure
15500 * 1) strictly increasing AND
15501 * 2) bounded by prog->len
15503 * The linfo[0].insn_off == 0 check logically falls into
15504 * the later "missing bpf_line_info for func..." case
15505 * because the first linfo[0].insn_off must be the
15506 * first sub also and the first sub must have
15507 * subprog_info[0].start == 0.
15509 if ((i && linfo[i].insn_off <= prev_offset) ||
15510 linfo[i].insn_off >= prog->len) {
15511 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15512 i, linfo[i].insn_off, prev_offset,
15518 if (!prog->insnsi[linfo[i].insn_off].code) {
15520 "Invalid insn code at line_info[%u].insn_off\n",
15526 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15527 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15528 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15533 if (s != env->subprog_cnt) {
15534 if (linfo[i].insn_off == sub[s].start) {
15535 sub[s].linfo_idx = i;
15537 } else if (sub[s].start < linfo[i].insn_off) {
15538 verbose(env, "missing bpf_line_info for func#%u\n", s);
15544 prev_offset = linfo[i].insn_off;
15545 bpfptr_add(&ulinfo, rec_size);
15548 if (s != env->subprog_cnt) {
15549 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15550 env->subprog_cnt - s, s);
15555 prog->aux->linfo = linfo;
15556 prog->aux->nr_linfo = nr_linfo;
15565 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
15566 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
15568 static int check_core_relo(struct bpf_verifier_env *env,
15569 const union bpf_attr *attr,
15572 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15573 struct bpf_core_relo core_relo = {};
15574 struct bpf_prog *prog = env->prog;
15575 const struct btf *btf = prog->aux->btf;
15576 struct bpf_core_ctx ctx = {
15580 bpfptr_t u_core_relo;
15583 nr_core_relo = attr->core_relo_cnt;
15586 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15589 rec_size = attr->core_relo_rec_size;
15590 if (rec_size < MIN_CORE_RELO_SIZE ||
15591 rec_size > MAX_CORE_RELO_SIZE ||
15592 rec_size % sizeof(u32))
15595 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15596 expected_size = sizeof(struct bpf_core_relo);
15597 ncopy = min_t(u32, expected_size, rec_size);
15599 /* Unlike func_info and line_info, copy and apply each CO-RE
15600 * relocation record one at a time.
15602 for (i = 0; i < nr_core_relo; i++) {
15603 /* future proofing when sizeof(bpf_core_relo) changes */
15604 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15606 if (err == -E2BIG) {
15607 verbose(env, "nonzero tailing record in core_relo");
15608 if (copy_to_bpfptr_offset(uattr,
15609 offsetof(union bpf_attr, core_relo_rec_size),
15610 &expected_size, sizeof(expected_size)))
15616 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15621 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15622 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15623 i, core_relo.insn_off, prog->len);
15628 err = bpf_core_apply(&ctx, &core_relo, i,
15629 &prog->insnsi[core_relo.insn_off / 8]);
15632 bpfptr_add(&u_core_relo, rec_size);
15637 static int check_btf_info(struct bpf_verifier_env *env,
15638 const union bpf_attr *attr,
15644 if (!attr->func_info_cnt && !attr->line_info_cnt) {
15645 if (check_abnormal_return(env))
15650 btf = btf_get_by_fd(attr->prog_btf_fd);
15652 return PTR_ERR(btf);
15653 if (btf_is_kernel(btf)) {
15657 env->prog->aux->btf = btf;
15659 err = check_btf_func(env, attr, uattr);
15663 err = check_btf_line(env, attr, uattr);
15667 err = check_core_relo(env, attr, uattr);
15674 /* check %cur's range satisfies %old's */
15675 static bool range_within(struct bpf_reg_state *old,
15676 struct bpf_reg_state *cur)
15678 return old->umin_value <= cur->umin_value &&
15679 old->umax_value >= cur->umax_value &&
15680 old->smin_value <= cur->smin_value &&
15681 old->smax_value >= cur->smax_value &&
15682 old->u32_min_value <= cur->u32_min_value &&
15683 old->u32_max_value >= cur->u32_max_value &&
15684 old->s32_min_value <= cur->s32_min_value &&
15685 old->s32_max_value >= cur->s32_max_value;
15688 /* If in the old state two registers had the same id, then they need to have
15689 * the same id in the new state as well. But that id could be different from
15690 * the old state, so we need to track the mapping from old to new ids.
15691 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15692 * regs with old id 5 must also have new id 9 for the new state to be safe. But
15693 * regs with a different old id could still have new id 9, we don't care about
15695 * So we look through our idmap to see if this old id has been seen before. If
15696 * so, we require the new id to match; otherwise, we add the id pair to the map.
15698 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15700 struct bpf_id_pair *map = idmap->map;
15703 /* either both IDs should be set or both should be zero */
15704 if (!!old_id != !!cur_id)
15707 if (old_id == 0) /* cur_id == 0 as well */
15710 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15712 /* Reached an empty slot; haven't seen this id before */
15713 map[i].old = old_id;
15714 map[i].cur = cur_id;
15717 if (map[i].old == old_id)
15718 return map[i].cur == cur_id;
15719 if (map[i].cur == cur_id)
15722 /* We ran out of idmap slots, which should be impossible */
15727 /* Similar to check_ids(), but allocate a unique temporary ID
15728 * for 'old_id' or 'cur_id' of zero.
15729 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15731 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15733 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15734 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15736 return check_ids(old_id, cur_id, idmap);
15739 static void clean_func_state(struct bpf_verifier_env *env,
15740 struct bpf_func_state *st)
15742 enum bpf_reg_liveness live;
15745 for (i = 0; i < BPF_REG_FP; i++) {
15746 live = st->regs[i].live;
15747 /* liveness must not touch this register anymore */
15748 st->regs[i].live |= REG_LIVE_DONE;
15749 if (!(live & REG_LIVE_READ))
15750 /* since the register is unused, clear its state
15751 * to make further comparison simpler
15753 __mark_reg_not_init(env, &st->regs[i]);
15756 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15757 live = st->stack[i].spilled_ptr.live;
15758 /* liveness must not touch this stack slot anymore */
15759 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15760 if (!(live & REG_LIVE_READ)) {
15761 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15762 for (j = 0; j < BPF_REG_SIZE; j++)
15763 st->stack[i].slot_type[j] = STACK_INVALID;
15768 static void clean_verifier_state(struct bpf_verifier_env *env,
15769 struct bpf_verifier_state *st)
15773 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15774 /* all regs in this state in all frames were already marked */
15777 for (i = 0; i <= st->curframe; i++)
15778 clean_func_state(env, st->frame[i]);
15781 /* the parentage chains form a tree.
15782 * the verifier states are added to state lists at given insn and
15783 * pushed into state stack for future exploration.
15784 * when the verifier reaches bpf_exit insn some of the verifer states
15785 * stored in the state lists have their final liveness state already,
15786 * but a lot of states will get revised from liveness point of view when
15787 * the verifier explores other branches.
15790 * 2: if r1 == 100 goto pc+1
15793 * when the verifier reaches exit insn the register r0 in the state list of
15794 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15795 * of insn 2 and goes exploring further. At the insn 4 it will walk the
15796 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15798 * Since the verifier pushes the branch states as it sees them while exploring
15799 * the program the condition of walking the branch instruction for the second
15800 * time means that all states below this branch were already explored and
15801 * their final liveness marks are already propagated.
15802 * Hence when the verifier completes the search of state list in is_state_visited()
15803 * we can call this clean_live_states() function to mark all liveness states
15804 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15805 * will not be used.
15806 * This function also clears the registers and stack for states that !READ
15807 * to simplify state merging.
15809 * Important note here that walking the same branch instruction in the callee
15810 * doesn't meant that the states are DONE. The verifier has to compare
15813 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15814 struct bpf_verifier_state *cur)
15816 struct bpf_verifier_state_list *sl;
15818 sl = *explored_state(env, insn);
15820 if (sl->state.branches)
15822 if (sl->state.insn_idx != insn ||
15823 !same_callsites(&sl->state, cur))
15825 clean_verifier_state(env, &sl->state);
15831 static bool regs_exact(const struct bpf_reg_state *rold,
15832 const struct bpf_reg_state *rcur,
15833 struct bpf_idmap *idmap)
15835 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15836 check_ids(rold->id, rcur->id, idmap) &&
15837 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15840 /* Returns true if (rold safe implies rcur safe) */
15841 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15842 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
15845 return regs_exact(rold, rcur, idmap);
15847 if (!(rold->live & REG_LIVE_READ))
15848 /* explored state didn't use this */
15850 if (rold->type == NOT_INIT)
15851 /* explored state can't have used this */
15853 if (rcur->type == NOT_INIT)
15856 /* Enforce that register types have to match exactly, including their
15857 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15860 * One can make a point that using a pointer register as unbounded
15861 * SCALAR would be technically acceptable, but this could lead to
15862 * pointer leaks because scalars are allowed to leak while pointers
15863 * are not. We could make this safe in special cases if root is
15864 * calling us, but it's probably not worth the hassle.
15866 * Also, register types that are *not* MAYBE_NULL could technically be
15867 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15868 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15869 * to the same map).
15870 * However, if the old MAYBE_NULL register then got NULL checked,
15871 * doing so could have affected others with the same id, and we can't
15872 * check for that because we lost the id when we converted to
15873 * a non-MAYBE_NULL variant.
15874 * So, as a general rule we don't allow mixing MAYBE_NULL and
15875 * non-MAYBE_NULL registers as well.
15877 if (rold->type != rcur->type)
15880 switch (base_type(rold->type)) {
15882 if (env->explore_alu_limits) {
15883 /* explore_alu_limits disables tnum_in() and range_within()
15884 * logic and requires everything to be strict
15886 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15887 check_scalar_ids(rold->id, rcur->id, idmap);
15889 if (!rold->precise)
15891 /* Why check_ids() for scalar registers?
15893 * Consider the following BPF code:
15894 * 1: r6 = ... unbound scalar, ID=a ...
15895 * 2: r7 = ... unbound scalar, ID=b ...
15896 * 3: if (r6 > r7) goto +1
15898 * 5: if (r6 > X) goto ...
15899 * 6: ... memory operation using r7 ...
15901 * First verification path is [1-6]:
15902 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15903 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15904 * r7 <= X, because r6 and r7 share same id.
15905 * Next verification path is [1-4, 6].
15907 * Instruction (6) would be reached in two states:
15908 * I. r6{.id=b}, r7{.id=b} via path 1-6;
15909 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15911 * Use check_ids() to distinguish these states.
15913 * Also verify that new value satisfies old value range knowledge.
15915 return range_within(rold, rcur) &&
15916 tnum_in(rold->var_off, rcur->var_off) &&
15917 check_scalar_ids(rold->id, rcur->id, idmap);
15918 case PTR_TO_MAP_KEY:
15919 case PTR_TO_MAP_VALUE:
15922 case PTR_TO_TP_BUFFER:
15923 /* If the new min/max/var_off satisfy the old ones and
15924 * everything else matches, we are OK.
15926 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15927 range_within(rold, rcur) &&
15928 tnum_in(rold->var_off, rcur->var_off) &&
15929 check_ids(rold->id, rcur->id, idmap) &&
15930 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15931 case PTR_TO_PACKET_META:
15932 case PTR_TO_PACKET:
15933 /* We must have at least as much range as the old ptr
15934 * did, so that any accesses which were safe before are
15935 * still safe. This is true even if old range < old off,
15936 * since someone could have accessed through (ptr - k), or
15937 * even done ptr -= k in a register, to get a safe access.
15939 if (rold->range > rcur->range)
15941 /* If the offsets don't match, we can't trust our alignment;
15942 * nor can we be sure that we won't fall out of range.
15944 if (rold->off != rcur->off)
15946 /* id relations must be preserved */
15947 if (!check_ids(rold->id, rcur->id, idmap))
15949 /* new val must satisfy old val knowledge */
15950 return range_within(rold, rcur) &&
15951 tnum_in(rold->var_off, rcur->var_off);
15953 /* two stack pointers are equal only if they're pointing to
15954 * the same stack frame, since fp-8 in foo != fp-8 in bar
15956 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15958 return regs_exact(rold, rcur, idmap);
15962 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15963 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
15967 /* walk slots of the explored stack and ignore any additional
15968 * slots in the current stack, since explored(safe) state
15971 for (i = 0; i < old->allocated_stack; i++) {
15972 struct bpf_reg_state *old_reg, *cur_reg;
15974 spi = i / BPF_REG_SIZE;
15977 old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15978 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15981 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
15982 i += BPF_REG_SIZE - 1;
15983 /* explored state didn't use this */
15987 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15990 if (env->allow_uninit_stack &&
15991 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15994 /* explored stack has more populated slots than current stack
15995 * and these slots were used
15997 if (i >= cur->allocated_stack)
16000 /* if old state was safe with misc data in the stack
16001 * it will be safe with zero-initialized stack.
16002 * The opposite is not true
16004 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16005 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16007 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16008 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16009 /* Ex: old explored (safe) state has STACK_SPILL in
16010 * this stack slot, but current has STACK_MISC ->
16011 * this verifier states are not equivalent,
16012 * return false to continue verification of this path
16015 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16017 /* Both old and cur are having same slot_type */
16018 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16020 /* when explored and current stack slot are both storing
16021 * spilled registers, check that stored pointers types
16022 * are the same as well.
16023 * Ex: explored safe path could have stored
16024 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16025 * but current path has stored:
16026 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16027 * such verifier states are not equivalent.
16028 * return false to continue verification of this path
16030 if (!regsafe(env, &old->stack[spi].spilled_ptr,
16031 &cur->stack[spi].spilled_ptr, idmap, exact))
16035 old_reg = &old->stack[spi].spilled_ptr;
16036 cur_reg = &cur->stack[spi].spilled_ptr;
16037 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16038 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16039 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16043 old_reg = &old->stack[spi].spilled_ptr;
16044 cur_reg = &cur->stack[spi].spilled_ptr;
16045 /* iter.depth is not compared between states as it
16046 * doesn't matter for correctness and would otherwise
16047 * prevent convergence; we maintain it only to prevent
16048 * infinite loop check triggering, see
16049 * iter_active_depths_differ()
16051 if (old_reg->iter.btf != cur_reg->iter.btf ||
16052 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16053 old_reg->iter.state != cur_reg->iter.state ||
16054 /* ignore {old_reg,cur_reg}->iter.depth, see above */
16055 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16060 case STACK_INVALID:
16062 /* Ensure that new unhandled slot types return false by default */
16070 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16071 struct bpf_idmap *idmap)
16075 if (old->acquired_refs != cur->acquired_refs)
16078 for (i = 0; i < old->acquired_refs; i++) {
16079 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16086 /* compare two verifier states
16088 * all states stored in state_list are known to be valid, since
16089 * verifier reached 'bpf_exit' instruction through them
16091 * this function is called when verifier exploring different branches of
16092 * execution popped from the state stack. If it sees an old state that has
16093 * more strict register state and more strict stack state then this execution
16094 * branch doesn't need to be explored further, since verifier already
16095 * concluded that more strict state leads to valid finish.
16097 * Therefore two states are equivalent if register state is more conservative
16098 * and explored stack state is more conservative than the current one.
16101 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16102 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16104 * In other words if current stack state (one being explored) has more
16105 * valid slots than old one that already passed validation, it means
16106 * the verifier can stop exploring and conclude that current state is valid too
16108 * Similarly with registers. If explored state has register type as invalid
16109 * whereas register type in current state is meaningful, it means that
16110 * the current state will reach 'bpf_exit' instruction safely
16112 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16113 struct bpf_func_state *cur, bool exact)
16117 for (i = 0; i < MAX_BPF_REG; i++)
16118 if (!regsafe(env, &old->regs[i], &cur->regs[i],
16119 &env->idmap_scratch, exact))
16122 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16125 if (!refsafe(old, cur, &env->idmap_scratch))
16131 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16133 env->idmap_scratch.tmp_id_gen = env->id_gen;
16134 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16137 static bool states_equal(struct bpf_verifier_env *env,
16138 struct bpf_verifier_state *old,
16139 struct bpf_verifier_state *cur,
16144 if (old->curframe != cur->curframe)
16147 reset_idmap_scratch(env);
16149 /* Verification state from speculative execution simulation
16150 * must never prune a non-speculative execution one.
16152 if (old->speculative && !cur->speculative)
16155 if (old->active_lock.ptr != cur->active_lock.ptr)
16158 /* Old and cur active_lock's have to be either both present
16161 if (!!old->active_lock.id != !!cur->active_lock.id)
16164 if (old->active_lock.id &&
16165 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16168 if (old->active_rcu_lock != cur->active_rcu_lock)
16171 /* for states to be equal callsites have to be the same
16172 * and all frame states need to be equivalent
16174 for (i = 0; i <= old->curframe; i++) {
16175 if (old->frame[i]->callsite != cur->frame[i]->callsite)
16177 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16183 /* Return 0 if no propagation happened. Return negative error code if error
16184 * happened. Otherwise, return the propagated bit.
16186 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16187 struct bpf_reg_state *reg,
16188 struct bpf_reg_state *parent_reg)
16190 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16191 u8 flag = reg->live & REG_LIVE_READ;
16194 /* When comes here, read flags of PARENT_REG or REG could be any of
16195 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16196 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16198 if (parent_flag == REG_LIVE_READ64 ||
16199 /* Or if there is no read flag from REG. */
16201 /* Or if the read flag from REG is the same as PARENT_REG. */
16202 parent_flag == flag)
16205 err = mark_reg_read(env, reg, parent_reg, flag);
16212 /* A write screens off any subsequent reads; but write marks come from the
16213 * straight-line code between a state and its parent. When we arrive at an
16214 * equivalent state (jump target or such) we didn't arrive by the straight-line
16215 * code, so read marks in the state must propagate to the parent regardless
16216 * of the state's write marks. That's what 'parent == state->parent' comparison
16217 * in mark_reg_read() is for.
16219 static int propagate_liveness(struct bpf_verifier_env *env,
16220 const struct bpf_verifier_state *vstate,
16221 struct bpf_verifier_state *vparent)
16223 struct bpf_reg_state *state_reg, *parent_reg;
16224 struct bpf_func_state *state, *parent;
16225 int i, frame, err = 0;
16227 if (vparent->curframe != vstate->curframe) {
16228 WARN(1, "propagate_live: parent frame %d current frame %d\n",
16229 vparent->curframe, vstate->curframe);
16232 /* Propagate read liveness of registers... */
16233 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16234 for (frame = 0; frame <= vstate->curframe; frame++) {
16235 parent = vparent->frame[frame];
16236 state = vstate->frame[frame];
16237 parent_reg = parent->regs;
16238 state_reg = state->regs;
16239 /* We don't need to worry about FP liveness, it's read-only */
16240 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16241 err = propagate_liveness_reg(env, &state_reg[i],
16245 if (err == REG_LIVE_READ64)
16246 mark_insn_zext(env, &parent_reg[i]);
16249 /* Propagate stack slots. */
16250 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16251 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16252 parent_reg = &parent->stack[i].spilled_ptr;
16253 state_reg = &state->stack[i].spilled_ptr;
16254 err = propagate_liveness_reg(env, state_reg,
16263 /* find precise scalars in the previous equivalent state and
16264 * propagate them into the current state
16266 static int propagate_precision(struct bpf_verifier_env *env,
16267 const struct bpf_verifier_state *old)
16269 struct bpf_reg_state *state_reg;
16270 struct bpf_func_state *state;
16271 int i, err = 0, fr;
16274 for (fr = old->curframe; fr >= 0; fr--) {
16275 state = old->frame[fr];
16276 state_reg = state->regs;
16278 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16279 if (state_reg->type != SCALAR_VALUE ||
16280 !state_reg->precise ||
16281 !(state_reg->live & REG_LIVE_READ))
16283 if (env->log.level & BPF_LOG_LEVEL2) {
16285 verbose(env, "frame %d: propagating r%d", fr, i);
16287 verbose(env, ",r%d", i);
16289 bt_set_frame_reg(&env->bt, fr, i);
16293 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16294 if (!is_spilled_reg(&state->stack[i]))
16296 state_reg = &state->stack[i].spilled_ptr;
16297 if (state_reg->type != SCALAR_VALUE ||
16298 !state_reg->precise ||
16299 !(state_reg->live & REG_LIVE_READ))
16301 if (env->log.level & BPF_LOG_LEVEL2) {
16303 verbose(env, "frame %d: propagating fp%d",
16304 fr, (-i - 1) * BPF_REG_SIZE);
16306 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16308 bt_set_frame_slot(&env->bt, fr, i);
16312 verbose(env, "\n");
16315 err = mark_chain_precision_batch(env);
16322 static bool states_maybe_looping(struct bpf_verifier_state *old,
16323 struct bpf_verifier_state *cur)
16325 struct bpf_func_state *fold, *fcur;
16326 int i, fr = cur->curframe;
16328 if (old->curframe != fr)
16331 fold = old->frame[fr];
16332 fcur = cur->frame[fr];
16333 for (i = 0; i < MAX_BPF_REG; i++)
16334 if (memcmp(&fold->regs[i], &fcur->regs[i],
16335 offsetof(struct bpf_reg_state, parent)))
16340 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16342 return env->insn_aux_data[insn_idx].is_iter_next;
16345 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16346 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16347 * states to match, which otherwise would look like an infinite loop. So while
16348 * iter_next() calls are taken care of, we still need to be careful and
16349 * prevent erroneous and too eager declaration of "ininite loop", when
16350 * iterators are involved.
16352 * Here's a situation in pseudo-BPF assembly form:
16354 * 0: again: ; set up iter_next() call args
16355 * 1: r1 = &it ; <CHECKPOINT HERE>
16356 * 2: call bpf_iter_num_next ; this is iter_next() call
16357 * 3: if r0 == 0 goto done
16358 * 4: ... something useful here ...
16359 * 5: goto again ; another iteration
16362 * 8: call bpf_iter_num_destroy ; clean up iter state
16365 * This is a typical loop. Let's assume that we have a prune point at 1:,
16366 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16367 * again`, assuming other heuristics don't get in a way).
16369 * When we first time come to 1:, let's say we have some state X. We proceed
16370 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16371 * Now we come back to validate that forked ACTIVE state. We proceed through
16372 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16373 * are converging. But the problem is that we don't know that yet, as this
16374 * convergence has to happen at iter_next() call site only. So if nothing is
16375 * done, at 1: verifier will use bounded loop logic and declare infinite
16376 * looping (and would be *technically* correct, if not for iterator's
16377 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16378 * don't want that. So what we do in process_iter_next_call() when we go on
16379 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16380 * a different iteration. So when we suspect an infinite loop, we additionally
16381 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16382 * pretend we are not looping and wait for next iter_next() call.
16384 * This only applies to ACTIVE state. In DRAINED state we don't expect to
16385 * loop, because that would actually mean infinite loop, as DRAINED state is
16386 * "sticky", and so we'll keep returning into the same instruction with the
16387 * same state (at least in one of possible code paths).
16389 * This approach allows to keep infinite loop heuristic even in the face of
16390 * active iterator. E.g., C snippet below is and will be detected as
16391 * inifintely looping:
16393 * struct bpf_iter_num it;
16396 * bpf_iter_num_new(&it, 0, 10);
16397 * while ((p = bpf_iter_num_next(&t))) {
16399 * while (x--) {} // <<-- infinite loop here
16403 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16405 struct bpf_reg_state *slot, *cur_slot;
16406 struct bpf_func_state *state;
16409 for (fr = old->curframe; fr >= 0; fr--) {
16410 state = old->frame[fr];
16411 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16412 if (state->stack[i].slot_type[0] != STACK_ITER)
16415 slot = &state->stack[i].spilled_ptr;
16416 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16419 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16420 if (cur_slot->iter.depth != slot->iter.depth)
16427 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16429 struct bpf_verifier_state_list *new_sl;
16430 struct bpf_verifier_state_list *sl, **pprev;
16431 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16432 int i, j, n, err, states_cnt = 0;
16433 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16434 bool add_new_state = force_new_state;
16437 /* bpf progs typically have pruning point every 4 instructions
16438 * http://vger.kernel.org/bpfconf2019.html#session-1
16439 * Do not add new state for future pruning if the verifier hasn't seen
16440 * at least 2 jumps and at least 8 instructions.
16441 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16442 * In tests that amounts to up to 50% reduction into total verifier
16443 * memory consumption and 20% verifier time speedup.
16445 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16446 env->insn_processed - env->prev_insn_processed >= 8)
16447 add_new_state = true;
16449 pprev = explored_state(env, insn_idx);
16452 clean_live_states(env, insn_idx, cur);
16456 if (sl->state.insn_idx != insn_idx)
16459 if (sl->state.branches) {
16460 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16462 if (frame->in_async_callback_fn &&
16463 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16464 /* Different async_entry_cnt means that the verifier is
16465 * processing another entry into async callback.
16466 * Seeing the same state is not an indication of infinite
16467 * loop or infinite recursion.
16468 * But finding the same state doesn't mean that it's safe
16469 * to stop processing the current state. The previous state
16470 * hasn't yet reached bpf_exit, since state.branches > 0.
16471 * Checking in_async_callback_fn alone is not enough either.
16472 * Since the verifier still needs to catch infinite loops
16473 * inside async callbacks.
16475 goto skip_inf_loop_check;
16477 /* BPF open-coded iterators loop detection is special.
16478 * states_maybe_looping() logic is too simplistic in detecting
16479 * states that *might* be equivalent, because it doesn't know
16480 * about ID remapping, so don't even perform it.
16481 * See process_iter_next_call() and iter_active_depths_differ()
16482 * for overview of the logic. When current and one of parent
16483 * states are detected as equivalent, it's a good thing: we prove
16484 * convergence and can stop simulating further iterations.
16485 * It's safe to assume that iterator loop will finish, taking into
16486 * account iter_next() contract of eventually returning
16487 * sticky NULL result.
16489 * Note, that states have to be compared exactly in this case because
16490 * read and precision marks might not be finalized inside the loop.
16491 * E.g. as in the program below:
16494 * 2. r6 = bpf_get_prandom_u32()
16495 * 3. while (bpf_iter_num_next(&fp[-8])) {
16496 * 4. if (r6 != 42) {
16498 * 6. r6 = bpf_get_prandom_u32()
16503 * 11. r8 = *(u64 *)(r0 + 0)
16504 * 12. r6 = bpf_get_prandom_u32()
16507 * Here verifier would first visit path 1-3, create a checkpoint at 3
16508 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16509 * not have read or precision mark for r7 yet, thus inexact states
16510 * comparison would discard current state with r7=-32
16511 * => unsafe memory access at 11 would not be caught.
16513 if (is_iter_next_insn(env, insn_idx)) {
16514 if (states_equal(env, &sl->state, cur, true)) {
16515 struct bpf_func_state *cur_frame;
16516 struct bpf_reg_state *iter_state, *iter_reg;
16519 cur_frame = cur->frame[cur->curframe];
16520 /* btf_check_iter_kfuncs() enforces that
16521 * iter state pointer is always the first arg
16523 iter_reg = &cur_frame->regs[BPF_REG_1];
16524 /* current state is valid due to states_equal(),
16525 * so we can assume valid iter and reg state,
16526 * no need for extra (re-)validations
16528 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16529 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16530 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16531 update_loop_entry(cur, &sl->state);
16535 goto skip_inf_loop_check;
16537 /* attempt to detect infinite loop to avoid unnecessary doomed work */
16538 if (states_maybe_looping(&sl->state, cur) &&
16539 states_equal(env, &sl->state, cur, false) &&
16540 !iter_active_depths_differ(&sl->state, cur)) {
16541 verbose_linfo(env, insn_idx, "; ");
16542 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16543 verbose(env, "cur state:");
16544 print_verifier_state(env, cur->frame[cur->curframe], true);
16545 verbose(env, "old state:");
16546 print_verifier_state(env, sl->state.frame[cur->curframe], true);
16549 /* if the verifier is processing a loop, avoid adding new state
16550 * too often, since different loop iterations have distinct
16551 * states and may not help future pruning.
16552 * This threshold shouldn't be too low to make sure that
16553 * a loop with large bound will be rejected quickly.
16554 * The most abusive loop will be:
16556 * if r1 < 1000000 goto pc-2
16557 * 1M insn_procssed limit / 100 == 10k peak states.
16558 * This threshold shouldn't be too high either, since states
16559 * at the end of the loop are likely to be useful in pruning.
16561 skip_inf_loop_check:
16562 if (!force_new_state &&
16563 env->jmps_processed - env->prev_jmps_processed < 20 &&
16564 env->insn_processed - env->prev_insn_processed < 100)
16565 add_new_state = false;
16568 /* If sl->state is a part of a loop and this loop's entry is a part of
16569 * current verification path then states have to be compared exactly.
16570 * 'force_exact' is needed to catch the following case:
16572 * initial Here state 'succ' was processed first,
16573 * | it was eventually tracked to produce a
16574 * V state identical to 'hdr'.
16575 * .---------> hdr All branches from 'succ' had been explored
16576 * | | and thus 'succ' has its .branches == 0.
16578 * | .------... Suppose states 'cur' and 'succ' correspond
16579 * | | | to the same instruction + callsites.
16580 * | V V In such case it is necessary to check
16581 * | ... ... if 'succ' and 'cur' are states_equal().
16582 * | | | If 'succ' and 'cur' are a part of the
16583 * | V V same loop exact flag has to be set.
16584 * | succ <- cur To check if that is the case, verify
16585 * | | if loop entry of 'succ' is in current
16591 * Additional details are in the comment before get_loop_entry().
16593 loop_entry = get_loop_entry(&sl->state);
16594 force_exact = loop_entry && loop_entry->branches > 0;
16595 if (states_equal(env, &sl->state, cur, force_exact)) {
16597 update_loop_entry(cur, loop_entry);
16600 /* reached equivalent register/stack state,
16601 * prune the search.
16602 * Registers read by the continuation are read by us.
16603 * If we have any write marks in env->cur_state, they
16604 * will prevent corresponding reads in the continuation
16605 * from reaching our parent (an explored_state). Our
16606 * own state will get the read marks recorded, but
16607 * they'll be immediately forgotten as we're pruning
16608 * this state and will pop a new one.
16610 err = propagate_liveness(env, &sl->state, cur);
16612 /* if previous state reached the exit with precision and
16613 * current state is equivalent to it (except precsion marks)
16614 * the precision needs to be propagated back in
16615 * the current state.
16617 err = err ? : push_jmp_history(env, cur);
16618 err = err ? : propagate_precision(env, &sl->state);
16624 /* when new state is not going to be added do not increase miss count.
16625 * Otherwise several loop iterations will remove the state
16626 * recorded earlier. The goal of these heuristics is to have
16627 * states from some iterations of the loop (some in the beginning
16628 * and some at the end) to help pruning.
16632 /* heuristic to determine whether this state is beneficial
16633 * to keep checking from state equivalence point of view.
16634 * Higher numbers increase max_states_per_insn and verification time,
16635 * but do not meaningfully decrease insn_processed.
16636 * 'n' controls how many times state could miss before eviction.
16637 * Use bigger 'n' for checkpoints because evicting checkpoint states
16638 * too early would hinder iterator convergence.
16640 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16641 if (sl->miss_cnt > sl->hit_cnt * n + n) {
16642 /* the state is unlikely to be useful. Remove it to
16643 * speed up verification
16646 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16647 !sl->state.used_as_loop_entry) {
16648 u32 br = sl->state.branches;
16651 "BUG live_done but branches_to_explore %d\n",
16653 free_verifier_state(&sl->state, false);
16655 env->peak_states--;
16657 /* cannot free this state, since parentage chain may
16658 * walk it later. Add it for free_list instead to
16659 * be freed at the end of verification
16661 sl->next = env->free_list;
16662 env->free_list = sl;
16672 if (env->max_states_per_insn < states_cnt)
16673 env->max_states_per_insn = states_cnt;
16675 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16678 if (!add_new_state)
16681 /* There were no equivalent states, remember the current one.
16682 * Technically the current state is not proven to be safe yet,
16683 * but it will either reach outer most bpf_exit (which means it's safe)
16684 * or it will be rejected. When there are no loops the verifier won't be
16685 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16686 * again on the way to bpf_exit.
16687 * When looping the sl->state.branches will be > 0 and this state
16688 * will not be considered for equivalence until branches == 0.
16690 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16693 env->total_states++;
16694 env->peak_states++;
16695 env->prev_jmps_processed = env->jmps_processed;
16696 env->prev_insn_processed = env->insn_processed;
16698 /* forget precise markings we inherited, see __mark_chain_precision */
16699 if (env->bpf_capable)
16700 mark_all_scalars_imprecise(env, cur);
16702 /* add new state to the head of linked list */
16703 new = &new_sl->state;
16704 err = copy_verifier_state(new, cur);
16706 free_verifier_state(new, false);
16710 new->insn_idx = insn_idx;
16711 WARN_ONCE(new->branches != 1,
16712 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16715 cur->first_insn_idx = insn_idx;
16716 cur->dfs_depth = new->dfs_depth + 1;
16717 clear_jmp_history(cur);
16718 new_sl->next = *explored_state(env, insn_idx);
16719 *explored_state(env, insn_idx) = new_sl;
16720 /* connect new state to parentage chain. Current frame needs all
16721 * registers connected. Only r6 - r9 of the callers are alive (pushed
16722 * to the stack implicitly by JITs) so in callers' frames connect just
16723 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16724 * the state of the call instruction (with WRITTEN set), and r0 comes
16725 * from callee with its full parentage chain, anyway.
16727 /* clear write marks in current state: the writes we did are not writes
16728 * our child did, so they don't screen off its reads from us.
16729 * (There are no read marks in current state, because reads always mark
16730 * their parent and current state never has children yet. Only
16731 * explored_states can get read marks.)
16733 for (j = 0; j <= cur->curframe; j++) {
16734 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16735 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16736 for (i = 0; i < BPF_REG_FP; i++)
16737 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16740 /* all stack frames are accessible from callee, clear them all */
16741 for (j = 0; j <= cur->curframe; j++) {
16742 struct bpf_func_state *frame = cur->frame[j];
16743 struct bpf_func_state *newframe = new->frame[j];
16745 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16746 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16747 frame->stack[i].spilled_ptr.parent =
16748 &newframe->stack[i].spilled_ptr;
16754 /* Return true if it's OK to have the same insn return a different type. */
16755 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16757 switch (base_type(type)) {
16759 case PTR_TO_SOCKET:
16760 case PTR_TO_SOCK_COMMON:
16761 case PTR_TO_TCP_SOCK:
16762 case PTR_TO_XDP_SOCK:
16763 case PTR_TO_BTF_ID:
16770 /* If an instruction was previously used with particular pointer types, then we
16771 * need to be careful to avoid cases such as the below, where it may be ok
16772 * for one branch accessing the pointer, but not ok for the other branch:
16777 * R1 = some_other_valid_ptr;
16780 * R2 = *(u32 *)(R1 + 0);
16782 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16784 return src != prev && (!reg_type_mismatch_ok(src) ||
16785 !reg_type_mismatch_ok(prev));
16788 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16789 bool allow_trust_missmatch)
16791 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16793 if (*prev_type == NOT_INIT) {
16794 /* Saw a valid insn
16795 * dst_reg = *(u32 *)(src_reg + off)
16796 * save type to validate intersecting paths
16799 } else if (reg_type_mismatch(type, *prev_type)) {
16800 /* Abuser program is trying to use the same insn
16801 * dst_reg = *(u32*) (src_reg + off)
16802 * with different pointer types:
16803 * src_reg == ctx in one branch and
16804 * src_reg == stack|map in some other branch.
16807 if (allow_trust_missmatch &&
16808 base_type(type) == PTR_TO_BTF_ID &&
16809 base_type(*prev_type) == PTR_TO_BTF_ID) {
16811 * Have to support a use case when one path through
16812 * the program yields TRUSTED pointer while another
16813 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16814 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16816 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16818 verbose(env, "same insn cannot be used with different pointers\n");
16826 static int do_check(struct bpf_verifier_env *env)
16828 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16829 struct bpf_verifier_state *state = env->cur_state;
16830 struct bpf_insn *insns = env->prog->insnsi;
16831 struct bpf_reg_state *regs;
16832 int insn_cnt = env->prog->len;
16833 bool do_print_state = false;
16834 int prev_insn_idx = -1;
16837 struct bpf_insn *insn;
16841 env->prev_insn_idx = prev_insn_idx;
16842 if (env->insn_idx >= insn_cnt) {
16843 verbose(env, "invalid insn idx %d insn_cnt %d\n",
16844 env->insn_idx, insn_cnt);
16848 insn = &insns[env->insn_idx];
16849 class = BPF_CLASS(insn->code);
16851 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16853 "BPF program is too large. Processed %d insn\n",
16854 env->insn_processed);
16858 state->last_insn_idx = env->prev_insn_idx;
16860 if (is_prune_point(env, env->insn_idx)) {
16861 err = is_state_visited(env, env->insn_idx);
16865 /* found equivalent state, can prune the search */
16866 if (env->log.level & BPF_LOG_LEVEL) {
16867 if (do_print_state)
16868 verbose(env, "\nfrom %d to %d%s: safe\n",
16869 env->prev_insn_idx, env->insn_idx,
16870 env->cur_state->speculative ?
16871 " (speculative execution)" : "");
16873 verbose(env, "%d: safe\n", env->insn_idx);
16875 goto process_bpf_exit;
16879 if (is_jmp_point(env, env->insn_idx)) {
16880 err = push_jmp_history(env, state);
16885 if (signal_pending(current))
16888 if (need_resched())
16891 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16892 verbose(env, "\nfrom %d to %d%s:",
16893 env->prev_insn_idx, env->insn_idx,
16894 env->cur_state->speculative ?
16895 " (speculative execution)" : "");
16896 print_verifier_state(env, state->frame[state->curframe], true);
16897 do_print_state = false;
16900 if (env->log.level & BPF_LOG_LEVEL) {
16901 const struct bpf_insn_cbs cbs = {
16902 .cb_call = disasm_kfunc_name,
16903 .cb_print = verbose,
16904 .private_data = env,
16907 if (verifier_state_scratched(env))
16908 print_insn_state(env, state->frame[state->curframe]);
16910 verbose_linfo(env, env->insn_idx, "; ");
16911 env->prev_log_pos = env->log.end_pos;
16912 verbose(env, "%d: ", env->insn_idx);
16913 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16914 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16915 env->prev_log_pos = env->log.end_pos;
16918 if (bpf_prog_is_offloaded(env->prog->aux)) {
16919 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16920 env->prev_insn_idx);
16925 regs = cur_regs(env);
16926 sanitize_mark_insn_seen(env);
16927 prev_insn_idx = env->insn_idx;
16929 if (class == BPF_ALU || class == BPF_ALU64) {
16930 err = check_alu_op(env, insn);
16934 } else if (class == BPF_LDX) {
16935 enum bpf_reg_type src_reg_type;
16937 /* check for reserved fields is already done */
16939 /* check src operand */
16940 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16944 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16948 src_reg_type = regs[insn->src_reg].type;
16950 /* check that memory (src_reg + off) is readable,
16951 * the state of dst_reg will be updated by this func
16953 err = check_mem_access(env, env->insn_idx, insn->src_reg,
16954 insn->off, BPF_SIZE(insn->code),
16955 BPF_READ, insn->dst_reg, false,
16956 BPF_MODE(insn->code) == BPF_MEMSX);
16960 err = save_aux_ptr_type(env, src_reg_type, true);
16963 } else if (class == BPF_STX) {
16964 enum bpf_reg_type dst_reg_type;
16966 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16967 err = check_atomic(env, env->insn_idx, insn);
16974 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16975 verbose(env, "BPF_STX uses reserved fields\n");
16979 /* check src1 operand */
16980 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16983 /* check src2 operand */
16984 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16988 dst_reg_type = regs[insn->dst_reg].type;
16990 /* check that memory (dst_reg + off) is writeable */
16991 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16992 insn->off, BPF_SIZE(insn->code),
16993 BPF_WRITE, insn->src_reg, false, false);
16997 err = save_aux_ptr_type(env, dst_reg_type, false);
17000 } else if (class == BPF_ST) {
17001 enum bpf_reg_type dst_reg_type;
17003 if (BPF_MODE(insn->code) != BPF_MEM ||
17004 insn->src_reg != BPF_REG_0) {
17005 verbose(env, "BPF_ST uses reserved fields\n");
17008 /* check src operand */
17009 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17013 dst_reg_type = regs[insn->dst_reg].type;
17015 /* check that memory (dst_reg + off) is writeable */
17016 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17017 insn->off, BPF_SIZE(insn->code),
17018 BPF_WRITE, -1, false, false);
17022 err = save_aux_ptr_type(env, dst_reg_type, false);
17025 } else if (class == BPF_JMP || class == BPF_JMP32) {
17026 u8 opcode = BPF_OP(insn->code);
17028 env->jmps_processed++;
17029 if (opcode == BPF_CALL) {
17030 if (BPF_SRC(insn->code) != BPF_K ||
17031 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17032 && insn->off != 0) ||
17033 (insn->src_reg != BPF_REG_0 &&
17034 insn->src_reg != BPF_PSEUDO_CALL &&
17035 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17036 insn->dst_reg != BPF_REG_0 ||
17037 class == BPF_JMP32) {
17038 verbose(env, "BPF_CALL uses reserved fields\n");
17042 if (env->cur_state->active_lock.ptr) {
17043 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17044 (insn->src_reg == BPF_PSEUDO_CALL) ||
17045 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17046 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17047 verbose(env, "function calls are not allowed while holding a lock\n");
17051 if (insn->src_reg == BPF_PSEUDO_CALL)
17052 err = check_func_call(env, insn, &env->insn_idx);
17053 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17054 err = check_kfunc_call(env, insn, &env->insn_idx);
17056 err = check_helper_call(env, insn, &env->insn_idx);
17060 mark_reg_scratched(env, BPF_REG_0);
17061 } else if (opcode == BPF_JA) {
17062 if (BPF_SRC(insn->code) != BPF_K ||
17063 insn->src_reg != BPF_REG_0 ||
17064 insn->dst_reg != BPF_REG_0 ||
17065 (class == BPF_JMP && insn->imm != 0) ||
17066 (class == BPF_JMP32 && insn->off != 0)) {
17067 verbose(env, "BPF_JA uses reserved fields\n");
17071 if (class == BPF_JMP)
17072 env->insn_idx += insn->off + 1;
17074 env->insn_idx += insn->imm + 1;
17077 } else if (opcode == BPF_EXIT) {
17078 if (BPF_SRC(insn->code) != BPF_K ||
17080 insn->src_reg != BPF_REG_0 ||
17081 insn->dst_reg != BPF_REG_0 ||
17082 class == BPF_JMP32) {
17083 verbose(env, "BPF_EXIT uses reserved fields\n");
17087 if (env->cur_state->active_lock.ptr &&
17088 !in_rbtree_lock_required_cb(env)) {
17089 verbose(env, "bpf_spin_unlock is missing\n");
17093 if (env->cur_state->active_rcu_lock &&
17094 !in_rbtree_lock_required_cb(env)) {
17095 verbose(env, "bpf_rcu_read_unlock is missing\n");
17099 /* We must do check_reference_leak here before
17100 * prepare_func_exit to handle the case when
17101 * state->curframe > 0, it may be a callback
17102 * function, for which reference_state must
17103 * match caller reference state when it exits.
17105 err = check_reference_leak(env);
17109 if (state->curframe) {
17110 /* exit from nested function */
17111 err = prepare_func_exit(env, &env->insn_idx);
17114 do_print_state = true;
17118 err = check_return_code(env);
17122 mark_verifier_state_scratched(env);
17123 update_branch_counts(env, env->cur_state);
17124 err = pop_stack(env, &prev_insn_idx,
17125 &env->insn_idx, pop_log);
17127 if (err != -ENOENT)
17131 do_print_state = true;
17135 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17139 } else if (class == BPF_LD) {
17140 u8 mode = BPF_MODE(insn->code);
17142 if (mode == BPF_ABS || mode == BPF_IND) {
17143 err = check_ld_abs(env, insn);
17147 } else if (mode == BPF_IMM) {
17148 err = check_ld_imm(env, insn);
17153 sanitize_mark_insn_seen(env);
17155 verbose(env, "invalid BPF_LD mode\n");
17159 verbose(env, "unknown insn class %d\n", class);
17169 static int find_btf_percpu_datasec(struct btf *btf)
17171 const struct btf_type *t;
17176 * Both vmlinux and module each have their own ".data..percpu"
17177 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17178 * types to look at only module's own BTF types.
17180 n = btf_nr_types(btf);
17181 if (btf_is_module(btf))
17182 i = btf_nr_types(btf_vmlinux);
17186 for(; i < n; i++) {
17187 t = btf_type_by_id(btf, i);
17188 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17191 tname = btf_name_by_offset(btf, t->name_off);
17192 if (!strcmp(tname, ".data..percpu"))
17199 /* replace pseudo btf_id with kernel symbol address */
17200 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17201 struct bpf_insn *insn,
17202 struct bpf_insn_aux_data *aux)
17204 const struct btf_var_secinfo *vsi;
17205 const struct btf_type *datasec;
17206 struct btf_mod_pair *btf_mod;
17207 const struct btf_type *t;
17208 const char *sym_name;
17209 bool percpu = false;
17210 u32 type, id = insn->imm;
17214 int i, btf_fd, err;
17216 btf_fd = insn[1].imm;
17218 btf = btf_get_by_fd(btf_fd);
17220 verbose(env, "invalid module BTF object FD specified.\n");
17224 if (!btf_vmlinux) {
17225 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17232 t = btf_type_by_id(btf, id);
17234 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17239 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17240 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17245 sym_name = btf_name_by_offset(btf, t->name_off);
17246 addr = kallsyms_lookup_name(sym_name);
17248 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17253 insn[0].imm = (u32)addr;
17254 insn[1].imm = addr >> 32;
17256 if (btf_type_is_func(t)) {
17257 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17258 aux->btf_var.mem_size = 0;
17262 datasec_id = find_btf_percpu_datasec(btf);
17263 if (datasec_id > 0) {
17264 datasec = btf_type_by_id(btf, datasec_id);
17265 for_each_vsi(i, datasec, vsi) {
17266 if (vsi->type == id) {
17274 t = btf_type_skip_modifiers(btf, type, NULL);
17276 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17277 aux->btf_var.btf = btf;
17278 aux->btf_var.btf_id = type;
17279 } else if (!btf_type_is_struct(t)) {
17280 const struct btf_type *ret;
17284 /* resolve the type size of ksym. */
17285 ret = btf_resolve_size(btf, t, &tsize);
17287 tname = btf_name_by_offset(btf, t->name_off);
17288 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17289 tname, PTR_ERR(ret));
17293 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17294 aux->btf_var.mem_size = tsize;
17296 aux->btf_var.reg_type = PTR_TO_BTF_ID;
17297 aux->btf_var.btf = btf;
17298 aux->btf_var.btf_id = type;
17301 /* check whether we recorded this BTF (and maybe module) already */
17302 for (i = 0; i < env->used_btf_cnt; i++) {
17303 if (env->used_btfs[i].btf == btf) {
17309 if (env->used_btf_cnt >= MAX_USED_BTFS) {
17314 btf_mod = &env->used_btfs[env->used_btf_cnt];
17315 btf_mod->btf = btf;
17316 btf_mod->module = NULL;
17318 /* if we reference variables from kernel module, bump its refcount */
17319 if (btf_is_module(btf)) {
17320 btf_mod->module = btf_try_get_module(btf);
17321 if (!btf_mod->module) {
17327 env->used_btf_cnt++;
17335 static bool is_tracing_prog_type(enum bpf_prog_type type)
17338 case BPF_PROG_TYPE_KPROBE:
17339 case BPF_PROG_TYPE_TRACEPOINT:
17340 case BPF_PROG_TYPE_PERF_EVENT:
17341 case BPF_PROG_TYPE_RAW_TRACEPOINT:
17342 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17349 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17350 struct bpf_map *map,
17351 struct bpf_prog *prog)
17354 enum bpf_prog_type prog_type = resolve_prog_type(prog);
17356 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17357 btf_record_has_field(map->record, BPF_RB_ROOT)) {
17358 if (is_tracing_prog_type(prog_type)) {
17359 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17364 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17365 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17366 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17370 if (is_tracing_prog_type(prog_type)) {
17371 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17376 if (btf_record_has_field(map->record, BPF_TIMER)) {
17377 if (is_tracing_prog_type(prog_type)) {
17378 verbose(env, "tracing progs cannot use bpf_timer yet\n");
17383 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17384 !bpf_offload_prog_map_match(prog, map)) {
17385 verbose(env, "offload device mismatch between prog and map\n");
17389 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17390 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17394 if (prog->aux->sleepable)
17395 switch (map->map_type) {
17396 case BPF_MAP_TYPE_HASH:
17397 case BPF_MAP_TYPE_LRU_HASH:
17398 case BPF_MAP_TYPE_ARRAY:
17399 case BPF_MAP_TYPE_PERCPU_HASH:
17400 case BPF_MAP_TYPE_PERCPU_ARRAY:
17401 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17402 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17403 case BPF_MAP_TYPE_HASH_OF_MAPS:
17404 case BPF_MAP_TYPE_RINGBUF:
17405 case BPF_MAP_TYPE_USER_RINGBUF:
17406 case BPF_MAP_TYPE_INODE_STORAGE:
17407 case BPF_MAP_TYPE_SK_STORAGE:
17408 case BPF_MAP_TYPE_TASK_STORAGE:
17409 case BPF_MAP_TYPE_CGRP_STORAGE:
17413 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17420 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17422 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17423 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17426 /* find and rewrite pseudo imm in ld_imm64 instructions:
17428 * 1. if it accesses map FD, replace it with actual map pointer.
17429 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17431 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17433 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17435 struct bpf_insn *insn = env->prog->insnsi;
17436 int insn_cnt = env->prog->len;
17439 err = bpf_prog_calc_tag(env->prog);
17443 for (i = 0; i < insn_cnt; i++, insn++) {
17444 if (BPF_CLASS(insn->code) == BPF_LDX &&
17445 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17447 verbose(env, "BPF_LDX uses reserved fields\n");
17451 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17452 struct bpf_insn_aux_data *aux;
17453 struct bpf_map *map;
17458 if (i == insn_cnt - 1 || insn[1].code != 0 ||
17459 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17460 insn[1].off != 0) {
17461 verbose(env, "invalid bpf_ld_imm64 insn\n");
17465 if (insn[0].src_reg == 0)
17466 /* valid generic load 64-bit imm */
17469 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17470 aux = &env->insn_aux_data[i];
17471 err = check_pseudo_btf_id(env, insn, aux);
17477 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17478 aux = &env->insn_aux_data[i];
17479 aux->ptr_type = PTR_TO_FUNC;
17483 /* In final convert_pseudo_ld_imm64() step, this is
17484 * converted into regular 64-bit imm load insn.
17486 switch (insn[0].src_reg) {
17487 case BPF_PSEUDO_MAP_VALUE:
17488 case BPF_PSEUDO_MAP_IDX_VALUE:
17490 case BPF_PSEUDO_MAP_FD:
17491 case BPF_PSEUDO_MAP_IDX:
17492 if (insn[1].imm == 0)
17496 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17500 switch (insn[0].src_reg) {
17501 case BPF_PSEUDO_MAP_IDX_VALUE:
17502 case BPF_PSEUDO_MAP_IDX:
17503 if (bpfptr_is_null(env->fd_array)) {
17504 verbose(env, "fd_idx without fd_array is invalid\n");
17507 if (copy_from_bpfptr_offset(&fd, env->fd_array,
17508 insn[0].imm * sizeof(fd),
17518 map = __bpf_map_get(f);
17520 verbose(env, "fd %d is not pointing to valid bpf_map\n",
17522 return PTR_ERR(map);
17525 err = check_map_prog_compatibility(env, map, env->prog);
17531 aux = &env->insn_aux_data[i];
17532 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17533 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17534 addr = (unsigned long)map;
17536 u32 off = insn[1].imm;
17538 if (off >= BPF_MAX_VAR_OFF) {
17539 verbose(env, "direct value offset of %u is not allowed\n", off);
17544 if (!map->ops->map_direct_value_addr) {
17545 verbose(env, "no direct value access support for this map type\n");
17550 err = map->ops->map_direct_value_addr(map, &addr, off);
17552 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17553 map->value_size, off);
17558 aux->map_off = off;
17562 insn[0].imm = (u32)addr;
17563 insn[1].imm = addr >> 32;
17565 /* check whether we recorded this map already */
17566 for (j = 0; j < env->used_map_cnt; j++) {
17567 if (env->used_maps[j] == map) {
17568 aux->map_index = j;
17574 if (env->used_map_cnt >= MAX_USED_MAPS) {
17579 /* hold the map. If the program is rejected by verifier,
17580 * the map will be released by release_maps() or it
17581 * will be used by the valid program until it's unloaded
17582 * and all maps are released in free_used_maps()
17586 aux->map_index = env->used_map_cnt;
17587 env->used_maps[env->used_map_cnt++] = map;
17589 if (bpf_map_is_cgroup_storage(map) &&
17590 bpf_cgroup_storage_assign(env->prog->aux, map)) {
17591 verbose(env, "only one cgroup storage of each type is allowed\n");
17603 /* Basic sanity check before we invest more work here. */
17604 if (!bpf_opcode_in_insntable(insn->code)) {
17605 verbose(env, "unknown opcode %02x\n", insn->code);
17610 /* now all pseudo BPF_LD_IMM64 instructions load valid
17611 * 'struct bpf_map *' into a register instead of user map_fd.
17612 * These pointers will be used later by verifier to validate map access.
17617 /* drop refcnt of maps used by the rejected program */
17618 static void release_maps(struct bpf_verifier_env *env)
17620 __bpf_free_used_maps(env->prog->aux, env->used_maps,
17621 env->used_map_cnt);
17624 /* drop refcnt of maps used by the rejected program */
17625 static void release_btfs(struct bpf_verifier_env *env)
17627 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17628 env->used_btf_cnt);
17631 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17632 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17634 struct bpf_insn *insn = env->prog->insnsi;
17635 int insn_cnt = env->prog->len;
17638 for (i = 0; i < insn_cnt; i++, insn++) {
17639 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17641 if (insn->src_reg == BPF_PSEUDO_FUNC)
17647 /* single env->prog->insni[off] instruction was replaced with the range
17648 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
17649 * [0, off) and [off, end) to new locations, so the patched range stays zero
17651 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17652 struct bpf_insn_aux_data *new_data,
17653 struct bpf_prog *new_prog, u32 off, u32 cnt)
17655 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17656 struct bpf_insn *insn = new_prog->insnsi;
17657 u32 old_seen = old_data[off].seen;
17661 /* aux info at OFF always needs adjustment, no matter fast path
17662 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17663 * original insn at old prog.
17665 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17669 prog_len = new_prog->len;
17671 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17672 memcpy(new_data + off + cnt - 1, old_data + off,
17673 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17674 for (i = off; i < off + cnt - 1; i++) {
17675 /* Expand insni[off]'s seen count to the patched range. */
17676 new_data[i].seen = old_seen;
17677 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17679 env->insn_aux_data = new_data;
17683 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17689 /* NOTE: fake 'exit' subprog should be updated as well. */
17690 for (i = 0; i <= env->subprog_cnt; i++) {
17691 if (env->subprog_info[i].start <= off)
17693 env->subprog_info[i].start += len - 1;
17697 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17699 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17700 int i, sz = prog->aux->size_poke_tab;
17701 struct bpf_jit_poke_descriptor *desc;
17703 for (i = 0; i < sz; i++) {
17705 if (desc->insn_idx <= off)
17707 desc->insn_idx += len - 1;
17711 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17712 const struct bpf_insn *patch, u32 len)
17714 struct bpf_prog *new_prog;
17715 struct bpf_insn_aux_data *new_data = NULL;
17718 new_data = vzalloc(array_size(env->prog->len + len - 1,
17719 sizeof(struct bpf_insn_aux_data)));
17724 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17725 if (IS_ERR(new_prog)) {
17726 if (PTR_ERR(new_prog) == -ERANGE)
17728 "insn %d cannot be patched due to 16-bit range\n",
17729 env->insn_aux_data[off].orig_idx);
17733 adjust_insn_aux_data(env, new_data, new_prog, off, len);
17734 adjust_subprog_starts(env, off, len);
17735 adjust_poke_descs(new_prog, off, len);
17739 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17744 /* find first prog starting at or after off (first to remove) */
17745 for (i = 0; i < env->subprog_cnt; i++)
17746 if (env->subprog_info[i].start >= off)
17748 /* find first prog starting at or after off + cnt (first to stay) */
17749 for (j = i; j < env->subprog_cnt; j++)
17750 if (env->subprog_info[j].start >= off + cnt)
17752 /* if j doesn't start exactly at off + cnt, we are just removing
17753 * the front of previous prog
17755 if (env->subprog_info[j].start != off + cnt)
17759 struct bpf_prog_aux *aux = env->prog->aux;
17762 /* move fake 'exit' subprog as well */
17763 move = env->subprog_cnt + 1 - j;
17765 memmove(env->subprog_info + i,
17766 env->subprog_info + j,
17767 sizeof(*env->subprog_info) * move);
17768 env->subprog_cnt -= j - i;
17770 /* remove func_info */
17771 if (aux->func_info) {
17772 move = aux->func_info_cnt - j;
17774 memmove(aux->func_info + i,
17775 aux->func_info + j,
17776 sizeof(*aux->func_info) * move);
17777 aux->func_info_cnt -= j - i;
17778 /* func_info->insn_off is set after all code rewrites,
17779 * in adjust_btf_func() - no need to adjust
17783 /* convert i from "first prog to remove" to "first to adjust" */
17784 if (env->subprog_info[i].start == off)
17788 /* update fake 'exit' subprog as well */
17789 for (; i <= env->subprog_cnt; i++)
17790 env->subprog_info[i].start -= cnt;
17795 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17798 struct bpf_prog *prog = env->prog;
17799 u32 i, l_off, l_cnt, nr_linfo;
17800 struct bpf_line_info *linfo;
17802 nr_linfo = prog->aux->nr_linfo;
17806 linfo = prog->aux->linfo;
17808 /* find first line info to remove, count lines to be removed */
17809 for (i = 0; i < nr_linfo; i++)
17810 if (linfo[i].insn_off >= off)
17815 for (; i < nr_linfo; i++)
17816 if (linfo[i].insn_off < off + cnt)
17821 /* First live insn doesn't match first live linfo, it needs to "inherit"
17822 * last removed linfo. prog is already modified, so prog->len == off
17823 * means no live instructions after (tail of the program was removed).
17825 if (prog->len != off && l_cnt &&
17826 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17828 linfo[--i].insn_off = off + cnt;
17831 /* remove the line info which refer to the removed instructions */
17833 memmove(linfo + l_off, linfo + i,
17834 sizeof(*linfo) * (nr_linfo - i));
17836 prog->aux->nr_linfo -= l_cnt;
17837 nr_linfo = prog->aux->nr_linfo;
17840 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17841 for (i = l_off; i < nr_linfo; i++)
17842 linfo[i].insn_off -= cnt;
17844 /* fix up all subprogs (incl. 'exit') which start >= off */
17845 for (i = 0; i <= env->subprog_cnt; i++)
17846 if (env->subprog_info[i].linfo_idx > l_off) {
17847 /* program may have started in the removed region but
17848 * may not be fully removed
17850 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17851 env->subprog_info[i].linfo_idx -= l_cnt;
17853 env->subprog_info[i].linfo_idx = l_off;
17859 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17861 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17862 unsigned int orig_prog_len = env->prog->len;
17865 if (bpf_prog_is_offloaded(env->prog->aux))
17866 bpf_prog_offload_remove_insns(env, off, cnt);
17868 err = bpf_remove_insns(env->prog, off, cnt);
17872 err = adjust_subprog_starts_after_remove(env, off, cnt);
17876 err = bpf_adj_linfo_after_remove(env, off, cnt);
17880 memmove(aux_data + off, aux_data + off + cnt,
17881 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17886 /* The verifier does more data flow analysis than llvm and will not
17887 * explore branches that are dead at run time. Malicious programs can
17888 * have dead code too. Therefore replace all dead at-run-time code
17891 * Just nops are not optimal, e.g. if they would sit at the end of the
17892 * program and through another bug we would manage to jump there, then
17893 * we'd execute beyond program memory otherwise. Returning exception
17894 * code also wouldn't work since we can have subprogs where the dead
17895 * code could be located.
17897 static void sanitize_dead_code(struct bpf_verifier_env *env)
17899 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17900 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17901 struct bpf_insn *insn = env->prog->insnsi;
17902 const int insn_cnt = env->prog->len;
17905 for (i = 0; i < insn_cnt; i++) {
17906 if (aux_data[i].seen)
17908 memcpy(insn + i, &trap, sizeof(trap));
17909 aux_data[i].zext_dst = false;
17913 static bool insn_is_cond_jump(u8 code)
17918 if (BPF_CLASS(code) == BPF_JMP32)
17919 return op != BPF_JA;
17921 if (BPF_CLASS(code) != BPF_JMP)
17924 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17927 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17929 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17930 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17931 struct bpf_insn *insn = env->prog->insnsi;
17932 const int insn_cnt = env->prog->len;
17935 for (i = 0; i < insn_cnt; i++, insn++) {
17936 if (!insn_is_cond_jump(insn->code))
17939 if (!aux_data[i + 1].seen)
17940 ja.off = insn->off;
17941 else if (!aux_data[i + 1 + insn->off].seen)
17946 if (bpf_prog_is_offloaded(env->prog->aux))
17947 bpf_prog_offload_replace_insn(env, i, &ja);
17949 memcpy(insn, &ja, sizeof(ja));
17953 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17955 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17956 int insn_cnt = env->prog->len;
17959 for (i = 0; i < insn_cnt; i++) {
17963 while (i + j < insn_cnt && !aux_data[i + j].seen)
17968 err = verifier_remove_insns(env, i, j);
17971 insn_cnt = env->prog->len;
17977 static int opt_remove_nops(struct bpf_verifier_env *env)
17979 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17980 struct bpf_insn *insn = env->prog->insnsi;
17981 int insn_cnt = env->prog->len;
17984 for (i = 0; i < insn_cnt; i++) {
17985 if (memcmp(&insn[i], &ja, sizeof(ja)))
17988 err = verifier_remove_insns(env, i, 1);
17998 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17999 const union bpf_attr *attr)
18001 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18002 struct bpf_insn_aux_data *aux = env->insn_aux_data;
18003 int i, patch_len, delta = 0, len = env->prog->len;
18004 struct bpf_insn *insns = env->prog->insnsi;
18005 struct bpf_prog *new_prog;
18008 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18009 zext_patch[1] = BPF_ZEXT_REG(0);
18010 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18011 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18012 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18013 for (i = 0; i < len; i++) {
18014 int adj_idx = i + delta;
18015 struct bpf_insn insn;
18018 insn = insns[adj_idx];
18019 load_reg = insn_def_regno(&insn);
18020 if (!aux[adj_idx].zext_dst) {
18028 class = BPF_CLASS(code);
18029 if (load_reg == -1)
18032 /* NOTE: arg "reg" (the fourth one) is only used for
18033 * BPF_STX + SRC_OP, so it is safe to pass NULL
18036 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18037 if (class == BPF_LD &&
18038 BPF_MODE(code) == BPF_IMM)
18043 /* ctx load could be transformed into wider load. */
18044 if (class == BPF_LDX &&
18045 aux[adj_idx].ptr_type == PTR_TO_CTX)
18048 imm_rnd = get_random_u32();
18049 rnd_hi32_patch[0] = insn;
18050 rnd_hi32_patch[1].imm = imm_rnd;
18051 rnd_hi32_patch[3].dst_reg = load_reg;
18052 patch = rnd_hi32_patch;
18054 goto apply_patch_buffer;
18057 /* Add in an zero-extend instruction if a) the JIT has requested
18058 * it or b) it's a CMPXCHG.
18060 * The latter is because: BPF_CMPXCHG always loads a value into
18061 * R0, therefore always zero-extends. However some archs'
18062 * equivalent instruction only does this load when the
18063 * comparison is successful. This detail of CMPXCHG is
18064 * orthogonal to the general zero-extension behaviour of the
18065 * CPU, so it's treated independently of bpf_jit_needs_zext.
18067 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18070 /* Zero-extension is done by the caller. */
18071 if (bpf_pseudo_kfunc_call(&insn))
18074 if (WARN_ON(load_reg == -1)) {
18075 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18079 zext_patch[0] = insn;
18080 zext_patch[1].dst_reg = load_reg;
18081 zext_patch[1].src_reg = load_reg;
18082 patch = zext_patch;
18084 apply_patch_buffer:
18085 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18088 env->prog = new_prog;
18089 insns = new_prog->insnsi;
18090 aux = env->insn_aux_data;
18091 delta += patch_len - 1;
18097 /* convert load instructions that access fields of a context type into a
18098 * sequence of instructions that access fields of the underlying structure:
18099 * struct __sk_buff -> struct sk_buff
18100 * struct bpf_sock_ops -> struct sock
18102 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18104 const struct bpf_verifier_ops *ops = env->ops;
18105 int i, cnt, size, ctx_field_size, delta = 0;
18106 const int insn_cnt = env->prog->len;
18107 struct bpf_insn insn_buf[16], *insn;
18108 u32 target_size, size_default, off;
18109 struct bpf_prog *new_prog;
18110 enum bpf_access_type type;
18111 bool is_narrower_load;
18113 if (ops->gen_prologue || env->seen_direct_write) {
18114 if (!ops->gen_prologue) {
18115 verbose(env, "bpf verifier is misconfigured\n");
18118 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18120 if (cnt >= ARRAY_SIZE(insn_buf)) {
18121 verbose(env, "bpf verifier is misconfigured\n");
18124 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18128 env->prog = new_prog;
18133 if (bpf_prog_is_offloaded(env->prog->aux))
18136 insn = env->prog->insnsi + delta;
18138 for (i = 0; i < insn_cnt; i++, insn++) {
18139 bpf_convert_ctx_access_t convert_ctx_access;
18142 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18143 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18144 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18145 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18146 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18147 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18148 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18150 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18151 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18152 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18153 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18154 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18155 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18156 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18157 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18163 if (type == BPF_WRITE &&
18164 env->insn_aux_data[i + delta].sanitize_stack_spill) {
18165 struct bpf_insn patch[] = {
18170 cnt = ARRAY_SIZE(patch);
18171 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18176 env->prog = new_prog;
18177 insn = new_prog->insnsi + i + delta;
18181 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18183 if (!ops->convert_ctx_access)
18185 convert_ctx_access = ops->convert_ctx_access;
18187 case PTR_TO_SOCKET:
18188 case PTR_TO_SOCK_COMMON:
18189 convert_ctx_access = bpf_sock_convert_ctx_access;
18191 case PTR_TO_TCP_SOCK:
18192 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18194 case PTR_TO_XDP_SOCK:
18195 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18197 case PTR_TO_BTF_ID:
18198 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18199 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18200 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18201 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18202 * any faults for loads into such types. BPF_WRITE is disallowed
18205 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18206 if (type == BPF_READ) {
18207 if (BPF_MODE(insn->code) == BPF_MEM)
18208 insn->code = BPF_LDX | BPF_PROBE_MEM |
18209 BPF_SIZE((insn)->code);
18211 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18212 BPF_SIZE((insn)->code);
18213 env->prog->aux->num_exentries++;
18220 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18221 size = BPF_LDST_BYTES(insn);
18222 mode = BPF_MODE(insn->code);
18224 /* If the read access is a narrower load of the field,
18225 * convert to a 4/8-byte load, to minimum program type specific
18226 * convert_ctx_access changes. If conversion is successful,
18227 * we will apply proper mask to the result.
18229 is_narrower_load = size < ctx_field_size;
18230 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18232 if (is_narrower_load) {
18235 if (type == BPF_WRITE) {
18236 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18241 if (ctx_field_size == 4)
18243 else if (ctx_field_size == 8)
18244 size_code = BPF_DW;
18246 insn->off = off & ~(size_default - 1);
18247 insn->code = BPF_LDX | BPF_MEM | size_code;
18251 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18253 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18254 (ctx_field_size && !target_size)) {
18255 verbose(env, "bpf verifier is misconfigured\n");
18259 if (is_narrower_load && size < target_size) {
18260 u8 shift = bpf_ctx_narrow_access_offset(
18261 off, size, size_default) * 8;
18262 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18263 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18266 if (ctx_field_size <= 4) {
18268 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18271 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18272 (1 << size * 8) - 1);
18275 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18278 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18279 (1ULL << size * 8) - 1);
18282 if (mode == BPF_MEMSX)
18283 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18284 insn->dst_reg, insn->dst_reg,
18287 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18293 /* keep walking new program and skip insns we just inserted */
18294 env->prog = new_prog;
18295 insn = new_prog->insnsi + i + delta;
18301 static int jit_subprogs(struct bpf_verifier_env *env)
18303 struct bpf_prog *prog = env->prog, **func, *tmp;
18304 int i, j, subprog_start, subprog_end = 0, len, subprog;
18305 struct bpf_map *map_ptr;
18306 struct bpf_insn *insn;
18307 void *old_bpf_func;
18308 int err, num_exentries;
18310 if (env->subprog_cnt <= 1)
18313 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18314 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18317 /* Upon error here we cannot fall back to interpreter but
18318 * need a hard reject of the program. Thus -EFAULT is
18319 * propagated in any case.
18321 subprog = find_subprog(env, i + insn->imm + 1);
18323 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18324 i + insn->imm + 1);
18327 /* temporarily remember subprog id inside insn instead of
18328 * aux_data, since next loop will split up all insns into funcs
18330 insn->off = subprog;
18331 /* remember original imm in case JIT fails and fallback
18332 * to interpreter will be needed
18334 env->insn_aux_data[i].call_imm = insn->imm;
18335 /* point imm to __bpf_call_base+1 from JITs point of view */
18337 if (bpf_pseudo_func(insn))
18338 /* jit (e.g. x86_64) may emit fewer instructions
18339 * if it learns a u32 imm is the same as a u64 imm.
18340 * Force a non zero here.
18345 err = bpf_prog_alloc_jited_linfo(prog);
18347 goto out_undo_insn;
18350 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18352 goto out_undo_insn;
18354 for (i = 0; i < env->subprog_cnt; i++) {
18355 subprog_start = subprog_end;
18356 subprog_end = env->subprog_info[i + 1].start;
18358 len = subprog_end - subprog_start;
18359 /* bpf_prog_run() doesn't call subprogs directly,
18360 * hence main prog stats include the runtime of subprogs.
18361 * subprogs don't have IDs and not reachable via prog_get_next_id
18362 * func[i]->stats will never be accessed and stays NULL
18364 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18367 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18368 len * sizeof(struct bpf_insn));
18369 func[i]->type = prog->type;
18370 func[i]->len = len;
18371 if (bpf_prog_calc_tag(func[i]))
18373 func[i]->is_func = 1;
18374 func[i]->aux->func_idx = i;
18375 /* Below members will be freed only at prog->aux */
18376 func[i]->aux->btf = prog->aux->btf;
18377 func[i]->aux->func_info = prog->aux->func_info;
18378 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18379 func[i]->aux->poke_tab = prog->aux->poke_tab;
18380 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18382 for (j = 0; j < prog->aux->size_poke_tab; j++) {
18383 struct bpf_jit_poke_descriptor *poke;
18385 poke = &prog->aux->poke_tab[j];
18386 if (poke->insn_idx < subprog_end &&
18387 poke->insn_idx >= subprog_start)
18388 poke->aux = func[i]->aux;
18391 func[i]->aux->name[0] = 'F';
18392 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18393 func[i]->jit_requested = 1;
18394 func[i]->blinding_requested = prog->blinding_requested;
18395 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18396 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18397 func[i]->aux->linfo = prog->aux->linfo;
18398 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18399 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18400 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18402 insn = func[i]->insnsi;
18403 for (j = 0; j < func[i]->len; j++, insn++) {
18404 if (BPF_CLASS(insn->code) == BPF_LDX &&
18405 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18406 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18409 func[i]->aux->num_exentries = num_exentries;
18410 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18411 func[i] = bpf_int_jit_compile(func[i]);
18412 if (!func[i]->jited) {
18419 /* at this point all bpf functions were successfully JITed
18420 * now populate all bpf_calls with correct addresses and
18421 * run last pass of JIT
18423 for (i = 0; i < env->subprog_cnt; i++) {
18424 insn = func[i]->insnsi;
18425 for (j = 0; j < func[i]->len; j++, insn++) {
18426 if (bpf_pseudo_func(insn)) {
18427 subprog = insn->off;
18428 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18429 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18432 if (!bpf_pseudo_call(insn))
18434 subprog = insn->off;
18435 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18438 /* we use the aux data to keep a list of the start addresses
18439 * of the JITed images for each function in the program
18441 * for some architectures, such as powerpc64, the imm field
18442 * might not be large enough to hold the offset of the start
18443 * address of the callee's JITed image from __bpf_call_base
18445 * in such cases, we can lookup the start address of a callee
18446 * by using its subprog id, available from the off field of
18447 * the call instruction, as an index for this list
18449 func[i]->aux->func = func;
18450 func[i]->aux->func_cnt = env->subprog_cnt;
18452 for (i = 0; i < env->subprog_cnt; i++) {
18453 old_bpf_func = func[i]->bpf_func;
18454 tmp = bpf_int_jit_compile(func[i]);
18455 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18456 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18463 /* finally lock prog and jit images for all functions and
18464 * populate kallsysm. Begin at the first subprogram, since
18465 * bpf_prog_load will add the kallsyms for the main program.
18467 for (i = 1; i < env->subprog_cnt; i++) {
18468 bpf_prog_lock_ro(func[i]);
18469 bpf_prog_kallsyms_add(func[i]);
18472 /* Last step: make now unused interpreter insns from main
18473 * prog consistent for later dump requests, so they can
18474 * later look the same as if they were interpreted only.
18476 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18477 if (bpf_pseudo_func(insn)) {
18478 insn[0].imm = env->insn_aux_data[i].call_imm;
18479 insn[1].imm = insn->off;
18483 if (!bpf_pseudo_call(insn))
18485 insn->off = env->insn_aux_data[i].call_imm;
18486 subprog = find_subprog(env, i + insn->off + 1);
18487 insn->imm = subprog;
18491 prog->bpf_func = func[0]->bpf_func;
18492 prog->jited_len = func[0]->jited_len;
18493 prog->aux->extable = func[0]->aux->extable;
18494 prog->aux->num_exentries = func[0]->aux->num_exentries;
18495 prog->aux->func = func;
18496 prog->aux->func_cnt = env->subprog_cnt;
18497 bpf_prog_jit_attempt_done(prog);
18500 /* We failed JIT'ing, so at this point we need to unregister poke
18501 * descriptors from subprogs, so that kernel is not attempting to
18502 * patch it anymore as we're freeing the subprog JIT memory.
18504 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18505 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18506 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18508 /* At this point we're guaranteed that poke descriptors are not
18509 * live anymore. We can just unlink its descriptor table as it's
18510 * released with the main prog.
18512 for (i = 0; i < env->subprog_cnt; i++) {
18515 func[i]->aux->poke_tab = NULL;
18516 bpf_jit_free(func[i]);
18520 /* cleanup main prog to be interpreted */
18521 prog->jit_requested = 0;
18522 prog->blinding_requested = 0;
18523 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18524 if (!bpf_pseudo_call(insn))
18527 insn->imm = env->insn_aux_data[i].call_imm;
18529 bpf_prog_jit_attempt_done(prog);
18533 static int fixup_call_args(struct bpf_verifier_env *env)
18535 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18536 struct bpf_prog *prog = env->prog;
18537 struct bpf_insn *insn = prog->insnsi;
18538 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18543 if (env->prog->jit_requested &&
18544 !bpf_prog_is_offloaded(env->prog->aux)) {
18545 err = jit_subprogs(env);
18548 if (err == -EFAULT)
18551 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18552 if (has_kfunc_call) {
18553 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18556 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18557 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18558 * have to be rejected, since interpreter doesn't support them yet.
18560 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18563 for (i = 0; i < prog->len; i++, insn++) {
18564 if (bpf_pseudo_func(insn)) {
18565 /* When JIT fails the progs with callback calls
18566 * have to be rejected, since interpreter doesn't support them yet.
18568 verbose(env, "callbacks are not allowed in non-JITed programs\n");
18572 if (!bpf_pseudo_call(insn))
18574 depth = get_callee_stack_depth(env, insn, i);
18577 bpf_patch_call_args(insn, depth);
18584 /* replace a generic kfunc with a specialized version if necessary */
18585 static void specialize_kfunc(struct bpf_verifier_env *env,
18586 u32 func_id, u16 offset, unsigned long *addr)
18588 struct bpf_prog *prog = env->prog;
18589 bool seen_direct_write;
18593 if (bpf_dev_bound_kfunc_id(func_id)) {
18594 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18596 *addr = (unsigned long)xdp_kfunc;
18599 /* fallback to default kfunc when not supported by netdev */
18605 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18606 seen_direct_write = env->seen_direct_write;
18607 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18610 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18612 /* restore env->seen_direct_write to its original value, since
18613 * may_access_direct_pkt_data mutates it
18615 env->seen_direct_write = seen_direct_write;
18619 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18620 u16 struct_meta_reg,
18621 u16 node_offset_reg,
18622 struct bpf_insn *insn,
18623 struct bpf_insn *insn_buf,
18626 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18627 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18629 insn_buf[0] = addr[0];
18630 insn_buf[1] = addr[1];
18631 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18632 insn_buf[3] = *insn;
18636 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18637 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18639 const struct bpf_kfunc_desc *desc;
18642 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18648 /* insn->imm has the btf func_id. Replace it with an offset relative to
18649 * __bpf_call_base, unless the JIT needs to call functions that are
18650 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18652 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18654 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18659 if (!bpf_jit_supports_far_kfunc_call())
18660 insn->imm = BPF_CALL_IMM(desc->addr);
18663 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18664 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18665 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18666 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18668 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18669 insn_buf[1] = addr[0];
18670 insn_buf[2] = addr[1];
18671 insn_buf[3] = *insn;
18673 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18674 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18675 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18676 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18678 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18679 !kptr_struct_meta) {
18680 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18685 insn_buf[0] = addr[0];
18686 insn_buf[1] = addr[1];
18687 insn_buf[2] = *insn;
18689 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18690 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18691 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18692 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18693 int struct_meta_reg = BPF_REG_3;
18694 int node_offset_reg = BPF_REG_4;
18696 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18697 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18698 struct_meta_reg = BPF_REG_4;
18699 node_offset_reg = BPF_REG_5;
18702 if (!kptr_struct_meta) {
18703 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18708 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18709 node_offset_reg, insn, insn_buf, cnt);
18710 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18711 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18712 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18718 /* Do various post-verification rewrites in a single program pass.
18719 * These rewrites simplify JIT and interpreter implementations.
18721 static int do_misc_fixups(struct bpf_verifier_env *env)
18723 struct bpf_prog *prog = env->prog;
18724 enum bpf_attach_type eatype = prog->expected_attach_type;
18725 enum bpf_prog_type prog_type = resolve_prog_type(prog);
18726 struct bpf_insn *insn = prog->insnsi;
18727 const struct bpf_func_proto *fn;
18728 const int insn_cnt = prog->len;
18729 const struct bpf_map_ops *ops;
18730 struct bpf_insn_aux_data *aux;
18731 struct bpf_insn insn_buf[16];
18732 struct bpf_prog *new_prog;
18733 struct bpf_map *map_ptr;
18734 int i, ret, cnt, delta = 0;
18736 for (i = 0; i < insn_cnt; i++, insn++) {
18737 /* Make divide-by-zero exceptions impossible. */
18738 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18739 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18740 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18741 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18742 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18743 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18744 struct bpf_insn *patchlet;
18745 struct bpf_insn chk_and_div[] = {
18746 /* [R,W]x div 0 -> 0 */
18747 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18748 BPF_JNE | BPF_K, insn->src_reg,
18750 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18751 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18754 struct bpf_insn chk_and_mod[] = {
18755 /* [R,W]x mod 0 -> [R,W]x */
18756 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18757 BPF_JEQ | BPF_K, insn->src_reg,
18758 0, 1 + (is64 ? 0 : 1), 0),
18760 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18761 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18764 patchlet = isdiv ? chk_and_div : chk_and_mod;
18765 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18766 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18768 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18773 env->prog = prog = new_prog;
18774 insn = new_prog->insnsi + i + delta;
18778 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18779 if (BPF_CLASS(insn->code) == BPF_LD &&
18780 (BPF_MODE(insn->code) == BPF_ABS ||
18781 BPF_MODE(insn->code) == BPF_IND)) {
18782 cnt = env->ops->gen_ld_abs(insn, insn_buf);
18783 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18784 verbose(env, "bpf verifier is misconfigured\n");
18788 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18793 env->prog = prog = new_prog;
18794 insn = new_prog->insnsi + i + delta;
18798 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18799 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18800 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18801 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18802 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18803 struct bpf_insn *patch = &insn_buf[0];
18804 bool issrc, isneg, isimm;
18807 aux = &env->insn_aux_data[i + delta];
18808 if (!aux->alu_state ||
18809 aux->alu_state == BPF_ALU_NON_POINTER)
18812 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18813 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18814 BPF_ALU_SANITIZE_SRC;
18815 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18817 off_reg = issrc ? insn->src_reg : insn->dst_reg;
18819 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18822 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18823 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18824 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18825 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18826 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18827 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18828 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18831 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18832 insn->src_reg = BPF_REG_AX;
18834 insn->code = insn->code == code_add ?
18835 code_sub : code_add;
18837 if (issrc && isneg && !isimm)
18838 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18839 cnt = patch - insn_buf;
18841 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18846 env->prog = prog = new_prog;
18847 insn = new_prog->insnsi + i + delta;
18851 if (insn->code != (BPF_JMP | BPF_CALL))
18853 if (insn->src_reg == BPF_PSEUDO_CALL)
18855 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18856 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18862 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18867 env->prog = prog = new_prog;
18868 insn = new_prog->insnsi + i + delta;
18872 if (insn->imm == BPF_FUNC_get_route_realm)
18873 prog->dst_needed = 1;
18874 if (insn->imm == BPF_FUNC_get_prandom_u32)
18875 bpf_user_rnd_init_once();
18876 if (insn->imm == BPF_FUNC_override_return)
18877 prog->kprobe_override = 1;
18878 if (insn->imm == BPF_FUNC_tail_call) {
18879 /* If we tail call into other programs, we
18880 * cannot make any assumptions since they can
18881 * be replaced dynamically during runtime in
18882 * the program array.
18884 prog->cb_access = 1;
18885 if (!allow_tail_call_in_subprogs(env))
18886 prog->aux->stack_depth = MAX_BPF_STACK;
18887 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18889 /* mark bpf_tail_call as different opcode to avoid
18890 * conditional branch in the interpreter for every normal
18891 * call and to prevent accidental JITing by JIT compiler
18892 * that doesn't support bpf_tail_call yet
18895 insn->code = BPF_JMP | BPF_TAIL_CALL;
18897 aux = &env->insn_aux_data[i + delta];
18898 if (env->bpf_capable && !prog->blinding_requested &&
18899 prog->jit_requested &&
18900 !bpf_map_key_poisoned(aux) &&
18901 !bpf_map_ptr_poisoned(aux) &&
18902 !bpf_map_ptr_unpriv(aux)) {
18903 struct bpf_jit_poke_descriptor desc = {
18904 .reason = BPF_POKE_REASON_TAIL_CALL,
18905 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18906 .tail_call.key = bpf_map_key_immediate(aux),
18907 .insn_idx = i + delta,
18910 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18912 verbose(env, "adding tail call poke descriptor failed\n");
18916 insn->imm = ret + 1;
18920 if (!bpf_map_ptr_unpriv(aux))
18923 /* instead of changing every JIT dealing with tail_call
18924 * emit two extra insns:
18925 * if (index >= max_entries) goto out;
18926 * index &= array->index_mask;
18927 * to avoid out-of-bounds cpu speculation
18929 if (bpf_map_ptr_poisoned(aux)) {
18930 verbose(env, "tail_call abusing map_ptr\n");
18934 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18935 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18936 map_ptr->max_entries, 2);
18937 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18938 container_of(map_ptr,
18941 insn_buf[2] = *insn;
18943 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18948 env->prog = prog = new_prog;
18949 insn = new_prog->insnsi + i + delta;
18953 if (insn->imm == BPF_FUNC_timer_set_callback) {
18954 /* The verifier will process callback_fn as many times as necessary
18955 * with different maps and the register states prepared by
18956 * set_timer_callback_state will be accurate.
18958 * The following use case is valid:
18959 * map1 is shared by prog1, prog2, prog3.
18960 * prog1 calls bpf_timer_init for some map1 elements
18961 * prog2 calls bpf_timer_set_callback for some map1 elements.
18962 * Those that were not bpf_timer_init-ed will return -EINVAL.
18963 * prog3 calls bpf_timer_start for some map1 elements.
18964 * Those that were not both bpf_timer_init-ed and
18965 * bpf_timer_set_callback-ed will return -EINVAL.
18967 struct bpf_insn ld_addrs[2] = {
18968 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18971 insn_buf[0] = ld_addrs[0];
18972 insn_buf[1] = ld_addrs[1];
18973 insn_buf[2] = *insn;
18976 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18981 env->prog = prog = new_prog;
18982 insn = new_prog->insnsi + i + delta;
18983 goto patch_call_imm;
18986 if (is_storage_get_function(insn->imm)) {
18987 if (!env->prog->aux->sleepable ||
18988 env->insn_aux_data[i + delta].storage_get_func_atomic)
18989 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18991 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18992 insn_buf[1] = *insn;
18995 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19000 env->prog = prog = new_prog;
19001 insn = new_prog->insnsi + i + delta;
19002 goto patch_call_imm;
19005 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19006 * and other inlining handlers are currently limited to 64 bit
19009 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19010 (insn->imm == BPF_FUNC_map_lookup_elem ||
19011 insn->imm == BPF_FUNC_map_update_elem ||
19012 insn->imm == BPF_FUNC_map_delete_elem ||
19013 insn->imm == BPF_FUNC_map_push_elem ||
19014 insn->imm == BPF_FUNC_map_pop_elem ||
19015 insn->imm == BPF_FUNC_map_peek_elem ||
19016 insn->imm == BPF_FUNC_redirect_map ||
19017 insn->imm == BPF_FUNC_for_each_map_elem ||
19018 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19019 aux = &env->insn_aux_data[i + delta];
19020 if (bpf_map_ptr_poisoned(aux))
19021 goto patch_call_imm;
19023 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19024 ops = map_ptr->ops;
19025 if (insn->imm == BPF_FUNC_map_lookup_elem &&
19026 ops->map_gen_lookup) {
19027 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19028 if (cnt == -EOPNOTSUPP)
19029 goto patch_map_ops_generic;
19030 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19031 verbose(env, "bpf verifier is misconfigured\n");
19035 new_prog = bpf_patch_insn_data(env, i + delta,
19041 env->prog = prog = new_prog;
19042 insn = new_prog->insnsi + i + delta;
19046 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19047 (void *(*)(struct bpf_map *map, void *key))NULL));
19048 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19049 (long (*)(struct bpf_map *map, void *key))NULL));
19050 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19051 (long (*)(struct bpf_map *map, void *key, void *value,
19053 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19054 (long (*)(struct bpf_map *map, void *value,
19056 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19057 (long (*)(struct bpf_map *map, void *value))NULL));
19058 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19059 (long (*)(struct bpf_map *map, void *value))NULL));
19060 BUILD_BUG_ON(!__same_type(ops->map_redirect,
19061 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19062 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19063 (long (*)(struct bpf_map *map,
19064 bpf_callback_t callback_fn,
19065 void *callback_ctx,
19067 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19068 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19070 patch_map_ops_generic:
19071 switch (insn->imm) {
19072 case BPF_FUNC_map_lookup_elem:
19073 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19075 case BPF_FUNC_map_update_elem:
19076 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19078 case BPF_FUNC_map_delete_elem:
19079 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19081 case BPF_FUNC_map_push_elem:
19082 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19084 case BPF_FUNC_map_pop_elem:
19085 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19087 case BPF_FUNC_map_peek_elem:
19088 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19090 case BPF_FUNC_redirect_map:
19091 insn->imm = BPF_CALL_IMM(ops->map_redirect);
19093 case BPF_FUNC_for_each_map_elem:
19094 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19096 case BPF_FUNC_map_lookup_percpu_elem:
19097 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19101 goto patch_call_imm;
19104 /* Implement bpf_jiffies64 inline. */
19105 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19106 insn->imm == BPF_FUNC_jiffies64) {
19107 struct bpf_insn ld_jiffies_addr[2] = {
19108 BPF_LD_IMM64(BPF_REG_0,
19109 (unsigned long)&jiffies),
19112 insn_buf[0] = ld_jiffies_addr[0];
19113 insn_buf[1] = ld_jiffies_addr[1];
19114 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19118 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19124 env->prog = prog = new_prog;
19125 insn = new_prog->insnsi + i + delta;
19129 /* Implement bpf_get_func_arg inline. */
19130 if (prog_type == BPF_PROG_TYPE_TRACING &&
19131 insn->imm == BPF_FUNC_get_func_arg) {
19132 /* Load nr_args from ctx - 8 */
19133 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19134 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19135 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19136 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19137 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19138 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19139 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19140 insn_buf[7] = BPF_JMP_A(1);
19141 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19144 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19149 env->prog = prog = new_prog;
19150 insn = new_prog->insnsi + i + delta;
19154 /* Implement bpf_get_func_ret inline. */
19155 if (prog_type == BPF_PROG_TYPE_TRACING &&
19156 insn->imm == BPF_FUNC_get_func_ret) {
19157 if (eatype == BPF_TRACE_FEXIT ||
19158 eatype == BPF_MODIFY_RETURN) {
19159 /* Load nr_args from ctx - 8 */
19160 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19161 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19162 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19163 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19164 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19165 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19168 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19172 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19177 env->prog = prog = new_prog;
19178 insn = new_prog->insnsi + i + delta;
19182 /* Implement get_func_arg_cnt inline. */
19183 if (prog_type == BPF_PROG_TYPE_TRACING &&
19184 insn->imm == BPF_FUNC_get_func_arg_cnt) {
19185 /* Load nr_args from ctx - 8 */
19186 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19188 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19192 env->prog = prog = new_prog;
19193 insn = new_prog->insnsi + i + delta;
19197 /* Implement bpf_get_func_ip inline. */
19198 if (prog_type == BPF_PROG_TYPE_TRACING &&
19199 insn->imm == BPF_FUNC_get_func_ip) {
19200 /* Load IP address from ctx - 16 */
19201 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19203 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19207 env->prog = prog = new_prog;
19208 insn = new_prog->insnsi + i + delta;
19213 fn = env->ops->get_func_proto(insn->imm, env->prog);
19214 /* all functions that have prototype and verifier allowed
19215 * programs to call them, must be real in-kernel functions
19219 "kernel subsystem misconfigured func %s#%d\n",
19220 func_id_name(insn->imm), insn->imm);
19223 insn->imm = fn->func - __bpf_call_base;
19226 /* Since poke tab is now finalized, publish aux to tracker. */
19227 for (i = 0; i < prog->aux->size_poke_tab; i++) {
19228 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19229 if (!map_ptr->ops->map_poke_track ||
19230 !map_ptr->ops->map_poke_untrack ||
19231 !map_ptr->ops->map_poke_run) {
19232 verbose(env, "bpf verifier is misconfigured\n");
19236 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19238 verbose(env, "tracking tail call prog failed\n");
19243 sort_kfunc_descs_by_imm_off(env->prog);
19248 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19251 u32 callback_subprogno,
19254 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19255 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19256 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19257 int reg_loop_max = BPF_REG_6;
19258 int reg_loop_cnt = BPF_REG_7;
19259 int reg_loop_ctx = BPF_REG_8;
19261 struct bpf_prog *new_prog;
19262 u32 callback_start;
19263 u32 call_insn_offset;
19264 s32 callback_offset;
19266 /* This represents an inlined version of bpf_iter.c:bpf_loop,
19267 * be careful to modify this code in sync.
19269 struct bpf_insn insn_buf[] = {
19270 /* Return error and jump to the end of the patch if
19271 * expected number of iterations is too big.
19273 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19274 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19275 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19276 /* spill R6, R7, R8 to use these as loop vars */
19277 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19278 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19279 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19280 /* initialize loop vars */
19281 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19282 BPF_MOV32_IMM(reg_loop_cnt, 0),
19283 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19285 * if reg_loop_cnt >= reg_loop_max skip the loop body
19287 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19289 * correct callback offset would be set after patching
19291 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19292 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19294 /* increment loop counter */
19295 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19296 /* jump to loop header if callback returned 0 */
19297 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19298 /* return value of bpf_loop,
19299 * set R0 to the number of iterations
19301 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19302 /* restore original values of R6, R7, R8 */
19303 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19304 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19305 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19308 *cnt = ARRAY_SIZE(insn_buf);
19309 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19313 /* callback start is known only after patching */
19314 callback_start = env->subprog_info[callback_subprogno].start;
19315 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19316 call_insn_offset = position + 12;
19317 callback_offset = callback_start - call_insn_offset - 1;
19318 new_prog->insnsi[call_insn_offset].imm = callback_offset;
19323 static bool is_bpf_loop_call(struct bpf_insn *insn)
19325 return insn->code == (BPF_JMP | BPF_CALL) &&
19326 insn->src_reg == 0 &&
19327 insn->imm == BPF_FUNC_loop;
19330 /* For all sub-programs in the program (including main) check
19331 * insn_aux_data to see if there are bpf_loop calls that require
19332 * inlining. If such calls are found the calls are replaced with a
19333 * sequence of instructions produced by `inline_bpf_loop` function and
19334 * subprog stack_depth is increased by the size of 3 registers.
19335 * This stack space is used to spill values of the R6, R7, R8. These
19336 * registers are used to store the loop bound, counter and context
19339 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19341 struct bpf_subprog_info *subprogs = env->subprog_info;
19342 int i, cur_subprog = 0, cnt, delta = 0;
19343 struct bpf_insn *insn = env->prog->insnsi;
19344 int insn_cnt = env->prog->len;
19345 u16 stack_depth = subprogs[cur_subprog].stack_depth;
19346 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19347 u16 stack_depth_extra = 0;
19349 for (i = 0; i < insn_cnt; i++, insn++) {
19350 struct bpf_loop_inline_state *inline_state =
19351 &env->insn_aux_data[i + delta].loop_inline_state;
19353 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19354 struct bpf_prog *new_prog;
19356 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19357 new_prog = inline_bpf_loop(env,
19359 -(stack_depth + stack_depth_extra),
19360 inline_state->callback_subprogno,
19366 env->prog = new_prog;
19367 insn = new_prog->insnsi + i + delta;
19370 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19371 subprogs[cur_subprog].stack_depth += stack_depth_extra;
19373 stack_depth = subprogs[cur_subprog].stack_depth;
19374 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19375 stack_depth_extra = 0;
19379 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19384 static void free_states(struct bpf_verifier_env *env)
19386 struct bpf_verifier_state_list *sl, *sln;
19389 sl = env->free_list;
19392 free_verifier_state(&sl->state, false);
19396 env->free_list = NULL;
19398 if (!env->explored_states)
19401 for (i = 0; i < state_htab_size(env); i++) {
19402 sl = env->explored_states[i];
19406 free_verifier_state(&sl->state, false);
19410 env->explored_states[i] = NULL;
19414 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19416 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19417 struct bpf_verifier_state *state;
19418 struct bpf_reg_state *regs;
19421 env->prev_linfo = NULL;
19424 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19427 state->curframe = 0;
19428 state->speculative = false;
19429 state->branches = 1;
19430 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19431 if (!state->frame[0]) {
19435 env->cur_state = state;
19436 init_func_state(env, state->frame[0],
19437 BPF_MAIN_FUNC /* callsite */,
19440 state->first_insn_idx = env->subprog_info[subprog].start;
19441 state->last_insn_idx = -1;
19443 regs = state->frame[state->curframe]->regs;
19444 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19445 ret = btf_prepare_func_args(env, subprog, regs);
19448 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19449 if (regs[i].type == PTR_TO_CTX)
19450 mark_reg_known_zero(env, regs, i);
19451 else if (regs[i].type == SCALAR_VALUE)
19452 mark_reg_unknown(env, regs, i);
19453 else if (base_type(regs[i].type) == PTR_TO_MEM) {
19454 const u32 mem_size = regs[i].mem_size;
19456 mark_reg_known_zero(env, regs, i);
19457 regs[i].mem_size = mem_size;
19458 regs[i].id = ++env->id_gen;
19462 /* 1st arg to a function */
19463 regs[BPF_REG_1].type = PTR_TO_CTX;
19464 mark_reg_known_zero(env, regs, BPF_REG_1);
19465 ret = btf_check_subprog_arg_match(env, subprog, regs);
19466 if (ret == -EFAULT)
19467 /* unlikely verifier bug. abort.
19468 * ret == 0 and ret < 0 are sadly acceptable for
19469 * main() function due to backward compatibility.
19470 * Like socket filter program may be written as:
19471 * int bpf_prog(struct pt_regs *ctx)
19472 * and never dereference that ctx in the program.
19473 * 'struct pt_regs' is a type mismatch for socket
19474 * filter that should be using 'struct __sk_buff'.
19479 ret = do_check(env);
19481 /* check for NULL is necessary, since cur_state can be freed inside
19482 * do_check() under memory pressure.
19484 if (env->cur_state) {
19485 free_verifier_state(env->cur_state, true);
19486 env->cur_state = NULL;
19488 while (!pop_stack(env, NULL, NULL, false));
19489 if (!ret && pop_log)
19490 bpf_vlog_reset(&env->log, 0);
19495 /* Verify all global functions in a BPF program one by one based on their BTF.
19496 * All global functions must pass verification. Otherwise the whole program is rejected.
19507 * foo() will be verified first for R1=any_scalar_value. During verification it
19508 * will be assumed that bar() already verified successfully and call to bar()
19509 * from foo() will be checked for type match only. Later bar() will be verified
19510 * independently to check that it's safe for R1=any_scalar_value.
19512 static int do_check_subprogs(struct bpf_verifier_env *env)
19514 struct bpf_prog_aux *aux = env->prog->aux;
19517 if (!aux->func_info)
19520 for (i = 1; i < env->subprog_cnt; i++) {
19521 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19523 env->insn_idx = env->subprog_info[i].start;
19524 WARN_ON_ONCE(env->insn_idx == 0);
19525 ret = do_check_common(env, i);
19528 } else if (env->log.level & BPF_LOG_LEVEL) {
19530 "Func#%d is safe for any args that match its prototype\n",
19537 static int do_check_main(struct bpf_verifier_env *env)
19542 ret = do_check_common(env, 0);
19544 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19549 static void print_verification_stats(struct bpf_verifier_env *env)
19553 if (env->log.level & BPF_LOG_STATS) {
19554 verbose(env, "verification time %lld usec\n",
19555 div_u64(env->verification_time, 1000));
19556 verbose(env, "stack depth ");
19557 for (i = 0; i < env->subprog_cnt; i++) {
19558 u32 depth = env->subprog_info[i].stack_depth;
19560 verbose(env, "%d", depth);
19561 if (i + 1 < env->subprog_cnt)
19564 verbose(env, "\n");
19566 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19567 "total_states %d peak_states %d mark_read %d\n",
19568 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19569 env->max_states_per_insn, env->total_states,
19570 env->peak_states, env->longest_mark_read_walk);
19573 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19575 const struct btf_type *t, *func_proto;
19576 const struct bpf_struct_ops *st_ops;
19577 const struct btf_member *member;
19578 struct bpf_prog *prog = env->prog;
19579 u32 btf_id, member_idx;
19582 if (!prog->gpl_compatible) {
19583 verbose(env, "struct ops programs must have a GPL compatible license\n");
19587 btf_id = prog->aux->attach_btf_id;
19588 st_ops = bpf_struct_ops_find(btf_id);
19590 verbose(env, "attach_btf_id %u is not a supported struct\n",
19596 member_idx = prog->expected_attach_type;
19597 if (member_idx >= btf_type_vlen(t)) {
19598 verbose(env, "attach to invalid member idx %u of struct %s\n",
19599 member_idx, st_ops->name);
19603 member = &btf_type_member(t)[member_idx];
19604 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19605 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19608 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19609 mname, member_idx, st_ops->name);
19613 if (st_ops->check_member) {
19614 int err = st_ops->check_member(t, member, prog);
19617 verbose(env, "attach to unsupported member %s of struct %s\n",
19618 mname, st_ops->name);
19623 prog->aux->attach_func_proto = func_proto;
19624 prog->aux->attach_func_name = mname;
19625 env->ops = st_ops->verifier_ops;
19629 #define SECURITY_PREFIX "security_"
19631 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19633 if (within_error_injection_list(addr) ||
19634 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19640 /* list of non-sleepable functions that are otherwise on
19641 * ALLOW_ERROR_INJECTION list
19643 BTF_SET_START(btf_non_sleepable_error_inject)
19644 /* Three functions below can be called from sleepable and non-sleepable context.
19645 * Assume non-sleepable from bpf safety point of view.
19647 BTF_ID(func, __filemap_add_folio)
19648 BTF_ID(func, should_fail_alloc_page)
19649 BTF_ID(func, should_failslab)
19650 BTF_SET_END(btf_non_sleepable_error_inject)
19652 static int check_non_sleepable_error_inject(u32 btf_id)
19654 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19657 int bpf_check_attach_target(struct bpf_verifier_log *log,
19658 const struct bpf_prog *prog,
19659 const struct bpf_prog *tgt_prog,
19661 struct bpf_attach_target_info *tgt_info)
19663 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19664 const char prefix[] = "btf_trace_";
19665 int ret = 0, subprog = -1, i;
19666 const struct btf_type *t;
19667 bool conservative = true;
19671 struct module *mod = NULL;
19674 bpf_log(log, "Tracing programs must provide btf_id\n");
19677 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19680 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19683 t = btf_type_by_id(btf, btf_id);
19685 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19688 tname = btf_name_by_offset(btf, t->name_off);
19690 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19694 struct bpf_prog_aux *aux = tgt_prog->aux;
19696 if (bpf_prog_is_dev_bound(prog->aux) &&
19697 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19698 bpf_log(log, "Target program bound device mismatch");
19702 for (i = 0; i < aux->func_info_cnt; i++)
19703 if (aux->func_info[i].type_id == btf_id) {
19707 if (subprog == -1) {
19708 bpf_log(log, "Subprog %s doesn't exist\n", tname);
19711 conservative = aux->func_info_aux[subprog].unreliable;
19712 if (prog_extension) {
19713 if (conservative) {
19715 "Cannot replace static functions\n");
19718 if (!prog->jit_requested) {
19720 "Extension programs should be JITed\n");
19724 if (!tgt_prog->jited) {
19725 bpf_log(log, "Can attach to only JITed progs\n");
19728 if (tgt_prog->type == prog->type) {
19729 /* Cannot fentry/fexit another fentry/fexit program.
19730 * Cannot attach program extension to another extension.
19731 * It's ok to attach fentry/fexit to extension program.
19733 bpf_log(log, "Cannot recursively attach\n");
19736 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19738 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19739 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19740 /* Program extensions can extend all program types
19741 * except fentry/fexit. The reason is the following.
19742 * The fentry/fexit programs are used for performance
19743 * analysis, stats and can be attached to any program
19744 * type except themselves. When extension program is
19745 * replacing XDP function it is necessary to allow
19746 * performance analysis of all functions. Both original
19747 * XDP program and its program extension. Hence
19748 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19749 * allowed. If extending of fentry/fexit was allowed it
19750 * would be possible to create long call chain
19751 * fentry->extension->fentry->extension beyond
19752 * reasonable stack size. Hence extending fentry is not
19755 bpf_log(log, "Cannot extend fentry/fexit\n");
19759 if (prog_extension) {
19760 bpf_log(log, "Cannot replace kernel functions\n");
19765 switch (prog->expected_attach_type) {
19766 case BPF_TRACE_RAW_TP:
19769 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19772 if (!btf_type_is_typedef(t)) {
19773 bpf_log(log, "attach_btf_id %u is not a typedef\n",
19777 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19778 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19782 tname += sizeof(prefix) - 1;
19783 t = btf_type_by_id(btf, t->type);
19784 if (!btf_type_is_ptr(t))
19785 /* should never happen in valid vmlinux build */
19787 t = btf_type_by_id(btf, t->type);
19788 if (!btf_type_is_func_proto(t))
19789 /* should never happen in valid vmlinux build */
19793 case BPF_TRACE_ITER:
19794 if (!btf_type_is_func(t)) {
19795 bpf_log(log, "attach_btf_id %u is not a function\n",
19799 t = btf_type_by_id(btf, t->type);
19800 if (!btf_type_is_func_proto(t))
19802 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19807 if (!prog_extension)
19810 case BPF_MODIFY_RETURN:
19812 case BPF_LSM_CGROUP:
19813 case BPF_TRACE_FENTRY:
19814 case BPF_TRACE_FEXIT:
19815 if (!btf_type_is_func(t)) {
19816 bpf_log(log, "attach_btf_id %u is not a function\n",
19820 if (prog_extension &&
19821 btf_check_type_match(log, prog, btf, t))
19823 t = btf_type_by_id(btf, t->type);
19824 if (!btf_type_is_func_proto(t))
19827 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19828 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19829 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19832 if (tgt_prog && conservative)
19835 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19841 addr = (long) tgt_prog->bpf_func;
19843 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19845 if (btf_is_module(btf)) {
19846 mod = btf_try_get_module(btf);
19848 addr = find_kallsyms_symbol_value(mod, tname);
19852 addr = kallsyms_lookup_name(tname);
19857 "The address of function %s cannot be found\n",
19863 if (prog->aux->sleepable) {
19865 switch (prog->type) {
19866 case BPF_PROG_TYPE_TRACING:
19868 /* fentry/fexit/fmod_ret progs can be sleepable if they are
19869 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19871 if (!check_non_sleepable_error_inject(btf_id) &&
19872 within_error_injection_list(addr))
19874 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19875 * in the fmodret id set with the KF_SLEEPABLE flag.
19878 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19881 if (flags && (*flags & KF_SLEEPABLE))
19885 case BPF_PROG_TYPE_LSM:
19886 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19887 * Only some of them are sleepable.
19889 if (bpf_lsm_is_sleepable_hook(btf_id))
19897 bpf_log(log, "%s is not sleepable\n", tname);
19900 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19903 bpf_log(log, "can't modify return codes of BPF programs\n");
19907 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19908 !check_attach_modify_return(addr, tname))
19912 bpf_log(log, "%s() is not modifiable\n", tname);
19919 tgt_info->tgt_addr = addr;
19920 tgt_info->tgt_name = tname;
19921 tgt_info->tgt_type = t;
19922 tgt_info->tgt_mod = mod;
19926 BTF_SET_START(btf_id_deny)
19929 BTF_ID(func, migrate_disable)
19930 BTF_ID(func, migrate_enable)
19932 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19933 BTF_ID(func, rcu_read_unlock_strict)
19935 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19936 BTF_ID(func, preempt_count_add)
19937 BTF_ID(func, preempt_count_sub)
19939 #ifdef CONFIG_PREEMPT_RCU
19940 BTF_ID(func, __rcu_read_lock)
19941 BTF_ID(func, __rcu_read_unlock)
19943 BTF_SET_END(btf_id_deny)
19945 static bool can_be_sleepable(struct bpf_prog *prog)
19947 if (prog->type == BPF_PROG_TYPE_TRACING) {
19948 switch (prog->expected_attach_type) {
19949 case BPF_TRACE_FENTRY:
19950 case BPF_TRACE_FEXIT:
19951 case BPF_MODIFY_RETURN:
19952 case BPF_TRACE_ITER:
19958 return prog->type == BPF_PROG_TYPE_LSM ||
19959 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19960 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19963 static int check_attach_btf_id(struct bpf_verifier_env *env)
19965 struct bpf_prog *prog = env->prog;
19966 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19967 struct bpf_attach_target_info tgt_info = {};
19968 u32 btf_id = prog->aux->attach_btf_id;
19969 struct bpf_trampoline *tr;
19973 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19974 if (prog->aux->sleepable)
19975 /* attach_btf_id checked to be zero already */
19977 verbose(env, "Syscall programs can only be sleepable\n");
19981 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19982 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19986 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19987 return check_struct_ops_btf_id(env);
19989 if (prog->type != BPF_PROG_TYPE_TRACING &&
19990 prog->type != BPF_PROG_TYPE_LSM &&
19991 prog->type != BPF_PROG_TYPE_EXT)
19994 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19998 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19999 /* to make freplace equivalent to their targets, they need to
20000 * inherit env->ops and expected_attach_type for the rest of the
20003 env->ops = bpf_verifier_ops[tgt_prog->type];
20004 prog->expected_attach_type = tgt_prog->expected_attach_type;
20007 /* store info about the attachment target that will be used later */
20008 prog->aux->attach_func_proto = tgt_info.tgt_type;
20009 prog->aux->attach_func_name = tgt_info.tgt_name;
20010 prog->aux->mod = tgt_info.tgt_mod;
20013 prog->aux->saved_dst_prog_type = tgt_prog->type;
20014 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20017 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20018 prog->aux->attach_btf_trace = true;
20020 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20021 if (!bpf_iter_prog_supported(prog))
20026 if (prog->type == BPF_PROG_TYPE_LSM) {
20027 ret = bpf_lsm_verify_prog(&env->log, prog);
20030 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
20031 btf_id_set_contains(&btf_id_deny, btf_id)) {
20035 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20036 tr = bpf_trampoline_get(key, &tgt_info);
20040 if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20041 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20043 prog->aux->dst_trampoline = tr;
20047 struct btf *bpf_get_btf_vmlinux(void)
20049 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20050 mutex_lock(&bpf_verifier_lock);
20052 btf_vmlinux = btf_parse_vmlinux();
20053 mutex_unlock(&bpf_verifier_lock);
20055 return btf_vmlinux;
20058 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20060 u64 start_time = ktime_get_ns();
20061 struct bpf_verifier_env *env;
20062 int i, len, ret = -EINVAL, err;
20066 /* no program is valid */
20067 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20070 /* 'struct bpf_verifier_env' can be global, but since it's not small,
20071 * allocate/free it every time bpf_check() is called
20073 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20079 len = (*prog)->len;
20080 env->insn_aux_data =
20081 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20083 if (!env->insn_aux_data)
20085 for (i = 0; i < len; i++)
20086 env->insn_aux_data[i].orig_idx = i;
20088 env->ops = bpf_verifier_ops[env->prog->type];
20089 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20090 is_priv = bpf_capable();
20092 bpf_get_btf_vmlinux();
20094 /* grab the mutex to protect few globals used by verifier */
20096 mutex_lock(&bpf_verifier_lock);
20098 /* user could have requested verbose verifier output
20099 * and supplied buffer to store the verification trace
20101 ret = bpf_vlog_init(&env->log, attr->log_level,
20102 (char __user *) (unsigned long) attr->log_buf,
20107 mark_verifier_state_clean(env);
20109 if (IS_ERR(btf_vmlinux)) {
20110 /* Either gcc or pahole or kernel are broken. */
20111 verbose(env, "in-kernel BTF is malformed\n");
20112 ret = PTR_ERR(btf_vmlinux);
20113 goto skip_full_check;
20116 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20117 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20118 env->strict_alignment = true;
20119 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20120 env->strict_alignment = false;
20122 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20123 env->allow_uninit_stack = bpf_allow_uninit_stack();
20124 env->bypass_spec_v1 = bpf_bypass_spec_v1();
20125 env->bypass_spec_v4 = bpf_bypass_spec_v4();
20126 env->bpf_capable = bpf_capable();
20129 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20131 env->explored_states = kvcalloc(state_htab_size(env),
20132 sizeof(struct bpf_verifier_state_list *),
20135 if (!env->explored_states)
20136 goto skip_full_check;
20138 ret = add_subprog_and_kfunc(env);
20140 goto skip_full_check;
20142 ret = check_subprogs(env);
20144 goto skip_full_check;
20146 ret = check_btf_info(env, attr, uattr);
20148 goto skip_full_check;
20150 ret = check_attach_btf_id(env);
20152 goto skip_full_check;
20154 ret = resolve_pseudo_ldimm64(env);
20156 goto skip_full_check;
20158 if (bpf_prog_is_offloaded(env->prog->aux)) {
20159 ret = bpf_prog_offload_verifier_prep(env->prog);
20161 goto skip_full_check;
20164 ret = check_cfg(env);
20166 goto skip_full_check;
20168 ret = do_check_subprogs(env);
20169 ret = ret ?: do_check_main(env);
20171 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20172 ret = bpf_prog_offload_finalize(env);
20175 kvfree(env->explored_states);
20178 ret = check_max_stack_depth(env);
20180 /* instruction rewrites happen after this point */
20182 ret = optimize_bpf_loop(env);
20186 opt_hard_wire_dead_code_branches(env);
20188 ret = opt_remove_dead_code(env);
20190 ret = opt_remove_nops(env);
20193 sanitize_dead_code(env);
20197 /* program is valid, convert *(u32*)(ctx + off) accesses */
20198 ret = convert_ctx_accesses(env);
20201 ret = do_misc_fixups(env);
20203 /* do 32-bit optimization after insn patching has done so those patched
20204 * insns could be handled correctly.
20206 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20207 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20208 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20213 ret = fixup_call_args(env);
20215 env->verification_time = ktime_get_ns() - start_time;
20216 print_verification_stats(env);
20217 env->prog->aux->verified_insns = env->insn_processed;
20219 /* preserve original error even if log finalization is successful */
20220 err = bpf_vlog_finalize(&env->log, &log_true_size);
20224 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20225 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20226 &log_true_size, sizeof(log_true_size))) {
20228 goto err_release_maps;
20232 goto err_release_maps;
20234 if (env->used_map_cnt) {
20235 /* if program passed verifier, update used_maps in bpf_prog_info */
20236 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20237 sizeof(env->used_maps[0]),
20240 if (!env->prog->aux->used_maps) {
20242 goto err_release_maps;
20245 memcpy(env->prog->aux->used_maps, env->used_maps,
20246 sizeof(env->used_maps[0]) * env->used_map_cnt);
20247 env->prog->aux->used_map_cnt = env->used_map_cnt;
20249 if (env->used_btf_cnt) {
20250 /* if program passed verifier, update used_btfs in bpf_prog_aux */
20251 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20252 sizeof(env->used_btfs[0]),
20254 if (!env->prog->aux->used_btfs) {
20256 goto err_release_maps;
20259 memcpy(env->prog->aux->used_btfs, env->used_btfs,
20260 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20261 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20263 if (env->used_map_cnt || env->used_btf_cnt) {
20264 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
20265 * bpf_ld_imm64 instructions
20267 convert_pseudo_ld_imm64(env);
20270 adjust_btf_func(env);
20273 if (!env->prog->aux->used_maps)
20274 /* if we didn't copy map pointers into bpf_prog_info, release
20275 * them now. Otherwise free_used_maps() will release them.
20278 if (!env->prog->aux->used_btfs)
20281 /* extension progs temporarily inherit the attach_type of their targets
20282 for verification purposes, so set it back to zero before returning
20284 if (env->prog->type == BPF_PROG_TYPE_EXT)
20285 env->prog->expected_attach_type = 0;
20290 mutex_unlock(&bpf_verifier_lock);
20291 vfree(env->insn_aux_data);