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");
1518 mark_verifier_state_clean(env);
1521 static inline u32 vlog_alignment(u32 pos)
1523 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1524 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1527 static void print_insn_state(struct bpf_verifier_env *env,
1528 const struct bpf_func_state *state)
1530 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1531 /* remove new line character */
1532 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1533 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1535 verbose(env, "%d:", env->insn_idx);
1537 print_verifier_state(env, state, false);
1540 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1541 * small to hold src. This is different from krealloc since we don't want to preserve
1542 * the contents of dst.
1544 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1547 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1553 if (ZERO_OR_NULL_PTR(src))
1556 if (unlikely(check_mul_overflow(n, size, &bytes)))
1559 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1560 dst = krealloc(orig, alloc_bytes, flags);
1566 memcpy(dst, src, bytes);
1568 return dst ? dst : ZERO_SIZE_PTR;
1571 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1572 * small to hold new_n items. new items are zeroed out if the array grows.
1574 * Contrary to krealloc_array, does not free arr if new_n is zero.
1576 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1581 if (!new_n || old_n == new_n)
1584 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1585 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1593 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1596 return arr ? arr : ZERO_SIZE_PTR;
1599 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1601 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1602 sizeof(struct bpf_reference_state), GFP_KERNEL);
1606 dst->acquired_refs = src->acquired_refs;
1610 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1612 size_t n = src->allocated_stack / BPF_REG_SIZE;
1614 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1619 dst->allocated_stack = src->allocated_stack;
1623 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1625 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1626 sizeof(struct bpf_reference_state));
1630 state->acquired_refs = n;
1634 static int grow_stack_state(struct bpf_func_state *state, int size)
1636 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1641 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1645 state->allocated_stack = size;
1649 /* Acquire a pointer id from the env and update the state->refs to include
1650 * this new pointer reference.
1651 * On success, returns a valid pointer id to associate with the register
1652 * On failure, returns a negative errno.
1654 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1656 struct bpf_func_state *state = cur_func(env);
1657 int new_ofs = state->acquired_refs;
1660 err = resize_reference_state(state, state->acquired_refs + 1);
1664 state->refs[new_ofs].id = id;
1665 state->refs[new_ofs].insn_idx = insn_idx;
1666 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1671 /* release function corresponding to acquire_reference_state(). Idempotent. */
1672 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1676 last_idx = state->acquired_refs - 1;
1677 for (i = 0; i < state->acquired_refs; i++) {
1678 if (state->refs[i].id == ptr_id) {
1679 /* Cannot release caller references in callbacks */
1680 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1682 if (last_idx && i != last_idx)
1683 memcpy(&state->refs[i], &state->refs[last_idx],
1684 sizeof(*state->refs));
1685 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1686 state->acquired_refs--;
1693 static void free_func_state(struct bpf_func_state *state)
1698 kfree(state->stack);
1702 static void clear_jmp_history(struct bpf_verifier_state *state)
1704 kfree(state->jmp_history);
1705 state->jmp_history = NULL;
1706 state->jmp_history_cnt = 0;
1709 static void free_verifier_state(struct bpf_verifier_state *state,
1714 for (i = 0; i <= state->curframe; i++) {
1715 free_func_state(state->frame[i]);
1716 state->frame[i] = NULL;
1718 clear_jmp_history(state);
1723 /* copy verifier state from src to dst growing dst stack space
1724 * when necessary to accommodate larger src stack
1726 static int copy_func_state(struct bpf_func_state *dst,
1727 const struct bpf_func_state *src)
1731 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1732 err = copy_reference_state(dst, src);
1735 return copy_stack_state(dst, src);
1738 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1739 const struct bpf_verifier_state *src)
1741 struct bpf_func_state *dst;
1744 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1745 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1747 if (!dst_state->jmp_history)
1749 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1751 /* if dst has more stack frames then src frame, free them */
1752 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1753 free_func_state(dst_state->frame[i]);
1754 dst_state->frame[i] = NULL;
1756 dst_state->speculative = src->speculative;
1757 dst_state->active_rcu_lock = src->active_rcu_lock;
1758 dst_state->curframe = src->curframe;
1759 dst_state->active_lock.ptr = src->active_lock.ptr;
1760 dst_state->active_lock.id = src->active_lock.id;
1761 dst_state->branches = src->branches;
1762 dst_state->parent = src->parent;
1763 dst_state->first_insn_idx = src->first_insn_idx;
1764 dst_state->last_insn_idx = src->last_insn_idx;
1765 for (i = 0; i <= src->curframe; i++) {
1766 dst = dst_state->frame[i];
1768 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1771 dst_state->frame[i] = dst;
1773 err = copy_func_state(dst, src->frame[i]);
1780 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1783 u32 br = --st->branches;
1785 /* WARN_ON(br > 1) technically makes sense here,
1786 * but see comment in push_stack(), hence:
1788 WARN_ONCE((int)br < 0,
1789 "BUG update_branch_counts:branches_to_explore=%d\n",
1797 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1798 int *insn_idx, bool pop_log)
1800 struct bpf_verifier_state *cur = env->cur_state;
1801 struct bpf_verifier_stack_elem *elem, *head = env->head;
1804 if (env->head == NULL)
1808 err = copy_verifier_state(cur, &head->st);
1813 bpf_vlog_reset(&env->log, head->log_pos);
1815 *insn_idx = head->insn_idx;
1817 *prev_insn_idx = head->prev_insn_idx;
1819 free_verifier_state(&head->st, false);
1826 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1827 int insn_idx, int prev_insn_idx,
1830 struct bpf_verifier_state *cur = env->cur_state;
1831 struct bpf_verifier_stack_elem *elem;
1834 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1838 elem->insn_idx = insn_idx;
1839 elem->prev_insn_idx = prev_insn_idx;
1840 elem->next = env->head;
1841 elem->log_pos = env->log.end_pos;
1844 err = copy_verifier_state(&elem->st, cur);
1847 elem->st.speculative |= speculative;
1848 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1849 verbose(env, "The sequence of %d jumps is too complex.\n",
1853 if (elem->st.parent) {
1854 ++elem->st.parent->branches;
1855 /* WARN_ON(branches > 2) technically makes sense here,
1857 * 1. speculative states will bump 'branches' for non-branch
1859 * 2. is_state_visited() heuristics may decide not to create
1860 * a new state for a sequence of branches and all such current
1861 * and cloned states will be pointing to a single parent state
1862 * which might have large 'branches' count.
1867 free_verifier_state(env->cur_state, true);
1868 env->cur_state = NULL;
1869 /* pop all elements and return */
1870 while (!pop_stack(env, NULL, NULL, false));
1874 #define CALLER_SAVED_REGS 6
1875 static const int caller_saved[CALLER_SAVED_REGS] = {
1876 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1879 /* This helper doesn't clear reg->id */
1880 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1882 reg->var_off = tnum_const(imm);
1883 reg->smin_value = (s64)imm;
1884 reg->smax_value = (s64)imm;
1885 reg->umin_value = imm;
1886 reg->umax_value = imm;
1888 reg->s32_min_value = (s32)imm;
1889 reg->s32_max_value = (s32)imm;
1890 reg->u32_min_value = (u32)imm;
1891 reg->u32_max_value = (u32)imm;
1894 /* Mark the unknown part of a register (variable offset or scalar value) as
1895 * known to have the value @imm.
1897 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1899 /* Clear off and union(map_ptr, range) */
1900 memset(((u8 *)reg) + sizeof(reg->type), 0,
1901 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1903 reg->ref_obj_id = 0;
1904 ___mark_reg_known(reg, imm);
1907 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1909 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1910 reg->s32_min_value = (s32)imm;
1911 reg->s32_max_value = (s32)imm;
1912 reg->u32_min_value = (u32)imm;
1913 reg->u32_max_value = (u32)imm;
1916 /* Mark the 'variable offset' part of a register as zero. This should be
1917 * used only on registers holding a pointer type.
1919 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1921 __mark_reg_known(reg, 0);
1924 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1926 __mark_reg_known(reg, 0);
1927 reg->type = SCALAR_VALUE;
1930 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1931 struct bpf_reg_state *regs, u32 regno)
1933 if (WARN_ON(regno >= MAX_BPF_REG)) {
1934 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1935 /* Something bad happened, let's kill all regs */
1936 for (regno = 0; regno < MAX_BPF_REG; regno++)
1937 __mark_reg_not_init(env, regs + regno);
1940 __mark_reg_known_zero(regs + regno);
1943 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1944 bool first_slot, int dynptr_id)
1946 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1947 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1948 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1950 __mark_reg_known_zero(reg);
1951 reg->type = CONST_PTR_TO_DYNPTR;
1952 /* Give each dynptr a unique id to uniquely associate slices to it. */
1953 reg->id = dynptr_id;
1954 reg->dynptr.type = type;
1955 reg->dynptr.first_slot = first_slot;
1958 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1960 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1961 const struct bpf_map *map = reg->map_ptr;
1963 if (map->inner_map_meta) {
1964 reg->type = CONST_PTR_TO_MAP;
1965 reg->map_ptr = map->inner_map_meta;
1966 /* transfer reg's id which is unique for every map_lookup_elem
1967 * as UID of the inner map.
1969 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1970 reg->map_uid = reg->id;
1971 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1972 reg->type = PTR_TO_XDP_SOCK;
1973 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1974 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1975 reg->type = PTR_TO_SOCKET;
1977 reg->type = PTR_TO_MAP_VALUE;
1982 reg->type &= ~PTR_MAYBE_NULL;
1985 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1986 struct btf_field_graph_root *ds_head)
1988 __mark_reg_known_zero(®s[regno]);
1989 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1990 regs[regno].btf = ds_head->btf;
1991 regs[regno].btf_id = ds_head->value_btf_id;
1992 regs[regno].off = ds_head->node_offset;
1995 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1997 return type_is_pkt_pointer(reg->type);
2000 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2002 return reg_is_pkt_pointer(reg) ||
2003 reg->type == PTR_TO_PACKET_END;
2006 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2008 return base_type(reg->type) == PTR_TO_MEM &&
2009 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2012 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2013 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2014 enum bpf_reg_type which)
2016 /* The register can already have a range from prior markings.
2017 * This is fine as long as it hasn't been advanced from its
2020 return reg->type == which &&
2023 tnum_equals_const(reg->var_off, 0);
2026 /* Reset the min/max bounds of a register */
2027 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2029 reg->smin_value = S64_MIN;
2030 reg->smax_value = S64_MAX;
2031 reg->umin_value = 0;
2032 reg->umax_value = U64_MAX;
2034 reg->s32_min_value = S32_MIN;
2035 reg->s32_max_value = S32_MAX;
2036 reg->u32_min_value = 0;
2037 reg->u32_max_value = U32_MAX;
2040 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2042 reg->smin_value = S64_MIN;
2043 reg->smax_value = S64_MAX;
2044 reg->umin_value = 0;
2045 reg->umax_value = U64_MAX;
2048 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2050 reg->s32_min_value = S32_MIN;
2051 reg->s32_max_value = S32_MAX;
2052 reg->u32_min_value = 0;
2053 reg->u32_max_value = U32_MAX;
2056 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2058 struct tnum var32_off = tnum_subreg(reg->var_off);
2060 /* min signed is max(sign bit) | min(other bits) */
2061 reg->s32_min_value = max_t(s32, reg->s32_min_value,
2062 var32_off.value | (var32_off.mask & S32_MIN));
2063 /* max signed is min(sign bit) | max(other bits) */
2064 reg->s32_max_value = min_t(s32, reg->s32_max_value,
2065 var32_off.value | (var32_off.mask & S32_MAX));
2066 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2067 reg->u32_max_value = min(reg->u32_max_value,
2068 (u32)(var32_off.value | var32_off.mask));
2071 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2073 /* min signed is max(sign bit) | min(other bits) */
2074 reg->smin_value = max_t(s64, reg->smin_value,
2075 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2076 /* max signed is min(sign bit) | max(other bits) */
2077 reg->smax_value = min_t(s64, reg->smax_value,
2078 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2079 reg->umin_value = max(reg->umin_value, reg->var_off.value);
2080 reg->umax_value = min(reg->umax_value,
2081 reg->var_off.value | reg->var_off.mask);
2084 static void __update_reg_bounds(struct bpf_reg_state *reg)
2086 __update_reg32_bounds(reg);
2087 __update_reg64_bounds(reg);
2090 /* Uses signed min/max values to inform unsigned, and vice-versa */
2091 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2093 /* Learn sign from signed bounds.
2094 * If we cannot cross the sign boundary, then signed and unsigned bounds
2095 * are the same, so combine. This works even in the negative case, e.g.
2096 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2098 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2099 reg->s32_min_value = reg->u32_min_value =
2100 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2101 reg->s32_max_value = reg->u32_max_value =
2102 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2105 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2106 * boundary, so we must be careful.
2108 if ((s32)reg->u32_max_value >= 0) {
2109 /* Positive. We can't learn anything from the smin, but smax
2110 * is positive, hence safe.
2112 reg->s32_min_value = reg->u32_min_value;
2113 reg->s32_max_value = reg->u32_max_value =
2114 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2115 } else if ((s32)reg->u32_min_value < 0) {
2116 /* Negative. We can't learn anything from the smax, but smin
2117 * is negative, hence safe.
2119 reg->s32_min_value = reg->u32_min_value =
2120 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2121 reg->s32_max_value = reg->u32_max_value;
2125 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2127 /* Learn sign from signed bounds.
2128 * If we cannot cross the sign boundary, then signed and unsigned bounds
2129 * are the same, so combine. This works even in the negative case, e.g.
2130 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2132 if (reg->smin_value >= 0 || reg->smax_value < 0) {
2133 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2135 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2139 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2140 * boundary, so we must be careful.
2142 if ((s64)reg->umax_value >= 0) {
2143 /* Positive. We can't learn anything from the smin, but smax
2144 * is positive, hence safe.
2146 reg->smin_value = reg->umin_value;
2147 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2149 } else if ((s64)reg->umin_value < 0) {
2150 /* Negative. We can't learn anything from the smax, but smin
2151 * is negative, hence safe.
2153 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2155 reg->smax_value = reg->umax_value;
2159 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2161 __reg32_deduce_bounds(reg);
2162 __reg64_deduce_bounds(reg);
2165 /* Attempts to improve var_off based on unsigned min/max information */
2166 static void __reg_bound_offset(struct bpf_reg_state *reg)
2168 struct tnum var64_off = tnum_intersect(reg->var_off,
2169 tnum_range(reg->umin_value,
2171 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2172 tnum_range(reg->u32_min_value,
2173 reg->u32_max_value));
2175 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2178 static void reg_bounds_sync(struct bpf_reg_state *reg)
2180 /* We might have learned new bounds from the var_off. */
2181 __update_reg_bounds(reg);
2182 /* We might have learned something about the sign bit. */
2183 __reg_deduce_bounds(reg);
2184 /* We might have learned some bits from the bounds. */
2185 __reg_bound_offset(reg);
2186 /* Intersecting with the old var_off might have improved our bounds
2187 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2188 * then new var_off is (0; 0x7f...fc) which improves our umax.
2190 __update_reg_bounds(reg);
2193 static bool __reg32_bound_s64(s32 a)
2195 return a >= 0 && a <= S32_MAX;
2198 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2200 reg->umin_value = reg->u32_min_value;
2201 reg->umax_value = reg->u32_max_value;
2203 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2204 * be positive otherwise set to worse case bounds and refine later
2207 if (__reg32_bound_s64(reg->s32_min_value) &&
2208 __reg32_bound_s64(reg->s32_max_value)) {
2209 reg->smin_value = reg->s32_min_value;
2210 reg->smax_value = reg->s32_max_value;
2212 reg->smin_value = 0;
2213 reg->smax_value = U32_MAX;
2217 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2219 /* special case when 64-bit register has upper 32-bit register
2220 * zeroed. Typically happens after zext or <<32, >>32 sequence
2221 * allowing us to use 32-bit bounds directly,
2223 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2224 __reg_assign_32_into_64(reg);
2226 /* Otherwise the best we can do is push lower 32bit known and
2227 * unknown bits into register (var_off set from jmp logic)
2228 * then learn as much as possible from the 64-bit tnum
2229 * known and unknown bits. The previous smin/smax bounds are
2230 * invalid here because of jmp32 compare so mark them unknown
2231 * so they do not impact tnum bounds calculation.
2233 __mark_reg64_unbounded(reg);
2235 reg_bounds_sync(reg);
2238 static bool __reg64_bound_s32(s64 a)
2240 return a >= S32_MIN && a <= S32_MAX;
2243 static bool __reg64_bound_u32(u64 a)
2245 return a >= U32_MIN && a <= U32_MAX;
2248 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2250 __mark_reg32_unbounded(reg);
2251 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2252 reg->s32_min_value = (s32)reg->smin_value;
2253 reg->s32_max_value = (s32)reg->smax_value;
2255 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2256 reg->u32_min_value = (u32)reg->umin_value;
2257 reg->u32_max_value = (u32)reg->umax_value;
2259 reg_bounds_sync(reg);
2262 /* Mark a register as having a completely unknown (scalar) value. */
2263 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2264 struct bpf_reg_state *reg)
2267 * Clear type, off, and union(map_ptr, range) and
2268 * padding between 'type' and union
2270 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2271 reg->type = SCALAR_VALUE;
2273 reg->ref_obj_id = 0;
2274 reg->var_off = tnum_unknown;
2276 reg->precise = !env->bpf_capable;
2277 __mark_reg_unbounded(reg);
2280 static void mark_reg_unknown(struct bpf_verifier_env *env,
2281 struct bpf_reg_state *regs, u32 regno)
2283 if (WARN_ON(regno >= MAX_BPF_REG)) {
2284 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2285 /* Something bad happened, let's kill all regs except FP */
2286 for (regno = 0; regno < BPF_REG_FP; regno++)
2287 __mark_reg_not_init(env, regs + regno);
2290 __mark_reg_unknown(env, regs + regno);
2293 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2294 struct bpf_reg_state *reg)
2296 __mark_reg_unknown(env, reg);
2297 reg->type = NOT_INIT;
2300 static void mark_reg_not_init(struct bpf_verifier_env *env,
2301 struct bpf_reg_state *regs, u32 regno)
2303 if (WARN_ON(regno >= MAX_BPF_REG)) {
2304 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2305 /* Something bad happened, let's kill all regs except FP */
2306 for (regno = 0; regno < BPF_REG_FP; regno++)
2307 __mark_reg_not_init(env, regs + regno);
2310 __mark_reg_not_init(env, regs + regno);
2313 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2314 struct bpf_reg_state *regs, u32 regno,
2315 enum bpf_reg_type reg_type,
2316 struct btf *btf, u32 btf_id,
2317 enum bpf_type_flag flag)
2319 if (reg_type == SCALAR_VALUE) {
2320 mark_reg_unknown(env, regs, regno);
2323 mark_reg_known_zero(env, regs, regno);
2324 regs[regno].type = PTR_TO_BTF_ID | flag;
2325 regs[regno].btf = btf;
2326 regs[regno].btf_id = btf_id;
2329 #define DEF_NOT_SUBREG (0)
2330 static void init_reg_state(struct bpf_verifier_env *env,
2331 struct bpf_func_state *state)
2333 struct bpf_reg_state *regs = state->regs;
2336 for (i = 0; i < MAX_BPF_REG; i++) {
2337 mark_reg_not_init(env, regs, i);
2338 regs[i].live = REG_LIVE_NONE;
2339 regs[i].parent = NULL;
2340 regs[i].subreg_def = DEF_NOT_SUBREG;
2344 regs[BPF_REG_FP].type = PTR_TO_STACK;
2345 mark_reg_known_zero(env, regs, BPF_REG_FP);
2346 regs[BPF_REG_FP].frameno = state->frameno;
2349 #define BPF_MAIN_FUNC (-1)
2350 static void init_func_state(struct bpf_verifier_env *env,
2351 struct bpf_func_state *state,
2352 int callsite, int frameno, int subprogno)
2354 state->callsite = callsite;
2355 state->frameno = frameno;
2356 state->subprogno = subprogno;
2357 state->callback_ret_range = tnum_range(0, 0);
2358 init_reg_state(env, state);
2359 mark_verifier_state_scratched(env);
2362 /* Similar to push_stack(), but for async callbacks */
2363 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2364 int insn_idx, int prev_insn_idx,
2367 struct bpf_verifier_stack_elem *elem;
2368 struct bpf_func_state *frame;
2370 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2374 elem->insn_idx = insn_idx;
2375 elem->prev_insn_idx = prev_insn_idx;
2376 elem->next = env->head;
2377 elem->log_pos = env->log.end_pos;
2380 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2382 "The sequence of %d jumps is too complex for async cb.\n",
2386 /* Unlike push_stack() do not copy_verifier_state().
2387 * The caller state doesn't matter.
2388 * This is async callback. It starts in a fresh stack.
2389 * Initialize it similar to do_check_common().
2391 elem->st.branches = 1;
2392 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2395 init_func_state(env, frame,
2396 BPF_MAIN_FUNC /* callsite */,
2397 0 /* frameno within this callchain */,
2398 subprog /* subprog number within this prog */);
2399 elem->st.frame[0] = frame;
2402 free_verifier_state(env->cur_state, true);
2403 env->cur_state = NULL;
2404 /* pop all elements and return */
2405 while (!pop_stack(env, NULL, NULL, false));
2411 SRC_OP, /* register is used as source operand */
2412 DST_OP, /* register is used as destination operand */
2413 DST_OP_NO_MARK /* same as above, check only, don't mark */
2416 static int cmp_subprogs(const void *a, const void *b)
2418 return ((struct bpf_subprog_info *)a)->start -
2419 ((struct bpf_subprog_info *)b)->start;
2422 static int find_subprog(struct bpf_verifier_env *env, int off)
2424 struct bpf_subprog_info *p;
2426 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2427 sizeof(env->subprog_info[0]), cmp_subprogs);
2430 return p - env->subprog_info;
2434 static int add_subprog(struct bpf_verifier_env *env, int off)
2436 int insn_cnt = env->prog->len;
2439 if (off >= insn_cnt || off < 0) {
2440 verbose(env, "call to invalid destination\n");
2443 ret = find_subprog(env, off);
2446 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2447 verbose(env, "too many subprograms\n");
2450 /* determine subprog starts. The end is one before the next starts */
2451 env->subprog_info[env->subprog_cnt++].start = off;
2452 sort(env->subprog_info, env->subprog_cnt,
2453 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2454 return env->subprog_cnt - 1;
2457 #define MAX_KFUNC_DESCS 256
2458 #define MAX_KFUNC_BTFS 256
2460 struct bpf_kfunc_desc {
2461 struct btf_func_model func_model;
2468 struct bpf_kfunc_btf {
2470 struct module *module;
2474 struct bpf_kfunc_desc_tab {
2475 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2476 * verification. JITs do lookups by bpf_insn, where func_id may not be
2477 * available, therefore at the end of verification do_misc_fixups()
2478 * sorts this by imm and offset.
2480 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2484 struct bpf_kfunc_btf_tab {
2485 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2489 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2491 const struct bpf_kfunc_desc *d0 = a;
2492 const struct bpf_kfunc_desc *d1 = b;
2494 /* func_id is not greater than BTF_MAX_TYPE */
2495 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2498 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2500 const struct bpf_kfunc_btf *d0 = a;
2501 const struct bpf_kfunc_btf *d1 = b;
2503 return d0->offset - d1->offset;
2506 static const struct bpf_kfunc_desc *
2507 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2509 struct bpf_kfunc_desc desc = {
2513 struct bpf_kfunc_desc_tab *tab;
2515 tab = prog->aux->kfunc_tab;
2516 return bsearch(&desc, tab->descs, tab->nr_descs,
2517 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2520 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2521 u16 btf_fd_idx, u8 **func_addr)
2523 const struct bpf_kfunc_desc *desc;
2525 desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2529 *func_addr = (u8 *)desc->addr;
2533 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2536 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2537 struct bpf_kfunc_btf_tab *tab;
2538 struct bpf_kfunc_btf *b;
2543 tab = env->prog->aux->kfunc_btf_tab;
2544 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2545 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2547 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2548 verbose(env, "too many different module BTFs\n");
2549 return ERR_PTR(-E2BIG);
2552 if (bpfptr_is_null(env->fd_array)) {
2553 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2554 return ERR_PTR(-EPROTO);
2557 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2558 offset * sizeof(btf_fd),
2560 return ERR_PTR(-EFAULT);
2562 btf = btf_get_by_fd(btf_fd);
2564 verbose(env, "invalid module BTF fd specified\n");
2568 if (!btf_is_module(btf)) {
2569 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2571 return ERR_PTR(-EINVAL);
2574 mod = btf_try_get_module(btf);
2577 return ERR_PTR(-ENXIO);
2580 b = &tab->descs[tab->nr_descs++];
2585 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2586 kfunc_btf_cmp_by_off, NULL);
2591 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2596 while (tab->nr_descs--) {
2597 module_put(tab->descs[tab->nr_descs].module);
2598 btf_put(tab->descs[tab->nr_descs].btf);
2603 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2607 /* In the future, this can be allowed to increase limit
2608 * of fd index into fd_array, interpreted as u16.
2610 verbose(env, "negative offset disallowed for kernel module function call\n");
2611 return ERR_PTR(-EINVAL);
2614 return __find_kfunc_desc_btf(env, offset);
2616 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2619 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2621 const struct btf_type *func, *func_proto;
2622 struct bpf_kfunc_btf_tab *btf_tab;
2623 struct bpf_kfunc_desc_tab *tab;
2624 struct bpf_prog_aux *prog_aux;
2625 struct bpf_kfunc_desc *desc;
2626 const char *func_name;
2627 struct btf *desc_btf;
2628 unsigned long call_imm;
2632 prog_aux = env->prog->aux;
2633 tab = prog_aux->kfunc_tab;
2634 btf_tab = prog_aux->kfunc_btf_tab;
2637 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2641 if (!env->prog->jit_requested) {
2642 verbose(env, "JIT is required for calling kernel function\n");
2646 if (!bpf_jit_supports_kfunc_call()) {
2647 verbose(env, "JIT does not support calling kernel function\n");
2651 if (!env->prog->gpl_compatible) {
2652 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2656 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2659 prog_aux->kfunc_tab = tab;
2662 /* func_id == 0 is always invalid, but instead of returning an error, be
2663 * conservative and wait until the code elimination pass before returning
2664 * error, so that invalid calls that get pruned out can be in BPF programs
2665 * loaded from userspace. It is also required that offset be untouched
2668 if (!func_id && !offset)
2671 if (!btf_tab && offset) {
2672 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2675 prog_aux->kfunc_btf_tab = btf_tab;
2678 desc_btf = find_kfunc_desc_btf(env, offset);
2679 if (IS_ERR(desc_btf)) {
2680 verbose(env, "failed to find BTF for kernel function\n");
2681 return PTR_ERR(desc_btf);
2684 if (find_kfunc_desc(env->prog, func_id, offset))
2687 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2688 verbose(env, "too many different kernel function calls\n");
2692 func = btf_type_by_id(desc_btf, func_id);
2693 if (!func || !btf_type_is_func(func)) {
2694 verbose(env, "kernel btf_id %u is not a function\n",
2698 func_proto = btf_type_by_id(desc_btf, func->type);
2699 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2700 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2705 func_name = btf_name_by_offset(desc_btf, func->name_off);
2706 addr = kallsyms_lookup_name(func_name);
2708 verbose(env, "cannot find address for kernel function %s\n",
2712 specialize_kfunc(env, func_id, offset, &addr);
2714 if (bpf_jit_supports_far_kfunc_call()) {
2717 call_imm = BPF_CALL_IMM(addr);
2718 /* Check whether the relative offset overflows desc->imm */
2719 if ((unsigned long)(s32)call_imm != call_imm) {
2720 verbose(env, "address of kernel function %s is out of range\n",
2726 if (bpf_dev_bound_kfunc_id(func_id)) {
2727 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2732 desc = &tab->descs[tab->nr_descs++];
2733 desc->func_id = func_id;
2734 desc->imm = call_imm;
2735 desc->offset = offset;
2737 err = btf_distill_func_proto(&env->log, desc_btf,
2738 func_proto, func_name,
2741 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2742 kfunc_desc_cmp_by_id_off, NULL);
2746 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2748 const struct bpf_kfunc_desc *d0 = a;
2749 const struct bpf_kfunc_desc *d1 = b;
2751 if (d0->imm != d1->imm)
2752 return d0->imm < d1->imm ? -1 : 1;
2753 if (d0->offset != d1->offset)
2754 return d0->offset < d1->offset ? -1 : 1;
2758 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2760 struct bpf_kfunc_desc_tab *tab;
2762 tab = prog->aux->kfunc_tab;
2766 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2767 kfunc_desc_cmp_by_imm_off, NULL);
2770 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2772 return !!prog->aux->kfunc_tab;
2775 const struct btf_func_model *
2776 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2777 const struct bpf_insn *insn)
2779 const struct bpf_kfunc_desc desc = {
2781 .offset = insn->off,
2783 const struct bpf_kfunc_desc *res;
2784 struct bpf_kfunc_desc_tab *tab;
2786 tab = prog->aux->kfunc_tab;
2787 res = bsearch(&desc, tab->descs, tab->nr_descs,
2788 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2790 return res ? &res->func_model : NULL;
2793 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2795 struct bpf_subprog_info *subprog = env->subprog_info;
2796 struct bpf_insn *insn = env->prog->insnsi;
2797 int i, ret, insn_cnt = env->prog->len;
2799 /* Add entry function. */
2800 ret = add_subprog(env, 0);
2804 for (i = 0; i < insn_cnt; i++, insn++) {
2805 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2806 !bpf_pseudo_kfunc_call(insn))
2809 if (!env->bpf_capable) {
2810 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2814 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2815 ret = add_subprog(env, i + insn->imm + 1);
2817 ret = add_kfunc_call(env, insn->imm, insn->off);
2823 /* Add a fake 'exit' subprog which could simplify subprog iteration
2824 * logic. 'subprog_cnt' should not be increased.
2826 subprog[env->subprog_cnt].start = insn_cnt;
2828 if (env->log.level & BPF_LOG_LEVEL2)
2829 for (i = 0; i < env->subprog_cnt; i++)
2830 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2835 static int check_subprogs(struct bpf_verifier_env *env)
2837 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2838 struct bpf_subprog_info *subprog = env->subprog_info;
2839 struct bpf_insn *insn = env->prog->insnsi;
2840 int insn_cnt = env->prog->len;
2842 /* now check that all jumps are within the same subprog */
2843 subprog_start = subprog[cur_subprog].start;
2844 subprog_end = subprog[cur_subprog + 1].start;
2845 for (i = 0; i < insn_cnt; i++) {
2846 u8 code = insn[i].code;
2848 if (code == (BPF_JMP | BPF_CALL) &&
2849 insn[i].src_reg == 0 &&
2850 insn[i].imm == BPF_FUNC_tail_call)
2851 subprog[cur_subprog].has_tail_call = true;
2852 if (BPF_CLASS(code) == BPF_LD &&
2853 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2854 subprog[cur_subprog].has_ld_abs = true;
2855 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2857 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2859 if (code == (BPF_JMP32 | BPF_JA))
2860 off = i + insn[i].imm + 1;
2862 off = i + insn[i].off + 1;
2863 if (off < subprog_start || off >= subprog_end) {
2864 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2868 if (i == subprog_end - 1) {
2869 /* to avoid fall-through from one subprog into another
2870 * the last insn of the subprog should be either exit
2871 * or unconditional jump back
2873 if (code != (BPF_JMP | BPF_EXIT) &&
2874 code != (BPF_JMP32 | BPF_JA) &&
2875 code != (BPF_JMP | BPF_JA)) {
2876 verbose(env, "last insn is not an exit or jmp\n");
2879 subprog_start = subprog_end;
2881 if (cur_subprog < env->subprog_cnt)
2882 subprog_end = subprog[cur_subprog + 1].start;
2888 /* Parentage chain of this register (or stack slot) should take care of all
2889 * issues like callee-saved registers, stack slot allocation time, etc.
2891 static int mark_reg_read(struct bpf_verifier_env *env,
2892 const struct bpf_reg_state *state,
2893 struct bpf_reg_state *parent, u8 flag)
2895 bool writes = parent == state->parent; /* Observe write marks */
2899 /* if read wasn't screened by an earlier write ... */
2900 if (writes && state->live & REG_LIVE_WRITTEN)
2902 if (parent->live & REG_LIVE_DONE) {
2903 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2904 reg_type_str(env, parent->type),
2905 parent->var_off.value, parent->off);
2908 /* The first condition is more likely to be true than the
2909 * second, checked it first.
2911 if ((parent->live & REG_LIVE_READ) == flag ||
2912 parent->live & REG_LIVE_READ64)
2913 /* The parentage chain never changes and
2914 * this parent was already marked as LIVE_READ.
2915 * There is no need to keep walking the chain again and
2916 * keep re-marking all parents as LIVE_READ.
2917 * This case happens when the same register is read
2918 * multiple times without writes into it in-between.
2919 * Also, if parent has the stronger REG_LIVE_READ64 set,
2920 * then no need to set the weak REG_LIVE_READ32.
2923 /* ... then we depend on parent's value */
2924 parent->live |= flag;
2925 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2926 if (flag == REG_LIVE_READ64)
2927 parent->live &= ~REG_LIVE_READ32;
2929 parent = state->parent;
2934 if (env->longest_mark_read_walk < cnt)
2935 env->longest_mark_read_walk = cnt;
2939 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2941 struct bpf_func_state *state = func(env, reg);
2944 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2945 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2948 if (reg->type == CONST_PTR_TO_DYNPTR)
2950 spi = dynptr_get_spi(env, reg);
2953 /* Caller ensures dynptr is valid and initialized, which means spi is in
2954 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2957 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2958 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2961 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2962 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2965 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2966 int spi, int nr_slots)
2968 struct bpf_func_state *state = func(env, reg);
2971 for (i = 0; i < nr_slots; i++) {
2972 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2974 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2978 mark_stack_slot_scratched(env, spi - i);
2984 /* This function is supposed to be used by the following 32-bit optimization
2985 * code only. It returns TRUE if the source or destination register operates
2986 * on 64-bit, otherwise return FALSE.
2988 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2989 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2994 class = BPF_CLASS(code);
2996 if (class == BPF_JMP) {
2997 /* BPF_EXIT for "main" will reach here. Return TRUE
3002 if (op == BPF_CALL) {
3003 /* BPF to BPF call will reach here because of marking
3004 * caller saved clobber with DST_OP_NO_MARK for which we
3005 * don't care the register def because they are anyway
3006 * marked as NOT_INIT already.
3008 if (insn->src_reg == BPF_PSEUDO_CALL)
3010 /* Helper call will reach here because of arg type
3011 * check, conservatively return TRUE.
3020 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3023 if (class == BPF_ALU64 || class == BPF_JMP ||
3024 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3027 if (class == BPF_ALU || class == BPF_JMP32)
3030 if (class == BPF_LDX) {
3032 return BPF_SIZE(code) == BPF_DW;
3033 /* LDX source must be ptr. */
3037 if (class == BPF_STX) {
3038 /* BPF_STX (including atomic variants) has multiple source
3039 * operands, one of which is a ptr. Check whether the caller is
3042 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3044 return BPF_SIZE(code) == BPF_DW;
3047 if (class == BPF_LD) {
3048 u8 mode = BPF_MODE(code);
3051 if (mode == BPF_IMM)
3054 /* Both LD_IND and LD_ABS return 32-bit data. */
3058 /* Implicit ctx ptr. */
3059 if (regno == BPF_REG_6)
3062 /* Explicit source could be any width. */
3066 if (class == BPF_ST)
3067 /* The only source register for BPF_ST is a ptr. */
3070 /* Conservatively return true at default. */
3074 /* Return the regno defined by the insn, or -1. */
3075 static int insn_def_regno(const struct bpf_insn *insn)
3077 switch (BPF_CLASS(insn->code)) {
3083 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3084 (insn->imm & BPF_FETCH)) {
3085 if (insn->imm == BPF_CMPXCHG)
3088 return insn->src_reg;
3093 return insn->dst_reg;
3097 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3098 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3100 int dst_reg = insn_def_regno(insn);
3105 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3108 static void mark_insn_zext(struct bpf_verifier_env *env,
3109 struct bpf_reg_state *reg)
3111 s32 def_idx = reg->subreg_def;
3113 if (def_idx == DEF_NOT_SUBREG)
3116 env->insn_aux_data[def_idx - 1].zext_dst = true;
3117 /* The dst will be zero extended, so won't be sub-register anymore. */
3118 reg->subreg_def = DEF_NOT_SUBREG;
3121 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3122 enum reg_arg_type t)
3124 struct bpf_verifier_state *vstate = env->cur_state;
3125 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3126 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3127 struct bpf_reg_state *reg, *regs = state->regs;
3130 if (regno >= MAX_BPF_REG) {
3131 verbose(env, "R%d is invalid\n", regno);
3135 mark_reg_scratched(env, regno);
3138 rw64 = is_reg64(env, insn, regno, reg, t);
3140 /* check whether register used as source operand can be read */
3141 if (reg->type == NOT_INIT) {
3142 verbose(env, "R%d !read_ok\n", regno);
3145 /* We don't need to worry about FP liveness because it's read-only */
3146 if (regno == BPF_REG_FP)
3150 mark_insn_zext(env, reg);
3152 return mark_reg_read(env, reg, reg->parent,
3153 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3155 /* check whether register used as dest operand can be written to */
3156 if (regno == BPF_REG_FP) {
3157 verbose(env, "frame pointer is read only\n");
3160 reg->live |= REG_LIVE_WRITTEN;
3161 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3163 mark_reg_unknown(env, regs, regno);
3168 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3170 env->insn_aux_data[idx].jmp_point = true;
3173 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3175 return env->insn_aux_data[insn_idx].jmp_point;
3178 /* for any branch, call, exit record the history of jmps in the given state */
3179 static int push_jmp_history(struct bpf_verifier_env *env,
3180 struct bpf_verifier_state *cur)
3182 u32 cnt = cur->jmp_history_cnt;
3183 struct bpf_idx_pair *p;
3186 if (!is_jmp_point(env, env->insn_idx))
3190 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3191 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3194 p[cnt - 1].idx = env->insn_idx;
3195 p[cnt - 1].prev_idx = env->prev_insn_idx;
3196 cur->jmp_history = p;
3197 cur->jmp_history_cnt = cnt;
3201 /* Backtrack one insn at a time. If idx is not at the top of recorded
3202 * history then previous instruction came from straight line execution.
3204 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3209 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3210 i = st->jmp_history[cnt - 1].prev_idx;
3218 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3220 const struct btf_type *func;
3221 struct btf *desc_btf;
3223 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3226 desc_btf = find_kfunc_desc_btf(data, insn->off);
3227 if (IS_ERR(desc_btf))
3230 func = btf_type_by_id(desc_btf, insn->imm);
3231 return btf_name_by_offset(desc_btf, func->name_off);
3234 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3239 static inline void bt_reset(struct backtrack_state *bt)
3241 struct bpf_verifier_env *env = bt->env;
3243 memset(bt, 0, sizeof(*bt));
3247 static inline u32 bt_empty(struct backtrack_state *bt)
3252 for (i = 0; i <= bt->frame; i++)
3253 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3258 static inline int bt_subprog_enter(struct backtrack_state *bt)
3260 if (bt->frame == MAX_CALL_FRAMES - 1) {
3261 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3262 WARN_ONCE(1, "verifier backtracking bug");
3269 static inline int bt_subprog_exit(struct backtrack_state *bt)
3271 if (bt->frame == 0) {
3272 verbose(bt->env, "BUG subprog exit from frame 0\n");
3273 WARN_ONCE(1, "verifier backtracking bug");
3280 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3282 bt->reg_masks[frame] |= 1 << reg;
3285 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3287 bt->reg_masks[frame] &= ~(1 << reg);
3290 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3292 bt_set_frame_reg(bt, bt->frame, reg);
3295 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3297 bt_clear_frame_reg(bt, bt->frame, reg);
3300 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3302 bt->stack_masks[frame] |= 1ull << slot;
3305 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3307 bt->stack_masks[frame] &= ~(1ull << slot);
3310 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3312 bt_set_frame_slot(bt, bt->frame, slot);
3315 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3317 bt_clear_frame_slot(bt, bt->frame, slot);
3320 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3322 return bt->reg_masks[frame];
3325 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3327 return bt->reg_masks[bt->frame];
3330 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3332 return bt->stack_masks[frame];
3335 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3337 return bt->stack_masks[bt->frame];
3340 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3342 return bt->reg_masks[bt->frame] & (1 << reg);
3345 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3347 return bt->stack_masks[bt->frame] & (1ull << slot);
3350 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3351 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3353 DECLARE_BITMAP(mask, 64);
3359 bitmap_from_u64(mask, reg_mask);
3360 for_each_set_bit(i, mask, 32) {
3361 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3369 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3370 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3372 DECLARE_BITMAP(mask, 64);
3378 bitmap_from_u64(mask, stack_mask);
3379 for_each_set_bit(i, mask, 64) {
3380 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3389 /* For given verifier state backtrack_insn() is called from the last insn to
3390 * the first insn. Its purpose is to compute a bitmask of registers and
3391 * stack slots that needs precision in the parent verifier state.
3393 * @idx is an index of the instruction we are currently processing;
3394 * @subseq_idx is an index of the subsequent instruction that:
3395 * - *would be* executed next, if jump history is viewed in forward order;
3396 * - *was* processed previously during backtracking.
3398 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3399 struct backtrack_state *bt)
3401 const struct bpf_insn_cbs cbs = {
3402 .cb_call = disasm_kfunc_name,
3403 .cb_print = verbose,
3404 .private_data = env,
3406 struct bpf_insn *insn = env->prog->insnsi + idx;
3407 u8 class = BPF_CLASS(insn->code);
3408 u8 opcode = BPF_OP(insn->code);
3409 u8 mode = BPF_MODE(insn->code);
3410 u32 dreg = insn->dst_reg;
3411 u32 sreg = insn->src_reg;
3414 if (insn->code == 0)
3416 if (env->log.level & BPF_LOG_LEVEL2) {
3417 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3418 verbose(env, "mark_precise: frame%d: regs=%s ",
3419 bt->frame, env->tmp_str_buf);
3420 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3421 verbose(env, "stack=%s before ", env->tmp_str_buf);
3422 verbose(env, "%d: ", idx);
3423 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3426 if (class == BPF_ALU || class == BPF_ALU64) {
3427 if (!bt_is_reg_set(bt, dreg))
3429 if (opcode == BPF_MOV) {
3430 if (BPF_SRC(insn->code) == BPF_X) {
3431 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3432 * dreg needs precision after this insn
3433 * sreg needs precision before this insn
3435 bt_clear_reg(bt, dreg);
3436 bt_set_reg(bt, sreg);
3439 * dreg needs precision after this insn.
3440 * Corresponding register is already marked
3441 * as precise=true in this verifier state.
3442 * No further markings in parent are necessary
3444 bt_clear_reg(bt, dreg);
3447 if (BPF_SRC(insn->code) == BPF_X) {
3449 * both dreg and sreg need precision
3452 bt_set_reg(bt, sreg);
3454 * dreg still needs precision before this insn
3457 } else if (class == BPF_LDX) {
3458 if (!bt_is_reg_set(bt, dreg))
3460 bt_clear_reg(bt, dreg);
3462 /* scalars can only be spilled into stack w/o losing precision.
3463 * Load from any other memory can be zero extended.
3464 * The desire to keep that precision is already indicated
3465 * by 'precise' mark in corresponding register of this state.
3466 * No further tracking necessary.
3468 if (insn->src_reg != BPF_REG_FP)
3471 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3472 * that [fp - off] slot contains scalar that needs to be
3473 * tracked with precision
3475 spi = (-insn->off - 1) / BPF_REG_SIZE;
3477 verbose(env, "BUG spi %d\n", spi);
3478 WARN_ONCE(1, "verifier backtracking bug");
3481 bt_set_slot(bt, spi);
3482 } else if (class == BPF_STX || class == BPF_ST) {
3483 if (bt_is_reg_set(bt, dreg))
3484 /* stx & st shouldn't be using _scalar_ dst_reg
3485 * to access memory. It means backtracking
3486 * encountered a case of pointer subtraction.
3489 /* scalars can only be spilled into stack */
3490 if (insn->dst_reg != BPF_REG_FP)
3492 spi = (-insn->off - 1) / BPF_REG_SIZE;
3494 verbose(env, "BUG spi %d\n", spi);
3495 WARN_ONCE(1, "verifier backtracking bug");
3498 if (!bt_is_slot_set(bt, spi))
3500 bt_clear_slot(bt, spi);
3501 if (class == BPF_STX)
3502 bt_set_reg(bt, sreg);
3503 } else if (class == BPF_JMP || class == BPF_JMP32) {
3504 if (bpf_pseudo_call(insn)) {
3505 int subprog_insn_idx, subprog;
3507 subprog_insn_idx = idx + insn->imm + 1;
3508 subprog = find_subprog(env, subprog_insn_idx);
3512 if (subprog_is_global(env, subprog)) {
3513 /* check that jump history doesn't have any
3514 * extra instructions from subprog; the next
3515 * instruction after call to global subprog
3516 * should be literally next instruction in
3519 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3520 /* r1-r5 are invalidated after subprog call,
3521 * so for global func call it shouldn't be set
3524 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3525 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3526 WARN_ONCE(1, "verifier backtracking bug");
3529 /* global subprog always sets R0 */
3530 bt_clear_reg(bt, BPF_REG_0);
3533 /* static subprog call instruction, which
3534 * means that we are exiting current subprog,
3535 * so only r1-r5 could be still requested as
3536 * precise, r0 and r6-r10 or any stack slot in
3537 * the current frame should be zero by now
3539 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3540 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3541 WARN_ONCE(1, "verifier backtracking bug");
3544 /* we don't track register spills perfectly,
3545 * so fallback to force-precise instead of failing */
3546 if (bt_stack_mask(bt) != 0)
3548 /* propagate r1-r5 to the caller */
3549 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3550 if (bt_is_reg_set(bt, i)) {
3551 bt_clear_reg(bt, i);
3552 bt_set_frame_reg(bt, bt->frame - 1, i);
3555 if (bt_subprog_exit(bt))
3559 } else if ((bpf_helper_call(insn) &&
3560 is_callback_calling_function(insn->imm) &&
3561 !is_async_callback_calling_function(insn->imm)) ||
3562 (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3563 /* callback-calling helper or kfunc call, which means
3564 * we are exiting from subprog, but unlike the subprog
3565 * call handling above, we shouldn't propagate
3566 * precision of r1-r5 (if any requested), as they are
3567 * not actually arguments passed directly to callback
3570 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3571 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3572 WARN_ONCE(1, "verifier backtracking bug");
3575 if (bt_stack_mask(bt) != 0)
3577 /* clear r1-r5 in callback subprog's mask */
3578 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3579 bt_clear_reg(bt, i);
3580 if (bt_subprog_exit(bt))
3583 } else if (opcode == BPF_CALL) {
3584 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3585 * catch this error later. Make backtracking conservative
3588 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3590 /* regular helper call sets R0 */
3591 bt_clear_reg(bt, BPF_REG_0);
3592 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3593 /* if backtracing was looking for registers R1-R5
3594 * they should have been found already.
3596 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3597 WARN_ONCE(1, "verifier backtracking bug");
3600 } else if (opcode == BPF_EXIT) {
3603 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3604 /* if backtracing was looking for registers R1-R5
3605 * they should have been found already.
3607 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3608 WARN_ONCE(1, "verifier backtracking bug");
3612 /* BPF_EXIT in subprog or callback always returns
3613 * right after the call instruction, so by checking
3614 * whether the instruction at subseq_idx-1 is subprog
3615 * call or not we can distinguish actual exit from
3616 * *subprog* from exit from *callback*. In the former
3617 * case, we need to propagate r0 precision, if
3618 * necessary. In the former we never do that.
3620 r0_precise = subseq_idx - 1 >= 0 &&
3621 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3622 bt_is_reg_set(bt, BPF_REG_0);
3624 bt_clear_reg(bt, BPF_REG_0);
3625 if (bt_subprog_enter(bt))
3629 bt_set_reg(bt, BPF_REG_0);
3630 /* r6-r9 and stack slots will stay set in caller frame
3631 * bitmasks until we return back from callee(s)
3634 } else if (BPF_SRC(insn->code) == BPF_X) {
3635 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3638 * Both dreg and sreg need precision before
3639 * this insn. If only sreg was marked precise
3640 * before it would be equally necessary to
3641 * propagate it to dreg.
3643 bt_set_reg(bt, dreg);
3644 bt_set_reg(bt, sreg);
3645 /* else dreg <cond> K
3646 * Only dreg still needs precision before
3647 * this insn, so for the K-based conditional
3648 * there is nothing new to be marked.
3651 } else if (class == BPF_LD) {
3652 if (!bt_is_reg_set(bt, dreg))
3654 bt_clear_reg(bt, dreg);
3655 /* It's ld_imm64 or ld_abs or ld_ind.
3656 * For ld_imm64 no further tracking of precision
3657 * into parent is necessary
3659 if (mode == BPF_IND || mode == BPF_ABS)
3660 /* to be analyzed */
3666 /* the scalar precision tracking algorithm:
3667 * . at the start all registers have precise=false.
3668 * . scalar ranges are tracked as normal through alu and jmp insns.
3669 * . once precise value of the scalar register is used in:
3670 * . ptr + scalar alu
3671 * . if (scalar cond K|scalar)
3672 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3673 * backtrack through the verifier states and mark all registers and
3674 * stack slots with spilled constants that these scalar regisers
3675 * should be precise.
3676 * . during state pruning two registers (or spilled stack slots)
3677 * are equivalent if both are not precise.
3679 * Note the verifier cannot simply walk register parentage chain,
3680 * since many different registers and stack slots could have been
3681 * used to compute single precise scalar.
3683 * The approach of starting with precise=true for all registers and then
3684 * backtrack to mark a register as not precise when the verifier detects
3685 * that program doesn't care about specific value (e.g., when helper
3686 * takes register as ARG_ANYTHING parameter) is not safe.
3688 * It's ok to walk single parentage chain of the verifier states.
3689 * It's possible that this backtracking will go all the way till 1st insn.
3690 * All other branches will be explored for needing precision later.
3692 * The backtracking needs to deal with cases like:
3693 * 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)
3696 * if r5 > 0x79f goto pc+7
3697 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3700 * call bpf_perf_event_output#25
3701 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3705 * call foo // uses callee's r6 inside to compute r0
3709 * to track above reg_mask/stack_mask needs to be independent for each frame.
3711 * Also if parent's curframe > frame where backtracking started,
3712 * the verifier need to mark registers in both frames, otherwise callees
3713 * may incorrectly prune callers. This is similar to
3714 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3716 * For now backtracking falls back into conservative marking.
3718 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3719 struct bpf_verifier_state *st)
3721 struct bpf_func_state *func;
3722 struct bpf_reg_state *reg;
3725 if (env->log.level & BPF_LOG_LEVEL2) {
3726 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3730 /* big hammer: mark all scalars precise in this path.
3731 * pop_stack may still get !precise scalars.
3732 * We also skip current state and go straight to first parent state,
3733 * because precision markings in current non-checkpointed state are
3734 * not needed. See why in the comment in __mark_chain_precision below.
3736 for (st = st->parent; st; st = st->parent) {
3737 for (i = 0; i <= st->curframe; i++) {
3738 func = st->frame[i];
3739 for (j = 0; j < BPF_REG_FP; j++) {
3740 reg = &func->regs[j];
3741 if (reg->type != SCALAR_VALUE || reg->precise)
3743 reg->precise = true;
3744 if (env->log.level & BPF_LOG_LEVEL2) {
3745 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3749 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3750 if (!is_spilled_reg(&func->stack[j]))
3752 reg = &func->stack[j].spilled_ptr;
3753 if (reg->type != SCALAR_VALUE || reg->precise)
3755 reg->precise = true;
3756 if (env->log.level & BPF_LOG_LEVEL2) {
3757 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3765 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3767 struct bpf_func_state *func;
3768 struct bpf_reg_state *reg;
3771 for (i = 0; i <= st->curframe; i++) {
3772 func = st->frame[i];
3773 for (j = 0; j < BPF_REG_FP; j++) {
3774 reg = &func->regs[j];
3775 if (reg->type != SCALAR_VALUE)
3777 reg->precise = false;
3779 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3780 if (!is_spilled_reg(&func->stack[j]))
3782 reg = &func->stack[j].spilled_ptr;
3783 if (reg->type != SCALAR_VALUE)
3785 reg->precise = false;
3790 static bool idset_contains(struct bpf_idset *s, u32 id)
3794 for (i = 0; i < s->count; ++i)
3795 if (s->ids[i] == id)
3801 static int idset_push(struct bpf_idset *s, u32 id)
3803 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3805 s->ids[s->count++] = id;
3809 static void idset_reset(struct bpf_idset *s)
3814 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3815 * Mark all registers with these IDs as precise.
3817 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3819 struct bpf_idset *precise_ids = &env->idset_scratch;
3820 struct backtrack_state *bt = &env->bt;
3821 struct bpf_func_state *func;
3822 struct bpf_reg_state *reg;
3823 DECLARE_BITMAP(mask, 64);
3826 idset_reset(precise_ids);
3828 for (fr = bt->frame; fr >= 0; fr--) {
3829 func = st->frame[fr];
3831 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3832 for_each_set_bit(i, mask, 32) {
3833 reg = &func->regs[i];
3834 if (!reg->id || reg->type != SCALAR_VALUE)
3836 if (idset_push(precise_ids, reg->id))
3840 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3841 for_each_set_bit(i, mask, 64) {
3842 if (i >= func->allocated_stack / BPF_REG_SIZE)
3844 if (!is_spilled_scalar_reg(&func->stack[i]))
3846 reg = &func->stack[i].spilled_ptr;
3849 if (idset_push(precise_ids, reg->id))
3854 for (fr = 0; fr <= st->curframe; ++fr) {
3855 func = st->frame[fr];
3857 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3858 reg = &func->regs[i];
3861 if (!idset_contains(precise_ids, reg->id))
3863 bt_set_frame_reg(bt, fr, i);
3865 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3866 if (!is_spilled_scalar_reg(&func->stack[i]))
3868 reg = &func->stack[i].spilled_ptr;
3871 if (!idset_contains(precise_ids, reg->id))
3873 bt_set_frame_slot(bt, fr, i);
3881 * __mark_chain_precision() backtracks BPF program instruction sequence and
3882 * chain of verifier states making sure that register *regno* (if regno >= 0)
3883 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3884 * SCALARS, as well as any other registers and slots that contribute to
3885 * a tracked state of given registers/stack slots, depending on specific BPF
3886 * assembly instructions (see backtrack_insns() for exact instruction handling
3887 * logic). This backtracking relies on recorded jmp_history and is able to
3888 * traverse entire chain of parent states. This process ends only when all the
3889 * necessary registers/slots and their transitive dependencies are marked as
3892 * One important and subtle aspect is that precise marks *do not matter* in
3893 * the currently verified state (current state). It is important to understand
3894 * why this is the case.
3896 * First, note that current state is the state that is not yet "checkpointed",
3897 * i.e., it is not yet put into env->explored_states, and it has no children
3898 * states as well. It's ephemeral, and can end up either a) being discarded if
3899 * compatible explored state is found at some point or BPF_EXIT instruction is
3900 * reached or b) checkpointed and put into env->explored_states, branching out
3901 * into one or more children states.
3903 * In the former case, precise markings in current state are completely
3904 * ignored by state comparison code (see regsafe() for details). Only
3905 * checkpointed ("old") state precise markings are important, and if old
3906 * state's register/slot is precise, regsafe() assumes current state's
3907 * register/slot as precise and checks value ranges exactly and precisely. If
3908 * states turn out to be compatible, current state's necessary precise
3909 * markings and any required parent states' precise markings are enforced
3910 * after the fact with propagate_precision() logic, after the fact. But it's
3911 * important to realize that in this case, even after marking current state
3912 * registers/slots as precise, we immediately discard current state. So what
3913 * actually matters is any of the precise markings propagated into current
3914 * state's parent states, which are always checkpointed (due to b) case above).
3915 * As such, for scenario a) it doesn't matter if current state has precise
3916 * markings set or not.
3918 * Now, for the scenario b), checkpointing and forking into child(ren)
3919 * state(s). Note that before current state gets to checkpointing step, any
3920 * processed instruction always assumes precise SCALAR register/slot
3921 * knowledge: if precise value or range is useful to prune jump branch, BPF
3922 * verifier takes this opportunity enthusiastically. Similarly, when
3923 * register's value is used to calculate offset or memory address, exact
3924 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3925 * what we mentioned above about state comparison ignoring precise markings
3926 * during state comparison, BPF verifier ignores and also assumes precise
3927 * markings *at will* during instruction verification process. But as verifier
3928 * assumes precision, it also propagates any precision dependencies across
3929 * parent states, which are not yet finalized, so can be further restricted
3930 * based on new knowledge gained from restrictions enforced by their children
3931 * states. This is so that once those parent states are finalized, i.e., when
3932 * they have no more active children state, state comparison logic in
3933 * is_state_visited() would enforce strict and precise SCALAR ranges, if
3934 * required for correctness.
3936 * To build a bit more intuition, note also that once a state is checkpointed,
3937 * the path we took to get to that state is not important. This is crucial
3938 * property for state pruning. When state is checkpointed and finalized at
3939 * some instruction index, it can be correctly and safely used to "short
3940 * circuit" any *compatible* state that reaches exactly the same instruction
3941 * index. I.e., if we jumped to that instruction from a completely different
3942 * code path than original finalized state was derived from, it doesn't
3943 * matter, current state can be discarded because from that instruction
3944 * forward having a compatible state will ensure we will safely reach the
3945 * exit. States describe preconditions for further exploration, but completely
3946 * forget the history of how we got here.
3948 * This also means that even if we needed precise SCALAR range to get to
3949 * finalized state, but from that point forward *that same* SCALAR register is
3950 * never used in a precise context (i.e., it's precise value is not needed for
3951 * correctness), it's correct and safe to mark such register as "imprecise"
3952 * (i.e., precise marking set to false). This is what we rely on when we do
3953 * not set precise marking in current state. If no child state requires
3954 * precision for any given SCALAR register, it's safe to dictate that it can
3955 * be imprecise. If any child state does require this register to be precise,
3956 * we'll mark it precise later retroactively during precise markings
3957 * propagation from child state to parent states.
3959 * Skipping precise marking setting in current state is a mild version of
3960 * relying on the above observation. But we can utilize this property even
3961 * more aggressively by proactively forgetting any precise marking in the
3962 * current state (which we inherited from the parent state), right before we
3963 * checkpoint it and branch off into new child state. This is done by
3964 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3965 * finalized states which help in short circuiting more future states.
3967 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3969 struct backtrack_state *bt = &env->bt;
3970 struct bpf_verifier_state *st = env->cur_state;
3971 int first_idx = st->first_insn_idx;
3972 int last_idx = env->insn_idx;
3973 int subseq_idx = -1;
3974 struct bpf_func_state *func;
3975 struct bpf_reg_state *reg;
3976 bool skip_first = true;
3979 if (!env->bpf_capable)
3982 /* set frame number from which we are starting to backtrack */
3983 bt_init(bt, env->cur_state->curframe);
3985 /* Do sanity checks against current state of register and/or stack
3986 * slot, but don't set precise flag in current state, as precision
3987 * tracking in the current state is unnecessary.
3989 func = st->frame[bt->frame];
3991 reg = &func->regs[regno];
3992 if (reg->type != SCALAR_VALUE) {
3993 WARN_ONCE(1, "backtracing misuse");
3996 bt_set_reg(bt, regno);
4003 DECLARE_BITMAP(mask, 64);
4004 u32 history = st->jmp_history_cnt;
4006 if (env->log.level & BPF_LOG_LEVEL2) {
4007 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4008 bt->frame, last_idx, first_idx, subseq_idx);
4011 /* If some register with scalar ID is marked as precise,
4012 * make sure that all registers sharing this ID are also precise.
4013 * This is needed to estimate effect of find_equal_scalars().
4014 * Do this at the last instruction of each state,
4015 * bpf_reg_state::id fields are valid for these instructions.
4017 * Allows to track precision in situation like below:
4019 * r2 = unknown value
4023 * r1 = r2 // r1 and r2 now share the same ID
4025 * --- state #1 {r1.id = A, r2.id = A} ---
4027 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4029 * --- state #2 {r1.id = A, r2.id = A} ---
4031 * r3 += r1 // need to mark both r1 and r2
4033 if (mark_precise_scalar_ids(env, st))
4037 /* we are at the entry into subprog, which
4038 * is expected for global funcs, but only if
4039 * requested precise registers are R1-R5
4040 * (which are global func's input arguments)
4042 if (st->curframe == 0 &&
4043 st->frame[0]->subprogno > 0 &&
4044 st->frame[0]->callsite == BPF_MAIN_FUNC &&
4045 bt_stack_mask(bt) == 0 &&
4046 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4047 bitmap_from_u64(mask, bt_reg_mask(bt));
4048 for_each_set_bit(i, mask, 32) {
4049 reg = &st->frame[0]->regs[i];
4050 if (reg->type != SCALAR_VALUE) {
4051 bt_clear_reg(bt, i);
4054 reg->precise = true;
4059 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4060 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4061 WARN_ONCE(1, "verifier backtracking bug");
4065 for (i = last_idx;;) {
4070 err = backtrack_insn(env, i, subseq_idx, bt);
4072 if (err == -ENOTSUPP) {
4073 mark_all_scalars_precise(env, env->cur_state);
4080 /* Found assignment(s) into tracked register in this state.
4081 * Since this state is already marked, just return.
4082 * Nothing to be tracked further in the parent state.
4088 i = get_prev_insn_idx(st, i, &history);
4089 if (i >= env->prog->len) {
4090 /* This can happen if backtracking reached insn 0
4091 * and there are still reg_mask or stack_mask
4093 * It means the backtracking missed the spot where
4094 * particular register was initialized with a constant.
4096 verbose(env, "BUG backtracking idx %d\n", i);
4097 WARN_ONCE(1, "verifier backtracking bug");
4105 for (fr = bt->frame; fr >= 0; fr--) {
4106 func = st->frame[fr];
4107 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4108 for_each_set_bit(i, mask, 32) {
4109 reg = &func->regs[i];
4110 if (reg->type != SCALAR_VALUE) {
4111 bt_clear_frame_reg(bt, fr, i);
4115 bt_clear_frame_reg(bt, fr, i);
4117 reg->precise = true;
4120 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4121 for_each_set_bit(i, mask, 64) {
4122 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4123 /* the sequence of instructions:
4125 * 3: (7b) *(u64 *)(r3 -8) = r0
4126 * 4: (79) r4 = *(u64 *)(r10 -8)
4127 * doesn't contain jmps. It's backtracked
4128 * as a single block.
4129 * During backtracking insn 3 is not recognized as
4130 * stack access, so at the end of backtracking
4131 * stack slot fp-8 is still marked in stack_mask.
4132 * However the parent state may not have accessed
4133 * fp-8 and it's "unallocated" stack space.
4134 * In such case fallback to conservative.
4136 mark_all_scalars_precise(env, env->cur_state);
4141 if (!is_spilled_scalar_reg(&func->stack[i])) {
4142 bt_clear_frame_slot(bt, fr, i);
4145 reg = &func->stack[i].spilled_ptr;
4147 bt_clear_frame_slot(bt, fr, i);
4149 reg->precise = true;
4151 if (env->log.level & BPF_LOG_LEVEL2) {
4152 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4153 bt_frame_reg_mask(bt, fr));
4154 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4155 fr, env->tmp_str_buf);
4156 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4157 bt_frame_stack_mask(bt, fr));
4158 verbose(env, "stack=%s: ", env->tmp_str_buf);
4159 print_verifier_state(env, func, true);
4166 subseq_idx = first_idx;
4167 last_idx = st->last_insn_idx;
4168 first_idx = st->first_insn_idx;
4171 /* if we still have requested precise regs or slots, we missed
4172 * something (e.g., stack access through non-r10 register), so
4173 * fallback to marking all precise
4175 if (!bt_empty(bt)) {
4176 mark_all_scalars_precise(env, env->cur_state);
4183 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4185 return __mark_chain_precision(env, regno);
4188 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4189 * desired reg and stack masks across all relevant frames
4191 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4193 return __mark_chain_precision(env, -1);
4196 static bool is_spillable_regtype(enum bpf_reg_type type)
4198 switch (base_type(type)) {
4199 case PTR_TO_MAP_VALUE:
4203 case PTR_TO_PACKET_META:
4204 case PTR_TO_PACKET_END:
4205 case PTR_TO_FLOW_KEYS:
4206 case CONST_PTR_TO_MAP:
4208 case PTR_TO_SOCK_COMMON:
4209 case PTR_TO_TCP_SOCK:
4210 case PTR_TO_XDP_SOCK:
4215 case PTR_TO_MAP_KEY:
4222 /* Does this register contain a constant zero? */
4223 static bool register_is_null(struct bpf_reg_state *reg)
4225 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4228 static bool register_is_const(struct bpf_reg_state *reg)
4230 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4233 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4235 return tnum_is_unknown(reg->var_off) &&
4236 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4237 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4238 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4239 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4242 static bool register_is_bounded(struct bpf_reg_state *reg)
4244 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4247 static bool __is_pointer_value(bool allow_ptr_leaks,
4248 const struct bpf_reg_state *reg)
4250 if (allow_ptr_leaks)
4253 return reg->type != SCALAR_VALUE;
4256 /* Copy src state preserving dst->parent and dst->live fields */
4257 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4259 struct bpf_reg_state *parent = dst->parent;
4260 enum bpf_reg_liveness live = dst->live;
4263 dst->parent = parent;
4267 static void save_register_state(struct bpf_func_state *state,
4268 int spi, struct bpf_reg_state *reg,
4273 copy_register_state(&state->stack[spi].spilled_ptr, reg);
4274 if (size == BPF_REG_SIZE)
4275 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4277 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4278 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4280 /* size < 8 bytes spill */
4282 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4285 static bool is_bpf_st_mem(struct bpf_insn *insn)
4287 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4290 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4291 * stack boundary and alignment are checked in check_mem_access()
4293 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4294 /* stack frame we're writing to */
4295 struct bpf_func_state *state,
4296 int off, int size, int value_regno,
4299 struct bpf_func_state *cur; /* state of the current function */
4300 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4301 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4302 struct bpf_reg_state *reg = NULL;
4303 u32 dst_reg = insn->dst_reg;
4305 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4308 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4309 * so it's aligned access and [off, off + size) are within stack limits
4311 if (!env->allow_ptr_leaks &&
4312 state->stack[spi].slot_type[0] == STACK_SPILL &&
4313 size != BPF_REG_SIZE) {
4314 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4318 cur = env->cur_state->frame[env->cur_state->curframe];
4319 if (value_regno >= 0)
4320 reg = &cur->regs[value_regno];
4321 if (!env->bypass_spec_v4) {
4322 bool sanitize = reg && is_spillable_regtype(reg->type);
4324 for (i = 0; i < size; i++) {
4325 u8 type = state->stack[spi].slot_type[i];
4327 if (type != STACK_MISC && type != STACK_ZERO) {
4334 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4337 err = destroy_if_dynptr_stack_slot(env, state, spi);
4341 mark_stack_slot_scratched(env, spi);
4342 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4343 !register_is_null(reg) && env->bpf_capable) {
4344 if (dst_reg != BPF_REG_FP) {
4345 /* The backtracking logic can only recognize explicit
4346 * stack slot address like [fp - 8]. Other spill of
4347 * scalar via different register has to be conservative.
4348 * Backtrack from here and mark all registers as precise
4349 * that contributed into 'reg' being a constant.
4351 err = mark_chain_precision(env, value_regno);
4355 save_register_state(state, spi, reg, size);
4356 /* Break the relation on a narrowing spill. */
4357 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4358 state->stack[spi].spilled_ptr.id = 0;
4359 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4360 insn->imm != 0 && env->bpf_capable) {
4361 struct bpf_reg_state fake_reg = {};
4363 __mark_reg_known(&fake_reg, (u32)insn->imm);
4364 fake_reg.type = SCALAR_VALUE;
4365 save_register_state(state, spi, &fake_reg, size);
4366 } else if (reg && is_spillable_regtype(reg->type)) {
4367 /* register containing pointer is being spilled into stack */
4368 if (size != BPF_REG_SIZE) {
4369 verbose_linfo(env, insn_idx, "; ");
4370 verbose(env, "invalid size of register spill\n");
4373 if (state != cur && reg->type == PTR_TO_STACK) {
4374 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4377 save_register_state(state, spi, reg, size);
4379 u8 type = STACK_MISC;
4381 /* regular write of data into stack destroys any spilled ptr */
4382 state->stack[spi].spilled_ptr.type = NOT_INIT;
4383 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4384 if (is_stack_slot_special(&state->stack[spi]))
4385 for (i = 0; i < BPF_REG_SIZE; i++)
4386 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4388 /* only mark the slot as written if all 8 bytes were written
4389 * otherwise read propagation may incorrectly stop too soon
4390 * when stack slots are partially written.
4391 * This heuristic means that read propagation will be
4392 * conservative, since it will add reg_live_read marks
4393 * to stack slots all the way to first state when programs
4394 * writes+reads less than 8 bytes
4396 if (size == BPF_REG_SIZE)
4397 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4399 /* when we zero initialize stack slots mark them as such */
4400 if ((reg && register_is_null(reg)) ||
4401 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4402 /* backtracking doesn't work for STACK_ZERO yet. */
4403 err = mark_chain_precision(env, value_regno);
4409 /* Mark slots affected by this stack write. */
4410 for (i = 0; i < size; i++)
4411 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4417 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4418 * known to contain a variable offset.
4419 * This function checks whether the write is permitted and conservatively
4420 * tracks the effects of the write, considering that each stack slot in the
4421 * dynamic range is potentially written to.
4423 * 'off' includes 'regno->off'.
4424 * 'value_regno' can be -1, meaning that an unknown value is being written to
4427 * Spilled pointers in range are not marked as written because we don't know
4428 * what's going to be actually written. This means that read propagation for
4429 * future reads cannot be terminated by this write.
4431 * For privileged programs, uninitialized stack slots are considered
4432 * initialized by this write (even though we don't know exactly what offsets
4433 * are going to be written to). The idea is that we don't want the verifier to
4434 * reject future reads that access slots written to through variable offsets.
4436 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4437 /* func where register points to */
4438 struct bpf_func_state *state,
4439 int ptr_regno, int off, int size,
4440 int value_regno, int insn_idx)
4442 struct bpf_func_state *cur; /* state of the current function */
4443 int min_off, max_off;
4445 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4446 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4447 bool writing_zero = false;
4448 /* set if the fact that we're writing a zero is used to let any
4449 * stack slots remain STACK_ZERO
4451 bool zero_used = false;
4453 cur = env->cur_state->frame[env->cur_state->curframe];
4454 ptr_reg = &cur->regs[ptr_regno];
4455 min_off = ptr_reg->smin_value + off;
4456 max_off = ptr_reg->smax_value + off + size;
4457 if (value_regno >= 0)
4458 value_reg = &cur->regs[value_regno];
4459 if ((value_reg && register_is_null(value_reg)) ||
4460 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4461 writing_zero = true;
4463 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4467 for (i = min_off; i < max_off; i++) {
4471 err = destroy_if_dynptr_stack_slot(env, state, spi);
4476 /* Variable offset writes destroy any spilled pointers in range. */
4477 for (i = min_off; i < max_off; i++) {
4478 u8 new_type, *stype;
4482 spi = slot / BPF_REG_SIZE;
4483 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4484 mark_stack_slot_scratched(env, spi);
4486 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4487 /* Reject the write if range we may write to has not
4488 * been initialized beforehand. If we didn't reject
4489 * here, the ptr status would be erased below (even
4490 * though not all slots are actually overwritten),
4491 * possibly opening the door to leaks.
4493 * We do however catch STACK_INVALID case below, and
4494 * only allow reading possibly uninitialized memory
4495 * later for CAP_PERFMON, as the write may not happen to
4498 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4503 /* Erase all spilled pointers. */
4504 state->stack[spi].spilled_ptr.type = NOT_INIT;
4506 /* Update the slot type. */
4507 new_type = STACK_MISC;
4508 if (writing_zero && *stype == STACK_ZERO) {
4509 new_type = STACK_ZERO;
4512 /* If the slot is STACK_INVALID, we check whether it's OK to
4513 * pretend that it will be initialized by this write. The slot
4514 * might not actually be written to, and so if we mark it as
4515 * initialized future reads might leak uninitialized memory.
4516 * For privileged programs, we will accept such reads to slots
4517 * that may or may not be written because, if we're reject
4518 * them, the error would be too confusing.
4520 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4521 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4528 /* backtracking doesn't work for STACK_ZERO yet. */
4529 err = mark_chain_precision(env, value_regno);
4536 /* When register 'dst_regno' is assigned some values from stack[min_off,
4537 * max_off), we set the register's type according to the types of the
4538 * respective stack slots. If all the stack values are known to be zeros, then
4539 * so is the destination reg. Otherwise, the register is considered to be
4540 * SCALAR. This function does not deal with register filling; the caller must
4541 * ensure that all spilled registers in the stack range have been marked as
4544 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4545 /* func where src register points to */
4546 struct bpf_func_state *ptr_state,
4547 int min_off, int max_off, int dst_regno)
4549 struct bpf_verifier_state *vstate = env->cur_state;
4550 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4555 for (i = min_off; i < max_off; i++) {
4557 spi = slot / BPF_REG_SIZE;
4558 mark_stack_slot_scratched(env, spi);
4559 stype = ptr_state->stack[spi].slot_type;
4560 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4564 if (zeros == max_off - min_off) {
4565 /* any access_size read into register is zero extended,
4566 * so the whole register == const_zero
4568 __mark_reg_const_zero(&state->regs[dst_regno]);
4569 /* backtracking doesn't support STACK_ZERO yet,
4570 * so mark it precise here, so that later
4571 * backtracking can stop here.
4572 * Backtracking may not need this if this register
4573 * doesn't participate in pointer adjustment.
4574 * Forward propagation of precise flag is not
4575 * necessary either. This mark is only to stop
4576 * backtracking. Any register that contributed
4577 * to const 0 was marked precise before spill.
4579 state->regs[dst_regno].precise = true;
4581 /* have read misc data from the stack */
4582 mark_reg_unknown(env, state->regs, dst_regno);
4584 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4587 /* Read the stack at 'off' and put the results into the register indicated by
4588 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4591 * 'dst_regno' can be -1, meaning that the read value is not going to a
4594 * The access is assumed to be within the current stack bounds.
4596 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4597 /* func where src register points to */
4598 struct bpf_func_state *reg_state,
4599 int off, int size, int dst_regno)
4601 struct bpf_verifier_state *vstate = env->cur_state;
4602 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4603 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4604 struct bpf_reg_state *reg;
4607 stype = reg_state->stack[spi].slot_type;
4608 reg = ®_state->stack[spi].spilled_ptr;
4610 mark_stack_slot_scratched(env, spi);
4612 if (is_spilled_reg(®_state->stack[spi])) {
4615 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4618 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4619 if (reg->type != SCALAR_VALUE) {
4620 verbose_linfo(env, env->insn_idx, "; ");
4621 verbose(env, "invalid size of register fill\n");
4625 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4629 if (!(off % BPF_REG_SIZE) && size == spill_size) {
4630 /* The earlier check_reg_arg() has decided the
4631 * subreg_def for this insn. Save it first.
4633 s32 subreg_def = state->regs[dst_regno].subreg_def;
4635 copy_register_state(&state->regs[dst_regno], reg);
4636 state->regs[dst_regno].subreg_def = subreg_def;
4638 for (i = 0; i < size; i++) {
4639 type = stype[(slot - i) % BPF_REG_SIZE];
4640 if (type == STACK_SPILL)
4642 if (type == STACK_MISC)
4644 if (type == STACK_INVALID && env->allow_uninit_stack)
4646 verbose(env, "invalid read from stack off %d+%d size %d\n",
4650 mark_reg_unknown(env, state->regs, dst_regno);
4652 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4656 if (dst_regno >= 0) {
4657 /* restore register state from stack */
4658 copy_register_state(&state->regs[dst_regno], reg);
4659 /* mark reg as written since spilled pointer state likely
4660 * has its liveness marks cleared by is_state_visited()
4661 * which resets stack/reg liveness for state transitions
4663 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4664 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4665 /* If dst_regno==-1, the caller is asking us whether
4666 * it is acceptable to use this value as a SCALAR_VALUE
4668 * We must not allow unprivileged callers to do that
4669 * with spilled pointers.
4671 verbose(env, "leaking pointer from stack off %d\n",
4675 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4677 for (i = 0; i < size; i++) {
4678 type = stype[(slot - i) % BPF_REG_SIZE];
4679 if (type == STACK_MISC)
4681 if (type == STACK_ZERO)
4683 if (type == STACK_INVALID && env->allow_uninit_stack)
4685 verbose(env, "invalid read from stack off %d+%d size %d\n",
4689 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4691 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4696 enum bpf_access_src {
4697 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4698 ACCESS_HELPER = 2, /* the access is performed by a helper */
4701 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4702 int regno, int off, int access_size,
4703 bool zero_size_allowed,
4704 enum bpf_access_src type,
4705 struct bpf_call_arg_meta *meta);
4707 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4709 return cur_regs(env) + regno;
4712 /* Read the stack at 'ptr_regno + off' and put the result into the register
4714 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4715 * but not its variable offset.
4716 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4718 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4719 * filling registers (i.e. reads of spilled register cannot be detected when
4720 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4721 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4722 * offset; for a fixed offset check_stack_read_fixed_off should be used
4725 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4726 int ptr_regno, int off, int size, int dst_regno)
4728 /* The state of the source register. */
4729 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4730 struct bpf_func_state *ptr_state = func(env, reg);
4732 int min_off, max_off;
4734 /* Note that we pass a NULL meta, so raw access will not be permitted.
4736 err = check_stack_range_initialized(env, ptr_regno, off, size,
4737 false, ACCESS_DIRECT, NULL);
4741 min_off = reg->smin_value + off;
4742 max_off = reg->smax_value + off;
4743 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4747 /* check_stack_read dispatches to check_stack_read_fixed_off or
4748 * check_stack_read_var_off.
4750 * The caller must ensure that the offset falls within the allocated stack
4753 * 'dst_regno' is a register which will receive the value from the stack. It
4754 * can be -1, meaning that the read value is not going to a register.
4756 static int check_stack_read(struct bpf_verifier_env *env,
4757 int ptr_regno, int off, int size,
4760 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4761 struct bpf_func_state *state = func(env, reg);
4763 /* Some accesses are only permitted with a static offset. */
4764 bool var_off = !tnum_is_const(reg->var_off);
4766 /* The offset is required to be static when reads don't go to a
4767 * register, in order to not leak pointers (see
4768 * check_stack_read_fixed_off).
4770 if (dst_regno < 0 && var_off) {
4773 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4774 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4778 /* Variable offset is prohibited for unprivileged mode for simplicity
4779 * since it requires corresponding support in Spectre masking for stack
4780 * ALU. See also retrieve_ptr_limit(). The check in
4781 * check_stack_access_for_ptr_arithmetic() called by
4782 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4783 * with variable offsets, therefore no check is required here. Further,
4784 * just checking it here would be insufficient as speculative stack
4785 * writes could still lead to unsafe speculative behaviour.
4788 off += reg->var_off.value;
4789 err = check_stack_read_fixed_off(env, state, off, size,
4792 /* Variable offset stack reads need more conservative handling
4793 * than fixed offset ones. Note that dst_regno >= 0 on this
4796 err = check_stack_read_var_off(env, ptr_regno, off, size,
4803 /* check_stack_write dispatches to check_stack_write_fixed_off or
4804 * check_stack_write_var_off.
4806 * 'ptr_regno' is the register used as a pointer into the stack.
4807 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4808 * 'value_regno' is the register whose value we're writing to the stack. It can
4809 * be -1, meaning that we're not writing from a register.
4811 * The caller must ensure that the offset falls within the maximum stack size.
4813 static int check_stack_write(struct bpf_verifier_env *env,
4814 int ptr_regno, int off, int size,
4815 int value_regno, int insn_idx)
4817 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4818 struct bpf_func_state *state = func(env, reg);
4821 if (tnum_is_const(reg->var_off)) {
4822 off += reg->var_off.value;
4823 err = check_stack_write_fixed_off(env, state, off, size,
4824 value_regno, insn_idx);
4826 /* Variable offset stack reads need more conservative handling
4827 * than fixed offset ones.
4829 err = check_stack_write_var_off(env, state,
4830 ptr_regno, off, size,
4831 value_regno, insn_idx);
4836 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4837 int off, int size, enum bpf_access_type type)
4839 struct bpf_reg_state *regs = cur_regs(env);
4840 struct bpf_map *map = regs[regno].map_ptr;
4841 u32 cap = bpf_map_flags_to_cap(map);
4843 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4844 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4845 map->value_size, off, size);
4849 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4850 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4851 map->value_size, off, size);
4858 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4859 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4860 int off, int size, u32 mem_size,
4861 bool zero_size_allowed)
4863 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4864 struct bpf_reg_state *reg;
4866 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4869 reg = &cur_regs(env)[regno];
4870 switch (reg->type) {
4871 case PTR_TO_MAP_KEY:
4872 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4873 mem_size, off, size);
4875 case PTR_TO_MAP_VALUE:
4876 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4877 mem_size, off, size);
4880 case PTR_TO_PACKET_META:
4881 case PTR_TO_PACKET_END:
4882 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4883 off, size, regno, reg->id, off, mem_size);
4887 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4888 mem_size, off, size);
4894 /* check read/write into a memory region with possible variable offset */
4895 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4896 int off, int size, u32 mem_size,
4897 bool zero_size_allowed)
4899 struct bpf_verifier_state *vstate = env->cur_state;
4900 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4901 struct bpf_reg_state *reg = &state->regs[regno];
4904 /* We may have adjusted the register pointing to memory region, so we
4905 * need to try adding each of min_value and max_value to off
4906 * to make sure our theoretical access will be safe.
4908 * The minimum value is only important with signed
4909 * comparisons where we can't assume the floor of a
4910 * value is 0. If we are using signed variables for our
4911 * index'es we need to make sure that whatever we use
4912 * will have a set floor within our range.
4914 if (reg->smin_value < 0 &&
4915 (reg->smin_value == S64_MIN ||
4916 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4917 reg->smin_value + off < 0)) {
4918 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4922 err = __check_mem_access(env, regno, reg->smin_value + off, size,
4923 mem_size, zero_size_allowed);
4925 verbose(env, "R%d min value is outside of the allowed memory range\n",
4930 /* If we haven't set a max value then we need to bail since we can't be
4931 * sure we won't do bad things.
4932 * If reg->umax_value + off could overflow, treat that as unbounded too.
4934 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4935 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4939 err = __check_mem_access(env, regno, reg->umax_value + off, size,
4940 mem_size, zero_size_allowed);
4942 verbose(env, "R%d max value is outside of the allowed memory range\n",
4950 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4951 const struct bpf_reg_state *reg, int regno,
4954 /* Access to this pointer-typed register or passing it to a helper
4955 * is only allowed in its original, unmodified form.
4959 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4960 reg_type_str(env, reg->type), regno, reg->off);
4964 if (!fixed_off_ok && reg->off) {
4965 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4966 reg_type_str(env, reg->type), regno, reg->off);
4970 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4973 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4974 verbose(env, "variable %s access var_off=%s disallowed\n",
4975 reg_type_str(env, reg->type), tn_buf);
4982 int check_ptr_off_reg(struct bpf_verifier_env *env,
4983 const struct bpf_reg_state *reg, int regno)
4985 return __check_ptr_off_reg(env, reg, regno, false);
4988 static int map_kptr_match_type(struct bpf_verifier_env *env,
4989 struct btf_field *kptr_field,
4990 struct bpf_reg_state *reg, u32 regno)
4992 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4993 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4994 const char *reg_name = "";
4996 /* Only unreferenced case accepts untrusted pointers */
4997 if (kptr_field->type == BPF_KPTR_UNREF)
4998 perm_flags |= PTR_UNTRUSTED;
5000 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5003 if (!btf_is_kernel(reg->btf)) {
5004 verbose(env, "R%d must point to kernel BTF\n", regno);
5007 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5008 reg_name = btf_type_name(reg->btf, reg->btf_id);
5010 /* For ref_ptr case, release function check should ensure we get one
5011 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5012 * normal store of unreferenced kptr, we must ensure var_off is zero.
5013 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5014 * reg->off and reg->ref_obj_id are not needed here.
5016 if (__check_ptr_off_reg(env, reg, regno, true))
5019 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
5020 * we also need to take into account the reg->off.
5022 * We want to support cases like:
5030 * v = func(); // PTR_TO_BTF_ID
5031 * val->foo = v; // reg->off is zero, btf and btf_id match type
5032 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5033 * // first member type of struct after comparison fails
5034 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5037 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5038 * is zero. We must also ensure that btf_struct_ids_match does not walk
5039 * the struct to match type against first member of struct, i.e. reject
5040 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5041 * strict mode to true for type match.
5043 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5044 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5045 kptr_field->type == BPF_KPTR_REF))
5049 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5050 reg_type_str(env, reg->type), reg_name);
5051 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5052 if (kptr_field->type == BPF_KPTR_UNREF)
5053 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5060 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5061 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5063 static bool in_rcu_cs(struct bpf_verifier_env *env)
5065 return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
5068 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5069 BTF_SET_START(rcu_protected_types)
5070 BTF_ID(struct, prog_test_ref_kfunc)
5071 BTF_ID(struct, cgroup)
5072 BTF_ID(struct, bpf_cpumask)
5073 BTF_ID(struct, task_struct)
5074 BTF_SET_END(rcu_protected_types)
5076 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5078 if (!btf_is_kernel(btf))
5080 return btf_id_set_contains(&rcu_protected_types, btf_id);
5083 static bool rcu_safe_kptr(const struct btf_field *field)
5085 const struct btf_field_kptr *kptr = &field->kptr;
5087 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5090 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5091 int value_regno, int insn_idx,
5092 struct btf_field *kptr_field)
5094 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5095 int class = BPF_CLASS(insn->code);
5096 struct bpf_reg_state *val_reg;
5098 /* Things we already checked for in check_map_access and caller:
5099 * - Reject cases where variable offset may touch kptr
5100 * - size of access (must be BPF_DW)
5101 * - tnum_is_const(reg->var_off)
5102 * - kptr_field->offset == off + reg->var_off.value
5104 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5105 if (BPF_MODE(insn->code) != BPF_MEM) {
5106 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5110 /* We only allow loading referenced kptr, since it will be marked as
5111 * untrusted, similar to unreferenced kptr.
5113 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5114 verbose(env, "store to referenced kptr disallowed\n");
5118 if (class == BPF_LDX) {
5119 val_reg = reg_state(env, value_regno);
5120 /* We can simply mark the value_regno receiving the pointer
5121 * value from map as PTR_TO_BTF_ID, with the correct type.
5123 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5124 kptr_field->kptr.btf_id,
5125 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5126 PTR_MAYBE_NULL | MEM_RCU :
5127 PTR_MAYBE_NULL | PTR_UNTRUSTED);
5128 /* For mark_ptr_or_null_reg */
5129 val_reg->id = ++env->id_gen;
5130 } else if (class == BPF_STX) {
5131 val_reg = reg_state(env, value_regno);
5132 if (!register_is_null(val_reg) &&
5133 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5135 } else if (class == BPF_ST) {
5137 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5138 kptr_field->offset);
5142 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5148 /* check read/write into a map element with possible variable offset */
5149 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5150 int off, int size, bool zero_size_allowed,
5151 enum bpf_access_src src)
5153 struct bpf_verifier_state *vstate = env->cur_state;
5154 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5155 struct bpf_reg_state *reg = &state->regs[regno];
5156 struct bpf_map *map = reg->map_ptr;
5157 struct btf_record *rec;
5160 err = check_mem_region_access(env, regno, off, size, map->value_size,
5165 if (IS_ERR_OR_NULL(map->record))
5168 for (i = 0; i < rec->cnt; i++) {
5169 struct btf_field *field = &rec->fields[i];
5170 u32 p = field->offset;
5172 /* If any part of a field can be touched by load/store, reject
5173 * this program. To check that [x1, x2) overlaps with [y1, y2),
5174 * it is sufficient to check x1 < y2 && y1 < x2.
5176 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5177 p < reg->umax_value + off + size) {
5178 switch (field->type) {
5179 case BPF_KPTR_UNREF:
5181 if (src != ACCESS_DIRECT) {
5182 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5185 if (!tnum_is_const(reg->var_off)) {
5186 verbose(env, "kptr access cannot have variable offset\n");
5189 if (p != off + reg->var_off.value) {
5190 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5191 p, off + reg->var_off.value);
5194 if (size != bpf_size_to_bytes(BPF_DW)) {
5195 verbose(env, "kptr access size must be BPF_DW\n");
5200 verbose(env, "%s cannot be accessed directly by load/store\n",
5201 btf_field_type_name(field->type));
5209 #define MAX_PACKET_OFF 0xffff
5211 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5212 const struct bpf_call_arg_meta *meta,
5213 enum bpf_access_type t)
5215 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5217 switch (prog_type) {
5218 /* Program types only with direct read access go here! */
5219 case BPF_PROG_TYPE_LWT_IN:
5220 case BPF_PROG_TYPE_LWT_OUT:
5221 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5222 case BPF_PROG_TYPE_SK_REUSEPORT:
5223 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5224 case BPF_PROG_TYPE_CGROUP_SKB:
5229 /* Program types with direct read + write access go here! */
5230 case BPF_PROG_TYPE_SCHED_CLS:
5231 case BPF_PROG_TYPE_SCHED_ACT:
5232 case BPF_PROG_TYPE_XDP:
5233 case BPF_PROG_TYPE_LWT_XMIT:
5234 case BPF_PROG_TYPE_SK_SKB:
5235 case BPF_PROG_TYPE_SK_MSG:
5237 return meta->pkt_access;
5239 env->seen_direct_write = true;
5242 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5244 env->seen_direct_write = true;
5253 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5254 int size, bool zero_size_allowed)
5256 struct bpf_reg_state *regs = cur_regs(env);
5257 struct bpf_reg_state *reg = ®s[regno];
5260 /* We may have added a variable offset to the packet pointer; but any
5261 * reg->range we have comes after that. We are only checking the fixed
5265 /* We don't allow negative numbers, because we aren't tracking enough
5266 * detail to prove they're safe.
5268 if (reg->smin_value < 0) {
5269 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5274 err = reg->range < 0 ? -EINVAL :
5275 __check_mem_access(env, regno, off, size, reg->range,
5278 verbose(env, "R%d offset is outside of the packet\n", regno);
5282 /* __check_mem_access has made sure "off + size - 1" is within u16.
5283 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5284 * otherwise find_good_pkt_pointers would have refused to set range info
5285 * that __check_mem_access would have rejected this pkt access.
5286 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5288 env->prog->aux->max_pkt_offset =
5289 max_t(u32, env->prog->aux->max_pkt_offset,
5290 off + reg->umax_value + size - 1);
5295 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
5296 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5297 enum bpf_access_type t, enum bpf_reg_type *reg_type,
5298 struct btf **btf, u32 *btf_id)
5300 struct bpf_insn_access_aux info = {
5301 .reg_type = *reg_type,
5305 if (env->ops->is_valid_access &&
5306 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5307 /* A non zero info.ctx_field_size indicates that this field is a
5308 * candidate for later verifier transformation to load the whole
5309 * field and then apply a mask when accessed with a narrower
5310 * access than actual ctx access size. A zero info.ctx_field_size
5311 * will only allow for whole field access and rejects any other
5312 * type of narrower access.
5314 *reg_type = info.reg_type;
5316 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5318 *btf_id = info.btf_id;
5320 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5322 /* remember the offset of last byte accessed in ctx */
5323 if (env->prog->aux->max_ctx_offset < off + size)
5324 env->prog->aux->max_ctx_offset = off + size;
5328 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5332 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5335 if (size < 0 || off < 0 ||
5336 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5337 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5344 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5345 u32 regno, int off, int size,
5346 enum bpf_access_type t)
5348 struct bpf_reg_state *regs = cur_regs(env);
5349 struct bpf_reg_state *reg = ®s[regno];
5350 struct bpf_insn_access_aux info = {};
5353 if (reg->smin_value < 0) {
5354 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5359 switch (reg->type) {
5360 case PTR_TO_SOCK_COMMON:
5361 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5364 valid = bpf_sock_is_valid_access(off, size, t, &info);
5366 case PTR_TO_TCP_SOCK:
5367 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5369 case PTR_TO_XDP_SOCK:
5370 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5378 env->insn_aux_data[insn_idx].ctx_field_size =
5379 info.ctx_field_size;
5383 verbose(env, "R%d invalid %s access off=%d size=%d\n",
5384 regno, reg_type_str(env, reg->type), off, size);
5389 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5391 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5394 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5396 const struct bpf_reg_state *reg = reg_state(env, regno);
5398 return reg->type == PTR_TO_CTX;
5401 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5403 const struct bpf_reg_state *reg = reg_state(env, regno);
5405 return type_is_sk_pointer(reg->type);
5408 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5410 const struct bpf_reg_state *reg = reg_state(env, regno);
5412 return type_is_pkt_pointer(reg->type);
5415 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5417 const struct bpf_reg_state *reg = reg_state(env, regno);
5419 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5420 return reg->type == PTR_TO_FLOW_KEYS;
5423 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5425 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5426 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5427 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5429 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5432 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5434 /* A referenced register is always trusted. */
5435 if (reg->ref_obj_id)
5438 /* Types listed in the reg2btf_ids are always trusted */
5439 if (reg2btf_ids[base_type(reg->type)])
5442 /* If a register is not referenced, it is trusted if it has the
5443 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5444 * other type modifiers may be safe, but we elect to take an opt-in
5445 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5448 * Eventually, we should make PTR_TRUSTED the single source of truth
5449 * for whether a register is trusted.
5451 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5452 !bpf_type_has_unsafe_modifiers(reg->type);
5455 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5457 return reg->type & MEM_RCU;
5460 static void clear_trusted_flags(enum bpf_type_flag *flag)
5462 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5465 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5466 const struct bpf_reg_state *reg,
5467 int off, int size, bool strict)
5469 struct tnum reg_off;
5472 /* Byte size accesses are always allowed. */
5473 if (!strict || size == 1)
5476 /* For platforms that do not have a Kconfig enabling
5477 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5478 * NET_IP_ALIGN is universally set to '2'. And on platforms
5479 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5480 * to this code only in strict mode where we want to emulate
5481 * the NET_IP_ALIGN==2 checking. Therefore use an
5482 * unconditional IP align value of '2'.
5486 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5487 if (!tnum_is_aligned(reg_off, size)) {
5490 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5492 "misaligned packet access off %d+%s+%d+%d size %d\n",
5493 ip_align, tn_buf, reg->off, off, size);
5500 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5501 const struct bpf_reg_state *reg,
5502 const char *pointer_desc,
5503 int off, int size, bool strict)
5505 struct tnum reg_off;
5507 /* Byte size accesses are always allowed. */
5508 if (!strict || size == 1)
5511 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5512 if (!tnum_is_aligned(reg_off, size)) {
5515 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5516 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5517 pointer_desc, tn_buf, reg->off, off, size);
5524 static int check_ptr_alignment(struct bpf_verifier_env *env,
5525 const struct bpf_reg_state *reg, int off,
5526 int size, bool strict_alignment_once)
5528 bool strict = env->strict_alignment || strict_alignment_once;
5529 const char *pointer_desc = "";
5531 switch (reg->type) {
5533 case PTR_TO_PACKET_META:
5534 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5535 * right in front, treat it the very same way.
5537 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5538 case PTR_TO_FLOW_KEYS:
5539 pointer_desc = "flow keys ";
5541 case PTR_TO_MAP_KEY:
5542 pointer_desc = "key ";
5544 case PTR_TO_MAP_VALUE:
5545 pointer_desc = "value ";
5548 pointer_desc = "context ";
5551 pointer_desc = "stack ";
5552 /* The stack spill tracking logic in check_stack_write_fixed_off()
5553 * and check_stack_read_fixed_off() relies on stack accesses being
5559 pointer_desc = "sock ";
5561 case PTR_TO_SOCK_COMMON:
5562 pointer_desc = "sock_common ";
5564 case PTR_TO_TCP_SOCK:
5565 pointer_desc = "tcp_sock ";
5567 case PTR_TO_XDP_SOCK:
5568 pointer_desc = "xdp_sock ";
5573 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5577 static int update_stack_depth(struct bpf_verifier_env *env,
5578 const struct bpf_func_state *func,
5581 u16 stack = env->subprog_info[func->subprogno].stack_depth;
5586 /* update known max for given subprogram */
5587 env->subprog_info[func->subprogno].stack_depth = -off;
5591 /* starting from main bpf function walk all instructions of the function
5592 * and recursively walk all callees that given function can call.
5593 * Ignore jump and exit insns.
5594 * Since recursion is prevented by check_cfg() this algorithm
5595 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5597 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5599 struct bpf_subprog_info *subprog = env->subprog_info;
5600 struct bpf_insn *insn = env->prog->insnsi;
5601 int depth = 0, frame = 0, i, subprog_end;
5602 bool tail_call_reachable = false;
5603 int ret_insn[MAX_CALL_FRAMES];
5604 int ret_prog[MAX_CALL_FRAMES];
5607 i = subprog[idx].start;
5609 /* protect against potential stack overflow that might happen when
5610 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5611 * depth for such case down to 256 so that the worst case scenario
5612 * would result in 8k stack size (32 which is tailcall limit * 256 =
5615 * To get the idea what might happen, see an example:
5616 * func1 -> sub rsp, 128
5617 * subfunc1 -> sub rsp, 256
5618 * tailcall1 -> add rsp, 256
5619 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5620 * subfunc2 -> sub rsp, 64
5621 * subfunc22 -> sub rsp, 128
5622 * tailcall2 -> add rsp, 128
5623 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5625 * tailcall will unwind the current stack frame but it will not get rid
5626 * of caller's stack as shown on the example above.
5628 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5630 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5634 /* round up to 32-bytes, since this is granularity
5635 * of interpreter stack size
5637 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5638 if (depth > MAX_BPF_STACK) {
5639 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5644 subprog_end = subprog[idx + 1].start;
5645 for (; i < subprog_end; i++) {
5646 int next_insn, sidx;
5648 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5650 /* remember insn and function to return to */
5651 ret_insn[frame] = i + 1;
5652 ret_prog[frame] = idx;
5654 /* find the callee */
5655 next_insn = i + insn[i].imm + 1;
5656 sidx = find_subprog(env, next_insn);
5658 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5662 if (subprog[sidx].is_async_cb) {
5663 if (subprog[sidx].has_tail_call) {
5664 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5667 /* async callbacks don't increase bpf prog stack size unless called directly */
5668 if (!bpf_pseudo_call(insn + i))
5674 if (subprog[idx].has_tail_call)
5675 tail_call_reachable = true;
5678 if (frame >= MAX_CALL_FRAMES) {
5679 verbose(env, "the call stack of %d frames is too deep !\n",
5685 /* if tail call got detected across bpf2bpf calls then mark each of the
5686 * currently present subprog frames as tail call reachable subprogs;
5687 * this info will be utilized by JIT so that we will be preserving the
5688 * tail call counter throughout bpf2bpf calls combined with tailcalls
5690 if (tail_call_reachable)
5691 for (j = 0; j < frame; j++)
5692 subprog[ret_prog[j]].tail_call_reachable = true;
5693 if (subprog[0].tail_call_reachable)
5694 env->prog->aux->tail_call_reachable = true;
5696 /* end of for() loop means the last insn of the 'subprog'
5697 * was reached. Doesn't matter whether it was JA or EXIT
5701 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5703 i = ret_insn[frame];
5704 idx = ret_prog[frame];
5708 static int check_max_stack_depth(struct bpf_verifier_env *env)
5710 struct bpf_subprog_info *si = env->subprog_info;
5713 for (int i = 0; i < env->subprog_cnt; i++) {
5714 if (!i || si[i].is_async_cb) {
5715 ret = check_max_stack_depth_subprog(env, i);
5724 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5725 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5726 const struct bpf_insn *insn, int idx)
5728 int start = idx + insn->imm + 1, subprog;
5730 subprog = find_subprog(env, start);
5732 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5736 return env->subprog_info[subprog].stack_depth;
5740 static int __check_buffer_access(struct bpf_verifier_env *env,
5741 const char *buf_info,
5742 const struct bpf_reg_state *reg,
5743 int regno, int off, int size)
5747 "R%d invalid %s buffer access: off=%d, size=%d\n",
5748 regno, buf_info, off, size);
5751 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5754 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5756 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5757 regno, off, tn_buf);
5764 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5765 const struct bpf_reg_state *reg,
5766 int regno, int off, int size)
5770 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5774 if (off + size > env->prog->aux->max_tp_access)
5775 env->prog->aux->max_tp_access = off + size;
5780 static int check_buffer_access(struct bpf_verifier_env *env,
5781 const struct bpf_reg_state *reg,
5782 int regno, int off, int size,
5783 bool zero_size_allowed,
5786 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5789 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5793 if (off + size > *max_access)
5794 *max_access = off + size;
5799 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5800 static void zext_32_to_64(struct bpf_reg_state *reg)
5802 reg->var_off = tnum_subreg(reg->var_off);
5803 __reg_assign_32_into_64(reg);
5806 /* truncate register to smaller size (in bytes)
5807 * must be called with size < BPF_REG_SIZE
5809 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5813 /* clear high bits in bit representation */
5814 reg->var_off = tnum_cast(reg->var_off, size);
5816 /* fix arithmetic bounds */
5817 mask = ((u64)1 << (size * 8)) - 1;
5818 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5819 reg->umin_value &= mask;
5820 reg->umax_value &= mask;
5822 reg->umin_value = 0;
5823 reg->umax_value = mask;
5825 reg->smin_value = reg->umin_value;
5826 reg->smax_value = reg->umax_value;
5828 /* If size is smaller than 32bit register the 32bit register
5829 * values are also truncated so we push 64-bit bounds into
5830 * 32-bit bounds. Above were truncated < 32-bits already.
5834 __reg_combine_64_into_32(reg);
5837 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5840 reg->smin_value = reg->s32_min_value = S8_MIN;
5841 reg->smax_value = reg->s32_max_value = S8_MAX;
5842 } else if (size == 2) {
5843 reg->smin_value = reg->s32_min_value = S16_MIN;
5844 reg->smax_value = reg->s32_max_value = S16_MAX;
5847 reg->smin_value = reg->s32_min_value = S32_MIN;
5848 reg->smax_value = reg->s32_max_value = S32_MAX;
5850 reg->umin_value = reg->u32_min_value = 0;
5851 reg->umax_value = U64_MAX;
5852 reg->u32_max_value = U32_MAX;
5853 reg->var_off = tnum_unknown;
5856 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5858 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5859 u64 top_smax_value, top_smin_value;
5860 u64 num_bits = size * 8;
5862 if (tnum_is_const(reg->var_off)) {
5863 u64_cval = reg->var_off.value;
5865 reg->var_off = tnum_const((s8)u64_cval);
5867 reg->var_off = tnum_const((s16)u64_cval);
5870 reg->var_off = tnum_const((s32)u64_cval);
5872 u64_cval = reg->var_off.value;
5873 reg->smax_value = reg->smin_value = u64_cval;
5874 reg->umax_value = reg->umin_value = u64_cval;
5875 reg->s32_max_value = reg->s32_min_value = u64_cval;
5876 reg->u32_max_value = reg->u32_min_value = u64_cval;
5880 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
5881 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
5883 if (top_smax_value != top_smin_value)
5886 /* find the s64_min and s64_min after sign extension */
5888 init_s64_max = (s8)reg->smax_value;
5889 init_s64_min = (s8)reg->smin_value;
5890 } else if (size == 2) {
5891 init_s64_max = (s16)reg->smax_value;
5892 init_s64_min = (s16)reg->smin_value;
5894 init_s64_max = (s32)reg->smax_value;
5895 init_s64_min = (s32)reg->smin_value;
5898 s64_max = max(init_s64_max, init_s64_min);
5899 s64_min = min(init_s64_max, init_s64_min);
5901 /* both of s64_max/s64_min positive or negative */
5902 if ((s64_max >= 0) == (s64_min >= 0)) {
5903 reg->smin_value = reg->s32_min_value = s64_min;
5904 reg->smax_value = reg->s32_max_value = s64_max;
5905 reg->umin_value = reg->u32_min_value = s64_min;
5906 reg->umax_value = reg->u32_max_value = s64_max;
5907 reg->var_off = tnum_range(s64_min, s64_max);
5912 set_sext64_default_val(reg, size);
5915 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
5918 reg->s32_min_value = S8_MIN;
5919 reg->s32_max_value = S8_MAX;
5922 reg->s32_min_value = S16_MIN;
5923 reg->s32_max_value = S16_MAX;
5925 reg->u32_min_value = 0;
5926 reg->u32_max_value = U32_MAX;
5929 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
5931 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
5932 u32 top_smax_value, top_smin_value;
5933 u32 num_bits = size * 8;
5935 if (tnum_is_const(reg->var_off)) {
5936 u32_val = reg->var_off.value;
5938 reg->var_off = tnum_const((s8)u32_val);
5940 reg->var_off = tnum_const((s16)u32_val);
5942 u32_val = reg->var_off.value;
5943 reg->s32_min_value = reg->s32_max_value = u32_val;
5944 reg->u32_min_value = reg->u32_max_value = u32_val;
5948 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
5949 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
5951 if (top_smax_value != top_smin_value)
5954 /* find the s32_min and s32_min after sign extension */
5956 init_s32_max = (s8)reg->s32_max_value;
5957 init_s32_min = (s8)reg->s32_min_value;
5960 init_s32_max = (s16)reg->s32_max_value;
5961 init_s32_min = (s16)reg->s32_min_value;
5963 s32_max = max(init_s32_max, init_s32_min);
5964 s32_min = min(init_s32_max, init_s32_min);
5966 if ((s32_min >= 0) == (s32_max >= 0)) {
5967 reg->s32_min_value = s32_min;
5968 reg->s32_max_value = s32_max;
5969 reg->u32_min_value = (u32)s32_min;
5970 reg->u32_max_value = (u32)s32_max;
5975 set_sext32_default_val(reg, size);
5978 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5980 /* A map is considered read-only if the following condition are true:
5982 * 1) BPF program side cannot change any of the map content. The
5983 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5984 * and was set at map creation time.
5985 * 2) The map value(s) have been initialized from user space by a
5986 * loader and then "frozen", such that no new map update/delete
5987 * operations from syscall side are possible for the rest of
5988 * the map's lifetime from that point onwards.
5989 * 3) Any parallel/pending map update/delete operations from syscall
5990 * side have been completed. Only after that point, it's safe to
5991 * assume that map value(s) are immutable.
5993 return (map->map_flags & BPF_F_RDONLY_PROG) &&
5994 READ_ONCE(map->frozen) &&
5995 !bpf_map_write_active(map);
5998 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6005 err = map->ops->map_direct_value_addr(map, &addr, off);
6008 ptr = (void *)(long)addr + off;
6012 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6015 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6018 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6029 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
6030 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6031 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
6034 * Allow list few fields as RCU trusted or full trusted.
6035 * This logic doesn't allow mix tagging and will be removed once GCC supports
6039 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6040 BTF_TYPE_SAFE_RCU(struct task_struct) {
6041 const cpumask_t *cpus_ptr;
6042 struct css_set __rcu *cgroups;
6043 struct task_struct __rcu *real_parent;
6044 struct task_struct *group_leader;
6047 BTF_TYPE_SAFE_RCU(struct cgroup) {
6048 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6049 struct kernfs_node *kn;
6052 BTF_TYPE_SAFE_RCU(struct css_set) {
6053 struct cgroup *dfl_cgrp;
6056 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6057 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6058 struct file __rcu *exe_file;
6061 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6062 * because bpf prog accessible sockets are SOCK_RCU_FREE.
6064 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6068 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6072 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6073 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6074 struct seq_file *seq;
6077 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6078 struct bpf_iter_meta *meta;
6079 struct task_struct *task;
6082 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6086 BTF_TYPE_SAFE_TRUSTED(struct file) {
6087 struct inode *f_inode;
6090 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6091 /* no negative dentry-s in places where bpf can see it */
6092 struct inode *d_inode;
6095 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6099 static bool type_is_rcu(struct bpf_verifier_env *env,
6100 struct bpf_reg_state *reg,
6101 const char *field_name, u32 btf_id)
6103 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6104 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6105 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6107 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6110 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6111 struct bpf_reg_state *reg,
6112 const char *field_name, u32 btf_id)
6114 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6115 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6116 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6118 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6121 static bool type_is_trusted(struct bpf_verifier_env *env,
6122 struct bpf_reg_state *reg,
6123 const char *field_name, u32 btf_id)
6125 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6126 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6127 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6128 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6129 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6130 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6132 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6135 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6136 struct bpf_reg_state *regs,
6137 int regno, int off, int size,
6138 enum bpf_access_type atype,
6141 struct bpf_reg_state *reg = regs + regno;
6142 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6143 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6144 const char *field_name = NULL;
6145 enum bpf_type_flag flag = 0;
6149 if (!env->allow_ptr_leaks) {
6151 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6155 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6157 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6163 "R%d is ptr_%s invalid negative access: off=%d\n",
6167 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6170 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6172 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6173 regno, tname, off, tn_buf);
6177 if (reg->type & MEM_USER) {
6179 "R%d is ptr_%s access user memory: off=%d\n",
6184 if (reg->type & MEM_PERCPU) {
6186 "R%d is ptr_%s access percpu memory: off=%d\n",
6191 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6192 if (!btf_is_kernel(reg->btf)) {
6193 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6196 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6198 /* Writes are permitted with default btf_struct_access for
6199 * program allocated objects (which always have ref_obj_id > 0),
6200 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6202 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6203 verbose(env, "only read is supported\n");
6207 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6209 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6213 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6219 if (ret != PTR_TO_BTF_ID) {
6222 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6223 /* If this is an untrusted pointer, all pointers formed by walking it
6224 * also inherit the untrusted flag.
6226 flag = PTR_UNTRUSTED;
6228 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6229 /* By default any pointer obtained from walking a trusted pointer is no
6230 * longer trusted, unless the field being accessed has explicitly been
6231 * marked as inheriting its parent's state of trust (either full or RCU).
6233 * 'cgroups' pointer is untrusted if task->cgroups dereference
6234 * happened in a sleepable program outside of bpf_rcu_read_lock()
6235 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6236 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6238 * A regular RCU-protected pointer with __rcu tag can also be deemed
6239 * trusted if we are in an RCU CS. Such pointer can be NULL.
6241 if (type_is_trusted(env, reg, field_name, btf_id)) {
6242 flag |= PTR_TRUSTED;
6243 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6244 if (type_is_rcu(env, reg, field_name, btf_id)) {
6245 /* ignore __rcu tag and mark it MEM_RCU */
6247 } else if (flag & MEM_RCU ||
6248 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6249 /* __rcu tagged pointers can be NULL */
6250 flag |= MEM_RCU | PTR_MAYBE_NULL;
6252 /* We always trust them */
6253 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6254 flag & PTR_UNTRUSTED)
6255 flag &= ~PTR_UNTRUSTED;
6256 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6259 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6260 clear_trusted_flags(&flag);
6264 * If not in RCU CS or MEM_RCU pointer can be NULL then
6265 * aggressively mark as untrusted otherwise such
6266 * pointers will be plain PTR_TO_BTF_ID without flags
6267 * and will be allowed to be passed into helpers for
6270 flag = PTR_UNTRUSTED;
6273 /* Old compat. Deprecated */
6274 clear_trusted_flags(&flag);
6277 if (atype == BPF_READ && value_regno >= 0)
6278 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6283 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6284 struct bpf_reg_state *regs,
6285 int regno, int off, int size,
6286 enum bpf_access_type atype,
6289 struct bpf_reg_state *reg = regs + regno;
6290 struct bpf_map *map = reg->map_ptr;
6291 struct bpf_reg_state map_reg;
6292 enum bpf_type_flag flag = 0;
6293 const struct btf_type *t;
6299 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6303 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6304 verbose(env, "map_ptr access not supported for map type %d\n",
6309 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6310 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6312 if (!env->allow_ptr_leaks) {
6314 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6320 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6325 if (atype != BPF_READ) {
6326 verbose(env, "only read from %s is supported\n", tname);
6330 /* Simulate access to a PTR_TO_BTF_ID */
6331 memset(&map_reg, 0, sizeof(map_reg));
6332 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6333 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6337 if (value_regno >= 0)
6338 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6343 /* Check that the stack access at the given offset is within bounds. The
6344 * maximum valid offset is -1.
6346 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6347 * -state->allocated_stack for reads.
6349 static int check_stack_slot_within_bounds(int off,
6350 struct bpf_func_state *state,
6351 enum bpf_access_type t)
6356 min_valid_off = -MAX_BPF_STACK;
6358 min_valid_off = -state->allocated_stack;
6360 if (off < min_valid_off || off > -1)
6365 /* Check that the stack access at 'regno + off' falls within the maximum stack
6368 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6370 static int check_stack_access_within_bounds(
6371 struct bpf_verifier_env *env,
6372 int regno, int off, int access_size,
6373 enum bpf_access_src src, enum bpf_access_type type)
6375 struct bpf_reg_state *regs = cur_regs(env);
6376 struct bpf_reg_state *reg = regs + regno;
6377 struct bpf_func_state *state = func(env, reg);
6378 int min_off, max_off;
6382 if (src == ACCESS_HELPER)
6383 /* We don't know if helpers are reading or writing (or both). */
6384 err_extra = " indirect access to";
6385 else if (type == BPF_READ)
6386 err_extra = " read from";
6388 err_extra = " write to";
6390 if (tnum_is_const(reg->var_off)) {
6391 min_off = reg->var_off.value + off;
6392 if (access_size > 0)
6393 max_off = min_off + access_size - 1;
6397 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6398 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6399 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6403 min_off = reg->smin_value + off;
6404 if (access_size > 0)
6405 max_off = reg->smax_value + off + access_size - 1;
6410 err = check_stack_slot_within_bounds(min_off, state, type);
6412 err = check_stack_slot_within_bounds(max_off, state, type);
6415 if (tnum_is_const(reg->var_off)) {
6416 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6417 err_extra, regno, off, access_size);
6421 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6422 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6423 err_extra, regno, tn_buf, access_size);
6429 /* check whether memory at (regno + off) is accessible for t = (read | write)
6430 * if t==write, value_regno is a register which value is stored into memory
6431 * if t==read, value_regno is a register which will receive the value from memory
6432 * if t==write && value_regno==-1, some unknown value is stored into memory
6433 * if t==read && value_regno==-1, don't care what we read from memory
6435 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6436 int off, int bpf_size, enum bpf_access_type t,
6437 int value_regno, bool strict_alignment_once, bool is_ldsx)
6439 struct bpf_reg_state *regs = cur_regs(env);
6440 struct bpf_reg_state *reg = regs + regno;
6441 struct bpf_func_state *state;
6444 size = bpf_size_to_bytes(bpf_size);
6448 /* alignment checks will add in reg->off themselves */
6449 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6453 /* for access checks, reg->off is just part of off */
6456 if (reg->type == PTR_TO_MAP_KEY) {
6457 if (t == BPF_WRITE) {
6458 verbose(env, "write to change key R%d not allowed\n", regno);
6462 err = check_mem_region_access(env, regno, off, size,
6463 reg->map_ptr->key_size, false);
6466 if (value_regno >= 0)
6467 mark_reg_unknown(env, regs, value_regno);
6468 } else if (reg->type == PTR_TO_MAP_VALUE) {
6469 struct btf_field *kptr_field = NULL;
6471 if (t == BPF_WRITE && value_regno >= 0 &&
6472 is_pointer_value(env, value_regno)) {
6473 verbose(env, "R%d leaks addr into map\n", value_regno);
6476 err = check_map_access_type(env, regno, off, size, t);
6479 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6482 if (tnum_is_const(reg->var_off))
6483 kptr_field = btf_record_find(reg->map_ptr->record,
6484 off + reg->var_off.value, BPF_KPTR);
6486 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6487 } else if (t == BPF_READ && value_regno >= 0) {
6488 struct bpf_map *map = reg->map_ptr;
6490 /* if map is read-only, track its contents as scalars */
6491 if (tnum_is_const(reg->var_off) &&
6492 bpf_map_is_rdonly(map) &&
6493 map->ops->map_direct_value_addr) {
6494 int map_off = off + reg->var_off.value;
6497 err = bpf_map_direct_read(map, map_off, size,
6502 regs[value_regno].type = SCALAR_VALUE;
6503 __mark_reg_known(®s[value_regno], val);
6505 mark_reg_unknown(env, regs, value_regno);
6508 } else if (base_type(reg->type) == PTR_TO_MEM) {
6509 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6511 if (type_may_be_null(reg->type)) {
6512 verbose(env, "R%d invalid mem access '%s'\n", regno,
6513 reg_type_str(env, reg->type));
6517 if (t == BPF_WRITE && rdonly_mem) {
6518 verbose(env, "R%d cannot write into %s\n",
6519 regno, reg_type_str(env, reg->type));
6523 if (t == BPF_WRITE && value_regno >= 0 &&
6524 is_pointer_value(env, value_regno)) {
6525 verbose(env, "R%d leaks addr into mem\n", value_regno);
6529 err = check_mem_region_access(env, regno, off, size,
6530 reg->mem_size, false);
6531 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6532 mark_reg_unknown(env, regs, value_regno);
6533 } else if (reg->type == PTR_TO_CTX) {
6534 enum bpf_reg_type reg_type = SCALAR_VALUE;
6535 struct btf *btf = NULL;
6538 if (t == BPF_WRITE && value_regno >= 0 &&
6539 is_pointer_value(env, value_regno)) {
6540 verbose(env, "R%d leaks addr into ctx\n", value_regno);
6544 err = check_ptr_off_reg(env, reg, regno);
6548 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
6551 verbose_linfo(env, insn_idx, "; ");
6552 if (!err && t == BPF_READ && value_regno >= 0) {
6553 /* ctx access returns either a scalar, or a
6554 * PTR_TO_PACKET[_META,_END]. In the latter
6555 * case, we know the offset is zero.
6557 if (reg_type == SCALAR_VALUE) {
6558 mark_reg_unknown(env, regs, value_regno);
6560 mark_reg_known_zero(env, regs,
6562 if (type_may_be_null(reg_type))
6563 regs[value_regno].id = ++env->id_gen;
6564 /* A load of ctx field could have different
6565 * actual load size with the one encoded in the
6566 * insn. When the dst is PTR, it is for sure not
6569 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6570 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6571 regs[value_regno].btf = btf;
6572 regs[value_regno].btf_id = btf_id;
6575 regs[value_regno].type = reg_type;
6578 } else if (reg->type == PTR_TO_STACK) {
6579 /* Basic bounds checks. */
6580 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6584 state = func(env, reg);
6585 err = update_stack_depth(env, state, off);
6590 err = check_stack_read(env, regno, off, size,
6593 err = check_stack_write(env, regno, off, size,
6594 value_regno, insn_idx);
6595 } else if (reg_is_pkt_pointer(reg)) {
6596 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6597 verbose(env, "cannot write into packet\n");
6600 if (t == BPF_WRITE && value_regno >= 0 &&
6601 is_pointer_value(env, value_regno)) {
6602 verbose(env, "R%d leaks addr into packet\n",
6606 err = check_packet_access(env, regno, off, size, false);
6607 if (!err && t == BPF_READ && value_regno >= 0)
6608 mark_reg_unknown(env, regs, value_regno);
6609 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6610 if (t == BPF_WRITE && value_regno >= 0 &&
6611 is_pointer_value(env, value_regno)) {
6612 verbose(env, "R%d leaks addr into flow keys\n",
6617 err = check_flow_keys_access(env, off, size);
6618 if (!err && t == BPF_READ && value_regno >= 0)
6619 mark_reg_unknown(env, regs, value_regno);
6620 } else if (type_is_sk_pointer(reg->type)) {
6621 if (t == BPF_WRITE) {
6622 verbose(env, "R%d cannot write into %s\n",
6623 regno, reg_type_str(env, reg->type));
6626 err = check_sock_access(env, insn_idx, regno, off, size, t);
6627 if (!err && value_regno >= 0)
6628 mark_reg_unknown(env, regs, value_regno);
6629 } else if (reg->type == PTR_TO_TP_BUFFER) {
6630 err = check_tp_buffer_access(env, reg, regno, off, size);
6631 if (!err && t == BPF_READ && value_regno >= 0)
6632 mark_reg_unknown(env, regs, value_regno);
6633 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6634 !type_may_be_null(reg->type)) {
6635 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6637 } else if (reg->type == CONST_PTR_TO_MAP) {
6638 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6640 } else if (base_type(reg->type) == PTR_TO_BUF) {
6641 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6645 if (t == BPF_WRITE) {
6646 verbose(env, "R%d cannot write into %s\n",
6647 regno, reg_type_str(env, reg->type));
6650 max_access = &env->prog->aux->max_rdonly_access;
6652 max_access = &env->prog->aux->max_rdwr_access;
6655 err = check_buffer_access(env, reg, regno, off, size, false,
6658 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6659 mark_reg_unknown(env, regs, value_regno);
6661 verbose(env, "R%d invalid mem access '%s'\n", regno,
6662 reg_type_str(env, reg->type));
6666 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6667 regs[value_regno].type == SCALAR_VALUE) {
6669 /* b/h/w load zero-extends, mark upper bits as known 0 */
6670 coerce_reg_to_size(®s[value_regno], size);
6672 coerce_reg_to_size_sx(®s[value_regno], size);
6677 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6682 switch (insn->imm) {
6684 case BPF_ADD | BPF_FETCH:
6686 case BPF_AND | BPF_FETCH:
6688 case BPF_OR | BPF_FETCH:
6690 case BPF_XOR | BPF_FETCH:
6695 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6699 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6700 verbose(env, "invalid atomic operand size\n");
6704 /* check src1 operand */
6705 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6709 /* check src2 operand */
6710 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6714 if (insn->imm == BPF_CMPXCHG) {
6715 /* Check comparison of R0 with memory location */
6716 const u32 aux_reg = BPF_REG_0;
6718 err = check_reg_arg(env, aux_reg, SRC_OP);
6722 if (is_pointer_value(env, aux_reg)) {
6723 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6728 if (is_pointer_value(env, insn->src_reg)) {
6729 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6733 if (is_ctx_reg(env, insn->dst_reg) ||
6734 is_pkt_reg(env, insn->dst_reg) ||
6735 is_flow_key_reg(env, insn->dst_reg) ||
6736 is_sk_reg(env, insn->dst_reg)) {
6737 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6739 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6743 if (insn->imm & BPF_FETCH) {
6744 if (insn->imm == BPF_CMPXCHG)
6745 load_reg = BPF_REG_0;
6747 load_reg = insn->src_reg;
6749 /* check and record load of old value */
6750 err = check_reg_arg(env, load_reg, DST_OP);
6754 /* This instruction accesses a memory location but doesn't
6755 * actually load it into a register.
6760 /* Check whether we can read the memory, with second call for fetch
6761 * case to simulate the register fill.
6763 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6764 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6765 if (!err && load_reg >= 0)
6766 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6767 BPF_SIZE(insn->code), BPF_READ, load_reg,
6772 /* Check whether we can write into the same memory. */
6773 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6774 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6781 /* When register 'regno' is used to read the stack (either directly or through
6782 * a helper function) make sure that it's within stack boundary and, depending
6783 * on the access type, that all elements of the stack are initialized.
6785 * 'off' includes 'regno->off', but not its dynamic part (if any).
6787 * All registers that have been spilled on the stack in the slots within the
6788 * read offsets are marked as read.
6790 static int check_stack_range_initialized(
6791 struct bpf_verifier_env *env, int regno, int off,
6792 int access_size, bool zero_size_allowed,
6793 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6795 struct bpf_reg_state *reg = reg_state(env, regno);
6796 struct bpf_func_state *state = func(env, reg);
6797 int err, min_off, max_off, i, j, slot, spi;
6798 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6799 enum bpf_access_type bounds_check_type;
6800 /* Some accesses can write anything into the stack, others are
6803 bool clobber = false;
6805 if (access_size == 0 && !zero_size_allowed) {
6806 verbose(env, "invalid zero-sized read\n");
6810 if (type == ACCESS_HELPER) {
6811 /* The bounds checks for writes are more permissive than for
6812 * reads. However, if raw_mode is not set, we'll do extra
6815 bounds_check_type = BPF_WRITE;
6818 bounds_check_type = BPF_READ;
6820 err = check_stack_access_within_bounds(env, regno, off, access_size,
6821 type, bounds_check_type);
6826 if (tnum_is_const(reg->var_off)) {
6827 min_off = max_off = reg->var_off.value + off;
6829 /* Variable offset is prohibited for unprivileged mode for
6830 * simplicity since it requires corresponding support in
6831 * Spectre masking for stack ALU.
6832 * See also retrieve_ptr_limit().
6834 if (!env->bypass_spec_v1) {
6837 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6838 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6839 regno, err_extra, tn_buf);
6842 /* Only initialized buffer on stack is allowed to be accessed
6843 * with variable offset. With uninitialized buffer it's hard to
6844 * guarantee that whole memory is marked as initialized on
6845 * helper return since specific bounds are unknown what may
6846 * cause uninitialized stack leaking.
6848 if (meta && meta->raw_mode)
6851 min_off = reg->smin_value + off;
6852 max_off = reg->smax_value + off;
6855 if (meta && meta->raw_mode) {
6856 /* Ensure we won't be overwriting dynptrs when simulating byte
6857 * by byte access in check_helper_call using meta.access_size.
6858 * This would be a problem if we have a helper in the future
6861 * helper(uninit_mem, len, dynptr)
6863 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6864 * may end up writing to dynptr itself when touching memory from
6865 * arg 1. This can be relaxed on a case by case basis for known
6866 * safe cases, but reject due to the possibilitiy of aliasing by
6869 for (i = min_off; i < max_off + access_size; i++) {
6870 int stack_off = -i - 1;
6873 /* raw_mode may write past allocated_stack */
6874 if (state->allocated_stack <= stack_off)
6876 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6877 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6881 meta->access_size = access_size;
6882 meta->regno = regno;
6886 for (i = min_off; i < max_off + access_size; i++) {
6890 spi = slot / BPF_REG_SIZE;
6891 if (state->allocated_stack <= slot)
6893 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6894 if (*stype == STACK_MISC)
6896 if ((*stype == STACK_ZERO) ||
6897 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6899 /* helper can write anything into the stack */
6900 *stype = STACK_MISC;
6905 if (is_spilled_reg(&state->stack[spi]) &&
6906 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6907 env->allow_ptr_leaks)) {
6909 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6910 for (j = 0; j < BPF_REG_SIZE; j++)
6911 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6917 if (tnum_is_const(reg->var_off)) {
6918 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6919 err_extra, regno, min_off, i - min_off, access_size);
6923 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6924 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6925 err_extra, regno, tn_buf, i - min_off, access_size);
6929 /* reading any byte out of 8-byte 'spill_slot' will cause
6930 * the whole slot to be marked as 'read'
6932 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6933 state->stack[spi].spilled_ptr.parent,
6935 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6936 * be sure that whether stack slot is written to or not. Hence,
6937 * we must still conservatively propagate reads upwards even if
6938 * helper may write to the entire memory range.
6941 return update_stack_depth(env, state, min_off);
6944 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6945 int access_size, bool zero_size_allowed,
6946 struct bpf_call_arg_meta *meta)
6948 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6951 switch (base_type(reg->type)) {
6953 case PTR_TO_PACKET_META:
6954 return check_packet_access(env, regno, reg->off, access_size,
6956 case PTR_TO_MAP_KEY:
6957 if (meta && meta->raw_mode) {
6958 verbose(env, "R%d cannot write into %s\n", regno,
6959 reg_type_str(env, reg->type));
6962 return check_mem_region_access(env, regno, reg->off, access_size,
6963 reg->map_ptr->key_size, false);
6964 case PTR_TO_MAP_VALUE:
6965 if (check_map_access_type(env, regno, reg->off, access_size,
6966 meta && meta->raw_mode ? BPF_WRITE :
6969 return check_map_access(env, regno, reg->off, access_size,
6970 zero_size_allowed, ACCESS_HELPER);
6972 if (type_is_rdonly_mem(reg->type)) {
6973 if (meta && meta->raw_mode) {
6974 verbose(env, "R%d cannot write into %s\n", regno,
6975 reg_type_str(env, reg->type));
6979 return check_mem_region_access(env, regno, reg->off,
6980 access_size, reg->mem_size,
6983 if (type_is_rdonly_mem(reg->type)) {
6984 if (meta && meta->raw_mode) {
6985 verbose(env, "R%d cannot write into %s\n", regno,
6986 reg_type_str(env, reg->type));
6990 max_access = &env->prog->aux->max_rdonly_access;
6992 max_access = &env->prog->aux->max_rdwr_access;
6994 return check_buffer_access(env, reg, regno, reg->off,
6995 access_size, zero_size_allowed,
6998 return check_stack_range_initialized(
7000 regno, reg->off, access_size,
7001 zero_size_allowed, ACCESS_HELPER, meta);
7003 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7004 access_size, BPF_READ, -1);
7006 /* in case the function doesn't know how to access the context,
7007 * (because we are in a program of type SYSCALL for example), we
7008 * can not statically check its size.
7009 * Dynamically check it now.
7011 if (!env->ops->convert_ctx_access) {
7012 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7013 int offset = access_size - 1;
7015 /* Allow zero-byte read from PTR_TO_CTX */
7016 if (access_size == 0)
7017 return zero_size_allowed ? 0 : -EACCES;
7019 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7020 atype, -1, false, false);
7024 default: /* scalar_value or invalid ptr */
7025 /* Allow zero-byte read from NULL, regardless of pointer type */
7026 if (zero_size_allowed && access_size == 0 &&
7027 register_is_null(reg))
7030 verbose(env, "R%d type=%s ", regno,
7031 reg_type_str(env, reg->type));
7032 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7037 static int check_mem_size_reg(struct bpf_verifier_env *env,
7038 struct bpf_reg_state *reg, u32 regno,
7039 bool zero_size_allowed,
7040 struct bpf_call_arg_meta *meta)
7044 /* This is used to refine r0 return value bounds for helpers
7045 * that enforce this value as an upper bound on return values.
7046 * See do_refine_retval_range() for helpers that can refine
7047 * the return value. C type of helper is u32 so we pull register
7048 * bound from umax_value however, if negative verifier errors
7049 * out. Only upper bounds can be learned because retval is an
7050 * int type and negative retvals are allowed.
7052 meta->msize_max_value = reg->umax_value;
7054 /* The register is SCALAR_VALUE; the access check
7055 * happens using its boundaries.
7057 if (!tnum_is_const(reg->var_off))
7058 /* For unprivileged variable accesses, disable raw
7059 * mode so that the program is required to
7060 * initialize all the memory that the helper could
7061 * just partially fill up.
7065 if (reg->smin_value < 0) {
7066 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7071 if (reg->umin_value == 0) {
7072 err = check_helper_mem_access(env, regno - 1, 0,
7079 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7080 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7084 err = check_helper_mem_access(env, regno - 1,
7086 zero_size_allowed, meta);
7088 err = mark_chain_precision(env, regno);
7092 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7093 u32 regno, u32 mem_size)
7095 bool may_be_null = type_may_be_null(reg->type);
7096 struct bpf_reg_state saved_reg;
7097 struct bpf_call_arg_meta meta;
7100 if (register_is_null(reg))
7103 memset(&meta, 0, sizeof(meta));
7104 /* Assuming that the register contains a value check if the memory
7105 * access is safe. Temporarily save and restore the register's state as
7106 * the conversion shouldn't be visible to a caller.
7110 mark_ptr_not_null_reg(reg);
7113 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7114 /* Check access for BPF_WRITE */
7115 meta.raw_mode = true;
7116 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7124 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7127 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7128 bool may_be_null = type_may_be_null(mem_reg->type);
7129 struct bpf_reg_state saved_reg;
7130 struct bpf_call_arg_meta meta;
7133 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7135 memset(&meta, 0, sizeof(meta));
7138 saved_reg = *mem_reg;
7139 mark_ptr_not_null_reg(mem_reg);
7142 err = check_mem_size_reg(env, reg, regno, true, &meta);
7143 /* Check access for BPF_WRITE */
7144 meta.raw_mode = true;
7145 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7148 *mem_reg = saved_reg;
7152 /* Implementation details:
7153 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7154 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7155 * Two bpf_map_lookups (even with the same key) will have different reg->id.
7156 * Two separate bpf_obj_new will also have different reg->id.
7157 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7158 * clears reg->id after value_or_null->value transition, since the verifier only
7159 * cares about the range of access to valid map value pointer and doesn't care
7160 * about actual address of the map element.
7161 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7162 * reg->id > 0 after value_or_null->value transition. By doing so
7163 * two bpf_map_lookups will be considered two different pointers that
7164 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7165 * returned from bpf_obj_new.
7166 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7168 * Since only one bpf_spin_lock is allowed the checks are simpler than
7169 * reg_is_refcounted() logic. The verifier needs to remember only
7170 * one spin_lock instead of array of acquired_refs.
7171 * cur_state->active_lock remembers which map value element or allocated
7172 * object got locked and clears it after bpf_spin_unlock.
7174 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7177 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7178 struct bpf_verifier_state *cur = env->cur_state;
7179 bool is_const = tnum_is_const(reg->var_off);
7180 u64 val = reg->var_off.value;
7181 struct bpf_map *map = NULL;
7182 struct btf *btf = NULL;
7183 struct btf_record *rec;
7187 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7191 if (reg->type == PTR_TO_MAP_VALUE) {
7195 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7203 rec = reg_btf_record(reg);
7204 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7205 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7206 map ? map->name : "kptr");
7209 if (rec->spin_lock_off != val + reg->off) {
7210 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7211 val + reg->off, rec->spin_lock_off);
7215 if (cur->active_lock.ptr) {
7217 "Locking two bpf_spin_locks are not allowed\n");
7221 cur->active_lock.ptr = map;
7223 cur->active_lock.ptr = btf;
7224 cur->active_lock.id = reg->id;
7233 if (!cur->active_lock.ptr) {
7234 verbose(env, "bpf_spin_unlock without taking a lock\n");
7237 if (cur->active_lock.ptr != ptr ||
7238 cur->active_lock.id != reg->id) {
7239 verbose(env, "bpf_spin_unlock of different lock\n");
7243 invalidate_non_owning_refs(env);
7245 cur->active_lock.ptr = NULL;
7246 cur->active_lock.id = 0;
7251 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7252 struct bpf_call_arg_meta *meta)
7254 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7255 bool is_const = tnum_is_const(reg->var_off);
7256 struct bpf_map *map = reg->map_ptr;
7257 u64 val = reg->var_off.value;
7261 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7266 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7270 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7271 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7274 if (map->record->timer_off != val + reg->off) {
7275 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7276 val + reg->off, map->record->timer_off);
7279 if (meta->map_ptr) {
7280 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7283 meta->map_uid = reg->map_uid;
7284 meta->map_ptr = map;
7288 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7289 struct bpf_call_arg_meta *meta)
7291 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7292 struct bpf_map *map_ptr = reg->map_ptr;
7293 struct btf_field *kptr_field;
7296 if (!tnum_is_const(reg->var_off)) {
7298 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7302 if (!map_ptr->btf) {
7303 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7307 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7308 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7312 meta->map_ptr = map_ptr;
7313 kptr_off = reg->off + reg->var_off.value;
7314 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7316 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7319 if (kptr_field->type != BPF_KPTR_REF) {
7320 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7323 meta->kptr_field = kptr_field;
7327 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7328 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7330 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7331 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7332 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7334 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7335 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7336 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7337 * mutate the view of the dynptr and also possibly destroy it. In the latter
7338 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7339 * memory that dynptr points to.
7341 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7342 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7343 * readonly dynptr view yet, hence only the first case is tracked and checked.
7345 * This is consistent with how C applies the const modifier to a struct object,
7346 * where the pointer itself inside bpf_dynptr becomes const but not what it
7349 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7350 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7352 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7353 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7355 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7358 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7359 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7361 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7362 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7366 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7367 * constructing a mutable bpf_dynptr object.
7369 * Currently, this is only possible with PTR_TO_STACK
7370 * pointing to a region of at least 16 bytes which doesn't
7371 * contain an existing bpf_dynptr.
7373 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7374 * mutated or destroyed. However, the memory it points to
7377 * None - Points to a initialized dynptr that can be mutated and
7378 * destroyed, including mutation of the memory it points
7381 if (arg_type & MEM_UNINIT) {
7384 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7385 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7389 /* we write BPF_DW bits (8 bytes) at a time */
7390 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7391 err = check_mem_access(env, insn_idx, regno,
7392 i, BPF_DW, BPF_WRITE, -1, false, false);
7397 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7398 } else /* MEM_RDONLY and None case from above */ {
7399 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7400 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7401 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7405 if (!is_dynptr_reg_valid_init(env, reg)) {
7407 "Expected an initialized dynptr as arg #%d\n",
7412 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7413 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7415 "Expected a dynptr of type %s as arg #%d\n",
7416 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7420 err = mark_dynptr_read(env, reg);
7425 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7427 struct bpf_func_state *state = func(env, reg);
7429 return state->stack[spi].spilled_ptr.ref_obj_id;
7432 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7434 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7437 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7439 return meta->kfunc_flags & KF_ITER_NEW;
7442 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7444 return meta->kfunc_flags & KF_ITER_NEXT;
7447 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7449 return meta->kfunc_flags & KF_ITER_DESTROY;
7452 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7454 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7455 * kfunc is iter state pointer
7457 return arg == 0 && is_iter_kfunc(meta);
7460 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7461 struct bpf_kfunc_call_arg_meta *meta)
7463 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7464 const struct btf_type *t;
7465 const struct btf_param *arg;
7466 int spi, err, i, nr_slots;
7469 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7470 arg = &btf_params(meta->func_proto)[0];
7471 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7472 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7473 nr_slots = t->size / BPF_REG_SIZE;
7475 if (is_iter_new_kfunc(meta)) {
7476 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7477 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7478 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7479 iter_type_str(meta->btf, btf_id), regno);
7483 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7484 err = check_mem_access(env, insn_idx, regno,
7485 i, BPF_DW, BPF_WRITE, -1, false, false);
7490 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7494 /* iter_next() or iter_destroy() expect initialized iter state*/
7495 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7496 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7497 iter_type_str(meta->btf, btf_id), regno);
7501 spi = iter_get_spi(env, reg, nr_slots);
7505 err = mark_iter_read(env, reg, spi, nr_slots);
7509 /* remember meta->iter info for process_iter_next_call() */
7510 meta->iter.spi = spi;
7511 meta->iter.frameno = reg->frameno;
7512 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7514 if (is_iter_destroy_kfunc(meta)) {
7515 err = unmark_stack_slots_iter(env, reg, nr_slots);
7524 /* process_iter_next_call() is called when verifier gets to iterator's next
7525 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7526 * to it as just "iter_next()" in comments below.
7528 * BPF verifier relies on a crucial contract for any iter_next()
7529 * implementation: it should *eventually* return NULL, and once that happens
7530 * it should keep returning NULL. That is, once iterator exhausts elements to
7531 * iterate, it should never reset or spuriously return new elements.
7533 * With the assumption of such contract, process_iter_next_call() simulates
7534 * a fork in the verifier state to validate loop logic correctness and safety
7535 * without having to simulate infinite amount of iterations.
7537 * In current state, we first assume that iter_next() returned NULL and
7538 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7539 * conditions we should not form an infinite loop and should eventually reach
7542 * Besides that, we also fork current state and enqueue it for later
7543 * verification. In a forked state we keep iterator state as ACTIVE
7544 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7545 * also bump iteration depth to prevent erroneous infinite loop detection
7546 * later on (see iter_active_depths_differ() comment for details). In this
7547 * state we assume that we'll eventually loop back to another iter_next()
7548 * calls (it could be in exactly same location or in some other instruction,
7549 * it doesn't matter, we don't make any unnecessary assumptions about this,
7550 * everything revolves around iterator state in a stack slot, not which
7551 * instruction is calling iter_next()). When that happens, we either will come
7552 * to iter_next() with equivalent state and can conclude that next iteration
7553 * will proceed in exactly the same way as we just verified, so it's safe to
7554 * assume that loop converges. If not, we'll go on another iteration
7555 * simulation with a different input state, until all possible starting states
7556 * are validated or we reach maximum number of instructions limit.
7558 * This way, we will either exhaustively discover all possible input states
7559 * that iterator loop can start with and eventually will converge, or we'll
7560 * effectively regress into bounded loop simulation logic and either reach
7561 * maximum number of instructions if loop is not provably convergent, or there
7562 * is some statically known limit on number of iterations (e.g., if there is
7563 * an explicit `if n > 100 then break;` statement somewhere in the loop).
7565 * One very subtle but very important aspect is that we *always* simulate NULL
7566 * condition first (as the current state) before we simulate non-NULL case.
7567 * This has to do with intricacies of scalar precision tracking. By simulating
7568 * "exit condition" of iter_next() returning NULL first, we make sure all the
7569 * relevant precision marks *that will be set **after** we exit iterator loop*
7570 * are propagated backwards to common parent state of NULL and non-NULL
7571 * branches. Thanks to that, state equivalence checks done later in forked
7572 * state, when reaching iter_next() for ACTIVE iterator, can assume that
7573 * precision marks are finalized and won't change. Because simulating another
7574 * ACTIVE iterator iteration won't change them (because given same input
7575 * states we'll end up with exactly same output states which we are currently
7576 * comparing; and verification after the loop already propagated back what
7577 * needs to be **additionally** tracked as precise). It's subtle, grok
7578 * precision tracking for more intuitive understanding.
7580 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7581 struct bpf_kfunc_call_arg_meta *meta)
7583 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7584 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7585 struct bpf_reg_state *cur_iter, *queued_iter;
7586 int iter_frameno = meta->iter.frameno;
7587 int iter_spi = meta->iter.spi;
7589 BTF_TYPE_EMIT(struct bpf_iter);
7591 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7593 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7594 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7595 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7596 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7600 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7601 /* branch out active iter state */
7602 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7606 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7607 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7608 queued_iter->iter.depth++;
7610 queued_fr = queued_st->frame[queued_st->curframe];
7611 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7614 /* switch to DRAINED state, but keep the depth unchanged */
7615 /* mark current iter state as drained and assume returned NULL */
7616 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7617 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7622 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7624 return type == ARG_CONST_SIZE ||
7625 type == ARG_CONST_SIZE_OR_ZERO;
7628 static bool arg_type_is_release(enum bpf_arg_type type)
7630 return type & OBJ_RELEASE;
7633 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7635 return base_type(type) == ARG_PTR_TO_DYNPTR;
7638 static int int_ptr_type_to_size(enum bpf_arg_type type)
7640 if (type == ARG_PTR_TO_INT)
7642 else if (type == ARG_PTR_TO_LONG)
7648 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7649 const struct bpf_call_arg_meta *meta,
7650 enum bpf_arg_type *arg_type)
7652 if (!meta->map_ptr) {
7653 /* kernel subsystem misconfigured verifier */
7654 verbose(env, "invalid map_ptr to access map->type\n");
7658 switch (meta->map_ptr->map_type) {
7659 case BPF_MAP_TYPE_SOCKMAP:
7660 case BPF_MAP_TYPE_SOCKHASH:
7661 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7662 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7664 verbose(env, "invalid arg_type for sockmap/sockhash\n");
7668 case BPF_MAP_TYPE_BLOOM_FILTER:
7669 if (meta->func_id == BPF_FUNC_map_peek_elem)
7670 *arg_type = ARG_PTR_TO_MAP_VALUE;
7678 struct bpf_reg_types {
7679 const enum bpf_reg_type types[10];
7683 static const struct bpf_reg_types sock_types = {
7693 static const struct bpf_reg_types btf_id_sock_common_types = {
7700 PTR_TO_BTF_ID | PTR_TRUSTED,
7702 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7706 static const struct bpf_reg_types mem_types = {
7714 PTR_TO_MEM | MEM_RINGBUF,
7716 PTR_TO_BTF_ID | PTR_TRUSTED,
7720 static const struct bpf_reg_types int_ptr_types = {
7730 static const struct bpf_reg_types spin_lock_types = {
7733 PTR_TO_BTF_ID | MEM_ALLOC,
7737 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7738 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7739 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7740 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7741 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7742 static const struct bpf_reg_types btf_ptr_types = {
7745 PTR_TO_BTF_ID | PTR_TRUSTED,
7746 PTR_TO_BTF_ID | MEM_RCU,
7749 static const struct bpf_reg_types percpu_btf_ptr_types = {
7751 PTR_TO_BTF_ID | MEM_PERCPU,
7752 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7755 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7756 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7757 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7758 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7759 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7760 static const struct bpf_reg_types dynptr_types = {
7763 CONST_PTR_TO_DYNPTR,
7767 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7768 [ARG_PTR_TO_MAP_KEY] = &mem_types,
7769 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
7770 [ARG_CONST_SIZE] = &scalar_types,
7771 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
7772 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
7773 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
7774 [ARG_PTR_TO_CTX] = &context_types,
7775 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
7777 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7779 [ARG_PTR_TO_SOCKET] = &fullsock_types,
7780 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
7781 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
7782 [ARG_PTR_TO_MEM] = &mem_types,
7783 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
7784 [ARG_PTR_TO_INT] = &int_ptr_types,
7785 [ARG_PTR_TO_LONG] = &int_ptr_types,
7786 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
7787 [ARG_PTR_TO_FUNC] = &func_ptr_types,
7788 [ARG_PTR_TO_STACK] = &stack_ptr_types,
7789 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
7790 [ARG_PTR_TO_TIMER] = &timer_types,
7791 [ARG_PTR_TO_KPTR] = &kptr_types,
7792 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
7795 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7796 enum bpf_arg_type arg_type,
7797 const u32 *arg_btf_id,
7798 struct bpf_call_arg_meta *meta)
7800 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7801 enum bpf_reg_type expected, type = reg->type;
7802 const struct bpf_reg_types *compatible;
7805 compatible = compatible_reg_types[base_type(arg_type)];
7807 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7811 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7812 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7814 * Same for MAYBE_NULL:
7816 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7817 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7819 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7821 * Therefore we fold these flags depending on the arg_type before comparison.
7823 if (arg_type & MEM_RDONLY)
7824 type &= ~MEM_RDONLY;
7825 if (arg_type & PTR_MAYBE_NULL)
7826 type &= ~PTR_MAYBE_NULL;
7827 if (base_type(arg_type) == ARG_PTR_TO_MEM)
7828 type &= ~DYNPTR_TYPE_FLAG_MASK;
7830 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7833 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7834 expected = compatible->types[i];
7835 if (expected == NOT_INIT)
7838 if (type == expected)
7842 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7843 for (j = 0; j + 1 < i; j++)
7844 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7845 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7849 if (base_type(reg->type) != PTR_TO_BTF_ID)
7852 if (compatible == &mem_types) {
7853 if (!(arg_type & MEM_RDONLY)) {
7855 "%s() may write into memory pointed by R%d type=%s\n",
7856 func_id_name(meta->func_id),
7857 regno, reg_type_str(env, reg->type));
7863 switch ((int)reg->type) {
7865 case PTR_TO_BTF_ID | PTR_TRUSTED:
7866 case PTR_TO_BTF_ID | MEM_RCU:
7867 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7868 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7870 /* For bpf_sk_release, it needs to match against first member
7871 * 'struct sock_common', hence make an exception for it. This
7872 * allows bpf_sk_release to work for multiple socket types.
7874 bool strict_type_match = arg_type_is_release(arg_type) &&
7875 meta->func_id != BPF_FUNC_sk_release;
7877 if (type_may_be_null(reg->type) &&
7878 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7879 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7884 if (!compatible->btf_id) {
7885 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7888 arg_btf_id = compatible->btf_id;
7891 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7892 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7895 if (arg_btf_id == BPF_PTR_POISON) {
7896 verbose(env, "verifier internal error:");
7897 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7902 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7903 btf_vmlinux, *arg_btf_id,
7904 strict_type_match)) {
7905 verbose(env, "R%d is of type %s but %s is expected\n",
7906 regno, btf_type_name(reg->btf, reg->btf_id),
7907 btf_type_name(btf_vmlinux, *arg_btf_id));
7913 case PTR_TO_BTF_ID | MEM_ALLOC:
7914 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7915 meta->func_id != BPF_FUNC_kptr_xchg) {
7916 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7919 /* Handled by helper specific checks */
7921 case PTR_TO_BTF_ID | MEM_PERCPU:
7922 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7923 /* Handled by helper specific checks */
7926 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7932 static struct btf_field *
7933 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7935 struct btf_field *field;
7936 struct btf_record *rec;
7938 rec = reg_btf_record(reg);
7942 field = btf_record_find(rec, off, fields);
7949 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7950 const struct bpf_reg_state *reg, int regno,
7951 enum bpf_arg_type arg_type)
7953 u32 type = reg->type;
7955 /* When referenced register is passed to release function, its fixed
7958 * We will check arg_type_is_release reg has ref_obj_id when storing
7959 * meta->release_regno.
7961 if (arg_type_is_release(arg_type)) {
7962 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7963 * may not directly point to the object being released, but to
7964 * dynptr pointing to such object, which might be at some offset
7965 * on the stack. In that case, we simply to fallback to the
7968 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7971 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7972 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7973 return __check_ptr_off_reg(env, reg, regno, true);
7975 verbose(env, "R%d must have zero offset when passed to release func\n",
7977 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7978 btf_type_name(reg->btf, reg->btf_id), reg->off);
7982 /* Doing check_ptr_off_reg check for the offset will catch this
7983 * because fixed_off_ok is false, but checking here allows us
7984 * to give the user a better error message.
7987 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7991 return __check_ptr_off_reg(env, reg, regno, false);
7995 /* Pointer types where both fixed and variable offset is explicitly allowed: */
7998 case PTR_TO_PACKET_META:
7999 case PTR_TO_MAP_KEY:
8000 case PTR_TO_MAP_VALUE:
8002 case PTR_TO_MEM | MEM_RDONLY:
8003 case PTR_TO_MEM | MEM_RINGBUF:
8005 case PTR_TO_BUF | MEM_RDONLY:
8008 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8012 case PTR_TO_BTF_ID | MEM_ALLOC:
8013 case PTR_TO_BTF_ID | PTR_TRUSTED:
8014 case PTR_TO_BTF_ID | MEM_RCU:
8015 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8016 /* When referenced PTR_TO_BTF_ID is passed to release function,
8017 * its fixed offset must be 0. In the other cases, fixed offset
8018 * can be non-zero. This was already checked above. So pass
8019 * fixed_off_ok as true to allow fixed offset for all other
8020 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8021 * still need to do checks instead of returning.
8023 return __check_ptr_off_reg(env, reg, regno, true);
8025 return __check_ptr_off_reg(env, reg, regno, false);
8029 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8030 const struct bpf_func_proto *fn,
8031 struct bpf_reg_state *regs)
8033 struct bpf_reg_state *state = NULL;
8036 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8037 if (arg_type_is_dynptr(fn->arg_type[i])) {
8039 verbose(env, "verifier internal error: multiple dynptr args\n");
8042 state = ®s[BPF_REG_1 + i];
8046 verbose(env, "verifier internal error: no dynptr arg found\n");
8051 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8053 struct bpf_func_state *state = func(env, reg);
8056 if (reg->type == CONST_PTR_TO_DYNPTR)
8058 spi = dynptr_get_spi(env, reg);
8061 return state->stack[spi].spilled_ptr.id;
8064 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8066 struct bpf_func_state *state = func(env, reg);
8069 if (reg->type == CONST_PTR_TO_DYNPTR)
8070 return reg->ref_obj_id;
8071 spi = dynptr_get_spi(env, reg);
8074 return state->stack[spi].spilled_ptr.ref_obj_id;
8077 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8078 struct bpf_reg_state *reg)
8080 struct bpf_func_state *state = func(env, reg);
8083 if (reg->type == CONST_PTR_TO_DYNPTR)
8084 return reg->dynptr.type;
8086 spi = __get_spi(reg->off);
8088 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8089 return BPF_DYNPTR_TYPE_INVALID;
8092 return state->stack[spi].spilled_ptr.dynptr.type;
8095 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8096 struct bpf_call_arg_meta *meta,
8097 const struct bpf_func_proto *fn,
8100 u32 regno = BPF_REG_1 + arg;
8101 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8102 enum bpf_arg_type arg_type = fn->arg_type[arg];
8103 enum bpf_reg_type type = reg->type;
8104 u32 *arg_btf_id = NULL;
8107 if (arg_type == ARG_DONTCARE)
8110 err = check_reg_arg(env, regno, SRC_OP);
8114 if (arg_type == ARG_ANYTHING) {
8115 if (is_pointer_value(env, regno)) {
8116 verbose(env, "R%d leaks addr into helper function\n",
8123 if (type_is_pkt_pointer(type) &&
8124 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8125 verbose(env, "helper access to the packet is not allowed\n");
8129 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8130 err = resolve_map_arg_type(env, meta, &arg_type);
8135 if (register_is_null(reg) && type_may_be_null(arg_type))
8136 /* A NULL register has a SCALAR_VALUE type, so skip
8139 goto skip_type_check;
8141 /* arg_btf_id and arg_size are in a union. */
8142 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8143 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8144 arg_btf_id = fn->arg_btf_id[arg];
8146 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8150 err = check_func_arg_reg_off(env, reg, regno, arg_type);
8155 if (arg_type_is_release(arg_type)) {
8156 if (arg_type_is_dynptr(arg_type)) {
8157 struct bpf_func_state *state = func(env, reg);
8160 /* Only dynptr created on stack can be released, thus
8161 * the get_spi and stack state checks for spilled_ptr
8162 * should only be done before process_dynptr_func for
8165 if (reg->type == PTR_TO_STACK) {
8166 spi = dynptr_get_spi(env, reg);
8167 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8168 verbose(env, "arg %d is an unacquired reference\n", regno);
8172 verbose(env, "cannot release unowned const bpf_dynptr\n");
8175 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8176 verbose(env, "R%d must be referenced when passed to release function\n",
8180 if (meta->release_regno) {
8181 verbose(env, "verifier internal error: more than one release argument\n");
8184 meta->release_regno = regno;
8187 if (reg->ref_obj_id) {
8188 if (meta->ref_obj_id) {
8189 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8190 regno, reg->ref_obj_id,
8194 meta->ref_obj_id = reg->ref_obj_id;
8197 switch (base_type(arg_type)) {
8198 case ARG_CONST_MAP_PTR:
8199 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8200 if (meta->map_ptr) {
8201 /* Use map_uid (which is unique id of inner map) to reject:
8202 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8203 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8204 * if (inner_map1 && inner_map2) {
8205 * timer = bpf_map_lookup_elem(inner_map1);
8207 * // mismatch would have been allowed
8208 * bpf_timer_init(timer, inner_map2);
8211 * Comparing map_ptr is enough to distinguish normal and outer maps.
8213 if (meta->map_ptr != reg->map_ptr ||
8214 meta->map_uid != reg->map_uid) {
8216 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8217 meta->map_uid, reg->map_uid);
8221 meta->map_ptr = reg->map_ptr;
8222 meta->map_uid = reg->map_uid;
8224 case ARG_PTR_TO_MAP_KEY:
8225 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8226 * check that [key, key + map->key_size) are within
8227 * stack limits and initialized
8229 if (!meta->map_ptr) {
8230 /* in function declaration map_ptr must come before
8231 * map_key, so that it's verified and known before
8232 * we have to check map_key here. Otherwise it means
8233 * that kernel subsystem misconfigured verifier
8235 verbose(env, "invalid map_ptr to access map->key\n");
8238 err = check_helper_mem_access(env, regno,
8239 meta->map_ptr->key_size, false,
8242 case ARG_PTR_TO_MAP_VALUE:
8243 if (type_may_be_null(arg_type) && register_is_null(reg))
8246 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8247 * check [value, value + map->value_size) validity
8249 if (!meta->map_ptr) {
8250 /* kernel subsystem misconfigured verifier */
8251 verbose(env, "invalid map_ptr to access map->value\n");
8254 meta->raw_mode = arg_type & MEM_UNINIT;
8255 err = check_helper_mem_access(env, regno,
8256 meta->map_ptr->value_size, false,
8259 case ARG_PTR_TO_PERCPU_BTF_ID:
8261 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8264 meta->ret_btf = reg->btf;
8265 meta->ret_btf_id = reg->btf_id;
8267 case ARG_PTR_TO_SPIN_LOCK:
8268 if (in_rbtree_lock_required_cb(env)) {
8269 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8272 if (meta->func_id == BPF_FUNC_spin_lock) {
8273 err = process_spin_lock(env, regno, true);
8276 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8277 err = process_spin_lock(env, regno, false);
8281 verbose(env, "verifier internal error\n");
8285 case ARG_PTR_TO_TIMER:
8286 err = process_timer_func(env, regno, meta);
8290 case ARG_PTR_TO_FUNC:
8291 meta->subprogno = reg->subprogno;
8293 case ARG_PTR_TO_MEM:
8294 /* The access to this pointer is only checked when we hit the
8295 * next is_mem_size argument below.
8297 meta->raw_mode = arg_type & MEM_UNINIT;
8298 if (arg_type & MEM_FIXED_SIZE) {
8299 err = check_helper_mem_access(env, regno,
8300 fn->arg_size[arg], false,
8304 case ARG_CONST_SIZE:
8305 err = check_mem_size_reg(env, reg, regno, false, meta);
8307 case ARG_CONST_SIZE_OR_ZERO:
8308 err = check_mem_size_reg(env, reg, regno, true, meta);
8310 case ARG_PTR_TO_DYNPTR:
8311 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8315 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8316 if (!tnum_is_const(reg->var_off)) {
8317 verbose(env, "R%d is not a known constant'\n",
8321 meta->mem_size = reg->var_off.value;
8322 err = mark_chain_precision(env, regno);
8326 case ARG_PTR_TO_INT:
8327 case ARG_PTR_TO_LONG:
8329 int size = int_ptr_type_to_size(arg_type);
8331 err = check_helper_mem_access(env, regno, size, false, meta);
8334 err = check_ptr_alignment(env, reg, 0, size, true);
8337 case ARG_PTR_TO_CONST_STR:
8339 struct bpf_map *map = reg->map_ptr;
8344 if (!bpf_map_is_rdonly(map)) {
8345 verbose(env, "R%d does not point to a readonly map'\n", regno);
8349 if (!tnum_is_const(reg->var_off)) {
8350 verbose(env, "R%d is not a constant address'\n", regno);
8354 if (!map->ops->map_direct_value_addr) {
8355 verbose(env, "no direct value access support for this map type\n");
8359 err = check_map_access(env, regno, reg->off,
8360 map->value_size - reg->off, false,
8365 map_off = reg->off + reg->var_off.value;
8366 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8368 verbose(env, "direct value access on string failed\n");
8372 str_ptr = (char *)(long)(map_addr);
8373 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8374 verbose(env, "string is not zero-terminated\n");
8379 case ARG_PTR_TO_KPTR:
8380 err = process_kptr_func(env, regno, meta);
8389 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8391 enum bpf_attach_type eatype = env->prog->expected_attach_type;
8392 enum bpf_prog_type type = resolve_prog_type(env->prog);
8394 if (func_id != BPF_FUNC_map_update_elem)
8397 /* It's not possible to get access to a locked struct sock in these
8398 * contexts, so updating is safe.
8401 case BPF_PROG_TYPE_TRACING:
8402 if (eatype == BPF_TRACE_ITER)
8405 case BPF_PROG_TYPE_SOCKET_FILTER:
8406 case BPF_PROG_TYPE_SCHED_CLS:
8407 case BPF_PROG_TYPE_SCHED_ACT:
8408 case BPF_PROG_TYPE_XDP:
8409 case BPF_PROG_TYPE_SK_REUSEPORT:
8410 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8411 case BPF_PROG_TYPE_SK_LOOKUP:
8417 verbose(env, "cannot update sockmap in this context\n");
8421 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8423 return env->prog->jit_requested &&
8424 bpf_jit_supports_subprog_tailcalls();
8427 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8428 struct bpf_map *map, int func_id)
8433 /* We need a two way check, first is from map perspective ... */
8434 switch (map->map_type) {
8435 case BPF_MAP_TYPE_PROG_ARRAY:
8436 if (func_id != BPF_FUNC_tail_call)
8439 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8440 if (func_id != BPF_FUNC_perf_event_read &&
8441 func_id != BPF_FUNC_perf_event_output &&
8442 func_id != BPF_FUNC_skb_output &&
8443 func_id != BPF_FUNC_perf_event_read_value &&
8444 func_id != BPF_FUNC_xdp_output)
8447 case BPF_MAP_TYPE_RINGBUF:
8448 if (func_id != BPF_FUNC_ringbuf_output &&
8449 func_id != BPF_FUNC_ringbuf_reserve &&
8450 func_id != BPF_FUNC_ringbuf_query &&
8451 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8452 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8453 func_id != BPF_FUNC_ringbuf_discard_dynptr)
8456 case BPF_MAP_TYPE_USER_RINGBUF:
8457 if (func_id != BPF_FUNC_user_ringbuf_drain)
8460 case BPF_MAP_TYPE_STACK_TRACE:
8461 if (func_id != BPF_FUNC_get_stackid)
8464 case BPF_MAP_TYPE_CGROUP_ARRAY:
8465 if (func_id != BPF_FUNC_skb_under_cgroup &&
8466 func_id != BPF_FUNC_current_task_under_cgroup)
8469 case BPF_MAP_TYPE_CGROUP_STORAGE:
8470 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8471 if (func_id != BPF_FUNC_get_local_storage)
8474 case BPF_MAP_TYPE_DEVMAP:
8475 case BPF_MAP_TYPE_DEVMAP_HASH:
8476 if (func_id != BPF_FUNC_redirect_map &&
8477 func_id != BPF_FUNC_map_lookup_elem)
8480 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8483 case BPF_MAP_TYPE_CPUMAP:
8484 if (func_id != BPF_FUNC_redirect_map)
8487 case BPF_MAP_TYPE_XSKMAP:
8488 if (func_id != BPF_FUNC_redirect_map &&
8489 func_id != BPF_FUNC_map_lookup_elem)
8492 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8493 case BPF_MAP_TYPE_HASH_OF_MAPS:
8494 if (func_id != BPF_FUNC_map_lookup_elem)
8497 case BPF_MAP_TYPE_SOCKMAP:
8498 if (func_id != BPF_FUNC_sk_redirect_map &&
8499 func_id != BPF_FUNC_sock_map_update &&
8500 func_id != BPF_FUNC_map_delete_elem &&
8501 func_id != BPF_FUNC_msg_redirect_map &&
8502 func_id != BPF_FUNC_sk_select_reuseport &&
8503 func_id != BPF_FUNC_map_lookup_elem &&
8504 !may_update_sockmap(env, func_id))
8507 case BPF_MAP_TYPE_SOCKHASH:
8508 if (func_id != BPF_FUNC_sk_redirect_hash &&
8509 func_id != BPF_FUNC_sock_hash_update &&
8510 func_id != BPF_FUNC_map_delete_elem &&
8511 func_id != BPF_FUNC_msg_redirect_hash &&
8512 func_id != BPF_FUNC_sk_select_reuseport &&
8513 func_id != BPF_FUNC_map_lookup_elem &&
8514 !may_update_sockmap(env, func_id))
8517 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8518 if (func_id != BPF_FUNC_sk_select_reuseport)
8521 case BPF_MAP_TYPE_QUEUE:
8522 case BPF_MAP_TYPE_STACK:
8523 if (func_id != BPF_FUNC_map_peek_elem &&
8524 func_id != BPF_FUNC_map_pop_elem &&
8525 func_id != BPF_FUNC_map_push_elem)
8528 case BPF_MAP_TYPE_SK_STORAGE:
8529 if (func_id != BPF_FUNC_sk_storage_get &&
8530 func_id != BPF_FUNC_sk_storage_delete &&
8531 func_id != BPF_FUNC_kptr_xchg)
8534 case BPF_MAP_TYPE_INODE_STORAGE:
8535 if (func_id != BPF_FUNC_inode_storage_get &&
8536 func_id != BPF_FUNC_inode_storage_delete &&
8537 func_id != BPF_FUNC_kptr_xchg)
8540 case BPF_MAP_TYPE_TASK_STORAGE:
8541 if (func_id != BPF_FUNC_task_storage_get &&
8542 func_id != BPF_FUNC_task_storage_delete &&
8543 func_id != BPF_FUNC_kptr_xchg)
8546 case BPF_MAP_TYPE_CGRP_STORAGE:
8547 if (func_id != BPF_FUNC_cgrp_storage_get &&
8548 func_id != BPF_FUNC_cgrp_storage_delete &&
8549 func_id != BPF_FUNC_kptr_xchg)
8552 case BPF_MAP_TYPE_BLOOM_FILTER:
8553 if (func_id != BPF_FUNC_map_peek_elem &&
8554 func_id != BPF_FUNC_map_push_elem)
8561 /* ... and second from the function itself. */
8563 case BPF_FUNC_tail_call:
8564 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8566 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8567 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8571 case BPF_FUNC_perf_event_read:
8572 case BPF_FUNC_perf_event_output:
8573 case BPF_FUNC_perf_event_read_value:
8574 case BPF_FUNC_skb_output:
8575 case BPF_FUNC_xdp_output:
8576 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8579 case BPF_FUNC_ringbuf_output:
8580 case BPF_FUNC_ringbuf_reserve:
8581 case BPF_FUNC_ringbuf_query:
8582 case BPF_FUNC_ringbuf_reserve_dynptr:
8583 case BPF_FUNC_ringbuf_submit_dynptr:
8584 case BPF_FUNC_ringbuf_discard_dynptr:
8585 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8588 case BPF_FUNC_user_ringbuf_drain:
8589 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8592 case BPF_FUNC_get_stackid:
8593 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8596 case BPF_FUNC_current_task_under_cgroup:
8597 case BPF_FUNC_skb_under_cgroup:
8598 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8601 case BPF_FUNC_redirect_map:
8602 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8603 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8604 map->map_type != BPF_MAP_TYPE_CPUMAP &&
8605 map->map_type != BPF_MAP_TYPE_XSKMAP)
8608 case BPF_FUNC_sk_redirect_map:
8609 case BPF_FUNC_msg_redirect_map:
8610 case BPF_FUNC_sock_map_update:
8611 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8614 case BPF_FUNC_sk_redirect_hash:
8615 case BPF_FUNC_msg_redirect_hash:
8616 case BPF_FUNC_sock_hash_update:
8617 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8620 case BPF_FUNC_get_local_storage:
8621 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8622 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8625 case BPF_FUNC_sk_select_reuseport:
8626 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8627 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8628 map->map_type != BPF_MAP_TYPE_SOCKHASH)
8631 case BPF_FUNC_map_pop_elem:
8632 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8633 map->map_type != BPF_MAP_TYPE_STACK)
8636 case BPF_FUNC_map_peek_elem:
8637 case BPF_FUNC_map_push_elem:
8638 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8639 map->map_type != BPF_MAP_TYPE_STACK &&
8640 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8643 case BPF_FUNC_map_lookup_percpu_elem:
8644 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8645 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8646 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8649 case BPF_FUNC_sk_storage_get:
8650 case BPF_FUNC_sk_storage_delete:
8651 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8654 case BPF_FUNC_inode_storage_get:
8655 case BPF_FUNC_inode_storage_delete:
8656 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8659 case BPF_FUNC_task_storage_get:
8660 case BPF_FUNC_task_storage_delete:
8661 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8664 case BPF_FUNC_cgrp_storage_get:
8665 case BPF_FUNC_cgrp_storage_delete:
8666 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8675 verbose(env, "cannot pass map_type %d into func %s#%d\n",
8676 map->map_type, func_id_name(func_id), func_id);
8680 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8684 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8686 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8688 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8690 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8692 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8695 /* We only support one arg being in raw mode at the moment,
8696 * which is sufficient for the helper functions we have
8702 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8704 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8705 bool has_size = fn->arg_size[arg] != 0;
8706 bool is_next_size = false;
8708 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8709 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8711 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8712 return is_next_size;
8714 return has_size == is_next_size || is_next_size == is_fixed;
8717 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8719 /* bpf_xxx(..., buf, len) call will access 'len'
8720 * bytes from memory 'buf'. Both arg types need
8721 * to be paired, so make sure there's no buggy
8722 * helper function specification.
8724 if (arg_type_is_mem_size(fn->arg1_type) ||
8725 check_args_pair_invalid(fn, 0) ||
8726 check_args_pair_invalid(fn, 1) ||
8727 check_args_pair_invalid(fn, 2) ||
8728 check_args_pair_invalid(fn, 3) ||
8729 check_args_pair_invalid(fn, 4))
8735 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8739 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8740 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8741 return !!fn->arg_btf_id[i];
8742 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8743 return fn->arg_btf_id[i] == BPF_PTR_POISON;
8744 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8745 /* arg_btf_id and arg_size are in a union. */
8746 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8747 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8754 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8756 return check_raw_mode_ok(fn) &&
8757 check_arg_pair_ok(fn) &&
8758 check_btf_id_ok(fn) ? 0 : -EINVAL;
8761 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8762 * are now invalid, so turn them into unknown SCALAR_VALUE.
8764 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8765 * since these slices point to packet data.
8767 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8769 struct bpf_func_state *state;
8770 struct bpf_reg_state *reg;
8772 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8773 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8774 mark_reg_invalid(env, reg);
8780 BEYOND_PKT_END = -2,
8783 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8785 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8786 struct bpf_reg_state *reg = &state->regs[regn];
8788 if (reg->type != PTR_TO_PACKET)
8789 /* PTR_TO_PACKET_META is not supported yet */
8792 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8793 * How far beyond pkt_end it goes is unknown.
8794 * if (!range_open) it's the case of pkt >= pkt_end
8795 * if (range_open) it's the case of pkt > pkt_end
8796 * hence this pointer is at least 1 byte bigger than pkt_end
8799 reg->range = BEYOND_PKT_END;
8801 reg->range = AT_PKT_END;
8804 /* The pointer with the specified id has released its reference to kernel
8805 * resources. Identify all copies of the same pointer and clear the reference.
8807 static int release_reference(struct bpf_verifier_env *env,
8810 struct bpf_func_state *state;
8811 struct bpf_reg_state *reg;
8814 err = release_reference_state(cur_func(env), ref_obj_id);
8818 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8819 if (reg->ref_obj_id == ref_obj_id)
8820 mark_reg_invalid(env, reg);
8826 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8828 struct bpf_func_state *unused;
8829 struct bpf_reg_state *reg;
8831 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8832 if (type_is_non_owning_ref(reg->type))
8833 mark_reg_invalid(env, reg);
8837 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8838 struct bpf_reg_state *regs)
8842 /* after the call registers r0 - r5 were scratched */
8843 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8844 mark_reg_not_init(env, regs, caller_saved[i]);
8845 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8849 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8850 struct bpf_func_state *caller,
8851 struct bpf_func_state *callee,
8854 static int set_callee_state(struct bpf_verifier_env *env,
8855 struct bpf_func_state *caller,
8856 struct bpf_func_state *callee, int insn_idx);
8858 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8859 int *insn_idx, int subprog,
8860 set_callee_state_fn set_callee_state_cb)
8862 struct bpf_verifier_state *state = env->cur_state;
8863 struct bpf_func_state *caller, *callee;
8866 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8867 verbose(env, "the call stack of %d frames is too deep\n",
8868 state->curframe + 2);
8872 caller = state->frame[state->curframe];
8873 if (state->frame[state->curframe + 1]) {
8874 verbose(env, "verifier bug. Frame %d already allocated\n",
8875 state->curframe + 1);
8879 err = btf_check_subprog_call(env, subprog, caller->regs);
8882 if (subprog_is_global(env, subprog)) {
8884 verbose(env, "Caller passes invalid args into func#%d\n",
8888 if (env->log.level & BPF_LOG_LEVEL)
8890 "Func#%d is global and valid. Skipping.\n",
8892 clear_caller_saved_regs(env, caller->regs);
8894 /* All global functions return a 64-bit SCALAR_VALUE */
8895 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8896 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8898 /* continue with next insn after call */
8903 /* set_callee_state is used for direct subprog calls, but we are
8904 * interested in validating only BPF helpers that can call subprogs as
8907 if (set_callee_state_cb != set_callee_state) {
8908 if (bpf_pseudo_kfunc_call(insn) &&
8909 !is_callback_calling_kfunc(insn->imm)) {
8910 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8911 func_id_name(insn->imm), insn->imm);
8913 } else if (!bpf_pseudo_kfunc_call(insn) &&
8914 !is_callback_calling_function(insn->imm)) { /* helper */
8915 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8916 func_id_name(insn->imm), insn->imm);
8921 if (insn->code == (BPF_JMP | BPF_CALL) &&
8922 insn->src_reg == 0 &&
8923 insn->imm == BPF_FUNC_timer_set_callback) {
8924 struct bpf_verifier_state *async_cb;
8926 /* there is no real recursion here. timer callbacks are async */
8927 env->subprog_info[subprog].is_async_cb = true;
8928 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8929 *insn_idx, subprog);
8932 callee = async_cb->frame[0];
8933 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8935 /* Convert bpf_timer_set_callback() args into timer callback args */
8936 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8940 clear_caller_saved_regs(env, caller->regs);
8941 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8942 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8943 /* continue with next insn after call */
8947 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8950 state->frame[state->curframe + 1] = callee;
8952 /* callee cannot access r0, r6 - r9 for reading and has to write
8953 * into its own stack before reading from it.
8954 * callee can read/write into caller's stack
8956 init_func_state(env, callee,
8957 /* remember the callsite, it will be used by bpf_exit */
8958 *insn_idx /* callsite */,
8959 state->curframe + 1 /* frameno within this callchain */,
8960 subprog /* subprog number within this prog */);
8962 /* Transfer references to the callee */
8963 err = copy_reference_state(callee, caller);
8967 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8971 clear_caller_saved_regs(env, caller->regs);
8973 /* only increment it after check_reg_arg() finished */
8976 /* and go analyze first insn of the callee */
8977 *insn_idx = env->subprog_info[subprog].start - 1;
8979 if (env->log.level & BPF_LOG_LEVEL) {
8980 verbose(env, "caller:\n");
8981 print_verifier_state(env, caller, true);
8982 verbose(env, "callee:\n");
8983 print_verifier_state(env, callee, true);
8988 free_func_state(callee);
8989 state->frame[state->curframe + 1] = NULL;
8993 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8994 struct bpf_func_state *caller,
8995 struct bpf_func_state *callee)
8997 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8998 * void *callback_ctx, u64 flags);
8999 * callback_fn(struct bpf_map *map, void *key, void *value,
9000 * void *callback_ctx);
9002 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9004 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9005 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9006 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9008 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9009 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9010 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9012 /* pointer to stack or null */
9013 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9016 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9020 static int set_callee_state(struct bpf_verifier_env *env,
9021 struct bpf_func_state *caller,
9022 struct bpf_func_state *callee, int insn_idx)
9026 /* copy r1 - r5 args that callee can access. The copy includes parent
9027 * pointers, which connects us up to the liveness chain
9029 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9030 callee->regs[i] = caller->regs[i];
9034 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9037 int subprog, target_insn;
9039 target_insn = *insn_idx + insn->imm + 1;
9040 subprog = find_subprog(env, target_insn);
9042 verbose(env, "verifier bug. No program starts at insn %d\n",
9047 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
9050 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9051 struct bpf_func_state *caller,
9052 struct bpf_func_state *callee,
9055 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9056 struct bpf_map *map;
9059 if (bpf_map_ptr_poisoned(insn_aux)) {
9060 verbose(env, "tail_call abusing map_ptr\n");
9064 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9065 if (!map->ops->map_set_for_each_callback_args ||
9066 !map->ops->map_for_each_callback) {
9067 verbose(env, "callback function not allowed for map\n");
9071 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9075 callee->in_callback_fn = true;
9076 callee->callback_ret_range = tnum_range(0, 1);
9080 static int set_loop_callback_state(struct bpf_verifier_env *env,
9081 struct bpf_func_state *caller,
9082 struct bpf_func_state *callee,
9085 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9087 * callback_fn(u32 index, void *callback_ctx);
9089 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9090 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9093 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9094 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9095 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9097 callee->in_callback_fn = true;
9098 callee->callback_ret_range = tnum_range(0, 1);
9102 static int set_timer_callback_state(struct bpf_verifier_env *env,
9103 struct bpf_func_state *caller,
9104 struct bpf_func_state *callee,
9107 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9109 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9110 * callback_fn(struct bpf_map *map, void *key, void *value);
9112 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9113 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9114 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9116 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9117 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9118 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9120 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9121 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9122 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9125 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9126 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9127 callee->in_async_callback_fn = true;
9128 callee->callback_ret_range = tnum_range(0, 1);
9132 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9133 struct bpf_func_state *caller,
9134 struct bpf_func_state *callee,
9137 /* bpf_find_vma(struct task_struct *task, u64 addr,
9138 * void *callback_fn, void *callback_ctx, u64 flags)
9139 * (callback_fn)(struct task_struct *task,
9140 * struct vm_area_struct *vma, void *callback_ctx);
9142 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9144 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9145 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9146 callee->regs[BPF_REG_2].btf = btf_vmlinux;
9147 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9149 /* pointer to stack or null */
9150 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9153 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9154 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9155 callee->in_callback_fn = true;
9156 callee->callback_ret_range = tnum_range(0, 1);
9160 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9161 struct bpf_func_state *caller,
9162 struct bpf_func_state *callee,
9165 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9166 * callback_ctx, u64 flags);
9167 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9169 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9170 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9171 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9174 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9175 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9176 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9178 callee->in_callback_fn = true;
9179 callee->callback_ret_range = tnum_range(0, 1);
9183 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9184 struct bpf_func_state *caller,
9185 struct bpf_func_state *callee,
9188 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9189 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9191 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9192 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9193 * by this point, so look at 'root'
9195 struct btf_field *field;
9197 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9199 if (!field || !field->graph_root.value_btf_id)
9202 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9203 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9204 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9205 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9207 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9208 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9209 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9210 callee->in_callback_fn = true;
9211 callee->callback_ret_range = tnum_range(0, 1);
9215 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9217 /* Are we currently verifying the callback for a rbtree helper that must
9218 * be called with lock held? If so, no need to complain about unreleased
9221 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9223 struct bpf_verifier_state *state = env->cur_state;
9224 struct bpf_insn *insn = env->prog->insnsi;
9225 struct bpf_func_state *callee;
9228 if (!state->curframe)
9231 callee = state->frame[state->curframe];
9233 if (!callee->in_callback_fn)
9236 kfunc_btf_id = insn[callee->callsite].imm;
9237 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9240 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9242 struct bpf_verifier_state *state = env->cur_state;
9243 struct bpf_func_state *caller, *callee;
9244 struct bpf_reg_state *r0;
9247 callee = state->frame[state->curframe];
9248 r0 = &callee->regs[BPF_REG_0];
9249 if (r0->type == PTR_TO_STACK) {
9250 /* technically it's ok to return caller's stack pointer
9251 * (or caller's caller's pointer) back to the caller,
9252 * since these pointers are valid. Only current stack
9253 * pointer will be invalid as soon as function exits,
9254 * but let's be conservative
9256 verbose(env, "cannot return stack pointer to the caller\n");
9260 caller = state->frame[state->curframe - 1];
9261 if (callee->in_callback_fn) {
9262 /* enforce R0 return value range [0, 1]. */
9263 struct tnum range = callee->callback_ret_range;
9265 if (r0->type != SCALAR_VALUE) {
9266 verbose(env, "R0 not a scalar value\n");
9269 if (!tnum_in(range, r0->var_off)) {
9270 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9274 /* return to the caller whatever r0 had in the callee */
9275 caller->regs[BPF_REG_0] = *r0;
9278 /* callback_fn frame should have released its own additions to parent's
9279 * reference state at this point, or check_reference_leak would
9280 * complain, hence it must be the same as the caller. There is no need
9283 if (!callee->in_callback_fn) {
9284 /* Transfer references to the caller */
9285 err = copy_reference_state(caller, callee);
9290 *insn_idx = callee->callsite + 1;
9291 if (env->log.level & BPF_LOG_LEVEL) {
9292 verbose(env, "returning from callee:\n");
9293 print_verifier_state(env, callee, true);
9294 verbose(env, "to caller at %d:\n", *insn_idx);
9295 print_verifier_state(env, caller, true);
9297 /* clear everything in the callee */
9298 free_func_state(callee);
9299 state->frame[state->curframe--] = NULL;
9303 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9305 struct bpf_call_arg_meta *meta)
9307 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
9309 if (ret_type != RET_INTEGER)
9313 case BPF_FUNC_get_stack:
9314 case BPF_FUNC_get_task_stack:
9315 case BPF_FUNC_probe_read_str:
9316 case BPF_FUNC_probe_read_kernel_str:
9317 case BPF_FUNC_probe_read_user_str:
9318 ret_reg->smax_value = meta->msize_max_value;
9319 ret_reg->s32_max_value = meta->msize_max_value;
9320 ret_reg->smin_value = -MAX_ERRNO;
9321 ret_reg->s32_min_value = -MAX_ERRNO;
9322 reg_bounds_sync(ret_reg);
9324 case BPF_FUNC_get_smp_processor_id:
9325 ret_reg->umax_value = nr_cpu_ids - 1;
9326 ret_reg->u32_max_value = nr_cpu_ids - 1;
9327 ret_reg->smax_value = nr_cpu_ids - 1;
9328 ret_reg->s32_max_value = nr_cpu_ids - 1;
9329 ret_reg->umin_value = 0;
9330 ret_reg->u32_min_value = 0;
9331 ret_reg->smin_value = 0;
9332 ret_reg->s32_min_value = 0;
9333 reg_bounds_sync(ret_reg);
9339 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9340 int func_id, int insn_idx)
9342 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9343 struct bpf_map *map = meta->map_ptr;
9345 if (func_id != BPF_FUNC_tail_call &&
9346 func_id != BPF_FUNC_map_lookup_elem &&
9347 func_id != BPF_FUNC_map_update_elem &&
9348 func_id != BPF_FUNC_map_delete_elem &&
9349 func_id != BPF_FUNC_map_push_elem &&
9350 func_id != BPF_FUNC_map_pop_elem &&
9351 func_id != BPF_FUNC_map_peek_elem &&
9352 func_id != BPF_FUNC_for_each_map_elem &&
9353 func_id != BPF_FUNC_redirect_map &&
9354 func_id != BPF_FUNC_map_lookup_percpu_elem)
9358 verbose(env, "kernel subsystem misconfigured verifier\n");
9362 /* In case of read-only, some additional restrictions
9363 * need to be applied in order to prevent altering the
9364 * state of the map from program side.
9366 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9367 (func_id == BPF_FUNC_map_delete_elem ||
9368 func_id == BPF_FUNC_map_update_elem ||
9369 func_id == BPF_FUNC_map_push_elem ||
9370 func_id == BPF_FUNC_map_pop_elem)) {
9371 verbose(env, "write into map forbidden\n");
9375 if (!BPF_MAP_PTR(aux->map_ptr_state))
9376 bpf_map_ptr_store(aux, meta->map_ptr,
9377 !meta->map_ptr->bypass_spec_v1);
9378 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9379 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9380 !meta->map_ptr->bypass_spec_v1);
9385 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9386 int func_id, int insn_idx)
9388 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9389 struct bpf_reg_state *regs = cur_regs(env), *reg;
9390 struct bpf_map *map = meta->map_ptr;
9394 if (func_id != BPF_FUNC_tail_call)
9396 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9397 verbose(env, "kernel subsystem misconfigured verifier\n");
9401 reg = ®s[BPF_REG_3];
9402 val = reg->var_off.value;
9403 max = map->max_entries;
9405 if (!(register_is_const(reg) && val < max)) {
9406 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9410 err = mark_chain_precision(env, BPF_REG_3);
9413 if (bpf_map_key_unseen(aux))
9414 bpf_map_key_store(aux, val);
9415 else if (!bpf_map_key_poisoned(aux) &&
9416 bpf_map_key_immediate(aux) != val)
9417 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9421 static int check_reference_leak(struct bpf_verifier_env *env)
9423 struct bpf_func_state *state = cur_func(env);
9424 bool refs_lingering = false;
9427 if (state->frameno && !state->in_callback_fn)
9430 for (i = 0; i < state->acquired_refs; i++) {
9431 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9433 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9434 state->refs[i].id, state->refs[i].insn_idx);
9435 refs_lingering = true;
9437 return refs_lingering ? -EINVAL : 0;
9440 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9441 struct bpf_reg_state *regs)
9443 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
9444 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
9445 struct bpf_map *fmt_map = fmt_reg->map_ptr;
9446 struct bpf_bprintf_data data = {};
9447 int err, fmt_map_off, num_args;
9451 /* data must be an array of u64 */
9452 if (data_len_reg->var_off.value % 8)
9454 num_args = data_len_reg->var_off.value / 8;
9456 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9457 * and map_direct_value_addr is set.
9459 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9460 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9463 verbose(env, "verifier bug\n");
9466 fmt = (char *)(long)fmt_addr + fmt_map_off;
9468 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9469 * can focus on validating the format specifiers.
9471 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9473 verbose(env, "Invalid format string\n");
9478 static int check_get_func_ip(struct bpf_verifier_env *env)
9480 enum bpf_prog_type type = resolve_prog_type(env->prog);
9481 int func_id = BPF_FUNC_get_func_ip;
9483 if (type == BPF_PROG_TYPE_TRACING) {
9484 if (!bpf_prog_has_trampoline(env->prog)) {
9485 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9486 func_id_name(func_id), func_id);
9490 } else if (type == BPF_PROG_TYPE_KPROBE) {
9494 verbose(env, "func %s#%d not supported for program type %d\n",
9495 func_id_name(func_id), func_id, type);
9499 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9501 return &env->insn_aux_data[env->insn_idx];
9504 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9506 struct bpf_reg_state *regs = cur_regs(env);
9507 struct bpf_reg_state *reg = ®s[BPF_REG_4];
9508 bool reg_is_null = register_is_null(reg);
9511 mark_chain_precision(env, BPF_REG_4);
9516 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9518 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9520 if (!state->initialized) {
9521 state->initialized = 1;
9522 state->fit_for_inline = loop_flag_is_zero(env);
9523 state->callback_subprogno = subprogno;
9527 if (!state->fit_for_inline)
9530 state->fit_for_inline = (loop_flag_is_zero(env) &&
9531 state->callback_subprogno == subprogno);
9534 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9537 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9538 const struct bpf_func_proto *fn = NULL;
9539 enum bpf_return_type ret_type;
9540 enum bpf_type_flag ret_flag;
9541 struct bpf_reg_state *regs;
9542 struct bpf_call_arg_meta meta;
9543 int insn_idx = *insn_idx_p;
9545 int i, err, func_id;
9547 /* find function prototype */
9548 func_id = insn->imm;
9549 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9550 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9555 if (env->ops->get_func_proto)
9556 fn = env->ops->get_func_proto(func_id, env->prog);
9558 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9563 /* eBPF programs must be GPL compatible to use GPL-ed functions */
9564 if (!env->prog->gpl_compatible && fn->gpl_only) {
9565 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9569 if (fn->allowed && !fn->allowed(env->prog)) {
9570 verbose(env, "helper call is not allowed in probe\n");
9574 if (!env->prog->aux->sleepable && fn->might_sleep) {
9575 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9579 /* With LD_ABS/IND some JITs save/restore skb from r1. */
9580 changes_data = bpf_helper_changes_pkt_data(fn->func);
9581 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9582 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9583 func_id_name(func_id), func_id);
9587 memset(&meta, 0, sizeof(meta));
9588 meta.pkt_access = fn->pkt_access;
9590 err = check_func_proto(fn, func_id);
9592 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9593 func_id_name(func_id), func_id);
9597 if (env->cur_state->active_rcu_lock) {
9598 if (fn->might_sleep) {
9599 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9600 func_id_name(func_id), func_id);
9604 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9605 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9608 meta.func_id = func_id;
9610 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9611 err = check_func_arg(env, i, &meta, fn, insn_idx);
9616 err = record_func_map(env, &meta, func_id, insn_idx);
9620 err = record_func_key(env, &meta, func_id, insn_idx);
9624 /* Mark slots with STACK_MISC in case of raw mode, stack offset
9625 * is inferred from register state.
9627 for (i = 0; i < meta.access_size; i++) {
9628 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9629 BPF_WRITE, -1, false, false);
9634 regs = cur_regs(env);
9636 if (meta.release_regno) {
9638 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9639 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9640 * is safe to do directly.
9642 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9643 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9644 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9647 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
9648 } else if (meta.ref_obj_id) {
9649 err = release_reference(env, meta.ref_obj_id);
9650 } else if (register_is_null(®s[meta.release_regno])) {
9651 /* meta.ref_obj_id can only be 0 if register that is meant to be
9652 * released is NULL, which must be > R0.
9657 verbose(env, "func %s#%d reference has not been acquired before\n",
9658 func_id_name(func_id), func_id);
9664 case BPF_FUNC_tail_call:
9665 err = check_reference_leak(env);
9667 verbose(env, "tail_call would lead to reference leak\n");
9671 case BPF_FUNC_get_local_storage:
9672 /* check that flags argument in get_local_storage(map, flags) is 0,
9673 * this is required because get_local_storage() can't return an error.
9675 if (!register_is_null(®s[BPF_REG_2])) {
9676 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9680 case BPF_FUNC_for_each_map_elem:
9681 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9682 set_map_elem_callback_state);
9684 case BPF_FUNC_timer_set_callback:
9685 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9686 set_timer_callback_state);
9688 case BPF_FUNC_find_vma:
9689 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9690 set_find_vma_callback_state);
9692 case BPF_FUNC_snprintf:
9693 err = check_bpf_snprintf_call(env, regs);
9696 update_loop_inline_state(env, meta.subprogno);
9697 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9698 set_loop_callback_state);
9700 case BPF_FUNC_dynptr_from_mem:
9701 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9702 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9703 reg_type_str(env, regs[BPF_REG_1].type));
9707 case BPF_FUNC_set_retval:
9708 if (prog_type == BPF_PROG_TYPE_LSM &&
9709 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9710 if (!env->prog->aux->attach_func_proto->type) {
9711 /* Make sure programs that attach to void
9712 * hooks don't try to modify return value.
9714 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9719 case BPF_FUNC_dynptr_data:
9721 struct bpf_reg_state *reg;
9724 reg = get_dynptr_arg_reg(env, fn, regs);
9729 if (meta.dynptr_id) {
9730 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9733 if (meta.ref_obj_id) {
9734 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9738 id = dynptr_id(env, reg);
9740 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9744 ref_obj_id = dynptr_ref_obj_id(env, reg);
9745 if (ref_obj_id < 0) {
9746 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9750 meta.dynptr_id = id;
9751 meta.ref_obj_id = ref_obj_id;
9755 case BPF_FUNC_dynptr_write:
9757 enum bpf_dynptr_type dynptr_type;
9758 struct bpf_reg_state *reg;
9760 reg = get_dynptr_arg_reg(env, fn, regs);
9764 dynptr_type = dynptr_get_type(env, reg);
9765 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9768 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9769 /* this will trigger clear_all_pkt_pointers(), which will
9770 * invalidate all dynptr slices associated with the skb
9772 changes_data = true;
9776 case BPF_FUNC_user_ringbuf_drain:
9777 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9778 set_user_ringbuf_callback_state);
9785 /* reset caller saved regs */
9786 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9787 mark_reg_not_init(env, regs, caller_saved[i]);
9788 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9791 /* helper call returns 64-bit value. */
9792 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9794 /* update return register (already marked as written above) */
9795 ret_type = fn->ret_type;
9796 ret_flag = type_flag(ret_type);
9798 switch (base_type(ret_type)) {
9800 /* sets type to SCALAR_VALUE */
9801 mark_reg_unknown(env, regs, BPF_REG_0);
9804 regs[BPF_REG_0].type = NOT_INIT;
9806 case RET_PTR_TO_MAP_VALUE:
9807 /* There is no offset yet applied, variable or fixed */
9808 mark_reg_known_zero(env, regs, BPF_REG_0);
9809 /* remember map_ptr, so that check_map_access()
9810 * can check 'value_size' boundary of memory access
9811 * to map element returned from bpf_map_lookup_elem()
9813 if (meta.map_ptr == NULL) {
9815 "kernel subsystem misconfigured verifier\n");
9818 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9819 regs[BPF_REG_0].map_uid = meta.map_uid;
9820 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9821 if (!type_may_be_null(ret_type) &&
9822 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9823 regs[BPF_REG_0].id = ++env->id_gen;
9826 case RET_PTR_TO_SOCKET:
9827 mark_reg_known_zero(env, regs, BPF_REG_0);
9828 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9830 case RET_PTR_TO_SOCK_COMMON:
9831 mark_reg_known_zero(env, regs, BPF_REG_0);
9832 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9834 case RET_PTR_TO_TCP_SOCK:
9835 mark_reg_known_zero(env, regs, BPF_REG_0);
9836 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9838 case RET_PTR_TO_MEM:
9839 mark_reg_known_zero(env, regs, BPF_REG_0);
9840 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9841 regs[BPF_REG_0].mem_size = meta.mem_size;
9843 case RET_PTR_TO_MEM_OR_BTF_ID:
9845 const struct btf_type *t;
9847 mark_reg_known_zero(env, regs, BPF_REG_0);
9848 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9849 if (!btf_type_is_struct(t)) {
9851 const struct btf_type *ret;
9854 /* resolve the type size of ksym. */
9855 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9857 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9858 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9859 tname, PTR_ERR(ret));
9862 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9863 regs[BPF_REG_0].mem_size = tsize;
9865 /* MEM_RDONLY may be carried from ret_flag, but it
9866 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9867 * it will confuse the check of PTR_TO_BTF_ID in
9868 * check_mem_access().
9870 ret_flag &= ~MEM_RDONLY;
9872 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9873 regs[BPF_REG_0].btf = meta.ret_btf;
9874 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9878 case RET_PTR_TO_BTF_ID:
9880 struct btf *ret_btf;
9883 mark_reg_known_zero(env, regs, BPF_REG_0);
9884 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9885 if (func_id == BPF_FUNC_kptr_xchg) {
9886 ret_btf = meta.kptr_field->kptr.btf;
9887 ret_btf_id = meta.kptr_field->kptr.btf_id;
9888 if (!btf_is_kernel(ret_btf))
9889 regs[BPF_REG_0].type |= MEM_ALLOC;
9891 if (fn->ret_btf_id == BPF_PTR_POISON) {
9892 verbose(env, "verifier internal error:");
9893 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9894 func_id_name(func_id));
9897 ret_btf = btf_vmlinux;
9898 ret_btf_id = *fn->ret_btf_id;
9900 if (ret_btf_id == 0) {
9901 verbose(env, "invalid return type %u of func %s#%d\n",
9902 base_type(ret_type), func_id_name(func_id),
9906 regs[BPF_REG_0].btf = ret_btf;
9907 regs[BPF_REG_0].btf_id = ret_btf_id;
9911 verbose(env, "unknown return type %u of func %s#%d\n",
9912 base_type(ret_type), func_id_name(func_id), func_id);
9916 if (type_may_be_null(regs[BPF_REG_0].type))
9917 regs[BPF_REG_0].id = ++env->id_gen;
9919 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9920 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9921 func_id_name(func_id), func_id);
9925 if (is_dynptr_ref_function(func_id))
9926 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9928 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9929 /* For release_reference() */
9930 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9931 } else if (is_acquire_function(func_id, meta.map_ptr)) {
9932 int id = acquire_reference_state(env, insn_idx);
9936 /* For mark_ptr_or_null_reg() */
9937 regs[BPF_REG_0].id = id;
9938 /* For release_reference() */
9939 regs[BPF_REG_0].ref_obj_id = id;
9942 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9944 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9948 if ((func_id == BPF_FUNC_get_stack ||
9949 func_id == BPF_FUNC_get_task_stack) &&
9950 !env->prog->has_callchain_buf) {
9951 const char *err_str;
9953 #ifdef CONFIG_PERF_EVENTS
9954 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9955 err_str = "cannot get callchain buffer for func %s#%d\n";
9958 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9961 verbose(env, err_str, func_id_name(func_id), func_id);
9965 env->prog->has_callchain_buf = true;
9968 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9969 env->prog->call_get_stack = true;
9971 if (func_id == BPF_FUNC_get_func_ip) {
9972 if (check_get_func_ip(env))
9974 env->prog->call_get_func_ip = true;
9978 clear_all_pkt_pointers(env);
9982 /* mark_btf_func_reg_size() is used when the reg size is determined by
9983 * the BTF func_proto's return value size and argument.
9985 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9988 struct bpf_reg_state *reg = &cur_regs(env)[regno];
9990 if (regno == BPF_REG_0) {
9991 /* Function return value */
9992 reg->live |= REG_LIVE_WRITTEN;
9993 reg->subreg_def = reg_size == sizeof(u64) ?
9994 DEF_NOT_SUBREG : env->insn_idx + 1;
9996 /* Function argument */
9997 if (reg_size == sizeof(u64)) {
9998 mark_insn_zext(env, reg);
9999 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10001 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10006 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10008 return meta->kfunc_flags & KF_ACQUIRE;
10011 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10013 return meta->kfunc_flags & KF_RELEASE;
10016 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10018 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10021 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10023 return meta->kfunc_flags & KF_SLEEPABLE;
10026 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10028 return meta->kfunc_flags & KF_DESTRUCTIVE;
10031 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10033 return meta->kfunc_flags & KF_RCU;
10036 static bool __kfunc_param_match_suffix(const struct btf *btf,
10037 const struct btf_param *arg,
10038 const char *suffix)
10040 int suffix_len = strlen(suffix), len;
10041 const char *param_name;
10043 /* In the future, this can be ported to use BTF tagging */
10044 param_name = btf_name_by_offset(btf, arg->name_off);
10045 if (str_is_empty(param_name))
10047 len = strlen(param_name);
10048 if (len < suffix_len)
10050 param_name += len - suffix_len;
10051 return !strncmp(param_name, suffix, suffix_len);
10054 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10055 const struct btf_param *arg,
10056 const struct bpf_reg_state *reg)
10058 const struct btf_type *t;
10060 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10061 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10064 return __kfunc_param_match_suffix(btf, arg, "__sz");
10067 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10068 const struct btf_param *arg,
10069 const struct bpf_reg_state *reg)
10071 const struct btf_type *t;
10073 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10074 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10077 return __kfunc_param_match_suffix(btf, arg, "__szk");
10080 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10082 return __kfunc_param_match_suffix(btf, arg, "__opt");
10085 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10087 return __kfunc_param_match_suffix(btf, arg, "__k");
10090 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10092 return __kfunc_param_match_suffix(btf, arg, "__ign");
10095 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10097 return __kfunc_param_match_suffix(btf, arg, "__alloc");
10100 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10102 return __kfunc_param_match_suffix(btf, arg, "__uninit");
10105 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10107 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10110 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10111 const struct btf_param *arg,
10114 int len, target_len = strlen(name);
10115 const char *param_name;
10117 param_name = btf_name_by_offset(btf, arg->name_off);
10118 if (str_is_empty(param_name))
10120 len = strlen(param_name);
10121 if (len != target_len)
10123 if (strcmp(param_name, name))
10131 KF_ARG_LIST_HEAD_ID,
10132 KF_ARG_LIST_NODE_ID,
10137 BTF_ID_LIST(kf_arg_btf_ids)
10138 BTF_ID(struct, bpf_dynptr_kern)
10139 BTF_ID(struct, bpf_list_head)
10140 BTF_ID(struct, bpf_list_node)
10141 BTF_ID(struct, bpf_rb_root)
10142 BTF_ID(struct, bpf_rb_node)
10144 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10145 const struct btf_param *arg, int type)
10147 const struct btf_type *t;
10150 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10153 if (!btf_type_is_ptr(t))
10155 t = btf_type_skip_modifiers(btf, t->type, &res_id);
10158 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10161 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10163 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10166 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10168 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10171 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10173 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10176 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10178 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10181 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10183 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10186 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10187 const struct btf_param *arg)
10189 const struct btf_type *t;
10191 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10198 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10199 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10200 const struct btf *btf,
10201 const struct btf_type *t, int rec)
10203 const struct btf_type *member_type;
10204 const struct btf_member *member;
10207 if (!btf_type_is_struct(t))
10210 for_each_member(i, t, member) {
10211 const struct btf_array *array;
10213 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10214 if (btf_type_is_struct(member_type)) {
10216 verbose(env, "max struct nesting depth exceeded\n");
10219 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10223 if (btf_type_is_array(member_type)) {
10224 array = btf_array(member_type);
10225 if (!array->nelems)
10227 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10228 if (!btf_type_is_scalar(member_type))
10232 if (!btf_type_is_scalar(member_type))
10238 enum kfunc_ptr_arg_type {
10240 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10241 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10242 KF_ARG_PTR_TO_DYNPTR,
10243 KF_ARG_PTR_TO_ITER,
10244 KF_ARG_PTR_TO_LIST_HEAD,
10245 KF_ARG_PTR_TO_LIST_NODE,
10246 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
10248 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
10249 KF_ARG_PTR_TO_CALLBACK,
10250 KF_ARG_PTR_TO_RB_ROOT,
10251 KF_ARG_PTR_TO_RB_NODE,
10254 enum special_kfunc_type {
10255 KF_bpf_obj_new_impl,
10256 KF_bpf_obj_drop_impl,
10257 KF_bpf_refcount_acquire_impl,
10258 KF_bpf_list_push_front_impl,
10259 KF_bpf_list_push_back_impl,
10260 KF_bpf_list_pop_front,
10261 KF_bpf_list_pop_back,
10262 KF_bpf_cast_to_kern_ctx,
10263 KF_bpf_rdonly_cast,
10264 KF_bpf_rcu_read_lock,
10265 KF_bpf_rcu_read_unlock,
10266 KF_bpf_rbtree_remove,
10267 KF_bpf_rbtree_add_impl,
10268 KF_bpf_rbtree_first,
10269 KF_bpf_dynptr_from_skb,
10270 KF_bpf_dynptr_from_xdp,
10271 KF_bpf_dynptr_slice,
10272 KF_bpf_dynptr_slice_rdwr,
10273 KF_bpf_dynptr_clone,
10276 BTF_SET_START(special_kfunc_set)
10277 BTF_ID(func, bpf_obj_new_impl)
10278 BTF_ID(func, bpf_obj_drop_impl)
10279 BTF_ID(func, bpf_refcount_acquire_impl)
10280 BTF_ID(func, bpf_list_push_front_impl)
10281 BTF_ID(func, bpf_list_push_back_impl)
10282 BTF_ID(func, bpf_list_pop_front)
10283 BTF_ID(func, bpf_list_pop_back)
10284 BTF_ID(func, bpf_cast_to_kern_ctx)
10285 BTF_ID(func, bpf_rdonly_cast)
10286 BTF_ID(func, bpf_rbtree_remove)
10287 BTF_ID(func, bpf_rbtree_add_impl)
10288 BTF_ID(func, bpf_rbtree_first)
10289 BTF_ID(func, bpf_dynptr_from_skb)
10290 BTF_ID(func, bpf_dynptr_from_xdp)
10291 BTF_ID(func, bpf_dynptr_slice)
10292 BTF_ID(func, bpf_dynptr_slice_rdwr)
10293 BTF_ID(func, bpf_dynptr_clone)
10294 BTF_SET_END(special_kfunc_set)
10296 BTF_ID_LIST(special_kfunc_list)
10297 BTF_ID(func, bpf_obj_new_impl)
10298 BTF_ID(func, bpf_obj_drop_impl)
10299 BTF_ID(func, bpf_refcount_acquire_impl)
10300 BTF_ID(func, bpf_list_push_front_impl)
10301 BTF_ID(func, bpf_list_push_back_impl)
10302 BTF_ID(func, bpf_list_pop_front)
10303 BTF_ID(func, bpf_list_pop_back)
10304 BTF_ID(func, bpf_cast_to_kern_ctx)
10305 BTF_ID(func, bpf_rdonly_cast)
10306 BTF_ID(func, bpf_rcu_read_lock)
10307 BTF_ID(func, bpf_rcu_read_unlock)
10308 BTF_ID(func, bpf_rbtree_remove)
10309 BTF_ID(func, bpf_rbtree_add_impl)
10310 BTF_ID(func, bpf_rbtree_first)
10311 BTF_ID(func, bpf_dynptr_from_skb)
10312 BTF_ID(func, bpf_dynptr_from_xdp)
10313 BTF_ID(func, bpf_dynptr_slice)
10314 BTF_ID(func, bpf_dynptr_slice_rdwr)
10315 BTF_ID(func, bpf_dynptr_clone)
10317 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10319 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10320 meta->arg_owning_ref) {
10324 return meta->kfunc_flags & KF_RET_NULL;
10327 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10329 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10332 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10334 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10337 static enum kfunc_ptr_arg_type
10338 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10339 struct bpf_kfunc_call_arg_meta *meta,
10340 const struct btf_type *t, const struct btf_type *ref_t,
10341 const char *ref_tname, const struct btf_param *args,
10342 int argno, int nargs)
10344 u32 regno = argno + 1;
10345 struct bpf_reg_state *regs = cur_regs(env);
10346 struct bpf_reg_state *reg = ®s[regno];
10347 bool arg_mem_size = false;
10349 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10350 return KF_ARG_PTR_TO_CTX;
10352 /* In this function, we verify the kfunc's BTF as per the argument type,
10353 * leaving the rest of the verification with respect to the register
10354 * type to our caller. When a set of conditions hold in the BTF type of
10355 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10357 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10358 return KF_ARG_PTR_TO_CTX;
10360 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10361 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10363 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10364 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10366 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10367 return KF_ARG_PTR_TO_DYNPTR;
10369 if (is_kfunc_arg_iter(meta, argno))
10370 return KF_ARG_PTR_TO_ITER;
10372 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10373 return KF_ARG_PTR_TO_LIST_HEAD;
10375 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10376 return KF_ARG_PTR_TO_LIST_NODE;
10378 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10379 return KF_ARG_PTR_TO_RB_ROOT;
10381 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10382 return KF_ARG_PTR_TO_RB_NODE;
10384 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10385 if (!btf_type_is_struct(ref_t)) {
10386 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10387 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10390 return KF_ARG_PTR_TO_BTF_ID;
10393 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10394 return KF_ARG_PTR_TO_CALLBACK;
10397 if (argno + 1 < nargs &&
10398 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
10399 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
10400 arg_mem_size = true;
10402 /* This is the catch all argument type of register types supported by
10403 * check_helper_mem_access. However, we only allow when argument type is
10404 * pointer to scalar, or struct composed (recursively) of scalars. When
10405 * arg_mem_size is true, the pointer can be void *.
10407 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10408 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10409 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10410 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10413 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10416 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10417 struct bpf_reg_state *reg,
10418 const struct btf_type *ref_t,
10419 const char *ref_tname, u32 ref_id,
10420 struct bpf_kfunc_call_arg_meta *meta,
10423 const struct btf_type *reg_ref_t;
10424 bool strict_type_match = false;
10425 const struct btf *reg_btf;
10426 const char *reg_ref_tname;
10429 if (base_type(reg->type) == PTR_TO_BTF_ID) {
10430 reg_btf = reg->btf;
10431 reg_ref_id = reg->btf_id;
10433 reg_btf = btf_vmlinux;
10434 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10437 /* Enforce strict type matching for calls to kfuncs that are acquiring
10438 * or releasing a reference, or are no-cast aliases. We do _not_
10439 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10440 * as we want to enable BPF programs to pass types that are bitwise
10441 * equivalent without forcing them to explicitly cast with something
10442 * like bpf_cast_to_kern_ctx().
10444 * For example, say we had a type like the following:
10446 * struct bpf_cpumask {
10447 * cpumask_t cpumask;
10448 * refcount_t usage;
10451 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10452 * to a struct cpumask, so it would be safe to pass a struct
10453 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10455 * The philosophy here is similar to how we allow scalars of different
10456 * types to be passed to kfuncs as long as the size is the same. The
10457 * only difference here is that we're simply allowing
10458 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10461 if (is_kfunc_acquire(meta) ||
10462 (is_kfunc_release(meta) && reg->ref_obj_id) ||
10463 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10464 strict_type_match = true;
10466 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10468 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
10469 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10470 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10471 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10472 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10473 btf_type_str(reg_ref_t), reg_ref_tname);
10479 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10481 struct bpf_verifier_state *state = env->cur_state;
10483 if (!state->active_lock.ptr) {
10484 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10488 if (type_flag(reg->type) & NON_OWN_REF) {
10489 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10493 reg->type |= NON_OWN_REF;
10497 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10499 struct bpf_func_state *state, *unused;
10500 struct bpf_reg_state *reg;
10503 state = cur_func(env);
10506 verbose(env, "verifier internal error: ref_obj_id is zero for "
10507 "owning -> non-owning conversion\n");
10511 for (i = 0; i < state->acquired_refs; i++) {
10512 if (state->refs[i].id != ref_obj_id)
10515 /* Clear ref_obj_id here so release_reference doesn't clobber
10518 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10519 if (reg->ref_obj_id == ref_obj_id) {
10520 reg->ref_obj_id = 0;
10521 ref_set_non_owning(env, reg);
10527 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10531 /* Implementation details:
10533 * Each register points to some region of memory, which we define as an
10534 * allocation. Each allocation may embed a bpf_spin_lock which protects any
10535 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10536 * allocation. The lock and the data it protects are colocated in the same
10539 * Hence, everytime a register holds a pointer value pointing to such
10540 * allocation, the verifier preserves a unique reg->id for it.
10542 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10543 * bpf_spin_lock is called.
10545 * To enable this, lock state in the verifier captures two values:
10546 * active_lock.ptr = Register's type specific pointer
10547 * active_lock.id = A unique ID for each register pointer value
10549 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10550 * supported register types.
10552 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10553 * allocated objects is the reg->btf pointer.
10555 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10556 * can establish the provenance of the map value statically for each distinct
10557 * lookup into such maps. They always contain a single map value hence unique
10558 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10560 * So, in case of global variables, they use array maps with max_entries = 1,
10561 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10562 * into the same map value as max_entries is 1, as described above).
10564 * In case of inner map lookups, the inner map pointer has same map_ptr as the
10565 * outer map pointer (in verifier context), but each lookup into an inner map
10566 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10567 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10568 * will get different reg->id assigned to each lookup, hence different
10571 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10572 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10573 * returned from bpf_obj_new. Each allocation receives a new reg->id.
10575 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10580 switch ((int)reg->type) {
10581 case PTR_TO_MAP_VALUE:
10582 ptr = reg->map_ptr;
10584 case PTR_TO_BTF_ID | MEM_ALLOC:
10588 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10593 if (!env->cur_state->active_lock.ptr)
10595 if (env->cur_state->active_lock.ptr != ptr ||
10596 env->cur_state->active_lock.id != id) {
10597 verbose(env, "held lock and object are not in the same allocation\n");
10603 static bool is_bpf_list_api_kfunc(u32 btf_id)
10605 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10606 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10607 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10608 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10611 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10613 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10614 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10615 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10618 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10620 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10621 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10624 static bool is_callback_calling_kfunc(u32 btf_id)
10626 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10629 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10631 return is_bpf_rbtree_api_kfunc(btf_id);
10634 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10635 enum btf_field_type head_field_type,
10640 switch (head_field_type) {
10641 case BPF_LIST_HEAD:
10642 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10645 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10648 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10649 btf_field_type_name(head_field_type));
10654 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10655 btf_field_type_name(head_field_type));
10659 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10660 enum btf_field_type node_field_type,
10665 switch (node_field_type) {
10666 case BPF_LIST_NODE:
10667 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10668 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10671 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10672 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10675 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10676 btf_field_type_name(node_field_type));
10681 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10682 btf_field_type_name(node_field_type));
10687 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10688 struct bpf_reg_state *reg, u32 regno,
10689 struct bpf_kfunc_call_arg_meta *meta,
10690 enum btf_field_type head_field_type,
10691 struct btf_field **head_field)
10693 const char *head_type_name;
10694 struct btf_field *field;
10695 struct btf_record *rec;
10698 if (meta->btf != btf_vmlinux) {
10699 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10703 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10706 head_type_name = btf_field_type_name(head_field_type);
10707 if (!tnum_is_const(reg->var_off)) {
10709 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10710 regno, head_type_name);
10714 rec = reg_btf_record(reg);
10715 head_off = reg->off + reg->var_off.value;
10716 field = btf_record_find(rec, head_off, head_field_type);
10718 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10722 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10723 if (check_reg_allocation_locked(env, reg)) {
10724 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10725 rec->spin_lock_off, head_type_name);
10730 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10733 *head_field = field;
10737 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10738 struct bpf_reg_state *reg, u32 regno,
10739 struct bpf_kfunc_call_arg_meta *meta)
10741 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10742 &meta->arg_list_head.field);
10745 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10746 struct bpf_reg_state *reg, u32 regno,
10747 struct bpf_kfunc_call_arg_meta *meta)
10749 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10750 &meta->arg_rbtree_root.field);
10754 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10755 struct bpf_reg_state *reg, u32 regno,
10756 struct bpf_kfunc_call_arg_meta *meta,
10757 enum btf_field_type head_field_type,
10758 enum btf_field_type node_field_type,
10759 struct btf_field **node_field)
10761 const char *node_type_name;
10762 const struct btf_type *et, *t;
10763 struct btf_field *field;
10766 if (meta->btf != btf_vmlinux) {
10767 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10771 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10774 node_type_name = btf_field_type_name(node_field_type);
10775 if (!tnum_is_const(reg->var_off)) {
10777 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10778 regno, node_type_name);
10782 node_off = reg->off + reg->var_off.value;
10783 field = reg_find_field_offset(reg, node_off, node_field_type);
10784 if (!field || field->offset != node_off) {
10785 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10789 field = *node_field;
10791 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10792 t = btf_type_by_id(reg->btf, reg->btf_id);
10793 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10794 field->graph_root.value_btf_id, true)) {
10795 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10796 "in struct %s, but arg is at offset=%d in struct %s\n",
10797 btf_field_type_name(head_field_type),
10798 btf_field_type_name(node_field_type),
10799 field->graph_root.node_offset,
10800 btf_name_by_offset(field->graph_root.btf, et->name_off),
10801 node_off, btf_name_by_offset(reg->btf, t->name_off));
10804 meta->arg_btf = reg->btf;
10805 meta->arg_btf_id = reg->btf_id;
10807 if (node_off != field->graph_root.node_offset) {
10808 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10809 node_off, btf_field_type_name(node_field_type),
10810 field->graph_root.node_offset,
10811 btf_name_by_offset(field->graph_root.btf, et->name_off));
10818 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10819 struct bpf_reg_state *reg, u32 regno,
10820 struct bpf_kfunc_call_arg_meta *meta)
10822 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10823 BPF_LIST_HEAD, BPF_LIST_NODE,
10824 &meta->arg_list_head.field);
10827 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10828 struct bpf_reg_state *reg, u32 regno,
10829 struct bpf_kfunc_call_arg_meta *meta)
10831 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10832 BPF_RB_ROOT, BPF_RB_NODE,
10833 &meta->arg_rbtree_root.field);
10836 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10839 const char *func_name = meta->func_name, *ref_tname;
10840 const struct btf *btf = meta->btf;
10841 const struct btf_param *args;
10842 struct btf_record *rec;
10846 args = (const struct btf_param *)(meta->func_proto + 1);
10847 nargs = btf_type_vlen(meta->func_proto);
10848 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10849 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10850 MAX_BPF_FUNC_REG_ARGS);
10854 /* Check that BTF function arguments match actual types that the
10857 for (i = 0; i < nargs; i++) {
10858 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
10859 const struct btf_type *t, *ref_t, *resolve_ret;
10860 enum bpf_arg_type arg_type = ARG_DONTCARE;
10861 u32 regno = i + 1, ref_id, type_size;
10862 bool is_ret_buf_sz = false;
10865 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10867 if (is_kfunc_arg_ignore(btf, &args[i]))
10870 if (btf_type_is_scalar(t)) {
10871 if (reg->type != SCALAR_VALUE) {
10872 verbose(env, "R%d is not a scalar\n", regno);
10876 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10877 if (meta->arg_constant.found) {
10878 verbose(env, "verifier internal error: only one constant argument permitted\n");
10881 if (!tnum_is_const(reg->var_off)) {
10882 verbose(env, "R%d must be a known constant\n", regno);
10885 ret = mark_chain_precision(env, regno);
10888 meta->arg_constant.found = true;
10889 meta->arg_constant.value = reg->var_off.value;
10890 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10891 meta->r0_rdonly = true;
10892 is_ret_buf_sz = true;
10893 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10894 is_ret_buf_sz = true;
10897 if (is_ret_buf_sz) {
10898 if (meta->r0_size) {
10899 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10903 if (!tnum_is_const(reg->var_off)) {
10904 verbose(env, "R%d is not a const\n", regno);
10908 meta->r0_size = reg->var_off.value;
10909 ret = mark_chain_precision(env, regno);
10916 if (!btf_type_is_ptr(t)) {
10917 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10921 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10922 (register_is_null(reg) || type_may_be_null(reg->type))) {
10923 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10927 if (reg->ref_obj_id) {
10928 if (is_kfunc_release(meta) && meta->ref_obj_id) {
10929 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10930 regno, reg->ref_obj_id,
10934 meta->ref_obj_id = reg->ref_obj_id;
10935 if (is_kfunc_release(meta))
10936 meta->release_regno = regno;
10939 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10940 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10942 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10943 if (kf_arg_type < 0)
10944 return kf_arg_type;
10946 switch (kf_arg_type) {
10947 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10948 case KF_ARG_PTR_TO_BTF_ID:
10949 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10952 if (!is_trusted_reg(reg)) {
10953 if (!is_kfunc_rcu(meta)) {
10954 verbose(env, "R%d must be referenced or trusted\n", regno);
10957 if (!is_rcu_reg(reg)) {
10958 verbose(env, "R%d must be a rcu pointer\n", regno);
10964 case KF_ARG_PTR_TO_CTX:
10965 /* Trusted arguments have the same offset checks as release arguments */
10966 arg_type |= OBJ_RELEASE;
10968 case KF_ARG_PTR_TO_DYNPTR:
10969 case KF_ARG_PTR_TO_ITER:
10970 case KF_ARG_PTR_TO_LIST_HEAD:
10971 case KF_ARG_PTR_TO_LIST_NODE:
10972 case KF_ARG_PTR_TO_RB_ROOT:
10973 case KF_ARG_PTR_TO_RB_NODE:
10974 case KF_ARG_PTR_TO_MEM:
10975 case KF_ARG_PTR_TO_MEM_SIZE:
10976 case KF_ARG_PTR_TO_CALLBACK:
10977 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10978 /* Trusted by default */
10985 if (is_kfunc_release(meta) && reg->ref_obj_id)
10986 arg_type |= OBJ_RELEASE;
10987 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10991 switch (kf_arg_type) {
10992 case KF_ARG_PTR_TO_CTX:
10993 if (reg->type != PTR_TO_CTX) {
10994 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10998 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10999 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11002 meta->ret_btf_id = ret;
11005 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11006 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11007 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11010 if (!reg->ref_obj_id) {
11011 verbose(env, "allocated object must be referenced\n");
11014 if (meta->btf == btf_vmlinux &&
11015 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11016 meta->arg_btf = reg->btf;
11017 meta->arg_btf_id = reg->btf_id;
11020 case KF_ARG_PTR_TO_DYNPTR:
11022 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11023 int clone_ref_obj_id = 0;
11025 if (reg->type != PTR_TO_STACK &&
11026 reg->type != CONST_PTR_TO_DYNPTR) {
11027 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11031 if (reg->type == CONST_PTR_TO_DYNPTR)
11032 dynptr_arg_type |= MEM_RDONLY;
11034 if (is_kfunc_arg_uninit(btf, &args[i]))
11035 dynptr_arg_type |= MEM_UNINIT;
11037 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11038 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11039 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11040 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11041 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11042 (dynptr_arg_type & MEM_UNINIT)) {
11043 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11045 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11046 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11050 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11051 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11052 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11053 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11058 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11062 if (!(dynptr_arg_type & MEM_UNINIT)) {
11063 int id = dynptr_id(env, reg);
11066 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11069 meta->initialized_dynptr.id = id;
11070 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11071 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11076 case KF_ARG_PTR_TO_ITER:
11077 ret = process_iter_arg(env, regno, insn_idx, meta);
11081 case KF_ARG_PTR_TO_LIST_HEAD:
11082 if (reg->type != PTR_TO_MAP_VALUE &&
11083 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11084 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11087 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11088 verbose(env, "allocated object must be referenced\n");
11091 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11095 case KF_ARG_PTR_TO_RB_ROOT:
11096 if (reg->type != PTR_TO_MAP_VALUE &&
11097 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11098 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11101 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11102 verbose(env, "allocated object must be referenced\n");
11105 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11109 case KF_ARG_PTR_TO_LIST_NODE:
11110 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11111 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11114 if (!reg->ref_obj_id) {
11115 verbose(env, "allocated object must be referenced\n");
11118 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11122 case KF_ARG_PTR_TO_RB_NODE:
11123 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11124 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11125 verbose(env, "rbtree_remove node input must be non-owning ref\n");
11128 if (in_rbtree_lock_required_cb(env)) {
11129 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11133 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11134 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11137 if (!reg->ref_obj_id) {
11138 verbose(env, "allocated object must be referenced\n");
11143 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11147 case KF_ARG_PTR_TO_BTF_ID:
11148 /* Only base_type is checked, further checks are done here */
11149 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11150 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11151 !reg2btf_ids[base_type(reg->type)]) {
11152 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11153 verbose(env, "expected %s or socket\n",
11154 reg_type_str(env, base_type(reg->type) |
11155 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11158 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11162 case KF_ARG_PTR_TO_MEM:
11163 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11164 if (IS_ERR(resolve_ret)) {
11165 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11166 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11169 ret = check_mem_reg(env, reg, regno, type_size);
11173 case KF_ARG_PTR_TO_MEM_SIZE:
11175 struct bpf_reg_state *buff_reg = ®s[regno];
11176 const struct btf_param *buff_arg = &args[i];
11177 struct bpf_reg_state *size_reg = ®s[regno + 1];
11178 const struct btf_param *size_arg = &args[i + 1];
11180 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11181 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11183 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11188 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11189 if (meta->arg_constant.found) {
11190 verbose(env, "verifier internal error: only one constant argument permitted\n");
11193 if (!tnum_is_const(size_reg->var_off)) {
11194 verbose(env, "R%d must be a known constant\n", regno + 1);
11197 meta->arg_constant.found = true;
11198 meta->arg_constant.value = size_reg->var_off.value;
11201 /* Skip next '__sz' or '__szk' argument */
11205 case KF_ARG_PTR_TO_CALLBACK:
11206 meta->subprogno = reg->subprogno;
11208 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11209 if (!type_is_ptr_alloc_obj(reg->type)) {
11210 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11213 if (!type_is_non_owning_ref(reg->type))
11214 meta->arg_owning_ref = true;
11216 rec = reg_btf_record(reg);
11218 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11222 if (rec->refcount_off < 0) {
11223 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11226 if (rec->refcount_off >= 0) {
11227 verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
11230 meta->arg_btf = reg->btf;
11231 meta->arg_btf_id = reg->btf_id;
11236 if (is_kfunc_release(meta) && !meta->release_regno) {
11237 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11245 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11246 struct bpf_insn *insn,
11247 struct bpf_kfunc_call_arg_meta *meta,
11248 const char **kfunc_name)
11250 const struct btf_type *func, *func_proto;
11251 u32 func_id, *kfunc_flags;
11252 const char *func_name;
11253 struct btf *desc_btf;
11256 *kfunc_name = NULL;
11261 desc_btf = find_kfunc_desc_btf(env, insn->off);
11262 if (IS_ERR(desc_btf))
11263 return PTR_ERR(desc_btf);
11265 func_id = insn->imm;
11266 func = btf_type_by_id(desc_btf, func_id);
11267 func_name = btf_name_by_offset(desc_btf, func->name_off);
11269 *kfunc_name = func_name;
11270 func_proto = btf_type_by_id(desc_btf, func->type);
11272 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11273 if (!kfunc_flags) {
11277 memset(meta, 0, sizeof(*meta));
11278 meta->btf = desc_btf;
11279 meta->func_id = func_id;
11280 meta->kfunc_flags = *kfunc_flags;
11281 meta->func_proto = func_proto;
11282 meta->func_name = func_name;
11287 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11290 const struct btf_type *t, *ptr_type;
11291 u32 i, nargs, ptr_type_id, release_ref_obj_id;
11292 struct bpf_reg_state *regs = cur_regs(env);
11293 const char *func_name, *ptr_type_name;
11294 bool sleepable, rcu_lock, rcu_unlock;
11295 struct bpf_kfunc_call_arg_meta meta;
11296 struct bpf_insn_aux_data *insn_aux;
11297 int err, insn_idx = *insn_idx_p;
11298 const struct btf_param *args;
11299 const struct btf_type *ret_t;
11300 struct btf *desc_btf;
11302 /* skip for now, but return error when we find this in fixup_kfunc_call */
11306 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11307 if (err == -EACCES && func_name)
11308 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11311 desc_btf = meta.btf;
11312 insn_aux = &env->insn_aux_data[insn_idx];
11314 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11316 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11317 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11321 sleepable = is_kfunc_sleepable(&meta);
11322 if (sleepable && !env->prog->aux->sleepable) {
11323 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11327 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11328 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11330 if (env->cur_state->active_rcu_lock) {
11331 struct bpf_func_state *state;
11332 struct bpf_reg_state *reg;
11335 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11337 } else if (rcu_unlock) {
11338 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11339 if (reg->type & MEM_RCU) {
11340 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11341 reg->type |= PTR_UNTRUSTED;
11344 env->cur_state->active_rcu_lock = false;
11345 } else if (sleepable) {
11346 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11349 } else if (rcu_lock) {
11350 env->cur_state->active_rcu_lock = true;
11351 } else if (rcu_unlock) {
11352 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11356 /* Check the arguments */
11357 err = check_kfunc_args(env, &meta, insn_idx);
11360 /* In case of release function, we get register number of refcounted
11361 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11363 if (meta.release_regno) {
11364 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11366 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11367 func_name, meta.func_id);
11372 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11373 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11374 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11375 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11376 insn_aux->insert_off = regs[BPF_REG_2].off;
11377 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11378 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11380 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11381 func_name, meta.func_id);
11385 err = release_reference(env, release_ref_obj_id);
11387 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11388 func_name, meta.func_id);
11393 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11394 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11395 set_rbtree_add_callback_state);
11397 verbose(env, "kfunc %s#%d failed callback verification\n",
11398 func_name, meta.func_id);
11403 for (i = 0; i < CALLER_SAVED_REGS; i++)
11404 mark_reg_not_init(env, regs, caller_saved[i]);
11406 /* Check return type */
11407 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11409 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11410 /* Only exception is bpf_obj_new_impl */
11411 if (meta.btf != btf_vmlinux ||
11412 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11413 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11414 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11419 if (btf_type_is_scalar(t)) {
11420 mark_reg_unknown(env, regs, BPF_REG_0);
11421 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11422 } else if (btf_type_is_ptr(t)) {
11423 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11425 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11426 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11427 struct btf *ret_btf;
11430 if (unlikely(!bpf_global_ma_set))
11433 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11434 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11438 ret_btf = env->prog->aux->btf;
11439 ret_btf_id = meta.arg_constant.value;
11441 /* This may be NULL due to user not supplying a BTF */
11443 verbose(env, "bpf_obj_new requires prog BTF\n");
11447 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11448 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11449 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11453 mark_reg_known_zero(env, regs, BPF_REG_0);
11454 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11455 regs[BPF_REG_0].btf = ret_btf;
11456 regs[BPF_REG_0].btf_id = ret_btf_id;
11458 insn_aux->obj_new_size = ret_t->size;
11459 insn_aux->kptr_struct_meta =
11460 btf_find_struct_meta(ret_btf, ret_btf_id);
11461 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11462 mark_reg_known_zero(env, regs, BPF_REG_0);
11463 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11464 regs[BPF_REG_0].btf = meta.arg_btf;
11465 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11467 insn_aux->kptr_struct_meta =
11468 btf_find_struct_meta(meta.arg_btf,
11470 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11471 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11472 struct btf_field *field = meta.arg_list_head.field;
11474 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11475 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11476 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11477 struct btf_field *field = meta.arg_rbtree_root.field;
11479 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11480 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11481 mark_reg_known_zero(env, regs, BPF_REG_0);
11482 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11483 regs[BPF_REG_0].btf = desc_btf;
11484 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11485 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11486 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11487 if (!ret_t || !btf_type_is_struct(ret_t)) {
11489 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11493 mark_reg_known_zero(env, regs, BPF_REG_0);
11494 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11495 regs[BPF_REG_0].btf = desc_btf;
11496 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11497 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11498 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11499 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11501 mark_reg_known_zero(env, regs, BPF_REG_0);
11503 if (!meta.arg_constant.found) {
11504 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11508 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11510 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11511 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11513 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11514 regs[BPF_REG_0].type |= MEM_RDONLY;
11516 /* this will set env->seen_direct_write to true */
11517 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11518 verbose(env, "the prog does not allow writes to packet data\n");
11523 if (!meta.initialized_dynptr.id) {
11524 verbose(env, "verifier internal error: no dynptr id\n");
11527 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11529 /* we don't need to set BPF_REG_0's ref obj id
11530 * because packet slices are not refcounted (see
11531 * dynptr_type_refcounted)
11534 verbose(env, "kernel function %s unhandled dynamic return type\n",
11538 } else if (!__btf_type_is_struct(ptr_type)) {
11539 if (!meta.r0_size) {
11542 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11544 meta.r0_rdonly = true;
11547 if (!meta.r0_size) {
11548 ptr_type_name = btf_name_by_offset(desc_btf,
11549 ptr_type->name_off);
11551 "kernel function %s returns pointer type %s %s is not supported\n",
11553 btf_type_str(ptr_type),
11558 mark_reg_known_zero(env, regs, BPF_REG_0);
11559 regs[BPF_REG_0].type = PTR_TO_MEM;
11560 regs[BPF_REG_0].mem_size = meta.r0_size;
11562 if (meta.r0_rdonly)
11563 regs[BPF_REG_0].type |= MEM_RDONLY;
11565 /* Ensures we don't access the memory after a release_reference() */
11566 if (meta.ref_obj_id)
11567 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11569 mark_reg_known_zero(env, regs, BPF_REG_0);
11570 regs[BPF_REG_0].btf = desc_btf;
11571 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11572 regs[BPF_REG_0].btf_id = ptr_type_id;
11575 if (is_kfunc_ret_null(&meta)) {
11576 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11577 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11578 regs[BPF_REG_0].id = ++env->id_gen;
11580 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11581 if (is_kfunc_acquire(&meta)) {
11582 int id = acquire_reference_state(env, insn_idx);
11586 if (is_kfunc_ret_null(&meta))
11587 regs[BPF_REG_0].id = id;
11588 regs[BPF_REG_0].ref_obj_id = id;
11589 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11590 ref_set_non_owning(env, ®s[BPF_REG_0]);
11593 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
11594 regs[BPF_REG_0].id = ++env->id_gen;
11595 } else if (btf_type_is_void(t)) {
11596 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11597 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11598 insn_aux->kptr_struct_meta =
11599 btf_find_struct_meta(meta.arg_btf,
11605 nargs = btf_type_vlen(meta.func_proto);
11606 args = (const struct btf_param *)(meta.func_proto + 1);
11607 for (i = 0; i < nargs; i++) {
11610 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11611 if (btf_type_is_ptr(t))
11612 mark_btf_func_reg_size(env, regno, sizeof(void *));
11614 /* scalar. ensured by btf_check_kfunc_arg_match() */
11615 mark_btf_func_reg_size(env, regno, t->size);
11618 if (is_iter_next_kfunc(&meta)) {
11619 err = process_iter_next_call(env, insn_idx, &meta);
11627 static bool signed_add_overflows(s64 a, s64 b)
11629 /* Do the add in u64, where overflow is well-defined */
11630 s64 res = (s64)((u64)a + (u64)b);
11637 static bool signed_add32_overflows(s32 a, s32 b)
11639 /* Do the add in u32, where overflow is well-defined */
11640 s32 res = (s32)((u32)a + (u32)b);
11647 static bool signed_sub_overflows(s64 a, s64 b)
11649 /* Do the sub in u64, where overflow is well-defined */
11650 s64 res = (s64)((u64)a - (u64)b);
11657 static bool signed_sub32_overflows(s32 a, s32 b)
11659 /* Do the sub in u32, where overflow is well-defined */
11660 s32 res = (s32)((u32)a - (u32)b);
11667 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11668 const struct bpf_reg_state *reg,
11669 enum bpf_reg_type type)
11671 bool known = tnum_is_const(reg->var_off);
11672 s64 val = reg->var_off.value;
11673 s64 smin = reg->smin_value;
11675 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11676 verbose(env, "math between %s pointer and %lld is not allowed\n",
11677 reg_type_str(env, type), val);
11681 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11682 verbose(env, "%s pointer offset %d is not allowed\n",
11683 reg_type_str(env, type), reg->off);
11687 if (smin == S64_MIN) {
11688 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11689 reg_type_str(env, type));
11693 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11694 verbose(env, "value %lld makes %s pointer be out of bounds\n",
11695 smin, reg_type_str(env, type));
11703 REASON_BOUNDS = -1,
11710 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11711 u32 *alu_limit, bool mask_to_left)
11713 u32 max = 0, ptr_limit = 0;
11715 switch (ptr_reg->type) {
11717 /* Offset 0 is out-of-bounds, but acceptable start for the
11718 * left direction, see BPF_REG_FP. Also, unknown scalar
11719 * offset where we would need to deal with min/max bounds is
11720 * currently prohibited for unprivileged.
11722 max = MAX_BPF_STACK + mask_to_left;
11723 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11725 case PTR_TO_MAP_VALUE:
11726 max = ptr_reg->map_ptr->value_size;
11727 ptr_limit = (mask_to_left ?
11728 ptr_reg->smin_value :
11729 ptr_reg->umax_value) + ptr_reg->off;
11732 return REASON_TYPE;
11735 if (ptr_limit >= max)
11736 return REASON_LIMIT;
11737 *alu_limit = ptr_limit;
11741 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11742 const struct bpf_insn *insn)
11744 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11747 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11748 u32 alu_state, u32 alu_limit)
11750 /* If we arrived here from different branches with different
11751 * state or limits to sanitize, then this won't work.
11753 if (aux->alu_state &&
11754 (aux->alu_state != alu_state ||
11755 aux->alu_limit != alu_limit))
11756 return REASON_PATHS;
11758 /* Corresponding fixup done in do_misc_fixups(). */
11759 aux->alu_state = alu_state;
11760 aux->alu_limit = alu_limit;
11764 static int sanitize_val_alu(struct bpf_verifier_env *env,
11765 struct bpf_insn *insn)
11767 struct bpf_insn_aux_data *aux = cur_aux(env);
11769 if (can_skip_alu_sanitation(env, insn))
11772 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11775 static bool sanitize_needed(u8 opcode)
11777 return opcode == BPF_ADD || opcode == BPF_SUB;
11780 struct bpf_sanitize_info {
11781 struct bpf_insn_aux_data aux;
11785 static struct bpf_verifier_state *
11786 sanitize_speculative_path(struct bpf_verifier_env *env,
11787 const struct bpf_insn *insn,
11788 u32 next_idx, u32 curr_idx)
11790 struct bpf_verifier_state *branch;
11791 struct bpf_reg_state *regs;
11793 branch = push_stack(env, next_idx, curr_idx, true);
11794 if (branch && insn) {
11795 regs = branch->frame[branch->curframe]->regs;
11796 if (BPF_SRC(insn->code) == BPF_K) {
11797 mark_reg_unknown(env, regs, insn->dst_reg);
11798 } else if (BPF_SRC(insn->code) == BPF_X) {
11799 mark_reg_unknown(env, regs, insn->dst_reg);
11800 mark_reg_unknown(env, regs, insn->src_reg);
11806 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11807 struct bpf_insn *insn,
11808 const struct bpf_reg_state *ptr_reg,
11809 const struct bpf_reg_state *off_reg,
11810 struct bpf_reg_state *dst_reg,
11811 struct bpf_sanitize_info *info,
11812 const bool commit_window)
11814 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11815 struct bpf_verifier_state *vstate = env->cur_state;
11816 bool off_is_imm = tnum_is_const(off_reg->var_off);
11817 bool off_is_neg = off_reg->smin_value < 0;
11818 bool ptr_is_dst_reg = ptr_reg == dst_reg;
11819 u8 opcode = BPF_OP(insn->code);
11820 u32 alu_state, alu_limit;
11821 struct bpf_reg_state tmp;
11825 if (can_skip_alu_sanitation(env, insn))
11828 /* We already marked aux for masking from non-speculative
11829 * paths, thus we got here in the first place. We only care
11830 * to explore bad access from here.
11832 if (vstate->speculative)
11835 if (!commit_window) {
11836 if (!tnum_is_const(off_reg->var_off) &&
11837 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11838 return REASON_BOUNDS;
11840 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
11841 (opcode == BPF_SUB && !off_is_neg);
11844 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11848 if (commit_window) {
11849 /* In commit phase we narrow the masking window based on
11850 * the observed pointer move after the simulated operation.
11852 alu_state = info->aux.alu_state;
11853 alu_limit = abs(info->aux.alu_limit - alu_limit);
11855 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11856 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11857 alu_state |= ptr_is_dst_reg ?
11858 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11860 /* Limit pruning on unknown scalars to enable deep search for
11861 * potential masking differences from other program paths.
11864 env->explore_alu_limits = true;
11867 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11871 /* If we're in commit phase, we're done here given we already
11872 * pushed the truncated dst_reg into the speculative verification
11875 * Also, when register is a known constant, we rewrite register-based
11876 * operation to immediate-based, and thus do not need masking (and as
11877 * a consequence, do not need to simulate the zero-truncation either).
11879 if (commit_window || off_is_imm)
11882 /* Simulate and find potential out-of-bounds access under
11883 * speculative execution from truncation as a result of
11884 * masking when off was not within expected range. If off
11885 * sits in dst, then we temporarily need to move ptr there
11886 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11887 * for cases where we use K-based arithmetic in one direction
11888 * and truncated reg-based in the other in order to explore
11891 if (!ptr_is_dst_reg) {
11893 copy_register_state(dst_reg, ptr_reg);
11895 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11897 if (!ptr_is_dst_reg && ret)
11899 return !ret ? REASON_STACK : 0;
11902 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11904 struct bpf_verifier_state *vstate = env->cur_state;
11906 /* If we simulate paths under speculation, we don't update the
11907 * insn as 'seen' such that when we verify unreachable paths in
11908 * the non-speculative domain, sanitize_dead_code() can still
11909 * rewrite/sanitize them.
11911 if (!vstate->speculative)
11912 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11915 static int sanitize_err(struct bpf_verifier_env *env,
11916 const struct bpf_insn *insn, int reason,
11917 const struct bpf_reg_state *off_reg,
11918 const struct bpf_reg_state *dst_reg)
11920 static const char *err = "pointer arithmetic with it prohibited for !root";
11921 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11922 u32 dst = insn->dst_reg, src = insn->src_reg;
11925 case REASON_BOUNDS:
11926 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11927 off_reg == dst_reg ? dst : src, err);
11930 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11931 off_reg == dst_reg ? src : dst, err);
11934 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11938 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11942 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11946 verbose(env, "verifier internal error: unknown reason (%d)\n",
11954 /* check that stack access falls within stack limits and that 'reg' doesn't
11955 * have a variable offset.
11957 * Variable offset is prohibited for unprivileged mode for simplicity since it
11958 * requires corresponding support in Spectre masking for stack ALU. See also
11959 * retrieve_ptr_limit().
11962 * 'off' includes 'reg->off'.
11964 static int check_stack_access_for_ptr_arithmetic(
11965 struct bpf_verifier_env *env,
11967 const struct bpf_reg_state *reg,
11970 if (!tnum_is_const(reg->var_off)) {
11973 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11974 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11975 regno, tn_buf, off);
11979 if (off >= 0 || off < -MAX_BPF_STACK) {
11980 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11981 "prohibited for !root; off=%d\n", regno, off);
11988 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11989 const struct bpf_insn *insn,
11990 const struct bpf_reg_state *dst_reg)
11992 u32 dst = insn->dst_reg;
11994 /* For unprivileged we require that resulting offset must be in bounds
11995 * in order to be able to sanitize access later on.
11997 if (env->bypass_spec_v1)
12000 switch (dst_reg->type) {
12002 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12003 dst_reg->off + dst_reg->var_off.value))
12006 case PTR_TO_MAP_VALUE:
12007 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12008 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12009 "prohibited for !root\n", dst);
12020 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12021 * Caller should also handle BPF_MOV case separately.
12022 * If we return -EACCES, caller may want to try again treating pointer as a
12023 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
12025 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12026 struct bpf_insn *insn,
12027 const struct bpf_reg_state *ptr_reg,
12028 const struct bpf_reg_state *off_reg)
12030 struct bpf_verifier_state *vstate = env->cur_state;
12031 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12032 struct bpf_reg_state *regs = state->regs, *dst_reg;
12033 bool known = tnum_is_const(off_reg->var_off);
12034 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12035 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12036 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12037 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12038 struct bpf_sanitize_info info = {};
12039 u8 opcode = BPF_OP(insn->code);
12040 u32 dst = insn->dst_reg;
12043 dst_reg = ®s[dst];
12045 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12046 smin_val > smax_val || umin_val > umax_val) {
12047 /* Taint dst register if offset had invalid bounds derived from
12048 * e.g. dead branches.
12050 __mark_reg_unknown(env, dst_reg);
12054 if (BPF_CLASS(insn->code) != BPF_ALU64) {
12055 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12056 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12057 __mark_reg_unknown(env, dst_reg);
12062 "R%d 32-bit pointer arithmetic prohibited\n",
12067 if (ptr_reg->type & PTR_MAYBE_NULL) {
12068 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12069 dst, reg_type_str(env, ptr_reg->type));
12073 switch (base_type(ptr_reg->type)) {
12074 case CONST_PTR_TO_MAP:
12075 /* smin_val represents the known value */
12076 if (known && smin_val == 0 && opcode == BPF_ADD)
12079 case PTR_TO_PACKET_END:
12080 case PTR_TO_SOCKET:
12081 case PTR_TO_SOCK_COMMON:
12082 case PTR_TO_TCP_SOCK:
12083 case PTR_TO_XDP_SOCK:
12084 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12085 dst, reg_type_str(env, ptr_reg->type));
12091 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12092 * The id may be overwritten later if we create a new variable offset.
12094 dst_reg->type = ptr_reg->type;
12095 dst_reg->id = ptr_reg->id;
12097 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12098 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12101 /* pointer types do not carry 32-bit bounds at the moment. */
12102 __mark_reg32_unbounded(dst_reg);
12104 if (sanitize_needed(opcode)) {
12105 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12108 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12113 /* We can take a fixed offset as long as it doesn't overflow
12114 * the s32 'off' field
12116 if (known && (ptr_reg->off + smin_val ==
12117 (s64)(s32)(ptr_reg->off + smin_val))) {
12118 /* pointer += K. Accumulate it into fixed offset */
12119 dst_reg->smin_value = smin_ptr;
12120 dst_reg->smax_value = smax_ptr;
12121 dst_reg->umin_value = umin_ptr;
12122 dst_reg->umax_value = umax_ptr;
12123 dst_reg->var_off = ptr_reg->var_off;
12124 dst_reg->off = ptr_reg->off + smin_val;
12125 dst_reg->raw = ptr_reg->raw;
12128 /* A new variable offset is created. Note that off_reg->off
12129 * == 0, since it's a scalar.
12130 * dst_reg gets the pointer type and since some positive
12131 * integer value was added to the pointer, give it a new 'id'
12132 * if it's a PTR_TO_PACKET.
12133 * this creates a new 'base' pointer, off_reg (variable) gets
12134 * added into the variable offset, and we copy the fixed offset
12137 if (signed_add_overflows(smin_ptr, smin_val) ||
12138 signed_add_overflows(smax_ptr, smax_val)) {
12139 dst_reg->smin_value = S64_MIN;
12140 dst_reg->smax_value = S64_MAX;
12142 dst_reg->smin_value = smin_ptr + smin_val;
12143 dst_reg->smax_value = smax_ptr + smax_val;
12145 if (umin_ptr + umin_val < umin_ptr ||
12146 umax_ptr + umax_val < umax_ptr) {
12147 dst_reg->umin_value = 0;
12148 dst_reg->umax_value = U64_MAX;
12150 dst_reg->umin_value = umin_ptr + umin_val;
12151 dst_reg->umax_value = umax_ptr + umax_val;
12153 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12154 dst_reg->off = ptr_reg->off;
12155 dst_reg->raw = ptr_reg->raw;
12156 if (reg_is_pkt_pointer(ptr_reg)) {
12157 dst_reg->id = ++env->id_gen;
12158 /* something was added to pkt_ptr, set range to zero */
12159 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12163 if (dst_reg == off_reg) {
12164 /* scalar -= pointer. Creates an unknown scalar */
12165 verbose(env, "R%d tried to subtract pointer from scalar\n",
12169 /* We don't allow subtraction from FP, because (according to
12170 * test_verifier.c test "invalid fp arithmetic", JITs might not
12171 * be able to deal with it.
12173 if (ptr_reg->type == PTR_TO_STACK) {
12174 verbose(env, "R%d subtraction from stack pointer prohibited\n",
12178 if (known && (ptr_reg->off - smin_val ==
12179 (s64)(s32)(ptr_reg->off - smin_val))) {
12180 /* pointer -= K. Subtract it from fixed offset */
12181 dst_reg->smin_value = smin_ptr;
12182 dst_reg->smax_value = smax_ptr;
12183 dst_reg->umin_value = umin_ptr;
12184 dst_reg->umax_value = umax_ptr;
12185 dst_reg->var_off = ptr_reg->var_off;
12186 dst_reg->id = ptr_reg->id;
12187 dst_reg->off = ptr_reg->off - smin_val;
12188 dst_reg->raw = ptr_reg->raw;
12191 /* A new variable offset is created. If the subtrahend is known
12192 * nonnegative, then any reg->range we had before is still good.
12194 if (signed_sub_overflows(smin_ptr, smax_val) ||
12195 signed_sub_overflows(smax_ptr, smin_val)) {
12196 /* Overflow possible, we know nothing */
12197 dst_reg->smin_value = S64_MIN;
12198 dst_reg->smax_value = S64_MAX;
12200 dst_reg->smin_value = smin_ptr - smax_val;
12201 dst_reg->smax_value = smax_ptr - smin_val;
12203 if (umin_ptr < umax_val) {
12204 /* Overflow possible, we know nothing */
12205 dst_reg->umin_value = 0;
12206 dst_reg->umax_value = U64_MAX;
12208 /* Cannot overflow (as long as bounds are consistent) */
12209 dst_reg->umin_value = umin_ptr - umax_val;
12210 dst_reg->umax_value = umax_ptr - umin_val;
12212 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12213 dst_reg->off = ptr_reg->off;
12214 dst_reg->raw = ptr_reg->raw;
12215 if (reg_is_pkt_pointer(ptr_reg)) {
12216 dst_reg->id = ++env->id_gen;
12217 /* something was added to pkt_ptr, set range to zero */
12219 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12225 /* bitwise ops on pointers are troublesome, prohibit. */
12226 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12227 dst, bpf_alu_string[opcode >> 4]);
12230 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12231 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12232 dst, bpf_alu_string[opcode >> 4]);
12236 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12238 reg_bounds_sync(dst_reg);
12239 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12241 if (sanitize_needed(opcode)) {
12242 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12245 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12251 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12252 struct bpf_reg_state *src_reg)
12254 s32 smin_val = src_reg->s32_min_value;
12255 s32 smax_val = src_reg->s32_max_value;
12256 u32 umin_val = src_reg->u32_min_value;
12257 u32 umax_val = src_reg->u32_max_value;
12259 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12260 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12261 dst_reg->s32_min_value = S32_MIN;
12262 dst_reg->s32_max_value = S32_MAX;
12264 dst_reg->s32_min_value += smin_val;
12265 dst_reg->s32_max_value += smax_val;
12267 if (dst_reg->u32_min_value + umin_val < umin_val ||
12268 dst_reg->u32_max_value + umax_val < umax_val) {
12269 dst_reg->u32_min_value = 0;
12270 dst_reg->u32_max_value = U32_MAX;
12272 dst_reg->u32_min_value += umin_val;
12273 dst_reg->u32_max_value += umax_val;
12277 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12278 struct bpf_reg_state *src_reg)
12280 s64 smin_val = src_reg->smin_value;
12281 s64 smax_val = src_reg->smax_value;
12282 u64 umin_val = src_reg->umin_value;
12283 u64 umax_val = src_reg->umax_value;
12285 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12286 signed_add_overflows(dst_reg->smax_value, smax_val)) {
12287 dst_reg->smin_value = S64_MIN;
12288 dst_reg->smax_value = S64_MAX;
12290 dst_reg->smin_value += smin_val;
12291 dst_reg->smax_value += smax_val;
12293 if (dst_reg->umin_value + umin_val < umin_val ||
12294 dst_reg->umax_value + umax_val < umax_val) {
12295 dst_reg->umin_value = 0;
12296 dst_reg->umax_value = U64_MAX;
12298 dst_reg->umin_value += umin_val;
12299 dst_reg->umax_value += umax_val;
12303 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12304 struct bpf_reg_state *src_reg)
12306 s32 smin_val = src_reg->s32_min_value;
12307 s32 smax_val = src_reg->s32_max_value;
12308 u32 umin_val = src_reg->u32_min_value;
12309 u32 umax_val = src_reg->u32_max_value;
12311 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12312 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12313 /* Overflow possible, we know nothing */
12314 dst_reg->s32_min_value = S32_MIN;
12315 dst_reg->s32_max_value = S32_MAX;
12317 dst_reg->s32_min_value -= smax_val;
12318 dst_reg->s32_max_value -= smin_val;
12320 if (dst_reg->u32_min_value < umax_val) {
12321 /* Overflow possible, we know nothing */
12322 dst_reg->u32_min_value = 0;
12323 dst_reg->u32_max_value = U32_MAX;
12325 /* Cannot overflow (as long as bounds are consistent) */
12326 dst_reg->u32_min_value -= umax_val;
12327 dst_reg->u32_max_value -= umin_val;
12331 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12332 struct bpf_reg_state *src_reg)
12334 s64 smin_val = src_reg->smin_value;
12335 s64 smax_val = src_reg->smax_value;
12336 u64 umin_val = src_reg->umin_value;
12337 u64 umax_val = src_reg->umax_value;
12339 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12340 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12341 /* Overflow possible, we know nothing */
12342 dst_reg->smin_value = S64_MIN;
12343 dst_reg->smax_value = S64_MAX;
12345 dst_reg->smin_value -= smax_val;
12346 dst_reg->smax_value -= smin_val;
12348 if (dst_reg->umin_value < umax_val) {
12349 /* Overflow possible, we know nothing */
12350 dst_reg->umin_value = 0;
12351 dst_reg->umax_value = U64_MAX;
12353 /* Cannot overflow (as long as bounds are consistent) */
12354 dst_reg->umin_value -= umax_val;
12355 dst_reg->umax_value -= umin_val;
12359 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12360 struct bpf_reg_state *src_reg)
12362 s32 smin_val = src_reg->s32_min_value;
12363 u32 umin_val = src_reg->u32_min_value;
12364 u32 umax_val = src_reg->u32_max_value;
12366 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12367 /* Ain't nobody got time to multiply that sign */
12368 __mark_reg32_unbounded(dst_reg);
12371 /* Both values are positive, so we can work with unsigned and
12372 * copy the result to signed (unless it exceeds S32_MAX).
12374 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12375 /* Potential overflow, we know nothing */
12376 __mark_reg32_unbounded(dst_reg);
12379 dst_reg->u32_min_value *= umin_val;
12380 dst_reg->u32_max_value *= umax_val;
12381 if (dst_reg->u32_max_value > S32_MAX) {
12382 /* Overflow possible, we know nothing */
12383 dst_reg->s32_min_value = S32_MIN;
12384 dst_reg->s32_max_value = S32_MAX;
12386 dst_reg->s32_min_value = dst_reg->u32_min_value;
12387 dst_reg->s32_max_value = dst_reg->u32_max_value;
12391 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12392 struct bpf_reg_state *src_reg)
12394 s64 smin_val = src_reg->smin_value;
12395 u64 umin_val = src_reg->umin_value;
12396 u64 umax_val = src_reg->umax_value;
12398 if (smin_val < 0 || dst_reg->smin_value < 0) {
12399 /* Ain't nobody got time to multiply that sign */
12400 __mark_reg64_unbounded(dst_reg);
12403 /* Both values are positive, so we can work with unsigned and
12404 * copy the result to signed (unless it exceeds S64_MAX).
12406 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12407 /* Potential overflow, we know nothing */
12408 __mark_reg64_unbounded(dst_reg);
12411 dst_reg->umin_value *= umin_val;
12412 dst_reg->umax_value *= umax_val;
12413 if (dst_reg->umax_value > S64_MAX) {
12414 /* Overflow possible, we know nothing */
12415 dst_reg->smin_value = S64_MIN;
12416 dst_reg->smax_value = S64_MAX;
12418 dst_reg->smin_value = dst_reg->umin_value;
12419 dst_reg->smax_value = dst_reg->umax_value;
12423 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12424 struct bpf_reg_state *src_reg)
12426 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12427 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12428 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12429 s32 smin_val = src_reg->s32_min_value;
12430 u32 umax_val = src_reg->u32_max_value;
12432 if (src_known && dst_known) {
12433 __mark_reg32_known(dst_reg, var32_off.value);
12437 /* We get our minimum from the var_off, since that's inherently
12438 * bitwise. Our maximum is the minimum of the operands' maxima.
12440 dst_reg->u32_min_value = var32_off.value;
12441 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12442 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12443 /* Lose signed bounds when ANDing negative numbers,
12444 * ain't nobody got time for that.
12446 dst_reg->s32_min_value = S32_MIN;
12447 dst_reg->s32_max_value = S32_MAX;
12449 /* ANDing two positives gives a positive, so safe to
12450 * cast result into s64.
12452 dst_reg->s32_min_value = dst_reg->u32_min_value;
12453 dst_reg->s32_max_value = dst_reg->u32_max_value;
12457 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12458 struct bpf_reg_state *src_reg)
12460 bool src_known = tnum_is_const(src_reg->var_off);
12461 bool dst_known = tnum_is_const(dst_reg->var_off);
12462 s64 smin_val = src_reg->smin_value;
12463 u64 umax_val = src_reg->umax_value;
12465 if (src_known && dst_known) {
12466 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12470 /* We get our minimum from the var_off, since that's inherently
12471 * bitwise. Our maximum is the minimum of the operands' maxima.
12473 dst_reg->umin_value = dst_reg->var_off.value;
12474 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12475 if (dst_reg->smin_value < 0 || smin_val < 0) {
12476 /* Lose signed bounds when ANDing negative numbers,
12477 * ain't nobody got time for that.
12479 dst_reg->smin_value = S64_MIN;
12480 dst_reg->smax_value = S64_MAX;
12482 /* ANDing two positives gives a positive, so safe to
12483 * cast result into s64.
12485 dst_reg->smin_value = dst_reg->umin_value;
12486 dst_reg->smax_value = dst_reg->umax_value;
12488 /* We may learn something more from the var_off */
12489 __update_reg_bounds(dst_reg);
12492 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12493 struct bpf_reg_state *src_reg)
12495 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12496 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12497 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12498 s32 smin_val = src_reg->s32_min_value;
12499 u32 umin_val = src_reg->u32_min_value;
12501 if (src_known && dst_known) {
12502 __mark_reg32_known(dst_reg, var32_off.value);
12506 /* We get our maximum from the var_off, and our minimum is the
12507 * maximum of the operands' minima
12509 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12510 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12511 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12512 /* Lose signed bounds when ORing negative numbers,
12513 * ain't nobody got time for that.
12515 dst_reg->s32_min_value = S32_MIN;
12516 dst_reg->s32_max_value = S32_MAX;
12518 /* ORing two positives gives a positive, so safe to
12519 * cast result into s64.
12521 dst_reg->s32_min_value = dst_reg->u32_min_value;
12522 dst_reg->s32_max_value = dst_reg->u32_max_value;
12526 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12527 struct bpf_reg_state *src_reg)
12529 bool src_known = tnum_is_const(src_reg->var_off);
12530 bool dst_known = tnum_is_const(dst_reg->var_off);
12531 s64 smin_val = src_reg->smin_value;
12532 u64 umin_val = src_reg->umin_value;
12534 if (src_known && dst_known) {
12535 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12539 /* We get our maximum from the var_off, and our minimum is the
12540 * maximum of the operands' minima
12542 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12543 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12544 if (dst_reg->smin_value < 0 || smin_val < 0) {
12545 /* Lose signed bounds when ORing negative numbers,
12546 * ain't nobody got time for that.
12548 dst_reg->smin_value = S64_MIN;
12549 dst_reg->smax_value = S64_MAX;
12551 /* ORing two positives gives a positive, so safe to
12552 * cast result into s64.
12554 dst_reg->smin_value = dst_reg->umin_value;
12555 dst_reg->smax_value = dst_reg->umax_value;
12557 /* We may learn something more from the var_off */
12558 __update_reg_bounds(dst_reg);
12561 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12562 struct bpf_reg_state *src_reg)
12564 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12565 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12566 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12567 s32 smin_val = src_reg->s32_min_value;
12569 if (src_known && dst_known) {
12570 __mark_reg32_known(dst_reg, var32_off.value);
12574 /* We get both minimum and maximum from the var32_off. */
12575 dst_reg->u32_min_value = var32_off.value;
12576 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12578 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12579 /* XORing two positive sign numbers gives a positive,
12580 * so safe to cast u32 result into s32.
12582 dst_reg->s32_min_value = dst_reg->u32_min_value;
12583 dst_reg->s32_max_value = dst_reg->u32_max_value;
12585 dst_reg->s32_min_value = S32_MIN;
12586 dst_reg->s32_max_value = S32_MAX;
12590 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12591 struct bpf_reg_state *src_reg)
12593 bool src_known = tnum_is_const(src_reg->var_off);
12594 bool dst_known = tnum_is_const(dst_reg->var_off);
12595 s64 smin_val = src_reg->smin_value;
12597 if (src_known && dst_known) {
12598 /* dst_reg->var_off.value has been updated earlier */
12599 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12603 /* We get both minimum and maximum from the var_off. */
12604 dst_reg->umin_value = dst_reg->var_off.value;
12605 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12607 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12608 /* XORing two positive sign numbers gives a positive,
12609 * so safe to cast u64 result into s64.
12611 dst_reg->smin_value = dst_reg->umin_value;
12612 dst_reg->smax_value = dst_reg->umax_value;
12614 dst_reg->smin_value = S64_MIN;
12615 dst_reg->smax_value = S64_MAX;
12618 __update_reg_bounds(dst_reg);
12621 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12622 u64 umin_val, u64 umax_val)
12624 /* We lose all sign bit information (except what we can pick
12627 dst_reg->s32_min_value = S32_MIN;
12628 dst_reg->s32_max_value = S32_MAX;
12629 /* If we might shift our top bit out, then we know nothing */
12630 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12631 dst_reg->u32_min_value = 0;
12632 dst_reg->u32_max_value = U32_MAX;
12634 dst_reg->u32_min_value <<= umin_val;
12635 dst_reg->u32_max_value <<= umax_val;
12639 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12640 struct bpf_reg_state *src_reg)
12642 u32 umax_val = src_reg->u32_max_value;
12643 u32 umin_val = src_reg->u32_min_value;
12644 /* u32 alu operation will zext upper bits */
12645 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12647 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12648 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12649 /* Not required but being careful mark reg64 bounds as unknown so
12650 * that we are forced to pick them up from tnum and zext later and
12651 * if some path skips this step we are still safe.
12653 __mark_reg64_unbounded(dst_reg);
12654 __update_reg32_bounds(dst_reg);
12657 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12658 u64 umin_val, u64 umax_val)
12660 /* Special case <<32 because it is a common compiler pattern to sign
12661 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12662 * positive we know this shift will also be positive so we can track
12663 * bounds correctly. Otherwise we lose all sign bit information except
12664 * what we can pick up from var_off. Perhaps we can generalize this
12665 * later to shifts of any length.
12667 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12668 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12670 dst_reg->smax_value = S64_MAX;
12672 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12673 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12675 dst_reg->smin_value = S64_MIN;
12677 /* If we might shift our top bit out, then we know nothing */
12678 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12679 dst_reg->umin_value = 0;
12680 dst_reg->umax_value = U64_MAX;
12682 dst_reg->umin_value <<= umin_val;
12683 dst_reg->umax_value <<= umax_val;
12687 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12688 struct bpf_reg_state *src_reg)
12690 u64 umax_val = src_reg->umax_value;
12691 u64 umin_val = src_reg->umin_value;
12693 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
12694 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12695 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12697 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12698 /* We may learn something more from the var_off */
12699 __update_reg_bounds(dst_reg);
12702 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12703 struct bpf_reg_state *src_reg)
12705 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12706 u32 umax_val = src_reg->u32_max_value;
12707 u32 umin_val = src_reg->u32_min_value;
12709 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12710 * be negative, then either:
12711 * 1) src_reg might be zero, so the sign bit of the result is
12712 * unknown, so we lose our signed bounds
12713 * 2) it's known negative, thus the unsigned bounds capture the
12715 * 3) the signed bounds cross zero, so they tell us nothing
12717 * If the value in dst_reg is known nonnegative, then again the
12718 * unsigned bounds capture the signed bounds.
12719 * Thus, in all cases it suffices to blow away our signed bounds
12720 * and rely on inferring new ones from the unsigned bounds and
12721 * var_off of the result.
12723 dst_reg->s32_min_value = S32_MIN;
12724 dst_reg->s32_max_value = S32_MAX;
12726 dst_reg->var_off = tnum_rshift(subreg, umin_val);
12727 dst_reg->u32_min_value >>= umax_val;
12728 dst_reg->u32_max_value >>= umin_val;
12730 __mark_reg64_unbounded(dst_reg);
12731 __update_reg32_bounds(dst_reg);
12734 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12735 struct bpf_reg_state *src_reg)
12737 u64 umax_val = src_reg->umax_value;
12738 u64 umin_val = src_reg->umin_value;
12740 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12741 * be negative, then either:
12742 * 1) src_reg might be zero, so the sign bit of the result is
12743 * unknown, so we lose our signed bounds
12744 * 2) it's known negative, thus the unsigned bounds capture the
12746 * 3) the signed bounds cross zero, so they tell us nothing
12748 * If the value in dst_reg is known nonnegative, then again the
12749 * unsigned bounds capture the signed bounds.
12750 * Thus, in all cases it suffices to blow away our signed bounds
12751 * and rely on inferring new ones from the unsigned bounds and
12752 * var_off of the result.
12754 dst_reg->smin_value = S64_MIN;
12755 dst_reg->smax_value = S64_MAX;
12756 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12757 dst_reg->umin_value >>= umax_val;
12758 dst_reg->umax_value >>= umin_val;
12760 /* Its not easy to operate on alu32 bounds here because it depends
12761 * on bits being shifted in. Take easy way out and mark unbounded
12762 * so we can recalculate later from tnum.
12764 __mark_reg32_unbounded(dst_reg);
12765 __update_reg_bounds(dst_reg);
12768 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12769 struct bpf_reg_state *src_reg)
12771 u64 umin_val = src_reg->u32_min_value;
12773 /* Upon reaching here, src_known is true and
12774 * umax_val is equal to umin_val.
12776 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12777 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12779 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12781 /* blow away the dst_reg umin_value/umax_value and rely on
12782 * dst_reg var_off to refine the result.
12784 dst_reg->u32_min_value = 0;
12785 dst_reg->u32_max_value = U32_MAX;
12787 __mark_reg64_unbounded(dst_reg);
12788 __update_reg32_bounds(dst_reg);
12791 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12792 struct bpf_reg_state *src_reg)
12794 u64 umin_val = src_reg->umin_value;
12796 /* Upon reaching here, src_known is true and umax_val is equal
12799 dst_reg->smin_value >>= umin_val;
12800 dst_reg->smax_value >>= umin_val;
12802 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12804 /* blow away the dst_reg umin_value/umax_value and rely on
12805 * dst_reg var_off to refine the result.
12807 dst_reg->umin_value = 0;
12808 dst_reg->umax_value = U64_MAX;
12810 /* Its not easy to operate on alu32 bounds here because it depends
12811 * on bits being shifted in from upper 32-bits. Take easy way out
12812 * and mark unbounded so we can recalculate later from tnum.
12814 __mark_reg32_unbounded(dst_reg);
12815 __update_reg_bounds(dst_reg);
12818 /* WARNING: This function does calculations on 64-bit values, but the actual
12819 * execution may occur on 32-bit values. Therefore, things like bitshifts
12820 * need extra checks in the 32-bit case.
12822 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12823 struct bpf_insn *insn,
12824 struct bpf_reg_state *dst_reg,
12825 struct bpf_reg_state src_reg)
12827 struct bpf_reg_state *regs = cur_regs(env);
12828 u8 opcode = BPF_OP(insn->code);
12830 s64 smin_val, smax_val;
12831 u64 umin_val, umax_val;
12832 s32 s32_min_val, s32_max_val;
12833 u32 u32_min_val, u32_max_val;
12834 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12835 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12838 smin_val = src_reg.smin_value;
12839 smax_val = src_reg.smax_value;
12840 umin_val = src_reg.umin_value;
12841 umax_val = src_reg.umax_value;
12843 s32_min_val = src_reg.s32_min_value;
12844 s32_max_val = src_reg.s32_max_value;
12845 u32_min_val = src_reg.u32_min_value;
12846 u32_max_val = src_reg.u32_max_value;
12849 src_known = tnum_subreg_is_const(src_reg.var_off);
12851 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12852 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12853 /* Taint dst register if offset had invalid bounds
12854 * derived from e.g. dead branches.
12856 __mark_reg_unknown(env, dst_reg);
12860 src_known = tnum_is_const(src_reg.var_off);
12862 (smin_val != smax_val || umin_val != umax_val)) ||
12863 smin_val > smax_val || umin_val > umax_val) {
12864 /* Taint dst register if offset had invalid bounds
12865 * derived from e.g. dead branches.
12867 __mark_reg_unknown(env, dst_reg);
12873 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12874 __mark_reg_unknown(env, dst_reg);
12878 if (sanitize_needed(opcode)) {
12879 ret = sanitize_val_alu(env, insn);
12881 return sanitize_err(env, insn, ret, NULL, NULL);
12884 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12885 * There are two classes of instructions: The first class we track both
12886 * alu32 and alu64 sign/unsigned bounds independently this provides the
12887 * greatest amount of precision when alu operations are mixed with jmp32
12888 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12889 * and BPF_OR. This is possible because these ops have fairly easy to
12890 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12891 * See alu32 verifier tests for examples. The second class of
12892 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12893 * with regards to tracking sign/unsigned bounds because the bits may
12894 * cross subreg boundaries in the alu64 case. When this happens we mark
12895 * the reg unbounded in the subreg bound space and use the resulting
12896 * tnum to calculate an approximation of the sign/unsigned bounds.
12900 scalar32_min_max_add(dst_reg, &src_reg);
12901 scalar_min_max_add(dst_reg, &src_reg);
12902 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12905 scalar32_min_max_sub(dst_reg, &src_reg);
12906 scalar_min_max_sub(dst_reg, &src_reg);
12907 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12910 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12911 scalar32_min_max_mul(dst_reg, &src_reg);
12912 scalar_min_max_mul(dst_reg, &src_reg);
12915 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12916 scalar32_min_max_and(dst_reg, &src_reg);
12917 scalar_min_max_and(dst_reg, &src_reg);
12920 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12921 scalar32_min_max_or(dst_reg, &src_reg);
12922 scalar_min_max_or(dst_reg, &src_reg);
12925 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12926 scalar32_min_max_xor(dst_reg, &src_reg);
12927 scalar_min_max_xor(dst_reg, &src_reg);
12930 if (umax_val >= insn_bitness) {
12931 /* Shifts greater than 31 or 63 are undefined.
12932 * This includes shifts by a negative number.
12934 mark_reg_unknown(env, regs, insn->dst_reg);
12938 scalar32_min_max_lsh(dst_reg, &src_reg);
12940 scalar_min_max_lsh(dst_reg, &src_reg);
12943 if (umax_val >= insn_bitness) {
12944 /* Shifts greater than 31 or 63 are undefined.
12945 * This includes shifts by a negative number.
12947 mark_reg_unknown(env, regs, insn->dst_reg);
12951 scalar32_min_max_rsh(dst_reg, &src_reg);
12953 scalar_min_max_rsh(dst_reg, &src_reg);
12956 if (umax_val >= insn_bitness) {
12957 /* Shifts greater than 31 or 63 are undefined.
12958 * This includes shifts by a negative number.
12960 mark_reg_unknown(env, regs, insn->dst_reg);
12964 scalar32_min_max_arsh(dst_reg, &src_reg);
12966 scalar_min_max_arsh(dst_reg, &src_reg);
12969 mark_reg_unknown(env, regs, insn->dst_reg);
12973 /* ALU32 ops are zero extended into 64bit register */
12975 zext_32_to_64(dst_reg);
12976 reg_bounds_sync(dst_reg);
12980 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12983 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12984 struct bpf_insn *insn)
12986 struct bpf_verifier_state *vstate = env->cur_state;
12987 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12988 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12989 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12990 u8 opcode = BPF_OP(insn->code);
12993 dst_reg = ®s[insn->dst_reg];
12995 if (dst_reg->type != SCALAR_VALUE)
12998 /* Make sure ID is cleared otherwise dst_reg min/max could be
12999 * incorrectly propagated into other registers by find_equal_scalars()
13002 if (BPF_SRC(insn->code) == BPF_X) {
13003 src_reg = ®s[insn->src_reg];
13004 if (src_reg->type != SCALAR_VALUE) {
13005 if (dst_reg->type != SCALAR_VALUE) {
13006 /* Combining two pointers by any ALU op yields
13007 * an arbitrary scalar. Disallow all math except
13008 * pointer subtraction
13010 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13011 mark_reg_unknown(env, regs, insn->dst_reg);
13014 verbose(env, "R%d pointer %s pointer prohibited\n",
13016 bpf_alu_string[opcode >> 4]);
13019 /* scalar += pointer
13020 * This is legal, but we have to reverse our
13021 * src/dest handling in computing the range
13023 err = mark_chain_precision(env, insn->dst_reg);
13026 return adjust_ptr_min_max_vals(env, insn,
13029 } else if (ptr_reg) {
13030 /* pointer += scalar */
13031 err = mark_chain_precision(env, insn->src_reg);
13034 return adjust_ptr_min_max_vals(env, insn,
13036 } else if (dst_reg->precise) {
13037 /* if dst_reg is precise, src_reg should be precise as well */
13038 err = mark_chain_precision(env, insn->src_reg);
13043 /* Pretend the src is a reg with a known value, since we only
13044 * need to be able to read from this state.
13046 off_reg.type = SCALAR_VALUE;
13047 __mark_reg_known(&off_reg, insn->imm);
13048 src_reg = &off_reg;
13049 if (ptr_reg) /* pointer += K */
13050 return adjust_ptr_min_max_vals(env, insn,
13054 /* Got here implies adding two SCALAR_VALUEs */
13055 if (WARN_ON_ONCE(ptr_reg)) {
13056 print_verifier_state(env, state, true);
13057 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13060 if (WARN_ON(!src_reg)) {
13061 print_verifier_state(env, state, true);
13062 verbose(env, "verifier internal error: no src_reg\n");
13065 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13068 /* check validity of 32-bit and 64-bit arithmetic operations */
13069 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13071 struct bpf_reg_state *regs = cur_regs(env);
13072 u8 opcode = BPF_OP(insn->code);
13075 if (opcode == BPF_END || opcode == BPF_NEG) {
13076 if (opcode == BPF_NEG) {
13077 if (BPF_SRC(insn->code) != BPF_K ||
13078 insn->src_reg != BPF_REG_0 ||
13079 insn->off != 0 || insn->imm != 0) {
13080 verbose(env, "BPF_NEG uses reserved fields\n");
13084 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13085 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13086 (BPF_CLASS(insn->code) == BPF_ALU64 &&
13087 BPF_SRC(insn->code) != BPF_TO_LE)) {
13088 verbose(env, "BPF_END uses reserved fields\n");
13093 /* check src operand */
13094 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13098 if (is_pointer_value(env, insn->dst_reg)) {
13099 verbose(env, "R%d pointer arithmetic prohibited\n",
13104 /* check dest operand */
13105 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13109 } else if (opcode == BPF_MOV) {
13111 if (BPF_SRC(insn->code) == BPF_X) {
13112 if (insn->imm != 0) {
13113 verbose(env, "BPF_MOV uses reserved fields\n");
13117 if (BPF_CLASS(insn->code) == BPF_ALU) {
13118 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13119 verbose(env, "BPF_MOV uses reserved fields\n");
13123 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13125 verbose(env, "BPF_MOV uses reserved fields\n");
13130 /* check src operand */
13131 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13135 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13136 verbose(env, "BPF_MOV uses reserved fields\n");
13141 /* check dest operand, mark as required later */
13142 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13146 if (BPF_SRC(insn->code) == BPF_X) {
13147 struct bpf_reg_state *src_reg = regs + insn->src_reg;
13148 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13149 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13150 !tnum_is_const(src_reg->var_off);
13152 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13153 if (insn->off == 0) {
13155 * copy register state to dest reg
13158 /* Assign src and dst registers the same ID
13159 * that will be used by find_equal_scalars()
13160 * to propagate min/max range.
13162 src_reg->id = ++env->id_gen;
13163 copy_register_state(dst_reg, src_reg);
13164 dst_reg->live |= REG_LIVE_WRITTEN;
13165 dst_reg->subreg_def = DEF_NOT_SUBREG;
13167 /* case: R1 = (s8, s16 s32)R2 */
13168 if (is_pointer_value(env, insn->src_reg)) {
13170 "R%d sign-extension part of pointer\n",
13173 } else if (src_reg->type == SCALAR_VALUE) {
13176 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13177 if (no_sext && need_id)
13178 src_reg->id = ++env->id_gen;
13179 copy_register_state(dst_reg, src_reg);
13182 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13183 dst_reg->live |= REG_LIVE_WRITTEN;
13184 dst_reg->subreg_def = DEF_NOT_SUBREG;
13186 mark_reg_unknown(env, regs, insn->dst_reg);
13190 /* R1 = (u32) R2 */
13191 if (is_pointer_value(env, insn->src_reg)) {
13193 "R%d partial copy of pointer\n",
13196 } else if (src_reg->type == SCALAR_VALUE) {
13197 if (insn->off == 0) {
13198 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13200 if (is_src_reg_u32 && need_id)
13201 src_reg->id = ++env->id_gen;
13202 copy_register_state(dst_reg, src_reg);
13203 /* Make sure ID is cleared if src_reg is not in u32
13204 * range otherwise dst_reg min/max could be incorrectly
13205 * propagated into src_reg by find_equal_scalars()
13207 if (!is_src_reg_u32)
13209 dst_reg->live |= REG_LIVE_WRITTEN;
13210 dst_reg->subreg_def = env->insn_idx + 1;
13212 /* case: W1 = (s8, s16)W2 */
13213 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13215 if (no_sext && need_id)
13216 src_reg->id = ++env->id_gen;
13217 copy_register_state(dst_reg, src_reg);
13220 dst_reg->live |= REG_LIVE_WRITTEN;
13221 dst_reg->subreg_def = env->insn_idx + 1;
13222 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13225 mark_reg_unknown(env, regs,
13228 zext_32_to_64(dst_reg);
13229 reg_bounds_sync(dst_reg);
13233 * remember the value we stored into this reg
13235 /* clear any state __mark_reg_known doesn't set */
13236 mark_reg_unknown(env, regs, insn->dst_reg);
13237 regs[insn->dst_reg].type = SCALAR_VALUE;
13238 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13239 __mark_reg_known(regs + insn->dst_reg,
13242 __mark_reg_known(regs + insn->dst_reg,
13247 } else if (opcode > BPF_END) {
13248 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13251 } else { /* all other ALU ops: and, sub, xor, add, ... */
13253 if (BPF_SRC(insn->code) == BPF_X) {
13254 if (insn->imm != 0 || insn->off > 1 ||
13255 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13256 verbose(env, "BPF_ALU uses reserved fields\n");
13259 /* check src1 operand */
13260 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13264 if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13265 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13266 verbose(env, "BPF_ALU uses reserved fields\n");
13271 /* check src2 operand */
13272 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13276 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13277 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13278 verbose(env, "div by zero\n");
13282 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13283 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13284 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13286 if (insn->imm < 0 || insn->imm >= size) {
13287 verbose(env, "invalid shift %d\n", insn->imm);
13292 /* check dest operand */
13293 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13297 return adjust_reg_min_max_vals(env, insn);
13303 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13304 struct bpf_reg_state *dst_reg,
13305 enum bpf_reg_type type,
13306 bool range_right_open)
13308 struct bpf_func_state *state;
13309 struct bpf_reg_state *reg;
13312 if (dst_reg->off < 0 ||
13313 (dst_reg->off == 0 && range_right_open))
13314 /* This doesn't give us any range */
13317 if (dst_reg->umax_value > MAX_PACKET_OFF ||
13318 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13319 /* Risk of overflow. For instance, ptr + (1<<63) may be less
13320 * than pkt_end, but that's because it's also less than pkt.
13324 new_range = dst_reg->off;
13325 if (range_right_open)
13328 /* Examples for register markings:
13330 * pkt_data in dst register:
13334 * if (r2 > pkt_end) goto <handle exception>
13339 * if (r2 < pkt_end) goto <access okay>
13340 * <handle exception>
13343 * r2 == dst_reg, pkt_end == src_reg
13344 * r2=pkt(id=n,off=8,r=0)
13345 * r3=pkt(id=n,off=0,r=0)
13347 * pkt_data in src register:
13351 * if (pkt_end >= r2) goto <access okay>
13352 * <handle exception>
13356 * if (pkt_end <= r2) goto <handle exception>
13360 * pkt_end == dst_reg, r2 == src_reg
13361 * r2=pkt(id=n,off=8,r=0)
13362 * r3=pkt(id=n,off=0,r=0)
13364 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13365 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13366 * and [r3, r3 + 8-1) respectively is safe to access depending on
13370 /* If our ids match, then we must have the same max_value. And we
13371 * don't care about the other reg's fixed offset, since if it's too big
13372 * the range won't allow anything.
13373 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13375 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13376 if (reg->type == type && reg->id == dst_reg->id)
13377 /* keep the maximum range already checked */
13378 reg->range = max(reg->range, new_range);
13382 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13384 struct tnum subreg = tnum_subreg(reg->var_off);
13385 s32 sval = (s32)val;
13389 if (tnum_is_const(subreg))
13390 return !!tnum_equals_const(subreg, val);
13391 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13395 if (tnum_is_const(subreg))
13396 return !tnum_equals_const(subreg, val);
13397 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13401 if ((~subreg.mask & subreg.value) & val)
13403 if (!((subreg.mask | subreg.value) & val))
13407 if (reg->u32_min_value > val)
13409 else if (reg->u32_max_value <= val)
13413 if (reg->s32_min_value > sval)
13415 else if (reg->s32_max_value <= sval)
13419 if (reg->u32_max_value < val)
13421 else if (reg->u32_min_value >= val)
13425 if (reg->s32_max_value < sval)
13427 else if (reg->s32_min_value >= sval)
13431 if (reg->u32_min_value >= val)
13433 else if (reg->u32_max_value < val)
13437 if (reg->s32_min_value >= sval)
13439 else if (reg->s32_max_value < sval)
13443 if (reg->u32_max_value <= val)
13445 else if (reg->u32_min_value > val)
13449 if (reg->s32_max_value <= sval)
13451 else if (reg->s32_min_value > sval)
13460 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13462 s64 sval = (s64)val;
13466 if (tnum_is_const(reg->var_off))
13467 return !!tnum_equals_const(reg->var_off, val);
13468 else if (val < reg->umin_value || val > reg->umax_value)
13472 if (tnum_is_const(reg->var_off))
13473 return !tnum_equals_const(reg->var_off, val);
13474 else if (val < reg->umin_value || val > reg->umax_value)
13478 if ((~reg->var_off.mask & reg->var_off.value) & val)
13480 if (!((reg->var_off.mask | reg->var_off.value) & val))
13484 if (reg->umin_value > val)
13486 else if (reg->umax_value <= val)
13490 if (reg->smin_value > sval)
13492 else if (reg->smax_value <= sval)
13496 if (reg->umax_value < val)
13498 else if (reg->umin_value >= val)
13502 if (reg->smax_value < sval)
13504 else if (reg->smin_value >= sval)
13508 if (reg->umin_value >= val)
13510 else if (reg->umax_value < val)
13514 if (reg->smin_value >= sval)
13516 else if (reg->smax_value < sval)
13520 if (reg->umax_value <= val)
13522 else if (reg->umin_value > val)
13526 if (reg->smax_value <= sval)
13528 else if (reg->smin_value > sval)
13536 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13538 * 1 - branch will be taken and "goto target" will be executed
13539 * 0 - branch will not be taken and fall-through to next insn
13540 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13543 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13546 if (__is_pointer_value(false, reg)) {
13547 if (!reg_not_null(reg))
13550 /* If pointer is valid tests against zero will fail so we can
13551 * use this to direct branch taken.
13567 return is_branch32_taken(reg, val, opcode);
13568 return is_branch64_taken(reg, val, opcode);
13571 static int flip_opcode(u32 opcode)
13573 /* How can we transform "a <op> b" into "b <op> a"? */
13574 static const u8 opcode_flip[16] = {
13575 /* these stay the same */
13576 [BPF_JEQ >> 4] = BPF_JEQ,
13577 [BPF_JNE >> 4] = BPF_JNE,
13578 [BPF_JSET >> 4] = BPF_JSET,
13579 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13580 [BPF_JGE >> 4] = BPF_JLE,
13581 [BPF_JGT >> 4] = BPF_JLT,
13582 [BPF_JLE >> 4] = BPF_JGE,
13583 [BPF_JLT >> 4] = BPF_JGT,
13584 [BPF_JSGE >> 4] = BPF_JSLE,
13585 [BPF_JSGT >> 4] = BPF_JSLT,
13586 [BPF_JSLE >> 4] = BPF_JSGE,
13587 [BPF_JSLT >> 4] = BPF_JSGT
13589 return opcode_flip[opcode >> 4];
13592 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13593 struct bpf_reg_state *src_reg,
13596 struct bpf_reg_state *pkt;
13598 if (src_reg->type == PTR_TO_PACKET_END) {
13600 } else if (dst_reg->type == PTR_TO_PACKET_END) {
13602 opcode = flip_opcode(opcode);
13607 if (pkt->range >= 0)
13612 /* pkt <= pkt_end */
13615 /* pkt > pkt_end */
13616 if (pkt->range == BEYOND_PKT_END)
13617 /* pkt has at last one extra byte beyond pkt_end */
13618 return opcode == BPF_JGT;
13621 /* pkt < pkt_end */
13624 /* pkt >= pkt_end */
13625 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13626 return opcode == BPF_JGE;
13632 /* Adjusts the register min/max values in the case that the dst_reg is the
13633 * variable register that we are working on, and src_reg is a constant or we're
13634 * simply doing a BPF_K check.
13635 * In JEQ/JNE cases we also adjust the var_off values.
13637 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13638 struct bpf_reg_state *false_reg,
13639 u64 val, u32 val32,
13640 u8 opcode, bool is_jmp32)
13642 struct tnum false_32off = tnum_subreg(false_reg->var_off);
13643 struct tnum false_64off = false_reg->var_off;
13644 struct tnum true_32off = tnum_subreg(true_reg->var_off);
13645 struct tnum true_64off = true_reg->var_off;
13646 s64 sval = (s64)val;
13647 s32 sval32 = (s32)val32;
13649 /* If the dst_reg is a pointer, we can't learn anything about its
13650 * variable offset from the compare (unless src_reg were a pointer into
13651 * the same object, but we don't bother with that.
13652 * Since false_reg and true_reg have the same type by construction, we
13653 * only need to check one of them for pointerness.
13655 if (__is_pointer_value(false, false_reg))
13659 /* JEQ/JNE comparison doesn't change the register equivalence.
13662 * if (r1 == 42) goto label;
13664 * label: // here both r1 and r2 are known to be 42.
13666 * Hence when marking register as known preserve it's ID.
13670 __mark_reg32_known(true_reg, val32);
13671 true_32off = tnum_subreg(true_reg->var_off);
13673 ___mark_reg_known(true_reg, val);
13674 true_64off = true_reg->var_off;
13679 __mark_reg32_known(false_reg, val32);
13680 false_32off = tnum_subreg(false_reg->var_off);
13682 ___mark_reg_known(false_reg, val);
13683 false_64off = false_reg->var_off;
13688 false_32off = tnum_and(false_32off, tnum_const(~val32));
13689 if (is_power_of_2(val32))
13690 true_32off = tnum_or(true_32off,
13691 tnum_const(val32));
13693 false_64off = tnum_and(false_64off, tnum_const(~val));
13694 if (is_power_of_2(val))
13695 true_64off = tnum_or(true_64off,
13703 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
13704 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13706 false_reg->u32_max_value = min(false_reg->u32_max_value,
13708 true_reg->u32_min_value = max(true_reg->u32_min_value,
13711 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
13712 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13714 false_reg->umax_value = min(false_reg->umax_value, false_umax);
13715 true_reg->umin_value = max(true_reg->umin_value, true_umin);
13723 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
13724 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13726 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13727 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13729 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
13730 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13732 false_reg->smax_value = min(false_reg->smax_value, false_smax);
13733 true_reg->smin_value = max(true_reg->smin_value, true_smin);
13741 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
13742 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13744 false_reg->u32_min_value = max(false_reg->u32_min_value,
13746 true_reg->u32_max_value = min(true_reg->u32_max_value,
13749 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
13750 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13752 false_reg->umin_value = max(false_reg->umin_value, false_umin);
13753 true_reg->umax_value = min(true_reg->umax_value, true_umax);
13761 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
13762 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13764 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13765 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13767 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
13768 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13770 false_reg->smin_value = max(false_reg->smin_value, false_smin);
13771 true_reg->smax_value = min(true_reg->smax_value, true_smax);
13780 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13781 tnum_subreg(false_32off));
13782 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13783 tnum_subreg(true_32off));
13784 __reg_combine_32_into_64(false_reg);
13785 __reg_combine_32_into_64(true_reg);
13787 false_reg->var_off = false_64off;
13788 true_reg->var_off = true_64off;
13789 __reg_combine_64_into_32(false_reg);
13790 __reg_combine_64_into_32(true_reg);
13794 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13795 * the variable reg.
13797 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13798 struct bpf_reg_state *false_reg,
13799 u64 val, u32 val32,
13800 u8 opcode, bool is_jmp32)
13802 opcode = flip_opcode(opcode);
13803 /* This uses zero as "not present in table"; luckily the zero opcode,
13804 * BPF_JA, can't get here.
13807 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13810 /* Regs are known to be equal, so intersect their min/max/var_off */
13811 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13812 struct bpf_reg_state *dst_reg)
13814 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13815 dst_reg->umin_value);
13816 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13817 dst_reg->umax_value);
13818 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13819 dst_reg->smin_value);
13820 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13821 dst_reg->smax_value);
13822 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13824 reg_bounds_sync(src_reg);
13825 reg_bounds_sync(dst_reg);
13828 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13829 struct bpf_reg_state *true_dst,
13830 struct bpf_reg_state *false_src,
13831 struct bpf_reg_state *false_dst,
13836 __reg_combine_min_max(true_src, true_dst);
13839 __reg_combine_min_max(false_src, false_dst);
13844 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13845 struct bpf_reg_state *reg, u32 id,
13848 if (type_may_be_null(reg->type) && reg->id == id &&
13849 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13850 /* Old offset (both fixed and variable parts) should have been
13851 * known-zero, because we don't allow pointer arithmetic on
13852 * pointers that might be NULL. If we see this happening, don't
13853 * convert the register.
13855 * But in some cases, some helpers that return local kptrs
13856 * advance offset for the returned pointer. In those cases, it
13857 * is fine to expect to see reg->off.
13859 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13861 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13862 WARN_ON_ONCE(reg->off))
13866 reg->type = SCALAR_VALUE;
13867 /* We don't need id and ref_obj_id from this point
13868 * onwards anymore, thus we should better reset it,
13869 * so that state pruning has chances to take effect.
13872 reg->ref_obj_id = 0;
13877 mark_ptr_not_null_reg(reg);
13879 if (!reg_may_point_to_spin_lock(reg)) {
13880 /* For not-NULL ptr, reg->ref_obj_id will be reset
13881 * in release_reference().
13883 * reg->id is still used by spin_lock ptr. Other
13884 * than spin_lock ptr type, reg->id can be reset.
13891 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13892 * be folded together at some point.
13894 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13897 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13898 struct bpf_reg_state *regs = state->regs, *reg;
13899 u32 ref_obj_id = regs[regno].ref_obj_id;
13900 u32 id = regs[regno].id;
13902 if (ref_obj_id && ref_obj_id == id && is_null)
13903 /* regs[regno] is in the " == NULL" branch.
13904 * No one could have freed the reference state before
13905 * doing the NULL check.
13907 WARN_ON_ONCE(release_reference_state(state, id));
13909 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13910 mark_ptr_or_null_reg(state, reg, id, is_null);
13914 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13915 struct bpf_reg_state *dst_reg,
13916 struct bpf_reg_state *src_reg,
13917 struct bpf_verifier_state *this_branch,
13918 struct bpf_verifier_state *other_branch)
13920 if (BPF_SRC(insn->code) != BPF_X)
13923 /* Pointers are always 64-bit. */
13924 if (BPF_CLASS(insn->code) == BPF_JMP32)
13927 switch (BPF_OP(insn->code)) {
13929 if ((dst_reg->type == PTR_TO_PACKET &&
13930 src_reg->type == PTR_TO_PACKET_END) ||
13931 (dst_reg->type == PTR_TO_PACKET_META &&
13932 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13933 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13934 find_good_pkt_pointers(this_branch, dst_reg,
13935 dst_reg->type, false);
13936 mark_pkt_end(other_branch, insn->dst_reg, true);
13937 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13938 src_reg->type == PTR_TO_PACKET) ||
13939 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13940 src_reg->type == PTR_TO_PACKET_META)) {
13941 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13942 find_good_pkt_pointers(other_branch, src_reg,
13943 src_reg->type, true);
13944 mark_pkt_end(this_branch, insn->src_reg, false);
13950 if ((dst_reg->type == PTR_TO_PACKET &&
13951 src_reg->type == PTR_TO_PACKET_END) ||
13952 (dst_reg->type == PTR_TO_PACKET_META &&
13953 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13954 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13955 find_good_pkt_pointers(other_branch, dst_reg,
13956 dst_reg->type, true);
13957 mark_pkt_end(this_branch, insn->dst_reg, false);
13958 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13959 src_reg->type == PTR_TO_PACKET) ||
13960 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13961 src_reg->type == PTR_TO_PACKET_META)) {
13962 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13963 find_good_pkt_pointers(this_branch, src_reg,
13964 src_reg->type, false);
13965 mark_pkt_end(other_branch, insn->src_reg, true);
13971 if ((dst_reg->type == PTR_TO_PACKET &&
13972 src_reg->type == PTR_TO_PACKET_END) ||
13973 (dst_reg->type == PTR_TO_PACKET_META &&
13974 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13975 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13976 find_good_pkt_pointers(this_branch, dst_reg,
13977 dst_reg->type, true);
13978 mark_pkt_end(other_branch, insn->dst_reg, false);
13979 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13980 src_reg->type == PTR_TO_PACKET) ||
13981 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13982 src_reg->type == PTR_TO_PACKET_META)) {
13983 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13984 find_good_pkt_pointers(other_branch, src_reg,
13985 src_reg->type, false);
13986 mark_pkt_end(this_branch, insn->src_reg, true);
13992 if ((dst_reg->type == PTR_TO_PACKET &&
13993 src_reg->type == PTR_TO_PACKET_END) ||
13994 (dst_reg->type == PTR_TO_PACKET_META &&
13995 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13996 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13997 find_good_pkt_pointers(other_branch, dst_reg,
13998 dst_reg->type, false);
13999 mark_pkt_end(this_branch, insn->dst_reg, true);
14000 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14001 src_reg->type == PTR_TO_PACKET) ||
14002 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14003 src_reg->type == PTR_TO_PACKET_META)) {
14004 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14005 find_good_pkt_pointers(this_branch, src_reg,
14006 src_reg->type, true);
14007 mark_pkt_end(other_branch, insn->src_reg, false);
14019 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14020 struct bpf_reg_state *known_reg)
14022 struct bpf_func_state *state;
14023 struct bpf_reg_state *reg;
14025 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14026 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14027 copy_register_state(reg, known_reg);
14031 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14032 struct bpf_insn *insn, int *insn_idx)
14034 struct bpf_verifier_state *this_branch = env->cur_state;
14035 struct bpf_verifier_state *other_branch;
14036 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14037 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14038 struct bpf_reg_state *eq_branch_regs;
14039 u8 opcode = BPF_OP(insn->code);
14044 /* Only conditional jumps are expected to reach here. */
14045 if (opcode == BPF_JA || opcode > BPF_JSLE) {
14046 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14050 if (BPF_SRC(insn->code) == BPF_X) {
14051 if (insn->imm != 0) {
14052 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14056 /* check src1 operand */
14057 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14061 if (is_pointer_value(env, insn->src_reg)) {
14062 verbose(env, "R%d pointer comparison prohibited\n",
14066 src_reg = ®s[insn->src_reg];
14068 if (insn->src_reg != BPF_REG_0) {
14069 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14074 /* check src2 operand */
14075 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14079 dst_reg = ®s[insn->dst_reg];
14080 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14082 if (BPF_SRC(insn->code) == BPF_K) {
14083 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14084 } else if (src_reg->type == SCALAR_VALUE &&
14085 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14086 pred = is_branch_taken(dst_reg,
14087 tnum_subreg(src_reg->var_off).value,
14090 } else if (src_reg->type == SCALAR_VALUE &&
14091 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14092 pred = is_branch_taken(dst_reg,
14093 src_reg->var_off.value,
14096 } else if (dst_reg->type == SCALAR_VALUE &&
14097 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14098 pred = is_branch_taken(src_reg,
14099 tnum_subreg(dst_reg->var_off).value,
14100 flip_opcode(opcode),
14102 } else if (dst_reg->type == SCALAR_VALUE &&
14103 !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14104 pred = is_branch_taken(src_reg,
14105 dst_reg->var_off.value,
14106 flip_opcode(opcode),
14108 } else if (reg_is_pkt_pointer_any(dst_reg) &&
14109 reg_is_pkt_pointer_any(src_reg) &&
14111 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14115 /* If we get here with a dst_reg pointer type it is because
14116 * above is_branch_taken() special cased the 0 comparison.
14118 if (!__is_pointer_value(false, dst_reg))
14119 err = mark_chain_precision(env, insn->dst_reg);
14120 if (BPF_SRC(insn->code) == BPF_X && !err &&
14121 !__is_pointer_value(false, src_reg))
14122 err = mark_chain_precision(env, insn->src_reg);
14128 /* Only follow the goto, ignore fall-through. If needed, push
14129 * the fall-through branch for simulation under speculative
14132 if (!env->bypass_spec_v1 &&
14133 !sanitize_speculative_path(env, insn, *insn_idx + 1,
14136 *insn_idx += insn->off;
14138 } else if (pred == 0) {
14139 /* Only follow the fall-through branch, since that's where the
14140 * program will go. If needed, push the goto branch for
14141 * simulation under speculative execution.
14143 if (!env->bypass_spec_v1 &&
14144 !sanitize_speculative_path(env, insn,
14145 *insn_idx + insn->off + 1,
14151 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14155 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14157 /* detect if we are comparing against a constant value so we can adjust
14158 * our min/max values for our dst register.
14159 * this is only legit if both are scalars (or pointers to the same
14160 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14161 * because otherwise the different base pointers mean the offsets aren't
14164 if (BPF_SRC(insn->code) == BPF_X) {
14165 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
14167 if (dst_reg->type == SCALAR_VALUE &&
14168 src_reg->type == SCALAR_VALUE) {
14169 if (tnum_is_const(src_reg->var_off) ||
14171 tnum_is_const(tnum_subreg(src_reg->var_off))))
14172 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14174 src_reg->var_off.value,
14175 tnum_subreg(src_reg->var_off).value,
14177 else if (tnum_is_const(dst_reg->var_off) ||
14179 tnum_is_const(tnum_subreg(dst_reg->var_off))))
14180 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14182 dst_reg->var_off.value,
14183 tnum_subreg(dst_reg->var_off).value,
14185 else if (!is_jmp32 &&
14186 (opcode == BPF_JEQ || opcode == BPF_JNE))
14187 /* Comparing for equality, we can combine knowledge */
14188 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14189 &other_branch_regs[insn->dst_reg],
14190 src_reg, dst_reg, opcode);
14192 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14193 find_equal_scalars(this_branch, src_reg);
14194 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14198 } else if (dst_reg->type == SCALAR_VALUE) {
14199 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14200 dst_reg, insn->imm, (u32)insn->imm,
14204 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14205 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14206 find_equal_scalars(this_branch, dst_reg);
14207 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14210 /* if one pointer register is compared to another pointer
14211 * register check if PTR_MAYBE_NULL could be lifted.
14212 * E.g. register A - maybe null
14213 * register B - not null
14214 * for JNE A, B, ... - A is not null in the false branch;
14215 * for JEQ A, B, ... - A is not null in the true branch.
14217 * Since PTR_TO_BTF_ID points to a kernel struct that does
14218 * not need to be null checked by the BPF program, i.e.,
14219 * could be null even without PTR_MAYBE_NULL marking, so
14220 * only propagate nullness when neither reg is that type.
14222 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14223 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14224 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14225 base_type(src_reg->type) != PTR_TO_BTF_ID &&
14226 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14227 eq_branch_regs = NULL;
14230 eq_branch_regs = other_branch_regs;
14233 eq_branch_regs = regs;
14239 if (eq_branch_regs) {
14240 if (type_may_be_null(src_reg->type))
14241 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14243 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14247 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14248 * NOTE: these optimizations below are related with pointer comparison
14249 * which will never be JMP32.
14251 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14252 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14253 type_may_be_null(dst_reg->type)) {
14254 /* Mark all identical registers in each branch as either
14255 * safe or unknown depending R == 0 or R != 0 conditional.
14257 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14258 opcode == BPF_JNE);
14259 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14260 opcode == BPF_JEQ);
14261 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
14262 this_branch, other_branch) &&
14263 is_pointer_value(env, insn->dst_reg)) {
14264 verbose(env, "R%d pointer comparison prohibited\n",
14268 if (env->log.level & BPF_LOG_LEVEL)
14269 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14273 /* verify BPF_LD_IMM64 instruction */
14274 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14276 struct bpf_insn_aux_data *aux = cur_aux(env);
14277 struct bpf_reg_state *regs = cur_regs(env);
14278 struct bpf_reg_state *dst_reg;
14279 struct bpf_map *map;
14282 if (BPF_SIZE(insn->code) != BPF_DW) {
14283 verbose(env, "invalid BPF_LD_IMM insn\n");
14286 if (insn->off != 0) {
14287 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14291 err = check_reg_arg(env, insn->dst_reg, DST_OP);
14295 dst_reg = ®s[insn->dst_reg];
14296 if (insn->src_reg == 0) {
14297 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14299 dst_reg->type = SCALAR_VALUE;
14300 __mark_reg_known(®s[insn->dst_reg], imm);
14304 /* All special src_reg cases are listed below. From this point onwards
14305 * we either succeed and assign a corresponding dst_reg->type after
14306 * zeroing the offset, or fail and reject the program.
14308 mark_reg_known_zero(env, regs, insn->dst_reg);
14310 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14311 dst_reg->type = aux->btf_var.reg_type;
14312 switch (base_type(dst_reg->type)) {
14314 dst_reg->mem_size = aux->btf_var.mem_size;
14316 case PTR_TO_BTF_ID:
14317 dst_reg->btf = aux->btf_var.btf;
14318 dst_reg->btf_id = aux->btf_var.btf_id;
14321 verbose(env, "bpf verifier is misconfigured\n");
14327 if (insn->src_reg == BPF_PSEUDO_FUNC) {
14328 struct bpf_prog_aux *aux = env->prog->aux;
14329 u32 subprogno = find_subprog(env,
14330 env->insn_idx + insn->imm + 1);
14332 if (!aux->func_info) {
14333 verbose(env, "missing btf func_info\n");
14336 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14337 verbose(env, "callback function not static\n");
14341 dst_reg->type = PTR_TO_FUNC;
14342 dst_reg->subprogno = subprogno;
14346 map = env->used_maps[aux->map_index];
14347 dst_reg->map_ptr = map;
14349 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14350 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14351 dst_reg->type = PTR_TO_MAP_VALUE;
14352 dst_reg->off = aux->map_off;
14353 WARN_ON_ONCE(map->max_entries != 1);
14354 /* We want reg->id to be same (0) as map_value is not distinct */
14355 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14356 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14357 dst_reg->type = CONST_PTR_TO_MAP;
14359 verbose(env, "bpf verifier is misconfigured\n");
14366 static bool may_access_skb(enum bpf_prog_type type)
14369 case BPF_PROG_TYPE_SOCKET_FILTER:
14370 case BPF_PROG_TYPE_SCHED_CLS:
14371 case BPF_PROG_TYPE_SCHED_ACT:
14378 /* verify safety of LD_ABS|LD_IND instructions:
14379 * - they can only appear in the programs where ctx == skb
14380 * - since they are wrappers of function calls, they scratch R1-R5 registers,
14381 * preserve R6-R9, and store return value into R0
14384 * ctx == skb == R6 == CTX
14387 * SRC == any register
14388 * IMM == 32-bit immediate
14391 * R0 - 8/16/32-bit skb data converted to cpu endianness
14393 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14395 struct bpf_reg_state *regs = cur_regs(env);
14396 static const int ctx_reg = BPF_REG_6;
14397 u8 mode = BPF_MODE(insn->code);
14400 if (!may_access_skb(resolve_prog_type(env->prog))) {
14401 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14405 if (!env->ops->gen_ld_abs) {
14406 verbose(env, "bpf verifier is misconfigured\n");
14410 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14411 BPF_SIZE(insn->code) == BPF_DW ||
14412 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14413 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14417 /* check whether implicit source operand (register R6) is readable */
14418 err = check_reg_arg(env, ctx_reg, SRC_OP);
14422 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14423 * gen_ld_abs() may terminate the program at runtime, leading to
14426 err = check_reference_leak(env);
14428 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14432 if (env->cur_state->active_lock.ptr) {
14433 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14437 if (env->cur_state->active_rcu_lock) {
14438 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14442 if (regs[ctx_reg].type != PTR_TO_CTX) {
14444 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14448 if (mode == BPF_IND) {
14449 /* check explicit source operand */
14450 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14455 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
14459 /* reset caller saved regs to unreadable */
14460 for (i = 0; i < CALLER_SAVED_REGS; i++) {
14461 mark_reg_not_init(env, regs, caller_saved[i]);
14462 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14465 /* mark destination R0 register as readable, since it contains
14466 * the value fetched from the packet.
14467 * Already marked as written above.
14469 mark_reg_unknown(env, regs, BPF_REG_0);
14470 /* ld_abs load up to 32-bit skb data. */
14471 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14475 static int check_return_code(struct bpf_verifier_env *env)
14477 struct tnum enforce_attach_type_range = tnum_unknown;
14478 const struct bpf_prog *prog = env->prog;
14479 struct bpf_reg_state *reg;
14480 struct tnum range = tnum_range(0, 1);
14481 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14483 struct bpf_func_state *frame = env->cur_state->frame[0];
14484 const bool is_subprog = frame->subprogno;
14486 /* LSM and struct_ops func-ptr's return type could be "void" */
14488 switch (prog_type) {
14489 case BPF_PROG_TYPE_LSM:
14490 if (prog->expected_attach_type == BPF_LSM_CGROUP)
14491 /* See below, can be 0 or 0-1 depending on hook. */
14494 case BPF_PROG_TYPE_STRUCT_OPS:
14495 if (!prog->aux->attach_func_proto->type)
14503 /* eBPF calling convention is such that R0 is used
14504 * to return the value from eBPF program.
14505 * Make sure that it's readable at this time
14506 * of bpf_exit, which means that program wrote
14507 * something into it earlier
14509 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14513 if (is_pointer_value(env, BPF_REG_0)) {
14514 verbose(env, "R0 leaks addr as return value\n");
14518 reg = cur_regs(env) + BPF_REG_0;
14520 if (frame->in_async_callback_fn) {
14521 /* enforce return zero from async callbacks like timer */
14522 if (reg->type != SCALAR_VALUE) {
14523 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14524 reg_type_str(env, reg->type));
14528 if (!tnum_in(tnum_const(0), reg->var_off)) {
14529 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14536 if (reg->type != SCALAR_VALUE) {
14537 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14538 reg_type_str(env, reg->type));
14544 switch (prog_type) {
14545 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14546 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14547 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14548 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14549 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14550 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14551 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14552 range = tnum_range(1, 1);
14553 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14554 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14555 range = tnum_range(0, 3);
14557 case BPF_PROG_TYPE_CGROUP_SKB:
14558 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14559 range = tnum_range(0, 3);
14560 enforce_attach_type_range = tnum_range(2, 3);
14563 case BPF_PROG_TYPE_CGROUP_SOCK:
14564 case BPF_PROG_TYPE_SOCK_OPS:
14565 case BPF_PROG_TYPE_CGROUP_DEVICE:
14566 case BPF_PROG_TYPE_CGROUP_SYSCTL:
14567 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14569 case BPF_PROG_TYPE_RAW_TRACEPOINT:
14570 if (!env->prog->aux->attach_btf_id)
14572 range = tnum_const(0);
14574 case BPF_PROG_TYPE_TRACING:
14575 switch (env->prog->expected_attach_type) {
14576 case BPF_TRACE_FENTRY:
14577 case BPF_TRACE_FEXIT:
14578 range = tnum_const(0);
14580 case BPF_TRACE_RAW_TP:
14581 case BPF_MODIFY_RETURN:
14583 case BPF_TRACE_ITER:
14589 case BPF_PROG_TYPE_SK_LOOKUP:
14590 range = tnum_range(SK_DROP, SK_PASS);
14593 case BPF_PROG_TYPE_LSM:
14594 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14595 /* Regular BPF_PROG_TYPE_LSM programs can return
14600 if (!env->prog->aux->attach_func_proto->type) {
14601 /* Make sure programs that attach to void
14602 * hooks don't try to modify return value.
14604 range = tnum_range(1, 1);
14608 case BPF_PROG_TYPE_NETFILTER:
14609 range = tnum_range(NF_DROP, NF_ACCEPT);
14611 case BPF_PROG_TYPE_EXT:
14612 /* freplace program can return anything as its return value
14613 * depends on the to-be-replaced kernel func or bpf program.
14619 if (reg->type != SCALAR_VALUE) {
14620 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14621 reg_type_str(env, reg->type));
14625 if (!tnum_in(range, reg->var_off)) {
14626 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14627 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14628 prog_type == BPF_PROG_TYPE_LSM &&
14629 !prog->aux->attach_func_proto->type)
14630 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14634 if (!tnum_is_unknown(enforce_attach_type_range) &&
14635 tnum_in(enforce_attach_type_range, reg->var_off))
14636 env->prog->enforce_expected_attach_type = 1;
14640 /* non-recursive DFS pseudo code
14641 * 1 procedure DFS-iterative(G,v):
14642 * 2 label v as discovered
14643 * 3 let S be a stack
14645 * 5 while S is not empty
14647 * 7 if t is what we're looking for:
14649 * 9 for all edges e in G.adjacentEdges(t) do
14650 * 10 if edge e is already labelled
14651 * 11 continue with the next edge
14652 * 12 w <- G.adjacentVertex(t,e)
14653 * 13 if vertex w is not discovered and not explored
14654 * 14 label e as tree-edge
14655 * 15 label w as discovered
14658 * 18 else if vertex w is discovered
14659 * 19 label e as back-edge
14661 * 21 // vertex w is explored
14662 * 22 label e as forward- or cross-edge
14663 * 23 label t as explored
14667 * 0x10 - discovered
14668 * 0x11 - discovered and fall-through edge labelled
14669 * 0x12 - discovered and fall-through and branch edges labelled
14680 static u32 state_htab_size(struct bpf_verifier_env *env)
14682 return env->prog->len;
14685 static struct bpf_verifier_state_list **explored_state(
14686 struct bpf_verifier_env *env,
14689 struct bpf_verifier_state *cur = env->cur_state;
14690 struct bpf_func_state *state = cur->frame[cur->curframe];
14692 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14695 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14697 env->insn_aux_data[idx].prune_point = true;
14700 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14702 return env->insn_aux_data[insn_idx].prune_point;
14705 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14707 env->insn_aux_data[idx].force_checkpoint = true;
14710 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14712 return env->insn_aux_data[insn_idx].force_checkpoint;
14717 DONE_EXPLORING = 0,
14718 KEEP_EXPLORING = 1,
14721 /* t, w, e - match pseudo-code above:
14722 * t - index of current instruction
14723 * w - next instruction
14726 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14729 int *insn_stack = env->cfg.insn_stack;
14730 int *insn_state = env->cfg.insn_state;
14732 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14733 return DONE_EXPLORING;
14735 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14736 return DONE_EXPLORING;
14738 if (w < 0 || w >= env->prog->len) {
14739 verbose_linfo(env, t, "%d: ", t);
14740 verbose(env, "jump out of range from insn %d to %d\n", t, w);
14745 /* mark branch target for state pruning */
14746 mark_prune_point(env, w);
14747 mark_jmp_point(env, w);
14750 if (insn_state[w] == 0) {
14752 insn_state[t] = DISCOVERED | e;
14753 insn_state[w] = DISCOVERED;
14754 if (env->cfg.cur_stack >= env->prog->len)
14756 insn_stack[env->cfg.cur_stack++] = w;
14757 return KEEP_EXPLORING;
14758 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14759 if (loop_ok && env->bpf_capable)
14760 return DONE_EXPLORING;
14761 verbose_linfo(env, t, "%d: ", t);
14762 verbose_linfo(env, w, "%d: ", w);
14763 verbose(env, "back-edge from insn %d to %d\n", t, w);
14765 } else if (insn_state[w] == EXPLORED) {
14766 /* forward- or cross-edge */
14767 insn_state[t] = DISCOVERED | e;
14769 verbose(env, "insn state internal bug\n");
14772 return DONE_EXPLORING;
14775 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14776 struct bpf_verifier_env *env,
14781 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14785 mark_prune_point(env, t + 1);
14786 /* when we exit from subprog, we need to record non-linear history */
14787 mark_jmp_point(env, t + 1);
14789 if (visit_callee) {
14790 mark_prune_point(env, t);
14791 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14792 /* It's ok to allow recursion from CFG point of
14793 * view. __check_func_call() will do the actual
14796 bpf_pseudo_func(insns + t));
14801 /* Visits the instruction at index t and returns one of the following:
14802 * < 0 - an error occurred
14803 * DONE_EXPLORING - the instruction was fully explored
14804 * KEEP_EXPLORING - there is still work to be done before it is fully explored
14806 static int visit_insn(int t, struct bpf_verifier_env *env)
14808 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14811 if (bpf_pseudo_func(insn))
14812 return visit_func_call_insn(t, insns, env, true);
14814 /* All non-branch instructions have a single fall-through edge. */
14815 if (BPF_CLASS(insn->code) != BPF_JMP &&
14816 BPF_CLASS(insn->code) != BPF_JMP32)
14817 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14819 switch (BPF_OP(insn->code)) {
14821 return DONE_EXPLORING;
14824 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14825 /* Mark this call insn as a prune point to trigger
14826 * is_state_visited() check before call itself is
14827 * processed by __check_func_call(). Otherwise new
14828 * async state will be pushed for further exploration.
14830 mark_prune_point(env, t);
14831 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14832 struct bpf_kfunc_call_arg_meta meta;
14834 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14835 if (ret == 0 && is_iter_next_kfunc(&meta)) {
14836 mark_prune_point(env, t);
14837 /* Checking and saving state checkpoints at iter_next() call
14838 * is crucial for fast convergence of open-coded iterator loop
14839 * logic, so we need to force it. If we don't do that,
14840 * is_state_visited() might skip saving a checkpoint, causing
14841 * unnecessarily long sequence of not checkpointed
14842 * instructions and jumps, leading to exhaustion of jump
14843 * history buffer, and potentially other undesired outcomes.
14844 * It is expected that with correct open-coded iterators
14845 * convergence will happen quickly, so we don't run a risk of
14846 * exhausting memory.
14848 mark_force_checkpoint(env, t);
14851 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14854 if (BPF_SRC(insn->code) != BPF_K)
14857 if (BPF_CLASS(insn->code) == BPF_JMP)
14862 /* unconditional jump with single edge */
14863 ret = push_insn(t, t + off + 1, FALLTHROUGH, env,
14868 mark_prune_point(env, t + off + 1);
14869 mark_jmp_point(env, t + off + 1);
14874 /* conditional jump with two edges */
14875 mark_prune_point(env, t);
14877 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14881 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14885 /* non-recursive depth-first-search to detect loops in BPF program
14886 * loop == back-edge in directed graph
14888 static int check_cfg(struct bpf_verifier_env *env)
14890 int insn_cnt = env->prog->len;
14891 int *insn_stack, *insn_state;
14895 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14899 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14901 kvfree(insn_state);
14905 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14906 insn_stack[0] = 0; /* 0 is the first instruction */
14907 env->cfg.cur_stack = 1;
14909 while (env->cfg.cur_stack > 0) {
14910 int t = insn_stack[env->cfg.cur_stack - 1];
14912 ret = visit_insn(t, env);
14914 case DONE_EXPLORING:
14915 insn_state[t] = EXPLORED;
14916 env->cfg.cur_stack--;
14918 case KEEP_EXPLORING:
14922 verbose(env, "visit_insn internal bug\n");
14929 if (env->cfg.cur_stack < 0) {
14930 verbose(env, "pop stack internal bug\n");
14935 for (i = 0; i < insn_cnt; i++) {
14936 if (insn_state[i] != EXPLORED) {
14937 verbose(env, "unreachable insn %d\n", i);
14942 ret = 0; /* cfg looks good */
14945 kvfree(insn_state);
14946 kvfree(insn_stack);
14947 env->cfg.insn_state = env->cfg.insn_stack = NULL;
14951 static int check_abnormal_return(struct bpf_verifier_env *env)
14955 for (i = 1; i < env->subprog_cnt; i++) {
14956 if (env->subprog_info[i].has_ld_abs) {
14957 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14960 if (env->subprog_info[i].has_tail_call) {
14961 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14968 /* The minimum supported BTF func info size */
14969 #define MIN_BPF_FUNCINFO_SIZE 8
14970 #define MAX_FUNCINFO_REC_SIZE 252
14972 static int check_btf_func(struct bpf_verifier_env *env,
14973 const union bpf_attr *attr,
14976 const struct btf_type *type, *func_proto, *ret_type;
14977 u32 i, nfuncs, urec_size, min_size;
14978 u32 krec_size = sizeof(struct bpf_func_info);
14979 struct bpf_func_info *krecord;
14980 struct bpf_func_info_aux *info_aux = NULL;
14981 struct bpf_prog *prog;
14982 const struct btf *btf;
14984 u32 prev_offset = 0;
14985 bool scalar_return;
14988 nfuncs = attr->func_info_cnt;
14990 if (check_abnormal_return(env))
14995 if (nfuncs != env->subprog_cnt) {
14996 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15000 urec_size = attr->func_info_rec_size;
15001 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15002 urec_size > MAX_FUNCINFO_REC_SIZE ||
15003 urec_size % sizeof(u32)) {
15004 verbose(env, "invalid func info rec size %u\n", urec_size);
15009 btf = prog->aux->btf;
15011 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15012 min_size = min_t(u32, krec_size, urec_size);
15014 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15017 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15021 for (i = 0; i < nfuncs; i++) {
15022 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15024 if (ret == -E2BIG) {
15025 verbose(env, "nonzero tailing record in func info");
15026 /* set the size kernel expects so loader can zero
15027 * out the rest of the record.
15029 if (copy_to_bpfptr_offset(uattr,
15030 offsetof(union bpf_attr, func_info_rec_size),
15031 &min_size, sizeof(min_size)))
15037 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15042 /* check insn_off */
15045 if (krecord[i].insn_off) {
15047 "nonzero insn_off %u for the first func info record",
15048 krecord[i].insn_off);
15051 } else if (krecord[i].insn_off <= prev_offset) {
15053 "same or smaller insn offset (%u) than previous func info record (%u)",
15054 krecord[i].insn_off, prev_offset);
15058 if (env->subprog_info[i].start != krecord[i].insn_off) {
15059 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15063 /* check type_id */
15064 type = btf_type_by_id(btf, krecord[i].type_id);
15065 if (!type || !btf_type_is_func(type)) {
15066 verbose(env, "invalid type id %d in func info",
15067 krecord[i].type_id);
15070 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15072 func_proto = btf_type_by_id(btf, type->type);
15073 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15074 /* btf_func_check() already verified it during BTF load */
15076 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15078 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15079 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15080 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15083 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15084 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15088 prev_offset = krecord[i].insn_off;
15089 bpfptr_add(&urecord, urec_size);
15092 prog->aux->func_info = krecord;
15093 prog->aux->func_info_cnt = nfuncs;
15094 prog->aux->func_info_aux = info_aux;
15103 static void adjust_btf_func(struct bpf_verifier_env *env)
15105 struct bpf_prog_aux *aux = env->prog->aux;
15108 if (!aux->func_info)
15111 for (i = 0; i < env->subprog_cnt; i++)
15112 aux->func_info[i].insn_off = env->subprog_info[i].start;
15115 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
15116 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
15118 static int check_btf_line(struct bpf_verifier_env *env,
15119 const union bpf_attr *attr,
15122 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15123 struct bpf_subprog_info *sub;
15124 struct bpf_line_info *linfo;
15125 struct bpf_prog *prog;
15126 const struct btf *btf;
15130 nr_linfo = attr->line_info_cnt;
15133 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15136 rec_size = attr->line_info_rec_size;
15137 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15138 rec_size > MAX_LINEINFO_REC_SIZE ||
15139 rec_size & (sizeof(u32) - 1))
15142 /* Need to zero it in case the userspace may
15143 * pass in a smaller bpf_line_info object.
15145 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15146 GFP_KERNEL | __GFP_NOWARN);
15151 btf = prog->aux->btf;
15154 sub = env->subprog_info;
15155 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15156 expected_size = sizeof(struct bpf_line_info);
15157 ncopy = min_t(u32, expected_size, rec_size);
15158 for (i = 0; i < nr_linfo; i++) {
15159 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15161 if (err == -E2BIG) {
15162 verbose(env, "nonzero tailing record in line_info");
15163 if (copy_to_bpfptr_offset(uattr,
15164 offsetof(union bpf_attr, line_info_rec_size),
15165 &expected_size, sizeof(expected_size)))
15171 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15177 * Check insn_off to ensure
15178 * 1) strictly increasing AND
15179 * 2) bounded by prog->len
15181 * The linfo[0].insn_off == 0 check logically falls into
15182 * the later "missing bpf_line_info for func..." case
15183 * because the first linfo[0].insn_off must be the
15184 * first sub also and the first sub must have
15185 * subprog_info[0].start == 0.
15187 if ((i && linfo[i].insn_off <= prev_offset) ||
15188 linfo[i].insn_off >= prog->len) {
15189 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15190 i, linfo[i].insn_off, prev_offset,
15196 if (!prog->insnsi[linfo[i].insn_off].code) {
15198 "Invalid insn code at line_info[%u].insn_off\n",
15204 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15205 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15206 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15211 if (s != env->subprog_cnt) {
15212 if (linfo[i].insn_off == sub[s].start) {
15213 sub[s].linfo_idx = i;
15215 } else if (sub[s].start < linfo[i].insn_off) {
15216 verbose(env, "missing bpf_line_info for func#%u\n", s);
15222 prev_offset = linfo[i].insn_off;
15223 bpfptr_add(&ulinfo, rec_size);
15226 if (s != env->subprog_cnt) {
15227 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15228 env->subprog_cnt - s, s);
15233 prog->aux->linfo = linfo;
15234 prog->aux->nr_linfo = nr_linfo;
15243 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
15244 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
15246 static int check_core_relo(struct bpf_verifier_env *env,
15247 const union bpf_attr *attr,
15250 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15251 struct bpf_core_relo core_relo = {};
15252 struct bpf_prog *prog = env->prog;
15253 const struct btf *btf = prog->aux->btf;
15254 struct bpf_core_ctx ctx = {
15258 bpfptr_t u_core_relo;
15261 nr_core_relo = attr->core_relo_cnt;
15264 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15267 rec_size = attr->core_relo_rec_size;
15268 if (rec_size < MIN_CORE_RELO_SIZE ||
15269 rec_size > MAX_CORE_RELO_SIZE ||
15270 rec_size % sizeof(u32))
15273 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15274 expected_size = sizeof(struct bpf_core_relo);
15275 ncopy = min_t(u32, expected_size, rec_size);
15277 /* Unlike func_info and line_info, copy and apply each CO-RE
15278 * relocation record one at a time.
15280 for (i = 0; i < nr_core_relo; i++) {
15281 /* future proofing when sizeof(bpf_core_relo) changes */
15282 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15284 if (err == -E2BIG) {
15285 verbose(env, "nonzero tailing record in core_relo");
15286 if (copy_to_bpfptr_offset(uattr,
15287 offsetof(union bpf_attr, core_relo_rec_size),
15288 &expected_size, sizeof(expected_size)))
15294 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15299 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15300 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15301 i, core_relo.insn_off, prog->len);
15306 err = bpf_core_apply(&ctx, &core_relo, i,
15307 &prog->insnsi[core_relo.insn_off / 8]);
15310 bpfptr_add(&u_core_relo, rec_size);
15315 static int check_btf_info(struct bpf_verifier_env *env,
15316 const union bpf_attr *attr,
15322 if (!attr->func_info_cnt && !attr->line_info_cnt) {
15323 if (check_abnormal_return(env))
15328 btf = btf_get_by_fd(attr->prog_btf_fd);
15330 return PTR_ERR(btf);
15331 if (btf_is_kernel(btf)) {
15335 env->prog->aux->btf = btf;
15337 err = check_btf_func(env, attr, uattr);
15341 err = check_btf_line(env, attr, uattr);
15345 err = check_core_relo(env, attr, uattr);
15352 /* check %cur's range satisfies %old's */
15353 static bool range_within(struct bpf_reg_state *old,
15354 struct bpf_reg_state *cur)
15356 return old->umin_value <= cur->umin_value &&
15357 old->umax_value >= cur->umax_value &&
15358 old->smin_value <= cur->smin_value &&
15359 old->smax_value >= cur->smax_value &&
15360 old->u32_min_value <= cur->u32_min_value &&
15361 old->u32_max_value >= cur->u32_max_value &&
15362 old->s32_min_value <= cur->s32_min_value &&
15363 old->s32_max_value >= cur->s32_max_value;
15366 /* If in the old state two registers had the same id, then they need to have
15367 * the same id in the new state as well. But that id could be different from
15368 * the old state, so we need to track the mapping from old to new ids.
15369 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15370 * regs with old id 5 must also have new id 9 for the new state to be safe. But
15371 * regs with a different old id could still have new id 9, we don't care about
15373 * So we look through our idmap to see if this old id has been seen before. If
15374 * so, we require the new id to match; otherwise, we add the id pair to the map.
15376 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15378 struct bpf_id_pair *map = idmap->map;
15381 /* either both IDs should be set or both should be zero */
15382 if (!!old_id != !!cur_id)
15385 if (old_id == 0) /* cur_id == 0 as well */
15388 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15390 /* Reached an empty slot; haven't seen this id before */
15391 map[i].old = old_id;
15392 map[i].cur = cur_id;
15395 if (map[i].old == old_id)
15396 return map[i].cur == cur_id;
15397 if (map[i].cur == cur_id)
15400 /* We ran out of idmap slots, which should be impossible */
15405 /* Similar to check_ids(), but allocate a unique temporary ID
15406 * for 'old_id' or 'cur_id' of zero.
15407 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15409 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15411 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15412 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15414 return check_ids(old_id, cur_id, idmap);
15417 static void clean_func_state(struct bpf_verifier_env *env,
15418 struct bpf_func_state *st)
15420 enum bpf_reg_liveness live;
15423 for (i = 0; i < BPF_REG_FP; i++) {
15424 live = st->regs[i].live;
15425 /* liveness must not touch this register anymore */
15426 st->regs[i].live |= REG_LIVE_DONE;
15427 if (!(live & REG_LIVE_READ))
15428 /* since the register is unused, clear its state
15429 * to make further comparison simpler
15431 __mark_reg_not_init(env, &st->regs[i]);
15434 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15435 live = st->stack[i].spilled_ptr.live;
15436 /* liveness must not touch this stack slot anymore */
15437 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15438 if (!(live & REG_LIVE_READ)) {
15439 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15440 for (j = 0; j < BPF_REG_SIZE; j++)
15441 st->stack[i].slot_type[j] = STACK_INVALID;
15446 static void clean_verifier_state(struct bpf_verifier_env *env,
15447 struct bpf_verifier_state *st)
15451 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15452 /* all regs in this state in all frames were already marked */
15455 for (i = 0; i <= st->curframe; i++)
15456 clean_func_state(env, st->frame[i]);
15459 /* the parentage chains form a tree.
15460 * the verifier states are added to state lists at given insn and
15461 * pushed into state stack for future exploration.
15462 * when the verifier reaches bpf_exit insn some of the verifer states
15463 * stored in the state lists have their final liveness state already,
15464 * but a lot of states will get revised from liveness point of view when
15465 * the verifier explores other branches.
15468 * 2: if r1 == 100 goto pc+1
15471 * when the verifier reaches exit insn the register r0 in the state list of
15472 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15473 * of insn 2 and goes exploring further. At the insn 4 it will walk the
15474 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15476 * Since the verifier pushes the branch states as it sees them while exploring
15477 * the program the condition of walking the branch instruction for the second
15478 * time means that all states below this branch were already explored and
15479 * their final liveness marks are already propagated.
15480 * Hence when the verifier completes the search of state list in is_state_visited()
15481 * we can call this clean_live_states() function to mark all liveness states
15482 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15483 * will not be used.
15484 * This function also clears the registers and stack for states that !READ
15485 * to simplify state merging.
15487 * Important note here that walking the same branch instruction in the callee
15488 * doesn't meant that the states are DONE. The verifier has to compare
15491 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15492 struct bpf_verifier_state *cur)
15494 struct bpf_verifier_state_list *sl;
15497 sl = *explored_state(env, insn);
15499 if (sl->state.branches)
15501 if (sl->state.insn_idx != insn ||
15502 sl->state.curframe != cur->curframe)
15504 for (i = 0; i <= cur->curframe; i++)
15505 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15507 clean_verifier_state(env, &sl->state);
15513 static bool regs_exact(const struct bpf_reg_state *rold,
15514 const struct bpf_reg_state *rcur,
15515 struct bpf_idmap *idmap)
15517 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15518 check_ids(rold->id, rcur->id, idmap) &&
15519 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15522 /* Returns true if (rold safe implies rcur safe) */
15523 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15524 struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15526 if (!(rold->live & REG_LIVE_READ))
15527 /* explored state didn't use this */
15529 if (rold->type == NOT_INIT)
15530 /* explored state can't have used this */
15532 if (rcur->type == NOT_INIT)
15535 /* Enforce that register types have to match exactly, including their
15536 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15539 * One can make a point that using a pointer register as unbounded
15540 * SCALAR would be technically acceptable, but this could lead to
15541 * pointer leaks because scalars are allowed to leak while pointers
15542 * are not. We could make this safe in special cases if root is
15543 * calling us, but it's probably not worth the hassle.
15545 * Also, register types that are *not* MAYBE_NULL could technically be
15546 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15547 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15548 * to the same map).
15549 * However, if the old MAYBE_NULL register then got NULL checked,
15550 * doing so could have affected others with the same id, and we can't
15551 * check for that because we lost the id when we converted to
15552 * a non-MAYBE_NULL variant.
15553 * So, as a general rule we don't allow mixing MAYBE_NULL and
15554 * non-MAYBE_NULL registers as well.
15556 if (rold->type != rcur->type)
15559 switch (base_type(rold->type)) {
15561 if (env->explore_alu_limits) {
15562 /* explore_alu_limits disables tnum_in() and range_within()
15563 * logic and requires everything to be strict
15565 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15566 check_scalar_ids(rold->id, rcur->id, idmap);
15568 if (!rold->precise)
15570 /* Why check_ids() for scalar registers?
15572 * Consider the following BPF code:
15573 * 1: r6 = ... unbound scalar, ID=a ...
15574 * 2: r7 = ... unbound scalar, ID=b ...
15575 * 3: if (r6 > r7) goto +1
15577 * 5: if (r6 > X) goto ...
15578 * 6: ... memory operation using r7 ...
15580 * First verification path is [1-6]:
15581 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15582 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15583 * r7 <= X, because r6 and r7 share same id.
15584 * Next verification path is [1-4, 6].
15586 * Instruction (6) would be reached in two states:
15587 * I. r6{.id=b}, r7{.id=b} via path 1-6;
15588 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15590 * Use check_ids() to distinguish these states.
15592 * Also verify that new value satisfies old value range knowledge.
15594 return range_within(rold, rcur) &&
15595 tnum_in(rold->var_off, rcur->var_off) &&
15596 check_scalar_ids(rold->id, rcur->id, idmap);
15597 case PTR_TO_MAP_KEY:
15598 case PTR_TO_MAP_VALUE:
15601 case PTR_TO_TP_BUFFER:
15602 /* If the new min/max/var_off satisfy the old ones and
15603 * everything else matches, we are OK.
15605 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15606 range_within(rold, rcur) &&
15607 tnum_in(rold->var_off, rcur->var_off) &&
15608 check_ids(rold->id, rcur->id, idmap) &&
15609 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15610 case PTR_TO_PACKET_META:
15611 case PTR_TO_PACKET:
15612 /* We must have at least as much range as the old ptr
15613 * did, so that any accesses which were safe before are
15614 * still safe. This is true even if old range < old off,
15615 * since someone could have accessed through (ptr - k), or
15616 * even done ptr -= k in a register, to get a safe access.
15618 if (rold->range > rcur->range)
15620 /* If the offsets don't match, we can't trust our alignment;
15621 * nor can we be sure that we won't fall out of range.
15623 if (rold->off != rcur->off)
15625 /* id relations must be preserved */
15626 if (!check_ids(rold->id, rcur->id, idmap))
15628 /* new val must satisfy old val knowledge */
15629 return range_within(rold, rcur) &&
15630 tnum_in(rold->var_off, rcur->var_off);
15632 /* two stack pointers are equal only if they're pointing to
15633 * the same stack frame, since fp-8 in foo != fp-8 in bar
15635 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15637 return regs_exact(rold, rcur, idmap);
15641 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15642 struct bpf_func_state *cur, struct bpf_idmap *idmap)
15646 /* walk slots of the explored stack and ignore any additional
15647 * slots in the current stack, since explored(safe) state
15650 for (i = 0; i < old->allocated_stack; i++) {
15651 struct bpf_reg_state *old_reg, *cur_reg;
15653 spi = i / BPF_REG_SIZE;
15655 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15656 i += BPF_REG_SIZE - 1;
15657 /* explored state didn't use this */
15661 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15664 if (env->allow_uninit_stack &&
15665 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15668 /* explored stack has more populated slots than current stack
15669 * and these slots were used
15671 if (i >= cur->allocated_stack)
15674 /* if old state was safe with misc data in the stack
15675 * it will be safe with zero-initialized stack.
15676 * The opposite is not true
15678 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15679 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15681 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15682 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15683 /* Ex: old explored (safe) state has STACK_SPILL in
15684 * this stack slot, but current has STACK_MISC ->
15685 * this verifier states are not equivalent,
15686 * return false to continue verification of this path
15689 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15691 /* Both old and cur are having same slot_type */
15692 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15694 /* when explored and current stack slot are both storing
15695 * spilled registers, check that stored pointers types
15696 * are the same as well.
15697 * Ex: explored safe path could have stored
15698 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15699 * but current path has stored:
15700 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15701 * such verifier states are not equivalent.
15702 * return false to continue verification of this path
15704 if (!regsafe(env, &old->stack[spi].spilled_ptr,
15705 &cur->stack[spi].spilled_ptr, idmap))
15709 old_reg = &old->stack[spi].spilled_ptr;
15710 cur_reg = &cur->stack[spi].spilled_ptr;
15711 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15712 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15713 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15717 old_reg = &old->stack[spi].spilled_ptr;
15718 cur_reg = &cur->stack[spi].spilled_ptr;
15719 /* iter.depth is not compared between states as it
15720 * doesn't matter for correctness and would otherwise
15721 * prevent convergence; we maintain it only to prevent
15722 * infinite loop check triggering, see
15723 * iter_active_depths_differ()
15725 if (old_reg->iter.btf != cur_reg->iter.btf ||
15726 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15727 old_reg->iter.state != cur_reg->iter.state ||
15728 /* ignore {old_reg,cur_reg}->iter.depth, see above */
15729 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15734 case STACK_INVALID:
15736 /* Ensure that new unhandled slot types return false by default */
15744 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15745 struct bpf_idmap *idmap)
15749 if (old->acquired_refs != cur->acquired_refs)
15752 for (i = 0; i < old->acquired_refs; i++) {
15753 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15760 /* compare two verifier states
15762 * all states stored in state_list are known to be valid, since
15763 * verifier reached 'bpf_exit' instruction through them
15765 * this function is called when verifier exploring different branches of
15766 * execution popped from the state stack. If it sees an old state that has
15767 * more strict register state and more strict stack state then this execution
15768 * branch doesn't need to be explored further, since verifier already
15769 * concluded that more strict state leads to valid finish.
15771 * Therefore two states are equivalent if register state is more conservative
15772 * and explored stack state is more conservative than the current one.
15775 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15776 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15778 * In other words if current stack state (one being explored) has more
15779 * valid slots than old one that already passed validation, it means
15780 * the verifier can stop exploring and conclude that current state is valid too
15782 * Similarly with registers. If explored state has register type as invalid
15783 * whereas register type in current state is meaningful, it means that
15784 * the current state will reach 'bpf_exit' instruction safely
15786 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15787 struct bpf_func_state *cur)
15791 for (i = 0; i < MAX_BPF_REG; i++)
15792 if (!regsafe(env, &old->regs[i], &cur->regs[i],
15793 &env->idmap_scratch))
15796 if (!stacksafe(env, old, cur, &env->idmap_scratch))
15799 if (!refsafe(old, cur, &env->idmap_scratch))
15805 static bool states_equal(struct bpf_verifier_env *env,
15806 struct bpf_verifier_state *old,
15807 struct bpf_verifier_state *cur)
15811 if (old->curframe != cur->curframe)
15814 env->idmap_scratch.tmp_id_gen = env->id_gen;
15815 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15817 /* Verification state from speculative execution simulation
15818 * must never prune a non-speculative execution one.
15820 if (old->speculative && !cur->speculative)
15823 if (old->active_lock.ptr != cur->active_lock.ptr)
15826 /* Old and cur active_lock's have to be either both present
15829 if (!!old->active_lock.id != !!cur->active_lock.id)
15832 if (old->active_lock.id &&
15833 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15836 if (old->active_rcu_lock != cur->active_rcu_lock)
15839 /* for states to be equal callsites have to be the same
15840 * and all frame states need to be equivalent
15842 for (i = 0; i <= old->curframe; i++) {
15843 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15845 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15851 /* Return 0 if no propagation happened. Return negative error code if error
15852 * happened. Otherwise, return the propagated bit.
15854 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15855 struct bpf_reg_state *reg,
15856 struct bpf_reg_state *parent_reg)
15858 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15859 u8 flag = reg->live & REG_LIVE_READ;
15862 /* When comes here, read flags of PARENT_REG or REG could be any of
15863 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15864 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15866 if (parent_flag == REG_LIVE_READ64 ||
15867 /* Or if there is no read flag from REG. */
15869 /* Or if the read flag from REG is the same as PARENT_REG. */
15870 parent_flag == flag)
15873 err = mark_reg_read(env, reg, parent_reg, flag);
15880 /* A write screens off any subsequent reads; but write marks come from the
15881 * straight-line code between a state and its parent. When we arrive at an
15882 * equivalent state (jump target or such) we didn't arrive by the straight-line
15883 * code, so read marks in the state must propagate to the parent regardless
15884 * of the state's write marks. That's what 'parent == state->parent' comparison
15885 * in mark_reg_read() is for.
15887 static int propagate_liveness(struct bpf_verifier_env *env,
15888 const struct bpf_verifier_state *vstate,
15889 struct bpf_verifier_state *vparent)
15891 struct bpf_reg_state *state_reg, *parent_reg;
15892 struct bpf_func_state *state, *parent;
15893 int i, frame, err = 0;
15895 if (vparent->curframe != vstate->curframe) {
15896 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15897 vparent->curframe, vstate->curframe);
15900 /* Propagate read liveness of registers... */
15901 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15902 for (frame = 0; frame <= vstate->curframe; frame++) {
15903 parent = vparent->frame[frame];
15904 state = vstate->frame[frame];
15905 parent_reg = parent->regs;
15906 state_reg = state->regs;
15907 /* We don't need to worry about FP liveness, it's read-only */
15908 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15909 err = propagate_liveness_reg(env, &state_reg[i],
15913 if (err == REG_LIVE_READ64)
15914 mark_insn_zext(env, &parent_reg[i]);
15917 /* Propagate stack slots. */
15918 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15919 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15920 parent_reg = &parent->stack[i].spilled_ptr;
15921 state_reg = &state->stack[i].spilled_ptr;
15922 err = propagate_liveness_reg(env, state_reg,
15931 /* find precise scalars in the previous equivalent state and
15932 * propagate them into the current state
15934 static int propagate_precision(struct bpf_verifier_env *env,
15935 const struct bpf_verifier_state *old)
15937 struct bpf_reg_state *state_reg;
15938 struct bpf_func_state *state;
15939 int i, err = 0, fr;
15942 for (fr = old->curframe; fr >= 0; fr--) {
15943 state = old->frame[fr];
15944 state_reg = state->regs;
15946 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15947 if (state_reg->type != SCALAR_VALUE ||
15948 !state_reg->precise ||
15949 !(state_reg->live & REG_LIVE_READ))
15951 if (env->log.level & BPF_LOG_LEVEL2) {
15953 verbose(env, "frame %d: propagating r%d", fr, i);
15955 verbose(env, ",r%d", i);
15957 bt_set_frame_reg(&env->bt, fr, i);
15961 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15962 if (!is_spilled_reg(&state->stack[i]))
15964 state_reg = &state->stack[i].spilled_ptr;
15965 if (state_reg->type != SCALAR_VALUE ||
15966 !state_reg->precise ||
15967 !(state_reg->live & REG_LIVE_READ))
15969 if (env->log.level & BPF_LOG_LEVEL2) {
15971 verbose(env, "frame %d: propagating fp%d",
15972 fr, (-i - 1) * BPF_REG_SIZE);
15974 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15976 bt_set_frame_slot(&env->bt, fr, i);
15980 verbose(env, "\n");
15983 err = mark_chain_precision_batch(env);
15990 static bool states_maybe_looping(struct bpf_verifier_state *old,
15991 struct bpf_verifier_state *cur)
15993 struct bpf_func_state *fold, *fcur;
15994 int i, fr = cur->curframe;
15996 if (old->curframe != fr)
15999 fold = old->frame[fr];
16000 fcur = cur->frame[fr];
16001 for (i = 0; i < MAX_BPF_REG; i++)
16002 if (memcmp(&fold->regs[i], &fcur->regs[i],
16003 offsetof(struct bpf_reg_state, parent)))
16008 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16010 return env->insn_aux_data[insn_idx].is_iter_next;
16013 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16014 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16015 * states to match, which otherwise would look like an infinite loop. So while
16016 * iter_next() calls are taken care of, we still need to be careful and
16017 * prevent erroneous and too eager declaration of "ininite loop", when
16018 * iterators are involved.
16020 * Here's a situation in pseudo-BPF assembly form:
16022 * 0: again: ; set up iter_next() call args
16023 * 1: r1 = &it ; <CHECKPOINT HERE>
16024 * 2: call bpf_iter_num_next ; this is iter_next() call
16025 * 3: if r0 == 0 goto done
16026 * 4: ... something useful here ...
16027 * 5: goto again ; another iteration
16030 * 8: call bpf_iter_num_destroy ; clean up iter state
16033 * This is a typical loop. Let's assume that we have a prune point at 1:,
16034 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16035 * again`, assuming other heuristics don't get in a way).
16037 * When we first time come to 1:, let's say we have some state X. We proceed
16038 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16039 * Now we come back to validate that forked ACTIVE state. We proceed through
16040 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16041 * are converging. But the problem is that we don't know that yet, as this
16042 * convergence has to happen at iter_next() call site only. So if nothing is
16043 * done, at 1: verifier will use bounded loop logic and declare infinite
16044 * looping (and would be *technically* correct, if not for iterator's
16045 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16046 * don't want that. So what we do in process_iter_next_call() when we go on
16047 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16048 * a different iteration. So when we suspect an infinite loop, we additionally
16049 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16050 * pretend we are not looping and wait for next iter_next() call.
16052 * This only applies to ACTIVE state. In DRAINED state we don't expect to
16053 * loop, because that would actually mean infinite loop, as DRAINED state is
16054 * "sticky", and so we'll keep returning into the same instruction with the
16055 * same state (at least in one of possible code paths).
16057 * This approach allows to keep infinite loop heuristic even in the face of
16058 * active iterator. E.g., C snippet below is and will be detected as
16059 * inifintely looping:
16061 * struct bpf_iter_num it;
16064 * bpf_iter_num_new(&it, 0, 10);
16065 * while ((p = bpf_iter_num_next(&t))) {
16067 * while (x--) {} // <<-- infinite loop here
16071 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16073 struct bpf_reg_state *slot, *cur_slot;
16074 struct bpf_func_state *state;
16077 for (fr = old->curframe; fr >= 0; fr--) {
16078 state = old->frame[fr];
16079 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16080 if (state->stack[i].slot_type[0] != STACK_ITER)
16083 slot = &state->stack[i].spilled_ptr;
16084 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16087 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16088 if (cur_slot->iter.depth != slot->iter.depth)
16095 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16097 struct bpf_verifier_state_list *new_sl;
16098 struct bpf_verifier_state_list *sl, **pprev;
16099 struct bpf_verifier_state *cur = env->cur_state, *new;
16100 int i, j, err, states_cnt = 0;
16101 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16102 bool add_new_state = force_new_state;
16104 /* bpf progs typically have pruning point every 4 instructions
16105 * http://vger.kernel.org/bpfconf2019.html#session-1
16106 * Do not add new state for future pruning if the verifier hasn't seen
16107 * at least 2 jumps and at least 8 instructions.
16108 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16109 * In tests that amounts to up to 50% reduction into total verifier
16110 * memory consumption and 20% verifier time speedup.
16112 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16113 env->insn_processed - env->prev_insn_processed >= 8)
16114 add_new_state = true;
16116 pprev = explored_state(env, insn_idx);
16119 clean_live_states(env, insn_idx, cur);
16123 if (sl->state.insn_idx != insn_idx)
16126 if (sl->state.branches) {
16127 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16129 if (frame->in_async_callback_fn &&
16130 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16131 /* Different async_entry_cnt means that the verifier is
16132 * processing another entry into async callback.
16133 * Seeing the same state is not an indication of infinite
16134 * loop or infinite recursion.
16135 * But finding the same state doesn't mean that it's safe
16136 * to stop processing the current state. The previous state
16137 * hasn't yet reached bpf_exit, since state.branches > 0.
16138 * Checking in_async_callback_fn alone is not enough either.
16139 * Since the verifier still needs to catch infinite loops
16140 * inside async callbacks.
16142 goto skip_inf_loop_check;
16144 /* BPF open-coded iterators loop detection is special.
16145 * states_maybe_looping() logic is too simplistic in detecting
16146 * states that *might* be equivalent, because it doesn't know
16147 * about ID remapping, so don't even perform it.
16148 * See process_iter_next_call() and iter_active_depths_differ()
16149 * for overview of the logic. When current and one of parent
16150 * states are detected as equivalent, it's a good thing: we prove
16151 * convergence and can stop simulating further iterations.
16152 * It's safe to assume that iterator loop will finish, taking into
16153 * account iter_next() contract of eventually returning
16154 * sticky NULL result.
16156 if (is_iter_next_insn(env, insn_idx)) {
16157 if (states_equal(env, &sl->state, cur)) {
16158 struct bpf_func_state *cur_frame;
16159 struct bpf_reg_state *iter_state, *iter_reg;
16162 cur_frame = cur->frame[cur->curframe];
16163 /* btf_check_iter_kfuncs() enforces that
16164 * iter state pointer is always the first arg
16166 iter_reg = &cur_frame->regs[BPF_REG_1];
16167 /* current state is valid due to states_equal(),
16168 * so we can assume valid iter and reg state,
16169 * no need for extra (re-)validations
16171 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16172 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16173 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
16176 goto skip_inf_loop_check;
16178 /* attempt to detect infinite loop to avoid unnecessary doomed work */
16179 if (states_maybe_looping(&sl->state, cur) &&
16180 states_equal(env, &sl->state, cur) &&
16181 !iter_active_depths_differ(&sl->state, cur)) {
16182 verbose_linfo(env, insn_idx, "; ");
16183 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16186 /* if the verifier is processing a loop, avoid adding new state
16187 * too often, since different loop iterations have distinct
16188 * states and may not help future pruning.
16189 * This threshold shouldn't be too low to make sure that
16190 * a loop with large bound will be rejected quickly.
16191 * The most abusive loop will be:
16193 * if r1 < 1000000 goto pc-2
16194 * 1M insn_procssed limit / 100 == 10k peak states.
16195 * This threshold shouldn't be too high either, since states
16196 * at the end of the loop are likely to be useful in pruning.
16198 skip_inf_loop_check:
16199 if (!force_new_state &&
16200 env->jmps_processed - env->prev_jmps_processed < 20 &&
16201 env->insn_processed - env->prev_insn_processed < 100)
16202 add_new_state = false;
16205 if (states_equal(env, &sl->state, cur)) {
16208 /* reached equivalent register/stack state,
16209 * prune the search.
16210 * Registers read by the continuation are read by us.
16211 * If we have any write marks in env->cur_state, they
16212 * will prevent corresponding reads in the continuation
16213 * from reaching our parent (an explored_state). Our
16214 * own state will get the read marks recorded, but
16215 * they'll be immediately forgotten as we're pruning
16216 * this state and will pop a new one.
16218 err = propagate_liveness(env, &sl->state, cur);
16220 /* if previous state reached the exit with precision and
16221 * current state is equivalent to it (except precsion marks)
16222 * the precision needs to be propagated back in
16223 * the current state.
16225 err = err ? : push_jmp_history(env, cur);
16226 err = err ? : propagate_precision(env, &sl->state);
16232 /* when new state is not going to be added do not increase miss count.
16233 * Otherwise several loop iterations will remove the state
16234 * recorded earlier. The goal of these heuristics is to have
16235 * states from some iterations of the loop (some in the beginning
16236 * and some at the end) to help pruning.
16240 /* heuristic to determine whether this state is beneficial
16241 * to keep checking from state equivalence point of view.
16242 * Higher numbers increase max_states_per_insn and verification time,
16243 * but do not meaningfully decrease insn_processed.
16245 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16246 /* the state is unlikely to be useful. Remove it to
16247 * speed up verification
16250 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16251 u32 br = sl->state.branches;
16254 "BUG live_done but branches_to_explore %d\n",
16256 free_verifier_state(&sl->state, false);
16258 env->peak_states--;
16260 /* cannot free this state, since parentage chain may
16261 * walk it later. Add it for free_list instead to
16262 * be freed at the end of verification
16264 sl->next = env->free_list;
16265 env->free_list = sl;
16275 if (env->max_states_per_insn < states_cnt)
16276 env->max_states_per_insn = states_cnt;
16278 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16281 if (!add_new_state)
16284 /* There were no equivalent states, remember the current one.
16285 * Technically the current state is not proven to be safe yet,
16286 * but it will either reach outer most bpf_exit (which means it's safe)
16287 * or it will be rejected. When there are no loops the verifier won't be
16288 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16289 * again on the way to bpf_exit.
16290 * When looping the sl->state.branches will be > 0 and this state
16291 * will not be considered for equivalence until branches == 0.
16293 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16296 env->total_states++;
16297 env->peak_states++;
16298 env->prev_jmps_processed = env->jmps_processed;
16299 env->prev_insn_processed = env->insn_processed;
16301 /* forget precise markings we inherited, see __mark_chain_precision */
16302 if (env->bpf_capable)
16303 mark_all_scalars_imprecise(env, cur);
16305 /* add new state to the head of linked list */
16306 new = &new_sl->state;
16307 err = copy_verifier_state(new, cur);
16309 free_verifier_state(new, false);
16313 new->insn_idx = insn_idx;
16314 WARN_ONCE(new->branches != 1,
16315 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16318 cur->first_insn_idx = insn_idx;
16319 clear_jmp_history(cur);
16320 new_sl->next = *explored_state(env, insn_idx);
16321 *explored_state(env, insn_idx) = new_sl;
16322 /* connect new state to parentage chain. Current frame needs all
16323 * registers connected. Only r6 - r9 of the callers are alive (pushed
16324 * to the stack implicitly by JITs) so in callers' frames connect just
16325 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16326 * the state of the call instruction (with WRITTEN set), and r0 comes
16327 * from callee with its full parentage chain, anyway.
16329 /* clear write marks in current state: the writes we did are not writes
16330 * our child did, so they don't screen off its reads from us.
16331 * (There are no read marks in current state, because reads always mark
16332 * their parent and current state never has children yet. Only
16333 * explored_states can get read marks.)
16335 for (j = 0; j <= cur->curframe; j++) {
16336 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16337 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16338 for (i = 0; i < BPF_REG_FP; i++)
16339 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16342 /* all stack frames are accessible from callee, clear them all */
16343 for (j = 0; j <= cur->curframe; j++) {
16344 struct bpf_func_state *frame = cur->frame[j];
16345 struct bpf_func_state *newframe = new->frame[j];
16347 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16348 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16349 frame->stack[i].spilled_ptr.parent =
16350 &newframe->stack[i].spilled_ptr;
16356 /* Return true if it's OK to have the same insn return a different type. */
16357 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16359 switch (base_type(type)) {
16361 case PTR_TO_SOCKET:
16362 case PTR_TO_SOCK_COMMON:
16363 case PTR_TO_TCP_SOCK:
16364 case PTR_TO_XDP_SOCK:
16365 case PTR_TO_BTF_ID:
16372 /* If an instruction was previously used with particular pointer types, then we
16373 * need to be careful to avoid cases such as the below, where it may be ok
16374 * for one branch accessing the pointer, but not ok for the other branch:
16379 * R1 = some_other_valid_ptr;
16382 * R2 = *(u32 *)(R1 + 0);
16384 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16386 return src != prev && (!reg_type_mismatch_ok(src) ||
16387 !reg_type_mismatch_ok(prev));
16390 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16391 bool allow_trust_missmatch)
16393 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16395 if (*prev_type == NOT_INIT) {
16396 /* Saw a valid insn
16397 * dst_reg = *(u32 *)(src_reg + off)
16398 * save type to validate intersecting paths
16401 } else if (reg_type_mismatch(type, *prev_type)) {
16402 /* Abuser program is trying to use the same insn
16403 * dst_reg = *(u32*) (src_reg + off)
16404 * with different pointer types:
16405 * src_reg == ctx in one branch and
16406 * src_reg == stack|map in some other branch.
16409 if (allow_trust_missmatch &&
16410 base_type(type) == PTR_TO_BTF_ID &&
16411 base_type(*prev_type) == PTR_TO_BTF_ID) {
16413 * Have to support a use case when one path through
16414 * the program yields TRUSTED pointer while another
16415 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16416 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16418 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16420 verbose(env, "same insn cannot be used with different pointers\n");
16428 static int do_check(struct bpf_verifier_env *env)
16430 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16431 struct bpf_verifier_state *state = env->cur_state;
16432 struct bpf_insn *insns = env->prog->insnsi;
16433 struct bpf_reg_state *regs;
16434 int insn_cnt = env->prog->len;
16435 bool do_print_state = false;
16436 int prev_insn_idx = -1;
16439 struct bpf_insn *insn;
16443 env->prev_insn_idx = prev_insn_idx;
16444 if (env->insn_idx >= insn_cnt) {
16445 verbose(env, "invalid insn idx %d insn_cnt %d\n",
16446 env->insn_idx, insn_cnt);
16450 insn = &insns[env->insn_idx];
16451 class = BPF_CLASS(insn->code);
16453 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16455 "BPF program is too large. Processed %d insn\n",
16456 env->insn_processed);
16460 state->last_insn_idx = env->prev_insn_idx;
16462 if (is_prune_point(env, env->insn_idx)) {
16463 err = is_state_visited(env, env->insn_idx);
16467 /* found equivalent state, can prune the search */
16468 if (env->log.level & BPF_LOG_LEVEL) {
16469 if (do_print_state)
16470 verbose(env, "\nfrom %d to %d%s: safe\n",
16471 env->prev_insn_idx, env->insn_idx,
16472 env->cur_state->speculative ?
16473 " (speculative execution)" : "");
16475 verbose(env, "%d: safe\n", env->insn_idx);
16477 goto process_bpf_exit;
16481 if (is_jmp_point(env, env->insn_idx)) {
16482 err = push_jmp_history(env, state);
16487 if (signal_pending(current))
16490 if (need_resched())
16493 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16494 verbose(env, "\nfrom %d to %d%s:",
16495 env->prev_insn_idx, env->insn_idx,
16496 env->cur_state->speculative ?
16497 " (speculative execution)" : "");
16498 print_verifier_state(env, state->frame[state->curframe], true);
16499 do_print_state = false;
16502 if (env->log.level & BPF_LOG_LEVEL) {
16503 const struct bpf_insn_cbs cbs = {
16504 .cb_call = disasm_kfunc_name,
16505 .cb_print = verbose,
16506 .private_data = env,
16509 if (verifier_state_scratched(env))
16510 print_insn_state(env, state->frame[state->curframe]);
16512 verbose_linfo(env, env->insn_idx, "; ");
16513 env->prev_log_pos = env->log.end_pos;
16514 verbose(env, "%d: ", env->insn_idx);
16515 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16516 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16517 env->prev_log_pos = env->log.end_pos;
16520 if (bpf_prog_is_offloaded(env->prog->aux)) {
16521 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16522 env->prev_insn_idx);
16527 regs = cur_regs(env);
16528 sanitize_mark_insn_seen(env);
16529 prev_insn_idx = env->insn_idx;
16531 if (class == BPF_ALU || class == BPF_ALU64) {
16532 err = check_alu_op(env, insn);
16536 } else if (class == BPF_LDX) {
16537 enum bpf_reg_type src_reg_type;
16539 /* check for reserved fields is already done */
16541 /* check src operand */
16542 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16546 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16550 src_reg_type = regs[insn->src_reg].type;
16552 /* check that memory (src_reg + off) is readable,
16553 * the state of dst_reg will be updated by this func
16555 err = check_mem_access(env, env->insn_idx, insn->src_reg,
16556 insn->off, BPF_SIZE(insn->code),
16557 BPF_READ, insn->dst_reg, false,
16558 BPF_MODE(insn->code) == BPF_MEMSX);
16562 err = save_aux_ptr_type(env, src_reg_type, true);
16565 } else if (class == BPF_STX) {
16566 enum bpf_reg_type dst_reg_type;
16568 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16569 err = check_atomic(env, env->insn_idx, insn);
16576 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16577 verbose(env, "BPF_STX uses reserved fields\n");
16581 /* check src1 operand */
16582 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16585 /* check src2 operand */
16586 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16590 dst_reg_type = regs[insn->dst_reg].type;
16592 /* check that memory (dst_reg + off) is writeable */
16593 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16594 insn->off, BPF_SIZE(insn->code),
16595 BPF_WRITE, insn->src_reg, false, false);
16599 err = save_aux_ptr_type(env, dst_reg_type, false);
16602 } else if (class == BPF_ST) {
16603 enum bpf_reg_type dst_reg_type;
16605 if (BPF_MODE(insn->code) != BPF_MEM ||
16606 insn->src_reg != BPF_REG_0) {
16607 verbose(env, "BPF_ST uses reserved fields\n");
16610 /* check src operand */
16611 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16615 dst_reg_type = regs[insn->dst_reg].type;
16617 /* check that memory (dst_reg + off) is writeable */
16618 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16619 insn->off, BPF_SIZE(insn->code),
16620 BPF_WRITE, -1, false, false);
16624 err = save_aux_ptr_type(env, dst_reg_type, false);
16627 } else if (class == BPF_JMP || class == BPF_JMP32) {
16628 u8 opcode = BPF_OP(insn->code);
16630 env->jmps_processed++;
16631 if (opcode == BPF_CALL) {
16632 if (BPF_SRC(insn->code) != BPF_K ||
16633 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16634 && insn->off != 0) ||
16635 (insn->src_reg != BPF_REG_0 &&
16636 insn->src_reg != BPF_PSEUDO_CALL &&
16637 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16638 insn->dst_reg != BPF_REG_0 ||
16639 class == BPF_JMP32) {
16640 verbose(env, "BPF_CALL uses reserved fields\n");
16644 if (env->cur_state->active_lock.ptr) {
16645 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16646 (insn->src_reg == BPF_PSEUDO_CALL) ||
16647 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16648 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16649 verbose(env, "function calls are not allowed while holding a lock\n");
16653 if (insn->src_reg == BPF_PSEUDO_CALL)
16654 err = check_func_call(env, insn, &env->insn_idx);
16655 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16656 err = check_kfunc_call(env, insn, &env->insn_idx);
16658 err = check_helper_call(env, insn, &env->insn_idx);
16662 mark_reg_scratched(env, BPF_REG_0);
16663 } else if (opcode == BPF_JA) {
16664 if (BPF_SRC(insn->code) != BPF_K ||
16665 insn->src_reg != BPF_REG_0 ||
16666 insn->dst_reg != BPF_REG_0 ||
16667 (class == BPF_JMP && insn->imm != 0) ||
16668 (class == BPF_JMP32 && insn->off != 0)) {
16669 verbose(env, "BPF_JA uses reserved fields\n");
16673 if (class == BPF_JMP)
16674 env->insn_idx += insn->off + 1;
16676 env->insn_idx += insn->imm + 1;
16679 } else if (opcode == BPF_EXIT) {
16680 if (BPF_SRC(insn->code) != BPF_K ||
16682 insn->src_reg != BPF_REG_0 ||
16683 insn->dst_reg != BPF_REG_0 ||
16684 class == BPF_JMP32) {
16685 verbose(env, "BPF_EXIT uses reserved fields\n");
16689 if (env->cur_state->active_lock.ptr &&
16690 !in_rbtree_lock_required_cb(env)) {
16691 verbose(env, "bpf_spin_unlock is missing\n");
16695 if (env->cur_state->active_rcu_lock) {
16696 verbose(env, "bpf_rcu_read_unlock is missing\n");
16700 /* We must do check_reference_leak here before
16701 * prepare_func_exit to handle the case when
16702 * state->curframe > 0, it may be a callback
16703 * function, for which reference_state must
16704 * match caller reference state when it exits.
16706 err = check_reference_leak(env);
16710 if (state->curframe) {
16711 /* exit from nested function */
16712 err = prepare_func_exit(env, &env->insn_idx);
16715 do_print_state = true;
16719 err = check_return_code(env);
16723 mark_verifier_state_scratched(env);
16724 update_branch_counts(env, env->cur_state);
16725 err = pop_stack(env, &prev_insn_idx,
16726 &env->insn_idx, pop_log);
16728 if (err != -ENOENT)
16732 do_print_state = true;
16736 err = check_cond_jmp_op(env, insn, &env->insn_idx);
16740 } else if (class == BPF_LD) {
16741 u8 mode = BPF_MODE(insn->code);
16743 if (mode == BPF_ABS || mode == BPF_IND) {
16744 err = check_ld_abs(env, insn);
16748 } else if (mode == BPF_IMM) {
16749 err = check_ld_imm(env, insn);
16754 sanitize_mark_insn_seen(env);
16756 verbose(env, "invalid BPF_LD mode\n");
16760 verbose(env, "unknown insn class %d\n", class);
16770 static int find_btf_percpu_datasec(struct btf *btf)
16772 const struct btf_type *t;
16777 * Both vmlinux and module each have their own ".data..percpu"
16778 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16779 * types to look at only module's own BTF types.
16781 n = btf_nr_types(btf);
16782 if (btf_is_module(btf))
16783 i = btf_nr_types(btf_vmlinux);
16787 for(; i < n; i++) {
16788 t = btf_type_by_id(btf, i);
16789 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16792 tname = btf_name_by_offset(btf, t->name_off);
16793 if (!strcmp(tname, ".data..percpu"))
16800 /* replace pseudo btf_id with kernel symbol address */
16801 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16802 struct bpf_insn *insn,
16803 struct bpf_insn_aux_data *aux)
16805 const struct btf_var_secinfo *vsi;
16806 const struct btf_type *datasec;
16807 struct btf_mod_pair *btf_mod;
16808 const struct btf_type *t;
16809 const char *sym_name;
16810 bool percpu = false;
16811 u32 type, id = insn->imm;
16815 int i, btf_fd, err;
16817 btf_fd = insn[1].imm;
16819 btf = btf_get_by_fd(btf_fd);
16821 verbose(env, "invalid module BTF object FD specified.\n");
16825 if (!btf_vmlinux) {
16826 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16833 t = btf_type_by_id(btf, id);
16835 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16840 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16841 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16846 sym_name = btf_name_by_offset(btf, t->name_off);
16847 addr = kallsyms_lookup_name(sym_name);
16849 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16854 insn[0].imm = (u32)addr;
16855 insn[1].imm = addr >> 32;
16857 if (btf_type_is_func(t)) {
16858 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16859 aux->btf_var.mem_size = 0;
16863 datasec_id = find_btf_percpu_datasec(btf);
16864 if (datasec_id > 0) {
16865 datasec = btf_type_by_id(btf, datasec_id);
16866 for_each_vsi(i, datasec, vsi) {
16867 if (vsi->type == id) {
16875 t = btf_type_skip_modifiers(btf, type, NULL);
16877 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16878 aux->btf_var.btf = btf;
16879 aux->btf_var.btf_id = type;
16880 } else if (!btf_type_is_struct(t)) {
16881 const struct btf_type *ret;
16885 /* resolve the type size of ksym. */
16886 ret = btf_resolve_size(btf, t, &tsize);
16888 tname = btf_name_by_offset(btf, t->name_off);
16889 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16890 tname, PTR_ERR(ret));
16894 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16895 aux->btf_var.mem_size = tsize;
16897 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16898 aux->btf_var.btf = btf;
16899 aux->btf_var.btf_id = type;
16902 /* check whether we recorded this BTF (and maybe module) already */
16903 for (i = 0; i < env->used_btf_cnt; i++) {
16904 if (env->used_btfs[i].btf == btf) {
16910 if (env->used_btf_cnt >= MAX_USED_BTFS) {
16915 btf_mod = &env->used_btfs[env->used_btf_cnt];
16916 btf_mod->btf = btf;
16917 btf_mod->module = NULL;
16919 /* if we reference variables from kernel module, bump its refcount */
16920 if (btf_is_module(btf)) {
16921 btf_mod->module = btf_try_get_module(btf);
16922 if (!btf_mod->module) {
16928 env->used_btf_cnt++;
16936 static bool is_tracing_prog_type(enum bpf_prog_type type)
16939 case BPF_PROG_TYPE_KPROBE:
16940 case BPF_PROG_TYPE_TRACEPOINT:
16941 case BPF_PROG_TYPE_PERF_EVENT:
16942 case BPF_PROG_TYPE_RAW_TRACEPOINT:
16943 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16950 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16951 struct bpf_map *map,
16952 struct bpf_prog *prog)
16955 enum bpf_prog_type prog_type = resolve_prog_type(prog);
16957 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16958 btf_record_has_field(map->record, BPF_RB_ROOT)) {
16959 if (is_tracing_prog_type(prog_type)) {
16960 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16965 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16966 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16967 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16971 if (is_tracing_prog_type(prog_type)) {
16972 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16976 if (prog->aux->sleepable) {
16977 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16982 if (btf_record_has_field(map->record, BPF_TIMER)) {
16983 if (is_tracing_prog_type(prog_type)) {
16984 verbose(env, "tracing progs cannot use bpf_timer yet\n");
16989 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16990 !bpf_offload_prog_map_match(prog, map)) {
16991 verbose(env, "offload device mismatch between prog and map\n");
16995 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16996 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17000 if (prog->aux->sleepable)
17001 switch (map->map_type) {
17002 case BPF_MAP_TYPE_HASH:
17003 case BPF_MAP_TYPE_LRU_HASH:
17004 case BPF_MAP_TYPE_ARRAY:
17005 case BPF_MAP_TYPE_PERCPU_HASH:
17006 case BPF_MAP_TYPE_PERCPU_ARRAY:
17007 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17008 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17009 case BPF_MAP_TYPE_HASH_OF_MAPS:
17010 case BPF_MAP_TYPE_RINGBUF:
17011 case BPF_MAP_TYPE_USER_RINGBUF:
17012 case BPF_MAP_TYPE_INODE_STORAGE:
17013 case BPF_MAP_TYPE_SK_STORAGE:
17014 case BPF_MAP_TYPE_TASK_STORAGE:
17015 case BPF_MAP_TYPE_CGRP_STORAGE:
17019 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17026 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17028 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17029 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17032 /* find and rewrite pseudo imm in ld_imm64 instructions:
17034 * 1. if it accesses map FD, replace it with actual map pointer.
17035 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17037 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17039 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17041 struct bpf_insn *insn = env->prog->insnsi;
17042 int insn_cnt = env->prog->len;
17045 err = bpf_prog_calc_tag(env->prog);
17049 for (i = 0; i < insn_cnt; i++, insn++) {
17050 if (BPF_CLASS(insn->code) == BPF_LDX &&
17051 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17053 verbose(env, "BPF_LDX uses reserved fields\n");
17057 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17058 struct bpf_insn_aux_data *aux;
17059 struct bpf_map *map;
17064 if (i == insn_cnt - 1 || insn[1].code != 0 ||
17065 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17066 insn[1].off != 0) {
17067 verbose(env, "invalid bpf_ld_imm64 insn\n");
17071 if (insn[0].src_reg == 0)
17072 /* valid generic load 64-bit imm */
17075 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17076 aux = &env->insn_aux_data[i];
17077 err = check_pseudo_btf_id(env, insn, aux);
17083 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17084 aux = &env->insn_aux_data[i];
17085 aux->ptr_type = PTR_TO_FUNC;
17089 /* In final convert_pseudo_ld_imm64() step, this is
17090 * converted into regular 64-bit imm load insn.
17092 switch (insn[0].src_reg) {
17093 case BPF_PSEUDO_MAP_VALUE:
17094 case BPF_PSEUDO_MAP_IDX_VALUE:
17096 case BPF_PSEUDO_MAP_FD:
17097 case BPF_PSEUDO_MAP_IDX:
17098 if (insn[1].imm == 0)
17102 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17106 switch (insn[0].src_reg) {
17107 case BPF_PSEUDO_MAP_IDX_VALUE:
17108 case BPF_PSEUDO_MAP_IDX:
17109 if (bpfptr_is_null(env->fd_array)) {
17110 verbose(env, "fd_idx without fd_array is invalid\n");
17113 if (copy_from_bpfptr_offset(&fd, env->fd_array,
17114 insn[0].imm * sizeof(fd),
17124 map = __bpf_map_get(f);
17126 verbose(env, "fd %d is not pointing to valid bpf_map\n",
17128 return PTR_ERR(map);
17131 err = check_map_prog_compatibility(env, map, env->prog);
17137 aux = &env->insn_aux_data[i];
17138 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17139 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17140 addr = (unsigned long)map;
17142 u32 off = insn[1].imm;
17144 if (off >= BPF_MAX_VAR_OFF) {
17145 verbose(env, "direct value offset of %u is not allowed\n", off);
17150 if (!map->ops->map_direct_value_addr) {
17151 verbose(env, "no direct value access support for this map type\n");
17156 err = map->ops->map_direct_value_addr(map, &addr, off);
17158 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17159 map->value_size, off);
17164 aux->map_off = off;
17168 insn[0].imm = (u32)addr;
17169 insn[1].imm = addr >> 32;
17171 /* check whether we recorded this map already */
17172 for (j = 0; j < env->used_map_cnt; j++) {
17173 if (env->used_maps[j] == map) {
17174 aux->map_index = j;
17180 if (env->used_map_cnt >= MAX_USED_MAPS) {
17185 /* hold the map. If the program is rejected by verifier,
17186 * the map will be released by release_maps() or it
17187 * will be used by the valid program until it's unloaded
17188 * and all maps are released in free_used_maps()
17192 aux->map_index = env->used_map_cnt;
17193 env->used_maps[env->used_map_cnt++] = map;
17195 if (bpf_map_is_cgroup_storage(map) &&
17196 bpf_cgroup_storage_assign(env->prog->aux, map)) {
17197 verbose(env, "only one cgroup storage of each type is allowed\n");
17209 /* Basic sanity check before we invest more work here. */
17210 if (!bpf_opcode_in_insntable(insn->code)) {
17211 verbose(env, "unknown opcode %02x\n", insn->code);
17216 /* now all pseudo BPF_LD_IMM64 instructions load valid
17217 * 'struct bpf_map *' into a register instead of user map_fd.
17218 * These pointers will be used later by verifier to validate map access.
17223 /* drop refcnt of maps used by the rejected program */
17224 static void release_maps(struct bpf_verifier_env *env)
17226 __bpf_free_used_maps(env->prog->aux, env->used_maps,
17227 env->used_map_cnt);
17230 /* drop refcnt of maps used by the rejected program */
17231 static void release_btfs(struct bpf_verifier_env *env)
17233 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17234 env->used_btf_cnt);
17237 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17238 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17240 struct bpf_insn *insn = env->prog->insnsi;
17241 int insn_cnt = env->prog->len;
17244 for (i = 0; i < insn_cnt; i++, insn++) {
17245 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17247 if (insn->src_reg == BPF_PSEUDO_FUNC)
17253 /* single env->prog->insni[off] instruction was replaced with the range
17254 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
17255 * [0, off) and [off, end) to new locations, so the patched range stays zero
17257 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17258 struct bpf_insn_aux_data *new_data,
17259 struct bpf_prog *new_prog, u32 off, u32 cnt)
17261 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17262 struct bpf_insn *insn = new_prog->insnsi;
17263 u32 old_seen = old_data[off].seen;
17267 /* aux info at OFF always needs adjustment, no matter fast path
17268 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17269 * original insn at old prog.
17271 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17275 prog_len = new_prog->len;
17277 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17278 memcpy(new_data + off + cnt - 1, old_data + off,
17279 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17280 for (i = off; i < off + cnt - 1; i++) {
17281 /* Expand insni[off]'s seen count to the patched range. */
17282 new_data[i].seen = old_seen;
17283 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17285 env->insn_aux_data = new_data;
17289 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17295 /* NOTE: fake 'exit' subprog should be updated as well. */
17296 for (i = 0; i <= env->subprog_cnt; i++) {
17297 if (env->subprog_info[i].start <= off)
17299 env->subprog_info[i].start += len - 1;
17303 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17305 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17306 int i, sz = prog->aux->size_poke_tab;
17307 struct bpf_jit_poke_descriptor *desc;
17309 for (i = 0; i < sz; i++) {
17311 if (desc->insn_idx <= off)
17313 desc->insn_idx += len - 1;
17317 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17318 const struct bpf_insn *patch, u32 len)
17320 struct bpf_prog *new_prog;
17321 struct bpf_insn_aux_data *new_data = NULL;
17324 new_data = vzalloc(array_size(env->prog->len + len - 1,
17325 sizeof(struct bpf_insn_aux_data)));
17330 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17331 if (IS_ERR(new_prog)) {
17332 if (PTR_ERR(new_prog) == -ERANGE)
17334 "insn %d cannot be patched due to 16-bit range\n",
17335 env->insn_aux_data[off].orig_idx);
17339 adjust_insn_aux_data(env, new_data, new_prog, off, len);
17340 adjust_subprog_starts(env, off, len);
17341 adjust_poke_descs(new_prog, off, len);
17345 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17350 /* find first prog starting at or after off (first to remove) */
17351 for (i = 0; i < env->subprog_cnt; i++)
17352 if (env->subprog_info[i].start >= off)
17354 /* find first prog starting at or after off + cnt (first to stay) */
17355 for (j = i; j < env->subprog_cnt; j++)
17356 if (env->subprog_info[j].start >= off + cnt)
17358 /* if j doesn't start exactly at off + cnt, we are just removing
17359 * the front of previous prog
17361 if (env->subprog_info[j].start != off + cnt)
17365 struct bpf_prog_aux *aux = env->prog->aux;
17368 /* move fake 'exit' subprog as well */
17369 move = env->subprog_cnt + 1 - j;
17371 memmove(env->subprog_info + i,
17372 env->subprog_info + j,
17373 sizeof(*env->subprog_info) * move);
17374 env->subprog_cnt -= j - i;
17376 /* remove func_info */
17377 if (aux->func_info) {
17378 move = aux->func_info_cnt - j;
17380 memmove(aux->func_info + i,
17381 aux->func_info + j,
17382 sizeof(*aux->func_info) * move);
17383 aux->func_info_cnt -= j - i;
17384 /* func_info->insn_off is set after all code rewrites,
17385 * in adjust_btf_func() - no need to adjust
17389 /* convert i from "first prog to remove" to "first to adjust" */
17390 if (env->subprog_info[i].start == off)
17394 /* update fake 'exit' subprog as well */
17395 for (; i <= env->subprog_cnt; i++)
17396 env->subprog_info[i].start -= cnt;
17401 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17404 struct bpf_prog *prog = env->prog;
17405 u32 i, l_off, l_cnt, nr_linfo;
17406 struct bpf_line_info *linfo;
17408 nr_linfo = prog->aux->nr_linfo;
17412 linfo = prog->aux->linfo;
17414 /* find first line info to remove, count lines to be removed */
17415 for (i = 0; i < nr_linfo; i++)
17416 if (linfo[i].insn_off >= off)
17421 for (; i < nr_linfo; i++)
17422 if (linfo[i].insn_off < off + cnt)
17427 /* First live insn doesn't match first live linfo, it needs to "inherit"
17428 * last removed linfo. prog is already modified, so prog->len == off
17429 * means no live instructions after (tail of the program was removed).
17431 if (prog->len != off && l_cnt &&
17432 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17434 linfo[--i].insn_off = off + cnt;
17437 /* remove the line info which refer to the removed instructions */
17439 memmove(linfo + l_off, linfo + i,
17440 sizeof(*linfo) * (nr_linfo - i));
17442 prog->aux->nr_linfo -= l_cnt;
17443 nr_linfo = prog->aux->nr_linfo;
17446 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17447 for (i = l_off; i < nr_linfo; i++)
17448 linfo[i].insn_off -= cnt;
17450 /* fix up all subprogs (incl. 'exit') which start >= off */
17451 for (i = 0; i <= env->subprog_cnt; i++)
17452 if (env->subprog_info[i].linfo_idx > l_off) {
17453 /* program may have started in the removed region but
17454 * may not be fully removed
17456 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17457 env->subprog_info[i].linfo_idx -= l_cnt;
17459 env->subprog_info[i].linfo_idx = l_off;
17465 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17467 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17468 unsigned int orig_prog_len = env->prog->len;
17471 if (bpf_prog_is_offloaded(env->prog->aux))
17472 bpf_prog_offload_remove_insns(env, off, cnt);
17474 err = bpf_remove_insns(env->prog, off, cnt);
17478 err = adjust_subprog_starts_after_remove(env, off, cnt);
17482 err = bpf_adj_linfo_after_remove(env, off, cnt);
17486 memmove(aux_data + off, aux_data + off + cnt,
17487 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17492 /* The verifier does more data flow analysis than llvm and will not
17493 * explore branches that are dead at run time. Malicious programs can
17494 * have dead code too. Therefore replace all dead at-run-time code
17497 * Just nops are not optimal, e.g. if they would sit at the end of the
17498 * program and through another bug we would manage to jump there, then
17499 * we'd execute beyond program memory otherwise. Returning exception
17500 * code also wouldn't work since we can have subprogs where the dead
17501 * code could be located.
17503 static void sanitize_dead_code(struct bpf_verifier_env *env)
17505 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17506 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17507 struct bpf_insn *insn = env->prog->insnsi;
17508 const int insn_cnt = env->prog->len;
17511 for (i = 0; i < insn_cnt; i++) {
17512 if (aux_data[i].seen)
17514 memcpy(insn + i, &trap, sizeof(trap));
17515 aux_data[i].zext_dst = false;
17519 static bool insn_is_cond_jump(u8 code)
17524 if (BPF_CLASS(code) == BPF_JMP32)
17525 return op != BPF_JA;
17527 if (BPF_CLASS(code) != BPF_JMP)
17530 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17533 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17535 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17536 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17537 struct bpf_insn *insn = env->prog->insnsi;
17538 const int insn_cnt = env->prog->len;
17541 for (i = 0; i < insn_cnt; i++, insn++) {
17542 if (!insn_is_cond_jump(insn->code))
17545 if (!aux_data[i + 1].seen)
17546 ja.off = insn->off;
17547 else if (!aux_data[i + 1 + insn->off].seen)
17552 if (bpf_prog_is_offloaded(env->prog->aux))
17553 bpf_prog_offload_replace_insn(env, i, &ja);
17555 memcpy(insn, &ja, sizeof(ja));
17559 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17561 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17562 int insn_cnt = env->prog->len;
17565 for (i = 0; i < insn_cnt; i++) {
17569 while (i + j < insn_cnt && !aux_data[i + j].seen)
17574 err = verifier_remove_insns(env, i, j);
17577 insn_cnt = env->prog->len;
17583 static int opt_remove_nops(struct bpf_verifier_env *env)
17585 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17586 struct bpf_insn *insn = env->prog->insnsi;
17587 int insn_cnt = env->prog->len;
17590 for (i = 0; i < insn_cnt; i++) {
17591 if (memcmp(&insn[i], &ja, sizeof(ja)))
17594 err = verifier_remove_insns(env, i, 1);
17604 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17605 const union bpf_attr *attr)
17607 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17608 struct bpf_insn_aux_data *aux = env->insn_aux_data;
17609 int i, patch_len, delta = 0, len = env->prog->len;
17610 struct bpf_insn *insns = env->prog->insnsi;
17611 struct bpf_prog *new_prog;
17614 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17615 zext_patch[1] = BPF_ZEXT_REG(0);
17616 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17617 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17618 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17619 for (i = 0; i < len; i++) {
17620 int adj_idx = i + delta;
17621 struct bpf_insn insn;
17624 insn = insns[adj_idx];
17625 load_reg = insn_def_regno(&insn);
17626 if (!aux[adj_idx].zext_dst) {
17634 class = BPF_CLASS(code);
17635 if (load_reg == -1)
17638 /* NOTE: arg "reg" (the fourth one) is only used for
17639 * BPF_STX + SRC_OP, so it is safe to pass NULL
17642 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17643 if (class == BPF_LD &&
17644 BPF_MODE(code) == BPF_IMM)
17649 /* ctx load could be transformed into wider load. */
17650 if (class == BPF_LDX &&
17651 aux[adj_idx].ptr_type == PTR_TO_CTX)
17654 imm_rnd = get_random_u32();
17655 rnd_hi32_patch[0] = insn;
17656 rnd_hi32_patch[1].imm = imm_rnd;
17657 rnd_hi32_patch[3].dst_reg = load_reg;
17658 patch = rnd_hi32_patch;
17660 goto apply_patch_buffer;
17663 /* Add in an zero-extend instruction if a) the JIT has requested
17664 * it or b) it's a CMPXCHG.
17666 * The latter is because: BPF_CMPXCHG always loads a value into
17667 * R0, therefore always zero-extends. However some archs'
17668 * equivalent instruction only does this load when the
17669 * comparison is successful. This detail of CMPXCHG is
17670 * orthogonal to the general zero-extension behaviour of the
17671 * CPU, so it's treated independently of bpf_jit_needs_zext.
17673 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17676 /* Zero-extension is done by the caller. */
17677 if (bpf_pseudo_kfunc_call(&insn))
17680 if (WARN_ON(load_reg == -1)) {
17681 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17685 zext_patch[0] = insn;
17686 zext_patch[1].dst_reg = load_reg;
17687 zext_patch[1].src_reg = load_reg;
17688 patch = zext_patch;
17690 apply_patch_buffer:
17691 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17694 env->prog = new_prog;
17695 insns = new_prog->insnsi;
17696 aux = env->insn_aux_data;
17697 delta += patch_len - 1;
17703 /* convert load instructions that access fields of a context type into a
17704 * sequence of instructions that access fields of the underlying structure:
17705 * struct __sk_buff -> struct sk_buff
17706 * struct bpf_sock_ops -> struct sock
17708 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17710 const struct bpf_verifier_ops *ops = env->ops;
17711 int i, cnt, size, ctx_field_size, delta = 0;
17712 const int insn_cnt = env->prog->len;
17713 struct bpf_insn insn_buf[16], *insn;
17714 u32 target_size, size_default, off;
17715 struct bpf_prog *new_prog;
17716 enum bpf_access_type type;
17717 bool is_narrower_load;
17719 if (ops->gen_prologue || env->seen_direct_write) {
17720 if (!ops->gen_prologue) {
17721 verbose(env, "bpf verifier is misconfigured\n");
17724 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17726 if (cnt >= ARRAY_SIZE(insn_buf)) {
17727 verbose(env, "bpf verifier is misconfigured\n");
17730 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17734 env->prog = new_prog;
17739 if (bpf_prog_is_offloaded(env->prog->aux))
17742 insn = env->prog->insnsi + delta;
17744 for (i = 0; i < insn_cnt; i++, insn++) {
17745 bpf_convert_ctx_access_t convert_ctx_access;
17748 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17749 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17750 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17751 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
17752 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
17753 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
17754 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
17756 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17757 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17758 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17759 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17760 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17761 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17762 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17763 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17769 if (type == BPF_WRITE &&
17770 env->insn_aux_data[i + delta].sanitize_stack_spill) {
17771 struct bpf_insn patch[] = {
17776 cnt = ARRAY_SIZE(patch);
17777 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17782 env->prog = new_prog;
17783 insn = new_prog->insnsi + i + delta;
17787 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17789 if (!ops->convert_ctx_access)
17791 convert_ctx_access = ops->convert_ctx_access;
17793 case PTR_TO_SOCKET:
17794 case PTR_TO_SOCK_COMMON:
17795 convert_ctx_access = bpf_sock_convert_ctx_access;
17797 case PTR_TO_TCP_SOCK:
17798 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17800 case PTR_TO_XDP_SOCK:
17801 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17803 case PTR_TO_BTF_ID:
17804 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17805 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17806 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17807 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17808 * any faults for loads into such types. BPF_WRITE is disallowed
17811 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17812 if (type == BPF_READ) {
17813 if (BPF_MODE(insn->code) == BPF_MEM)
17814 insn->code = BPF_LDX | BPF_PROBE_MEM |
17815 BPF_SIZE((insn)->code);
17817 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
17818 BPF_SIZE((insn)->code);
17819 env->prog->aux->num_exentries++;
17826 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17827 size = BPF_LDST_BYTES(insn);
17828 mode = BPF_MODE(insn->code);
17830 /* If the read access is a narrower load of the field,
17831 * convert to a 4/8-byte load, to minimum program type specific
17832 * convert_ctx_access changes. If conversion is successful,
17833 * we will apply proper mask to the result.
17835 is_narrower_load = size < ctx_field_size;
17836 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17838 if (is_narrower_load) {
17841 if (type == BPF_WRITE) {
17842 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17847 if (ctx_field_size == 4)
17849 else if (ctx_field_size == 8)
17850 size_code = BPF_DW;
17852 insn->off = off & ~(size_default - 1);
17853 insn->code = BPF_LDX | BPF_MEM | size_code;
17857 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17859 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17860 (ctx_field_size && !target_size)) {
17861 verbose(env, "bpf verifier is misconfigured\n");
17865 if (is_narrower_load && size < target_size) {
17866 u8 shift = bpf_ctx_narrow_access_offset(
17867 off, size, size_default) * 8;
17868 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17869 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17872 if (ctx_field_size <= 4) {
17874 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17877 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17878 (1 << size * 8) - 1);
17881 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17884 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17885 (1ULL << size * 8) - 1);
17888 if (mode == BPF_MEMSX)
17889 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
17890 insn->dst_reg, insn->dst_reg,
17893 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17899 /* keep walking new program and skip insns we just inserted */
17900 env->prog = new_prog;
17901 insn = new_prog->insnsi + i + delta;
17907 static int jit_subprogs(struct bpf_verifier_env *env)
17909 struct bpf_prog *prog = env->prog, **func, *tmp;
17910 int i, j, subprog_start, subprog_end = 0, len, subprog;
17911 struct bpf_map *map_ptr;
17912 struct bpf_insn *insn;
17913 void *old_bpf_func;
17914 int err, num_exentries;
17916 if (env->subprog_cnt <= 1)
17919 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17920 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17923 /* Upon error here we cannot fall back to interpreter but
17924 * need a hard reject of the program. Thus -EFAULT is
17925 * propagated in any case.
17927 subprog = find_subprog(env, i + insn->imm + 1);
17929 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17930 i + insn->imm + 1);
17933 /* temporarily remember subprog id inside insn instead of
17934 * aux_data, since next loop will split up all insns into funcs
17936 insn->off = subprog;
17937 /* remember original imm in case JIT fails and fallback
17938 * to interpreter will be needed
17940 env->insn_aux_data[i].call_imm = insn->imm;
17941 /* point imm to __bpf_call_base+1 from JITs point of view */
17943 if (bpf_pseudo_func(insn))
17944 /* jit (e.g. x86_64) may emit fewer instructions
17945 * if it learns a u32 imm is the same as a u64 imm.
17946 * Force a non zero here.
17951 err = bpf_prog_alloc_jited_linfo(prog);
17953 goto out_undo_insn;
17956 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17958 goto out_undo_insn;
17960 for (i = 0; i < env->subprog_cnt; i++) {
17961 subprog_start = subprog_end;
17962 subprog_end = env->subprog_info[i + 1].start;
17964 len = subprog_end - subprog_start;
17965 /* bpf_prog_run() doesn't call subprogs directly,
17966 * hence main prog stats include the runtime of subprogs.
17967 * subprogs don't have IDs and not reachable via prog_get_next_id
17968 * func[i]->stats will never be accessed and stays NULL
17970 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17973 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17974 len * sizeof(struct bpf_insn));
17975 func[i]->type = prog->type;
17976 func[i]->len = len;
17977 if (bpf_prog_calc_tag(func[i]))
17979 func[i]->is_func = 1;
17980 func[i]->aux->func_idx = i;
17981 /* Below members will be freed only at prog->aux */
17982 func[i]->aux->btf = prog->aux->btf;
17983 func[i]->aux->func_info = prog->aux->func_info;
17984 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17985 func[i]->aux->poke_tab = prog->aux->poke_tab;
17986 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17988 for (j = 0; j < prog->aux->size_poke_tab; j++) {
17989 struct bpf_jit_poke_descriptor *poke;
17991 poke = &prog->aux->poke_tab[j];
17992 if (poke->insn_idx < subprog_end &&
17993 poke->insn_idx >= subprog_start)
17994 poke->aux = func[i]->aux;
17997 func[i]->aux->name[0] = 'F';
17998 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17999 func[i]->jit_requested = 1;
18000 func[i]->blinding_requested = prog->blinding_requested;
18001 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18002 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18003 func[i]->aux->linfo = prog->aux->linfo;
18004 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18005 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18006 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18008 insn = func[i]->insnsi;
18009 for (j = 0; j < func[i]->len; j++, insn++) {
18010 if (BPF_CLASS(insn->code) == BPF_LDX &&
18011 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18012 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18015 func[i]->aux->num_exentries = num_exentries;
18016 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18017 func[i] = bpf_int_jit_compile(func[i]);
18018 if (!func[i]->jited) {
18025 /* at this point all bpf functions were successfully JITed
18026 * now populate all bpf_calls with correct addresses and
18027 * run last pass of JIT
18029 for (i = 0; i < env->subprog_cnt; i++) {
18030 insn = func[i]->insnsi;
18031 for (j = 0; j < func[i]->len; j++, insn++) {
18032 if (bpf_pseudo_func(insn)) {
18033 subprog = insn->off;
18034 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18035 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18038 if (!bpf_pseudo_call(insn))
18040 subprog = insn->off;
18041 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18044 /* we use the aux data to keep a list of the start addresses
18045 * of the JITed images for each function in the program
18047 * for some architectures, such as powerpc64, the imm field
18048 * might not be large enough to hold the offset of the start
18049 * address of the callee's JITed image from __bpf_call_base
18051 * in such cases, we can lookup the start address of a callee
18052 * by using its subprog id, available from the off field of
18053 * the call instruction, as an index for this list
18055 func[i]->aux->func = func;
18056 func[i]->aux->func_cnt = env->subprog_cnt;
18058 for (i = 0; i < env->subprog_cnt; i++) {
18059 old_bpf_func = func[i]->bpf_func;
18060 tmp = bpf_int_jit_compile(func[i]);
18061 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18062 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18069 /* finally lock prog and jit images for all functions and
18070 * populate kallsysm. Begin at the first subprogram, since
18071 * bpf_prog_load will add the kallsyms for the main program.
18073 for (i = 1; i < env->subprog_cnt; i++) {
18074 bpf_prog_lock_ro(func[i]);
18075 bpf_prog_kallsyms_add(func[i]);
18078 /* Last step: make now unused interpreter insns from main
18079 * prog consistent for later dump requests, so they can
18080 * later look the same as if they were interpreted only.
18082 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18083 if (bpf_pseudo_func(insn)) {
18084 insn[0].imm = env->insn_aux_data[i].call_imm;
18085 insn[1].imm = insn->off;
18089 if (!bpf_pseudo_call(insn))
18091 insn->off = env->insn_aux_data[i].call_imm;
18092 subprog = find_subprog(env, i + insn->off + 1);
18093 insn->imm = subprog;
18097 prog->bpf_func = func[0]->bpf_func;
18098 prog->jited_len = func[0]->jited_len;
18099 prog->aux->extable = func[0]->aux->extable;
18100 prog->aux->num_exentries = func[0]->aux->num_exentries;
18101 prog->aux->func = func;
18102 prog->aux->func_cnt = env->subprog_cnt;
18103 bpf_prog_jit_attempt_done(prog);
18106 /* We failed JIT'ing, so at this point we need to unregister poke
18107 * descriptors from subprogs, so that kernel is not attempting to
18108 * patch it anymore as we're freeing the subprog JIT memory.
18110 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18111 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18112 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18114 /* At this point we're guaranteed that poke descriptors are not
18115 * live anymore. We can just unlink its descriptor table as it's
18116 * released with the main prog.
18118 for (i = 0; i < env->subprog_cnt; i++) {
18121 func[i]->aux->poke_tab = NULL;
18122 bpf_jit_free(func[i]);
18126 /* cleanup main prog to be interpreted */
18127 prog->jit_requested = 0;
18128 prog->blinding_requested = 0;
18129 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18130 if (!bpf_pseudo_call(insn))
18133 insn->imm = env->insn_aux_data[i].call_imm;
18135 bpf_prog_jit_attempt_done(prog);
18139 static int fixup_call_args(struct bpf_verifier_env *env)
18141 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18142 struct bpf_prog *prog = env->prog;
18143 struct bpf_insn *insn = prog->insnsi;
18144 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18149 if (env->prog->jit_requested &&
18150 !bpf_prog_is_offloaded(env->prog->aux)) {
18151 err = jit_subprogs(env);
18154 if (err == -EFAULT)
18157 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18158 if (has_kfunc_call) {
18159 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18162 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18163 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18164 * have to be rejected, since interpreter doesn't support them yet.
18166 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18169 for (i = 0; i < prog->len; i++, insn++) {
18170 if (bpf_pseudo_func(insn)) {
18171 /* When JIT fails the progs with callback calls
18172 * have to be rejected, since interpreter doesn't support them yet.
18174 verbose(env, "callbacks are not allowed in non-JITed programs\n");
18178 if (!bpf_pseudo_call(insn))
18180 depth = get_callee_stack_depth(env, insn, i);
18183 bpf_patch_call_args(insn, depth);
18190 /* replace a generic kfunc with a specialized version if necessary */
18191 static void specialize_kfunc(struct bpf_verifier_env *env,
18192 u32 func_id, u16 offset, unsigned long *addr)
18194 struct bpf_prog *prog = env->prog;
18195 bool seen_direct_write;
18199 if (bpf_dev_bound_kfunc_id(func_id)) {
18200 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18202 *addr = (unsigned long)xdp_kfunc;
18205 /* fallback to default kfunc when not supported by netdev */
18211 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18212 seen_direct_write = env->seen_direct_write;
18213 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18216 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18218 /* restore env->seen_direct_write to its original value, since
18219 * may_access_direct_pkt_data mutates it
18221 env->seen_direct_write = seen_direct_write;
18225 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18226 u16 struct_meta_reg,
18227 u16 node_offset_reg,
18228 struct bpf_insn *insn,
18229 struct bpf_insn *insn_buf,
18232 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18233 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18235 insn_buf[0] = addr[0];
18236 insn_buf[1] = addr[1];
18237 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18238 insn_buf[3] = *insn;
18242 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18243 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18245 const struct bpf_kfunc_desc *desc;
18248 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18254 /* insn->imm has the btf func_id. Replace it with an offset relative to
18255 * __bpf_call_base, unless the JIT needs to call functions that are
18256 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18258 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18260 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18265 if (!bpf_jit_supports_far_kfunc_call())
18266 insn->imm = BPF_CALL_IMM(desc->addr);
18269 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18270 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18271 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18272 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18274 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18275 insn_buf[1] = addr[0];
18276 insn_buf[2] = addr[1];
18277 insn_buf[3] = *insn;
18279 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18280 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18281 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18282 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18284 insn_buf[0] = addr[0];
18285 insn_buf[1] = addr[1];
18286 insn_buf[2] = *insn;
18288 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18289 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18290 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18291 int struct_meta_reg = BPF_REG_3;
18292 int node_offset_reg = BPF_REG_4;
18294 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18295 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18296 struct_meta_reg = BPF_REG_4;
18297 node_offset_reg = BPF_REG_5;
18300 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18301 node_offset_reg, insn, insn_buf, cnt);
18302 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18303 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18304 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18310 /* Do various post-verification rewrites in a single program pass.
18311 * These rewrites simplify JIT and interpreter implementations.
18313 static int do_misc_fixups(struct bpf_verifier_env *env)
18315 struct bpf_prog *prog = env->prog;
18316 enum bpf_attach_type eatype = prog->expected_attach_type;
18317 enum bpf_prog_type prog_type = resolve_prog_type(prog);
18318 struct bpf_insn *insn = prog->insnsi;
18319 const struct bpf_func_proto *fn;
18320 const int insn_cnt = prog->len;
18321 const struct bpf_map_ops *ops;
18322 struct bpf_insn_aux_data *aux;
18323 struct bpf_insn insn_buf[16];
18324 struct bpf_prog *new_prog;
18325 struct bpf_map *map_ptr;
18326 int i, ret, cnt, delta = 0;
18328 for (i = 0; i < insn_cnt; i++, insn++) {
18329 /* Make divide-by-zero exceptions impossible. */
18330 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18331 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18332 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18333 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18334 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18335 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18336 struct bpf_insn *patchlet;
18337 struct bpf_insn chk_and_div[] = {
18338 /* [R,W]x div 0 -> 0 */
18339 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18340 BPF_JNE | BPF_K, insn->src_reg,
18342 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18343 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18346 struct bpf_insn chk_and_mod[] = {
18347 /* [R,W]x mod 0 -> [R,W]x */
18348 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18349 BPF_JEQ | BPF_K, insn->src_reg,
18350 0, 1 + (is64 ? 0 : 1), 0),
18352 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18353 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18356 patchlet = isdiv ? chk_and_div : chk_and_mod;
18357 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18358 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18360 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18365 env->prog = prog = new_prog;
18366 insn = new_prog->insnsi + i + delta;
18370 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18371 if (BPF_CLASS(insn->code) == BPF_LD &&
18372 (BPF_MODE(insn->code) == BPF_ABS ||
18373 BPF_MODE(insn->code) == BPF_IND)) {
18374 cnt = env->ops->gen_ld_abs(insn, insn_buf);
18375 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18376 verbose(env, "bpf verifier is misconfigured\n");
18380 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18385 env->prog = prog = new_prog;
18386 insn = new_prog->insnsi + i + delta;
18390 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18391 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18392 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18393 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18394 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18395 struct bpf_insn *patch = &insn_buf[0];
18396 bool issrc, isneg, isimm;
18399 aux = &env->insn_aux_data[i + delta];
18400 if (!aux->alu_state ||
18401 aux->alu_state == BPF_ALU_NON_POINTER)
18404 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18405 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18406 BPF_ALU_SANITIZE_SRC;
18407 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18409 off_reg = issrc ? insn->src_reg : insn->dst_reg;
18411 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18414 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18415 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18416 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18417 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18418 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18419 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18420 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18423 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18424 insn->src_reg = BPF_REG_AX;
18426 insn->code = insn->code == code_add ?
18427 code_sub : code_add;
18429 if (issrc && isneg && !isimm)
18430 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18431 cnt = patch - insn_buf;
18433 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18438 env->prog = prog = new_prog;
18439 insn = new_prog->insnsi + i + delta;
18443 if (insn->code != (BPF_JMP | BPF_CALL))
18445 if (insn->src_reg == BPF_PSEUDO_CALL)
18447 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18448 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18454 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18459 env->prog = prog = new_prog;
18460 insn = new_prog->insnsi + i + delta;
18464 if (insn->imm == BPF_FUNC_get_route_realm)
18465 prog->dst_needed = 1;
18466 if (insn->imm == BPF_FUNC_get_prandom_u32)
18467 bpf_user_rnd_init_once();
18468 if (insn->imm == BPF_FUNC_override_return)
18469 prog->kprobe_override = 1;
18470 if (insn->imm == BPF_FUNC_tail_call) {
18471 /* If we tail call into other programs, we
18472 * cannot make any assumptions since they can
18473 * be replaced dynamically during runtime in
18474 * the program array.
18476 prog->cb_access = 1;
18477 if (!allow_tail_call_in_subprogs(env))
18478 prog->aux->stack_depth = MAX_BPF_STACK;
18479 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18481 /* mark bpf_tail_call as different opcode to avoid
18482 * conditional branch in the interpreter for every normal
18483 * call and to prevent accidental JITing by JIT compiler
18484 * that doesn't support bpf_tail_call yet
18487 insn->code = BPF_JMP | BPF_TAIL_CALL;
18489 aux = &env->insn_aux_data[i + delta];
18490 if (env->bpf_capable && !prog->blinding_requested &&
18491 prog->jit_requested &&
18492 !bpf_map_key_poisoned(aux) &&
18493 !bpf_map_ptr_poisoned(aux) &&
18494 !bpf_map_ptr_unpriv(aux)) {
18495 struct bpf_jit_poke_descriptor desc = {
18496 .reason = BPF_POKE_REASON_TAIL_CALL,
18497 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18498 .tail_call.key = bpf_map_key_immediate(aux),
18499 .insn_idx = i + delta,
18502 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18504 verbose(env, "adding tail call poke descriptor failed\n");
18508 insn->imm = ret + 1;
18512 if (!bpf_map_ptr_unpriv(aux))
18515 /* instead of changing every JIT dealing with tail_call
18516 * emit two extra insns:
18517 * if (index >= max_entries) goto out;
18518 * index &= array->index_mask;
18519 * to avoid out-of-bounds cpu speculation
18521 if (bpf_map_ptr_poisoned(aux)) {
18522 verbose(env, "tail_call abusing map_ptr\n");
18526 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18527 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18528 map_ptr->max_entries, 2);
18529 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18530 container_of(map_ptr,
18533 insn_buf[2] = *insn;
18535 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18540 env->prog = prog = new_prog;
18541 insn = new_prog->insnsi + i + delta;
18545 if (insn->imm == BPF_FUNC_timer_set_callback) {
18546 /* The verifier will process callback_fn as many times as necessary
18547 * with different maps and the register states prepared by
18548 * set_timer_callback_state will be accurate.
18550 * The following use case is valid:
18551 * map1 is shared by prog1, prog2, prog3.
18552 * prog1 calls bpf_timer_init for some map1 elements
18553 * prog2 calls bpf_timer_set_callback for some map1 elements.
18554 * Those that were not bpf_timer_init-ed will return -EINVAL.
18555 * prog3 calls bpf_timer_start for some map1 elements.
18556 * Those that were not both bpf_timer_init-ed and
18557 * bpf_timer_set_callback-ed will return -EINVAL.
18559 struct bpf_insn ld_addrs[2] = {
18560 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18563 insn_buf[0] = ld_addrs[0];
18564 insn_buf[1] = ld_addrs[1];
18565 insn_buf[2] = *insn;
18568 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18573 env->prog = prog = new_prog;
18574 insn = new_prog->insnsi + i + delta;
18575 goto patch_call_imm;
18578 if (is_storage_get_function(insn->imm)) {
18579 if (!env->prog->aux->sleepable ||
18580 env->insn_aux_data[i + delta].storage_get_func_atomic)
18581 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18583 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18584 insn_buf[1] = *insn;
18587 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18592 env->prog = prog = new_prog;
18593 insn = new_prog->insnsi + i + delta;
18594 goto patch_call_imm;
18597 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18598 * and other inlining handlers are currently limited to 64 bit
18601 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18602 (insn->imm == BPF_FUNC_map_lookup_elem ||
18603 insn->imm == BPF_FUNC_map_update_elem ||
18604 insn->imm == BPF_FUNC_map_delete_elem ||
18605 insn->imm == BPF_FUNC_map_push_elem ||
18606 insn->imm == BPF_FUNC_map_pop_elem ||
18607 insn->imm == BPF_FUNC_map_peek_elem ||
18608 insn->imm == BPF_FUNC_redirect_map ||
18609 insn->imm == BPF_FUNC_for_each_map_elem ||
18610 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18611 aux = &env->insn_aux_data[i + delta];
18612 if (bpf_map_ptr_poisoned(aux))
18613 goto patch_call_imm;
18615 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18616 ops = map_ptr->ops;
18617 if (insn->imm == BPF_FUNC_map_lookup_elem &&
18618 ops->map_gen_lookup) {
18619 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18620 if (cnt == -EOPNOTSUPP)
18621 goto patch_map_ops_generic;
18622 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18623 verbose(env, "bpf verifier is misconfigured\n");
18627 new_prog = bpf_patch_insn_data(env, i + delta,
18633 env->prog = prog = new_prog;
18634 insn = new_prog->insnsi + i + delta;
18638 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18639 (void *(*)(struct bpf_map *map, void *key))NULL));
18640 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18641 (long (*)(struct bpf_map *map, void *key))NULL));
18642 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18643 (long (*)(struct bpf_map *map, void *key, void *value,
18645 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18646 (long (*)(struct bpf_map *map, void *value,
18648 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18649 (long (*)(struct bpf_map *map, void *value))NULL));
18650 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18651 (long (*)(struct bpf_map *map, void *value))NULL));
18652 BUILD_BUG_ON(!__same_type(ops->map_redirect,
18653 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18654 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18655 (long (*)(struct bpf_map *map,
18656 bpf_callback_t callback_fn,
18657 void *callback_ctx,
18659 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18660 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18662 patch_map_ops_generic:
18663 switch (insn->imm) {
18664 case BPF_FUNC_map_lookup_elem:
18665 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18667 case BPF_FUNC_map_update_elem:
18668 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18670 case BPF_FUNC_map_delete_elem:
18671 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18673 case BPF_FUNC_map_push_elem:
18674 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18676 case BPF_FUNC_map_pop_elem:
18677 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18679 case BPF_FUNC_map_peek_elem:
18680 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18682 case BPF_FUNC_redirect_map:
18683 insn->imm = BPF_CALL_IMM(ops->map_redirect);
18685 case BPF_FUNC_for_each_map_elem:
18686 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18688 case BPF_FUNC_map_lookup_percpu_elem:
18689 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18693 goto patch_call_imm;
18696 /* Implement bpf_jiffies64 inline. */
18697 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18698 insn->imm == BPF_FUNC_jiffies64) {
18699 struct bpf_insn ld_jiffies_addr[2] = {
18700 BPF_LD_IMM64(BPF_REG_0,
18701 (unsigned long)&jiffies),
18704 insn_buf[0] = ld_jiffies_addr[0];
18705 insn_buf[1] = ld_jiffies_addr[1];
18706 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18710 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18716 env->prog = prog = new_prog;
18717 insn = new_prog->insnsi + i + delta;
18721 /* Implement bpf_get_func_arg inline. */
18722 if (prog_type == BPF_PROG_TYPE_TRACING &&
18723 insn->imm == BPF_FUNC_get_func_arg) {
18724 /* Load nr_args from ctx - 8 */
18725 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18726 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18727 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18728 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18729 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18730 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18731 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18732 insn_buf[7] = BPF_JMP_A(1);
18733 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18736 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18741 env->prog = prog = new_prog;
18742 insn = new_prog->insnsi + i + delta;
18746 /* Implement bpf_get_func_ret inline. */
18747 if (prog_type == BPF_PROG_TYPE_TRACING &&
18748 insn->imm == BPF_FUNC_get_func_ret) {
18749 if (eatype == BPF_TRACE_FEXIT ||
18750 eatype == BPF_MODIFY_RETURN) {
18751 /* Load nr_args from ctx - 8 */
18752 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18753 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18754 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18755 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18756 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18757 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18760 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18764 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18769 env->prog = prog = new_prog;
18770 insn = new_prog->insnsi + i + delta;
18774 /* Implement get_func_arg_cnt inline. */
18775 if (prog_type == BPF_PROG_TYPE_TRACING &&
18776 insn->imm == BPF_FUNC_get_func_arg_cnt) {
18777 /* Load nr_args from ctx - 8 */
18778 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18780 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18784 env->prog = prog = new_prog;
18785 insn = new_prog->insnsi + i + delta;
18789 /* Implement bpf_get_func_ip inline. */
18790 if (prog_type == BPF_PROG_TYPE_TRACING &&
18791 insn->imm == BPF_FUNC_get_func_ip) {
18792 /* Load IP address from ctx - 16 */
18793 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18795 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18799 env->prog = prog = new_prog;
18800 insn = new_prog->insnsi + i + delta;
18805 fn = env->ops->get_func_proto(insn->imm, env->prog);
18806 /* all functions that have prototype and verifier allowed
18807 * programs to call them, must be real in-kernel functions
18811 "kernel subsystem misconfigured func %s#%d\n",
18812 func_id_name(insn->imm), insn->imm);
18815 insn->imm = fn->func - __bpf_call_base;
18818 /* Since poke tab is now finalized, publish aux to tracker. */
18819 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18820 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18821 if (!map_ptr->ops->map_poke_track ||
18822 !map_ptr->ops->map_poke_untrack ||
18823 !map_ptr->ops->map_poke_run) {
18824 verbose(env, "bpf verifier is misconfigured\n");
18828 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18830 verbose(env, "tracking tail call prog failed\n");
18835 sort_kfunc_descs_by_imm_off(env->prog);
18840 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18843 u32 callback_subprogno,
18846 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18847 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18848 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18849 int reg_loop_max = BPF_REG_6;
18850 int reg_loop_cnt = BPF_REG_7;
18851 int reg_loop_ctx = BPF_REG_8;
18853 struct bpf_prog *new_prog;
18854 u32 callback_start;
18855 u32 call_insn_offset;
18856 s32 callback_offset;
18858 /* This represents an inlined version of bpf_iter.c:bpf_loop,
18859 * be careful to modify this code in sync.
18861 struct bpf_insn insn_buf[] = {
18862 /* Return error and jump to the end of the patch if
18863 * expected number of iterations is too big.
18865 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18866 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18867 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18868 /* spill R6, R7, R8 to use these as loop vars */
18869 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18870 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18871 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18872 /* initialize loop vars */
18873 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18874 BPF_MOV32_IMM(reg_loop_cnt, 0),
18875 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18877 * if reg_loop_cnt >= reg_loop_max skip the loop body
18879 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18881 * correct callback offset would be set after patching
18883 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18884 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18886 /* increment loop counter */
18887 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18888 /* jump to loop header if callback returned 0 */
18889 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18890 /* return value of bpf_loop,
18891 * set R0 to the number of iterations
18893 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18894 /* restore original values of R6, R7, R8 */
18895 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18896 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18897 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18900 *cnt = ARRAY_SIZE(insn_buf);
18901 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18905 /* callback start is known only after patching */
18906 callback_start = env->subprog_info[callback_subprogno].start;
18907 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18908 call_insn_offset = position + 12;
18909 callback_offset = callback_start - call_insn_offset - 1;
18910 new_prog->insnsi[call_insn_offset].imm = callback_offset;
18915 static bool is_bpf_loop_call(struct bpf_insn *insn)
18917 return insn->code == (BPF_JMP | BPF_CALL) &&
18918 insn->src_reg == 0 &&
18919 insn->imm == BPF_FUNC_loop;
18922 /* For all sub-programs in the program (including main) check
18923 * insn_aux_data to see if there are bpf_loop calls that require
18924 * inlining. If such calls are found the calls are replaced with a
18925 * sequence of instructions produced by `inline_bpf_loop` function and
18926 * subprog stack_depth is increased by the size of 3 registers.
18927 * This stack space is used to spill values of the R6, R7, R8. These
18928 * registers are used to store the loop bound, counter and context
18931 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18933 struct bpf_subprog_info *subprogs = env->subprog_info;
18934 int i, cur_subprog = 0, cnt, delta = 0;
18935 struct bpf_insn *insn = env->prog->insnsi;
18936 int insn_cnt = env->prog->len;
18937 u16 stack_depth = subprogs[cur_subprog].stack_depth;
18938 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18939 u16 stack_depth_extra = 0;
18941 for (i = 0; i < insn_cnt; i++, insn++) {
18942 struct bpf_loop_inline_state *inline_state =
18943 &env->insn_aux_data[i + delta].loop_inline_state;
18945 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18946 struct bpf_prog *new_prog;
18948 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18949 new_prog = inline_bpf_loop(env,
18951 -(stack_depth + stack_depth_extra),
18952 inline_state->callback_subprogno,
18958 env->prog = new_prog;
18959 insn = new_prog->insnsi + i + delta;
18962 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18963 subprogs[cur_subprog].stack_depth += stack_depth_extra;
18965 stack_depth = subprogs[cur_subprog].stack_depth;
18966 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18967 stack_depth_extra = 0;
18971 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18976 static void free_states(struct bpf_verifier_env *env)
18978 struct bpf_verifier_state_list *sl, *sln;
18981 sl = env->free_list;
18984 free_verifier_state(&sl->state, false);
18988 env->free_list = NULL;
18990 if (!env->explored_states)
18993 for (i = 0; i < state_htab_size(env); i++) {
18994 sl = env->explored_states[i];
18998 free_verifier_state(&sl->state, false);
19002 env->explored_states[i] = NULL;
19006 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19008 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19009 struct bpf_verifier_state *state;
19010 struct bpf_reg_state *regs;
19013 env->prev_linfo = NULL;
19016 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19019 state->curframe = 0;
19020 state->speculative = false;
19021 state->branches = 1;
19022 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19023 if (!state->frame[0]) {
19027 env->cur_state = state;
19028 init_func_state(env, state->frame[0],
19029 BPF_MAIN_FUNC /* callsite */,
19032 state->first_insn_idx = env->subprog_info[subprog].start;
19033 state->last_insn_idx = -1;
19035 regs = state->frame[state->curframe]->regs;
19036 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19037 ret = btf_prepare_func_args(env, subprog, regs);
19040 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19041 if (regs[i].type == PTR_TO_CTX)
19042 mark_reg_known_zero(env, regs, i);
19043 else if (regs[i].type == SCALAR_VALUE)
19044 mark_reg_unknown(env, regs, i);
19045 else if (base_type(regs[i].type) == PTR_TO_MEM) {
19046 const u32 mem_size = regs[i].mem_size;
19048 mark_reg_known_zero(env, regs, i);
19049 regs[i].mem_size = mem_size;
19050 regs[i].id = ++env->id_gen;
19054 /* 1st arg to a function */
19055 regs[BPF_REG_1].type = PTR_TO_CTX;
19056 mark_reg_known_zero(env, regs, BPF_REG_1);
19057 ret = btf_check_subprog_arg_match(env, subprog, regs);
19058 if (ret == -EFAULT)
19059 /* unlikely verifier bug. abort.
19060 * ret == 0 and ret < 0 are sadly acceptable for
19061 * main() function due to backward compatibility.
19062 * Like socket filter program may be written as:
19063 * int bpf_prog(struct pt_regs *ctx)
19064 * and never dereference that ctx in the program.
19065 * 'struct pt_regs' is a type mismatch for socket
19066 * filter that should be using 'struct __sk_buff'.
19071 ret = do_check(env);
19073 /* check for NULL is necessary, since cur_state can be freed inside
19074 * do_check() under memory pressure.
19076 if (env->cur_state) {
19077 free_verifier_state(env->cur_state, true);
19078 env->cur_state = NULL;
19080 while (!pop_stack(env, NULL, NULL, false));
19081 if (!ret && pop_log)
19082 bpf_vlog_reset(&env->log, 0);
19087 /* Verify all global functions in a BPF program one by one based on their BTF.
19088 * All global functions must pass verification. Otherwise the whole program is rejected.
19099 * foo() will be verified first for R1=any_scalar_value. During verification it
19100 * will be assumed that bar() already verified successfully and call to bar()
19101 * from foo() will be checked for type match only. Later bar() will be verified
19102 * independently to check that it's safe for R1=any_scalar_value.
19104 static int do_check_subprogs(struct bpf_verifier_env *env)
19106 struct bpf_prog_aux *aux = env->prog->aux;
19109 if (!aux->func_info)
19112 for (i = 1; i < env->subprog_cnt; i++) {
19113 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19115 env->insn_idx = env->subprog_info[i].start;
19116 WARN_ON_ONCE(env->insn_idx == 0);
19117 ret = do_check_common(env, i);
19120 } else if (env->log.level & BPF_LOG_LEVEL) {
19122 "Func#%d is safe for any args that match its prototype\n",
19129 static int do_check_main(struct bpf_verifier_env *env)
19134 ret = do_check_common(env, 0);
19136 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19141 static void print_verification_stats(struct bpf_verifier_env *env)
19145 if (env->log.level & BPF_LOG_STATS) {
19146 verbose(env, "verification time %lld usec\n",
19147 div_u64(env->verification_time, 1000));
19148 verbose(env, "stack depth ");
19149 for (i = 0; i < env->subprog_cnt; i++) {
19150 u32 depth = env->subprog_info[i].stack_depth;
19152 verbose(env, "%d", depth);
19153 if (i + 1 < env->subprog_cnt)
19156 verbose(env, "\n");
19158 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19159 "total_states %d peak_states %d mark_read %d\n",
19160 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19161 env->max_states_per_insn, env->total_states,
19162 env->peak_states, env->longest_mark_read_walk);
19165 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19167 const struct btf_type *t, *func_proto;
19168 const struct bpf_struct_ops *st_ops;
19169 const struct btf_member *member;
19170 struct bpf_prog *prog = env->prog;
19171 u32 btf_id, member_idx;
19174 if (!prog->gpl_compatible) {
19175 verbose(env, "struct ops programs must have a GPL compatible license\n");
19179 btf_id = prog->aux->attach_btf_id;
19180 st_ops = bpf_struct_ops_find(btf_id);
19182 verbose(env, "attach_btf_id %u is not a supported struct\n",
19188 member_idx = prog->expected_attach_type;
19189 if (member_idx >= btf_type_vlen(t)) {
19190 verbose(env, "attach to invalid member idx %u of struct %s\n",
19191 member_idx, st_ops->name);
19195 member = &btf_type_member(t)[member_idx];
19196 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19197 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19200 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19201 mname, member_idx, st_ops->name);
19205 if (st_ops->check_member) {
19206 int err = st_ops->check_member(t, member, prog);
19209 verbose(env, "attach to unsupported member %s of struct %s\n",
19210 mname, st_ops->name);
19215 prog->aux->attach_func_proto = func_proto;
19216 prog->aux->attach_func_name = mname;
19217 env->ops = st_ops->verifier_ops;
19221 #define SECURITY_PREFIX "security_"
19223 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19225 if (within_error_injection_list(addr) ||
19226 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19232 /* list of non-sleepable functions that are otherwise on
19233 * ALLOW_ERROR_INJECTION list
19235 BTF_SET_START(btf_non_sleepable_error_inject)
19236 /* Three functions below can be called from sleepable and non-sleepable context.
19237 * Assume non-sleepable from bpf safety point of view.
19239 BTF_ID(func, __filemap_add_folio)
19240 BTF_ID(func, should_fail_alloc_page)
19241 BTF_ID(func, should_failslab)
19242 BTF_SET_END(btf_non_sleepable_error_inject)
19244 static int check_non_sleepable_error_inject(u32 btf_id)
19246 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19249 int bpf_check_attach_target(struct bpf_verifier_log *log,
19250 const struct bpf_prog *prog,
19251 const struct bpf_prog *tgt_prog,
19253 struct bpf_attach_target_info *tgt_info)
19255 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19256 const char prefix[] = "btf_trace_";
19257 int ret = 0, subprog = -1, i;
19258 const struct btf_type *t;
19259 bool conservative = true;
19263 struct module *mod = NULL;
19266 bpf_log(log, "Tracing programs must provide btf_id\n");
19269 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19272 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19275 t = btf_type_by_id(btf, btf_id);
19277 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19280 tname = btf_name_by_offset(btf, t->name_off);
19282 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19286 struct bpf_prog_aux *aux = tgt_prog->aux;
19288 if (bpf_prog_is_dev_bound(prog->aux) &&
19289 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19290 bpf_log(log, "Target program bound device mismatch");
19294 for (i = 0; i < aux->func_info_cnt; i++)
19295 if (aux->func_info[i].type_id == btf_id) {
19299 if (subprog == -1) {
19300 bpf_log(log, "Subprog %s doesn't exist\n", tname);
19303 conservative = aux->func_info_aux[subprog].unreliable;
19304 if (prog_extension) {
19305 if (conservative) {
19307 "Cannot replace static functions\n");
19310 if (!prog->jit_requested) {
19312 "Extension programs should be JITed\n");
19316 if (!tgt_prog->jited) {
19317 bpf_log(log, "Can attach to only JITed progs\n");
19320 if (tgt_prog->type == prog->type) {
19321 /* Cannot fentry/fexit another fentry/fexit program.
19322 * Cannot attach program extension to another extension.
19323 * It's ok to attach fentry/fexit to extension program.
19325 bpf_log(log, "Cannot recursively attach\n");
19328 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19330 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19331 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19332 /* Program extensions can extend all program types
19333 * except fentry/fexit. The reason is the following.
19334 * The fentry/fexit programs are used for performance
19335 * analysis, stats and can be attached to any program
19336 * type except themselves. When extension program is
19337 * replacing XDP function it is necessary to allow
19338 * performance analysis of all functions. Both original
19339 * XDP program and its program extension. Hence
19340 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19341 * allowed. If extending of fentry/fexit was allowed it
19342 * would be possible to create long call chain
19343 * fentry->extension->fentry->extension beyond
19344 * reasonable stack size. Hence extending fentry is not
19347 bpf_log(log, "Cannot extend fentry/fexit\n");
19351 if (prog_extension) {
19352 bpf_log(log, "Cannot replace kernel functions\n");
19357 switch (prog->expected_attach_type) {
19358 case BPF_TRACE_RAW_TP:
19361 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19364 if (!btf_type_is_typedef(t)) {
19365 bpf_log(log, "attach_btf_id %u is not a typedef\n",
19369 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19370 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19374 tname += sizeof(prefix) - 1;
19375 t = btf_type_by_id(btf, t->type);
19376 if (!btf_type_is_ptr(t))
19377 /* should never happen in valid vmlinux build */
19379 t = btf_type_by_id(btf, t->type);
19380 if (!btf_type_is_func_proto(t))
19381 /* should never happen in valid vmlinux build */
19385 case BPF_TRACE_ITER:
19386 if (!btf_type_is_func(t)) {
19387 bpf_log(log, "attach_btf_id %u is not a function\n",
19391 t = btf_type_by_id(btf, t->type);
19392 if (!btf_type_is_func_proto(t))
19394 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19399 if (!prog_extension)
19402 case BPF_MODIFY_RETURN:
19404 case BPF_LSM_CGROUP:
19405 case BPF_TRACE_FENTRY:
19406 case BPF_TRACE_FEXIT:
19407 if (!btf_type_is_func(t)) {
19408 bpf_log(log, "attach_btf_id %u is not a function\n",
19412 if (prog_extension &&
19413 btf_check_type_match(log, prog, btf, t))
19415 t = btf_type_by_id(btf, t->type);
19416 if (!btf_type_is_func_proto(t))
19419 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19420 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19421 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19424 if (tgt_prog && conservative)
19427 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19433 addr = (long) tgt_prog->bpf_func;
19435 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19437 if (btf_is_module(btf)) {
19438 mod = btf_try_get_module(btf);
19440 addr = find_kallsyms_symbol_value(mod, tname);
19444 addr = kallsyms_lookup_name(tname);
19449 "The address of function %s cannot be found\n",
19455 if (prog->aux->sleepable) {
19457 switch (prog->type) {
19458 case BPF_PROG_TYPE_TRACING:
19460 /* fentry/fexit/fmod_ret progs can be sleepable if they are
19461 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19463 if (!check_non_sleepable_error_inject(btf_id) &&
19464 within_error_injection_list(addr))
19466 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19467 * in the fmodret id set with the KF_SLEEPABLE flag.
19470 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19473 if (flags && (*flags & KF_SLEEPABLE))
19477 case BPF_PROG_TYPE_LSM:
19478 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19479 * Only some of them are sleepable.
19481 if (bpf_lsm_is_sleepable_hook(btf_id))
19489 bpf_log(log, "%s is not sleepable\n", tname);
19492 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19495 bpf_log(log, "can't modify return codes of BPF programs\n");
19499 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19500 !check_attach_modify_return(addr, tname))
19504 bpf_log(log, "%s() is not modifiable\n", tname);
19511 tgt_info->tgt_addr = addr;
19512 tgt_info->tgt_name = tname;
19513 tgt_info->tgt_type = t;
19514 tgt_info->tgt_mod = mod;
19518 BTF_SET_START(btf_id_deny)
19521 BTF_ID(func, migrate_disable)
19522 BTF_ID(func, migrate_enable)
19524 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19525 BTF_ID(func, rcu_read_unlock_strict)
19527 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19528 BTF_ID(func, preempt_count_add)
19529 BTF_ID(func, preempt_count_sub)
19531 #ifdef CONFIG_PREEMPT_RCU
19532 BTF_ID(func, __rcu_read_lock)
19533 BTF_ID(func, __rcu_read_unlock)
19535 BTF_SET_END(btf_id_deny)
19537 static bool can_be_sleepable(struct bpf_prog *prog)
19539 if (prog->type == BPF_PROG_TYPE_TRACING) {
19540 switch (prog->expected_attach_type) {
19541 case BPF_TRACE_FENTRY:
19542 case BPF_TRACE_FEXIT:
19543 case BPF_MODIFY_RETURN:
19544 case BPF_TRACE_ITER:
19550 return prog->type == BPF_PROG_TYPE_LSM ||
19551 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19552 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19555 static int check_attach_btf_id(struct bpf_verifier_env *env)
19557 struct bpf_prog *prog = env->prog;
19558 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19559 struct bpf_attach_target_info tgt_info = {};
19560 u32 btf_id = prog->aux->attach_btf_id;
19561 struct bpf_trampoline *tr;
19565 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19566 if (prog->aux->sleepable)
19567 /* attach_btf_id checked to be zero already */
19569 verbose(env, "Syscall programs can only be sleepable\n");
19573 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19574 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19578 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19579 return check_struct_ops_btf_id(env);
19581 if (prog->type != BPF_PROG_TYPE_TRACING &&
19582 prog->type != BPF_PROG_TYPE_LSM &&
19583 prog->type != BPF_PROG_TYPE_EXT)
19586 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19590 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19591 /* to make freplace equivalent to their targets, they need to
19592 * inherit env->ops and expected_attach_type for the rest of the
19595 env->ops = bpf_verifier_ops[tgt_prog->type];
19596 prog->expected_attach_type = tgt_prog->expected_attach_type;
19599 /* store info about the attachment target that will be used later */
19600 prog->aux->attach_func_proto = tgt_info.tgt_type;
19601 prog->aux->attach_func_name = tgt_info.tgt_name;
19602 prog->aux->mod = tgt_info.tgt_mod;
19605 prog->aux->saved_dst_prog_type = tgt_prog->type;
19606 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19609 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19610 prog->aux->attach_btf_trace = true;
19612 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19613 if (!bpf_iter_prog_supported(prog))
19618 if (prog->type == BPF_PROG_TYPE_LSM) {
19619 ret = bpf_lsm_verify_prog(&env->log, prog);
19622 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
19623 btf_id_set_contains(&btf_id_deny, btf_id)) {
19627 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19628 tr = bpf_trampoline_get(key, &tgt_info);
19632 prog->aux->dst_trampoline = tr;
19636 struct btf *bpf_get_btf_vmlinux(void)
19638 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19639 mutex_lock(&bpf_verifier_lock);
19641 btf_vmlinux = btf_parse_vmlinux();
19642 mutex_unlock(&bpf_verifier_lock);
19644 return btf_vmlinux;
19647 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19649 u64 start_time = ktime_get_ns();
19650 struct bpf_verifier_env *env;
19651 int i, len, ret = -EINVAL, err;
19655 /* no program is valid */
19656 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19659 /* 'struct bpf_verifier_env' can be global, but since it's not small,
19660 * allocate/free it every time bpf_check() is called
19662 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19668 len = (*prog)->len;
19669 env->insn_aux_data =
19670 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19672 if (!env->insn_aux_data)
19674 for (i = 0; i < len; i++)
19675 env->insn_aux_data[i].orig_idx = i;
19677 env->ops = bpf_verifier_ops[env->prog->type];
19678 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19679 is_priv = bpf_capable();
19681 bpf_get_btf_vmlinux();
19683 /* grab the mutex to protect few globals used by verifier */
19685 mutex_lock(&bpf_verifier_lock);
19687 /* user could have requested verbose verifier output
19688 * and supplied buffer to store the verification trace
19690 ret = bpf_vlog_init(&env->log, attr->log_level,
19691 (char __user *) (unsigned long) attr->log_buf,
19696 mark_verifier_state_clean(env);
19698 if (IS_ERR(btf_vmlinux)) {
19699 /* Either gcc or pahole or kernel are broken. */
19700 verbose(env, "in-kernel BTF is malformed\n");
19701 ret = PTR_ERR(btf_vmlinux);
19702 goto skip_full_check;
19705 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19706 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19707 env->strict_alignment = true;
19708 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19709 env->strict_alignment = false;
19711 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19712 env->allow_uninit_stack = bpf_allow_uninit_stack();
19713 env->bypass_spec_v1 = bpf_bypass_spec_v1();
19714 env->bypass_spec_v4 = bpf_bypass_spec_v4();
19715 env->bpf_capable = bpf_capable();
19718 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19720 env->explored_states = kvcalloc(state_htab_size(env),
19721 sizeof(struct bpf_verifier_state_list *),
19724 if (!env->explored_states)
19725 goto skip_full_check;
19727 ret = add_subprog_and_kfunc(env);
19729 goto skip_full_check;
19731 ret = check_subprogs(env);
19733 goto skip_full_check;
19735 ret = check_btf_info(env, attr, uattr);
19737 goto skip_full_check;
19739 ret = check_attach_btf_id(env);
19741 goto skip_full_check;
19743 ret = resolve_pseudo_ldimm64(env);
19745 goto skip_full_check;
19747 if (bpf_prog_is_offloaded(env->prog->aux)) {
19748 ret = bpf_prog_offload_verifier_prep(env->prog);
19750 goto skip_full_check;
19753 ret = check_cfg(env);
19755 goto skip_full_check;
19757 ret = do_check_subprogs(env);
19758 ret = ret ?: do_check_main(env);
19760 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19761 ret = bpf_prog_offload_finalize(env);
19764 kvfree(env->explored_states);
19767 ret = check_max_stack_depth(env);
19769 /* instruction rewrites happen after this point */
19771 ret = optimize_bpf_loop(env);
19775 opt_hard_wire_dead_code_branches(env);
19777 ret = opt_remove_dead_code(env);
19779 ret = opt_remove_nops(env);
19782 sanitize_dead_code(env);
19786 /* program is valid, convert *(u32*)(ctx + off) accesses */
19787 ret = convert_ctx_accesses(env);
19790 ret = do_misc_fixups(env);
19792 /* do 32-bit optimization after insn patching has done so those patched
19793 * insns could be handled correctly.
19795 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19796 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19797 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19802 ret = fixup_call_args(env);
19804 env->verification_time = ktime_get_ns() - start_time;
19805 print_verification_stats(env);
19806 env->prog->aux->verified_insns = env->insn_processed;
19808 /* preserve original error even if log finalization is successful */
19809 err = bpf_vlog_finalize(&env->log, &log_true_size);
19813 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19814 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19815 &log_true_size, sizeof(log_true_size))) {
19817 goto err_release_maps;
19821 goto err_release_maps;
19823 if (env->used_map_cnt) {
19824 /* if program passed verifier, update used_maps in bpf_prog_info */
19825 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19826 sizeof(env->used_maps[0]),
19829 if (!env->prog->aux->used_maps) {
19831 goto err_release_maps;
19834 memcpy(env->prog->aux->used_maps, env->used_maps,
19835 sizeof(env->used_maps[0]) * env->used_map_cnt);
19836 env->prog->aux->used_map_cnt = env->used_map_cnt;
19838 if (env->used_btf_cnt) {
19839 /* if program passed verifier, update used_btfs in bpf_prog_aux */
19840 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19841 sizeof(env->used_btfs[0]),
19843 if (!env->prog->aux->used_btfs) {
19845 goto err_release_maps;
19848 memcpy(env->prog->aux->used_btfs, env->used_btfs,
19849 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19850 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19852 if (env->used_map_cnt || env->used_btf_cnt) {
19853 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
19854 * bpf_ld_imm64 instructions
19856 convert_pseudo_ld_imm64(env);
19859 adjust_btf_func(env);
19862 if (!env->prog->aux->used_maps)
19863 /* if we didn't copy map pointers into bpf_prog_info, release
19864 * them now. Otherwise free_used_maps() will release them.
19867 if (!env->prog->aux->used_btfs)
19870 /* extension progs temporarily inherit the attach_type of their targets
19871 for verification purposes, so set it back to zero before returning
19873 if (env->prog->type == BPF_PROG_TYPE_EXT)
19874 env->prog->expected_attach_type = 0;
19879 mutex_unlock(&bpf_verifier_lock);
19880 vfree(env->insn_aux_data);