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>
31 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
32 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
33 [_id] = & _name ## _verifier_ops,
34 #define BPF_MAP_TYPE(_id, _ops)
35 #define BPF_LINK_TYPE(_id, _name)
36 #include <linux/bpf_types.h>
42 /* bpf_check() is a static code analyzer that walks eBPF program
43 * instruction by instruction and updates register/stack state.
44 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
46 * The first pass is depth-first-search to check that the program is a DAG.
47 * It rejects the following programs:
48 * - larger than BPF_MAXINSNS insns
49 * - if loop is present (detected via back-edge)
50 * - unreachable insns exist (shouldn't be a forest. program = one function)
51 * - out of bounds or malformed jumps
52 * The second pass is all possible path descent from the 1st insn.
53 * Since it's analyzing all paths through the program, the length of the
54 * analysis is limited to 64k insn, which may be hit even if total number of
55 * insn is less then 4K, but there are too many branches that change stack/regs.
56 * Number of 'branches to be analyzed' is limited to 1k
58 * On entry to each instruction, each register has a type, and the instruction
59 * changes the types of the registers depending on instruction semantics.
60 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63 * All registers are 64-bit.
64 * R0 - return register
65 * R1-R5 argument passing registers
66 * R6-R9 callee saved registers
67 * R10 - frame pointer read-only
69 * At the start of BPF program the register R1 contains a pointer to bpf_context
70 * and has type PTR_TO_CTX.
72 * Verifier tracks arithmetic operations on pointers in case:
73 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
74 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
75 * 1st insn copies R10 (which has FRAME_PTR) type into R1
76 * and 2nd arithmetic instruction is pattern matched to recognize
77 * that it wants to construct a pointer to some element within stack.
78 * So after 2nd insn, the register R1 has type PTR_TO_STACK
79 * (and -20 constant is saved for further stack bounds checking).
80 * Meaning that this reg is a pointer to stack plus known immediate constant.
82 * Most of the time the registers have SCALAR_VALUE type, which
83 * means the register has some value, but it's not a valid pointer.
84 * (like pointer plus pointer becomes SCALAR_VALUE type)
86 * When verifier sees load or store instructions the type of base register
87 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
88 * four pointer types recognized by check_mem_access() function.
90 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
91 * and the range of [ptr, ptr + map's value_size) is accessible.
93 * registers used to pass values to function calls are checked against
94 * function argument constraints.
96 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
97 * It means that the register type passed to this function must be
98 * PTR_TO_STACK and it will be used inside the function as
99 * 'pointer to map element key'
101 * For example the argument constraints for bpf_map_lookup_elem():
102 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
103 * .arg1_type = ARG_CONST_MAP_PTR,
104 * .arg2_type = ARG_PTR_TO_MAP_KEY,
106 * ret_type says that this function returns 'pointer to map elem value or null'
107 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
108 * 2nd argument should be a pointer to stack, which will be used inside
109 * the helper function as a pointer to map element key.
111 * On the kernel side the helper function looks like:
112 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
114 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
115 * void *key = (void *) (unsigned long) r2;
118 * here kernel can access 'key' and 'map' pointers safely, knowing that
119 * [key, key + map->key_size) bytes are valid and were initialized on
120 * the stack of eBPF program.
123 * Corresponding eBPF program may look like:
124 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
125 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
126 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
127 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
128 * here verifier looks at prototype of map_lookup_elem() and sees:
129 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
130 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
132 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
133 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
134 * and were initialized prior to this call.
135 * If it's ok, then verifier allows this BPF_CALL insn and looks at
136 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
137 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
138 * returns either pointer to map value or NULL.
140 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
141 * insn, the register holding that pointer in the true branch changes state to
142 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
143 * branch. See check_cond_jmp_op().
145 * After the call R0 is set to return type of the function and registers R1-R5
146 * are set to NOT_INIT to indicate that they are no longer readable.
148 * The following reference types represent a potential reference to a kernel
149 * resource which, after first being allocated, must be checked and freed by
151 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
153 * When the verifier sees a helper call return a reference type, it allocates a
154 * pointer id for the reference and stores it in the current function state.
155 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
156 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
157 * passes through a NULL-check conditional. For the branch wherein the state is
158 * changed to CONST_IMM, the verifier releases the reference.
160 * For each helper function that allocates a reference, such as
161 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
162 * bpf_sk_release(). When a reference type passes into the release function,
163 * the verifier also releases the reference. If any unchecked or unreleased
164 * reference remains at the end of the program, the verifier rejects it.
167 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
168 struct bpf_verifier_stack_elem {
169 /* verifer state is 'st'
170 * before processing instruction 'insn_idx'
171 * and after processing instruction 'prev_insn_idx'
173 struct bpf_verifier_state st;
176 struct bpf_verifier_stack_elem *next;
177 /* length of verifier log at the time this state was pushed on stack */
181 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
182 #define BPF_COMPLEXITY_LIMIT_STATES 64
184 #define BPF_MAP_KEY_POISON (1ULL << 63)
185 #define BPF_MAP_KEY_SEEN (1ULL << 62)
187 #define BPF_MAP_PTR_UNPRIV 1UL
188 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
189 POISON_POINTER_DELTA))
190 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
192 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
193 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
194 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
195 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
196 static int ref_set_non_owning(struct bpf_verifier_env *env,
197 struct bpf_reg_state *reg);
199 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
201 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
204 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
206 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
209 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
210 const struct bpf_map *map, bool unpriv)
212 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
213 unpriv |= bpf_map_ptr_unpriv(aux);
214 aux->map_ptr_state = (unsigned long)map |
215 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
218 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
220 return aux->map_key_state & BPF_MAP_KEY_POISON;
223 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
225 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
228 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
230 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
233 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
235 bool poisoned = bpf_map_key_poisoned(aux);
237 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
238 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
241 static bool bpf_pseudo_call(const struct bpf_insn *insn)
243 return insn->code == (BPF_JMP | BPF_CALL) &&
244 insn->src_reg == BPF_PSEUDO_CALL;
247 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
249 return insn->code == (BPF_JMP | BPF_CALL) &&
250 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
253 struct bpf_call_arg_meta {
254 struct bpf_map *map_ptr;
271 struct btf_field *kptr_field;
274 struct bpf_kfunc_call_arg_meta {
279 const struct btf_type *func_proto;
280 const char *func_name;
297 struct btf_field *field;
300 struct btf_field *field;
303 enum bpf_dynptr_type type;
305 } initialized_dynptr;
313 struct btf *btf_vmlinux;
315 static DEFINE_MUTEX(bpf_verifier_lock);
317 static const struct bpf_line_info *
318 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
320 const struct bpf_line_info *linfo;
321 const struct bpf_prog *prog;
325 nr_linfo = prog->aux->nr_linfo;
327 if (!nr_linfo || insn_off >= prog->len)
330 linfo = prog->aux->linfo;
331 for (i = 1; i < nr_linfo; i++)
332 if (insn_off < linfo[i].insn_off)
335 return &linfo[i - 1];
338 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
340 struct bpf_verifier_env *env = private_data;
343 if (!bpf_verifier_log_needed(&env->log))
347 bpf_verifier_vlog(&env->log, fmt, args);
351 static const char *ltrim(const char *s)
359 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
361 const char *prefix_fmt, ...)
363 const struct bpf_line_info *linfo;
365 if (!bpf_verifier_log_needed(&env->log))
368 linfo = find_linfo(env, insn_off);
369 if (!linfo || linfo == env->prev_linfo)
375 va_start(args, prefix_fmt);
376 bpf_verifier_vlog(&env->log, prefix_fmt, args);
381 ltrim(btf_name_by_offset(env->prog->aux->btf,
384 env->prev_linfo = linfo;
387 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
388 struct bpf_reg_state *reg,
389 struct tnum *range, const char *ctx,
390 const char *reg_name)
394 verbose(env, "At %s the register %s ", ctx, reg_name);
395 if (!tnum_is_unknown(reg->var_off)) {
396 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
397 verbose(env, "has value %s", tn_buf);
399 verbose(env, "has unknown scalar value");
401 tnum_strn(tn_buf, sizeof(tn_buf), *range);
402 verbose(env, " should have been in %s\n", tn_buf);
405 static bool type_is_pkt_pointer(enum bpf_reg_type type)
407 type = base_type(type);
408 return type == PTR_TO_PACKET ||
409 type == PTR_TO_PACKET_META;
412 static bool type_is_sk_pointer(enum bpf_reg_type type)
414 return type == PTR_TO_SOCKET ||
415 type == PTR_TO_SOCK_COMMON ||
416 type == PTR_TO_TCP_SOCK ||
417 type == PTR_TO_XDP_SOCK;
420 static bool type_may_be_null(u32 type)
422 return type & PTR_MAYBE_NULL;
425 static bool reg_type_not_null(enum bpf_reg_type type)
427 if (type_may_be_null(type))
430 type = base_type(type);
431 return type == PTR_TO_SOCKET ||
432 type == PTR_TO_TCP_SOCK ||
433 type == PTR_TO_MAP_VALUE ||
434 type == PTR_TO_MAP_KEY ||
435 type == PTR_TO_SOCK_COMMON ||
439 static bool type_is_ptr_alloc_obj(u32 type)
441 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
444 static bool type_is_non_owning_ref(u32 type)
446 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
449 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
451 struct btf_record *rec = NULL;
452 struct btf_struct_meta *meta;
454 if (reg->type == PTR_TO_MAP_VALUE) {
455 rec = reg->map_ptr->record;
456 } else if (type_is_ptr_alloc_obj(reg->type)) {
457 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
464 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
466 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
469 static bool type_is_rdonly_mem(u32 type)
471 return type & MEM_RDONLY;
474 static bool is_acquire_function(enum bpf_func_id func_id,
475 const struct bpf_map *map)
477 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
479 if (func_id == BPF_FUNC_sk_lookup_tcp ||
480 func_id == BPF_FUNC_sk_lookup_udp ||
481 func_id == BPF_FUNC_skc_lookup_tcp ||
482 func_id == BPF_FUNC_ringbuf_reserve ||
483 func_id == BPF_FUNC_kptr_xchg)
486 if (func_id == BPF_FUNC_map_lookup_elem &&
487 (map_type == BPF_MAP_TYPE_SOCKMAP ||
488 map_type == BPF_MAP_TYPE_SOCKHASH))
494 static bool is_ptr_cast_function(enum bpf_func_id func_id)
496 return func_id == BPF_FUNC_tcp_sock ||
497 func_id == BPF_FUNC_sk_fullsock ||
498 func_id == BPF_FUNC_skc_to_tcp_sock ||
499 func_id == BPF_FUNC_skc_to_tcp6_sock ||
500 func_id == BPF_FUNC_skc_to_udp6_sock ||
501 func_id == BPF_FUNC_skc_to_mptcp_sock ||
502 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
503 func_id == BPF_FUNC_skc_to_tcp_request_sock;
506 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
508 return func_id == BPF_FUNC_dynptr_data;
511 static bool is_callback_calling_function(enum bpf_func_id func_id)
513 return func_id == BPF_FUNC_for_each_map_elem ||
514 func_id == BPF_FUNC_timer_set_callback ||
515 func_id == BPF_FUNC_find_vma ||
516 func_id == BPF_FUNC_loop ||
517 func_id == BPF_FUNC_user_ringbuf_drain;
520 static bool is_storage_get_function(enum bpf_func_id func_id)
522 return func_id == BPF_FUNC_sk_storage_get ||
523 func_id == BPF_FUNC_inode_storage_get ||
524 func_id == BPF_FUNC_task_storage_get ||
525 func_id == BPF_FUNC_cgrp_storage_get;
528 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
529 const struct bpf_map *map)
531 int ref_obj_uses = 0;
533 if (is_ptr_cast_function(func_id))
535 if (is_acquire_function(func_id, map))
537 if (is_dynptr_ref_function(func_id))
540 return ref_obj_uses > 1;
543 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
545 return BPF_CLASS(insn->code) == BPF_STX &&
546 BPF_MODE(insn->code) == BPF_ATOMIC &&
547 insn->imm == BPF_CMPXCHG;
550 /* string representation of 'enum bpf_reg_type'
552 * Note that reg_type_str() can not appear more than once in a single verbose()
555 static const char *reg_type_str(struct bpf_verifier_env *env,
556 enum bpf_reg_type type)
558 char postfix[16] = {0}, prefix[64] = {0};
559 static const char * const str[] = {
561 [SCALAR_VALUE] = "scalar",
562 [PTR_TO_CTX] = "ctx",
563 [CONST_PTR_TO_MAP] = "map_ptr",
564 [PTR_TO_MAP_VALUE] = "map_value",
565 [PTR_TO_STACK] = "fp",
566 [PTR_TO_PACKET] = "pkt",
567 [PTR_TO_PACKET_META] = "pkt_meta",
568 [PTR_TO_PACKET_END] = "pkt_end",
569 [PTR_TO_FLOW_KEYS] = "flow_keys",
570 [PTR_TO_SOCKET] = "sock",
571 [PTR_TO_SOCK_COMMON] = "sock_common",
572 [PTR_TO_TCP_SOCK] = "tcp_sock",
573 [PTR_TO_TP_BUFFER] = "tp_buffer",
574 [PTR_TO_XDP_SOCK] = "xdp_sock",
575 [PTR_TO_BTF_ID] = "ptr_",
576 [PTR_TO_MEM] = "mem",
577 [PTR_TO_BUF] = "buf",
578 [PTR_TO_FUNC] = "func",
579 [PTR_TO_MAP_KEY] = "map_key",
580 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr",
583 if (type & PTR_MAYBE_NULL) {
584 if (base_type(type) == PTR_TO_BTF_ID)
585 strncpy(postfix, "or_null_", 16);
587 strncpy(postfix, "_or_null", 16);
590 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
591 type & MEM_RDONLY ? "rdonly_" : "",
592 type & MEM_RINGBUF ? "ringbuf_" : "",
593 type & MEM_USER ? "user_" : "",
594 type & MEM_PERCPU ? "percpu_" : "",
595 type & MEM_RCU ? "rcu_" : "",
596 type & PTR_UNTRUSTED ? "untrusted_" : "",
597 type & PTR_TRUSTED ? "trusted_" : ""
600 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
601 prefix, str[base_type(type)], postfix);
602 return env->type_str_buf;
605 static char slot_type_char[] = {
606 [STACK_INVALID] = '?',
610 [STACK_DYNPTR] = 'd',
614 static void print_liveness(struct bpf_verifier_env *env,
615 enum bpf_reg_liveness live)
617 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
619 if (live & REG_LIVE_READ)
621 if (live & REG_LIVE_WRITTEN)
623 if (live & REG_LIVE_DONE)
627 static int __get_spi(s32 off)
629 return (-off - 1) / BPF_REG_SIZE;
632 static struct bpf_func_state *func(struct bpf_verifier_env *env,
633 const struct bpf_reg_state *reg)
635 struct bpf_verifier_state *cur = env->cur_state;
637 return cur->frame[reg->frameno];
640 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
642 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
644 /* We need to check that slots between [spi - nr_slots + 1, spi] are
645 * within [0, allocated_stack).
647 * Please note that the spi grows downwards. For example, a dynptr
648 * takes the size of two stack slots; the first slot will be at
649 * spi and the second slot will be at spi - 1.
651 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
654 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
655 const char *obj_kind, int nr_slots)
659 if (!tnum_is_const(reg->var_off)) {
660 verbose(env, "%s has to be at a constant offset\n", obj_kind);
664 off = reg->off + reg->var_off.value;
665 if (off % BPF_REG_SIZE) {
666 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
670 spi = __get_spi(off);
671 if (spi + 1 < nr_slots) {
672 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
676 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
681 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
683 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
686 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
688 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
691 static const char *btf_type_name(const struct btf *btf, u32 id)
693 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
696 static const char *dynptr_type_str(enum bpf_dynptr_type type)
699 case BPF_DYNPTR_TYPE_LOCAL:
701 case BPF_DYNPTR_TYPE_RINGBUF:
703 case BPF_DYNPTR_TYPE_SKB:
705 case BPF_DYNPTR_TYPE_XDP:
707 case BPF_DYNPTR_TYPE_INVALID:
710 WARN_ONCE(1, "unknown dynptr type %d\n", type);
715 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
717 if (!btf || btf_id == 0)
720 /* we already validated that type is valid and has conforming name */
721 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
724 static const char *iter_state_str(enum bpf_iter_state state)
727 case BPF_ITER_STATE_ACTIVE:
729 case BPF_ITER_STATE_DRAINED:
731 case BPF_ITER_STATE_INVALID:
734 WARN_ONCE(1, "unknown iter state %d\n", state);
739 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
741 env->scratched_regs |= 1U << regno;
744 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
746 env->scratched_stack_slots |= 1ULL << spi;
749 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
751 return (env->scratched_regs >> regno) & 1;
754 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
756 return (env->scratched_stack_slots >> regno) & 1;
759 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
761 return env->scratched_regs || env->scratched_stack_slots;
764 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
766 env->scratched_regs = 0U;
767 env->scratched_stack_slots = 0ULL;
770 /* Used for printing the entire verifier state. */
771 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
773 env->scratched_regs = ~0U;
774 env->scratched_stack_slots = ~0ULL;
777 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
779 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
780 case DYNPTR_TYPE_LOCAL:
781 return BPF_DYNPTR_TYPE_LOCAL;
782 case DYNPTR_TYPE_RINGBUF:
783 return BPF_DYNPTR_TYPE_RINGBUF;
784 case DYNPTR_TYPE_SKB:
785 return BPF_DYNPTR_TYPE_SKB;
786 case DYNPTR_TYPE_XDP:
787 return BPF_DYNPTR_TYPE_XDP;
789 return BPF_DYNPTR_TYPE_INVALID;
793 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
796 case BPF_DYNPTR_TYPE_LOCAL:
797 return DYNPTR_TYPE_LOCAL;
798 case BPF_DYNPTR_TYPE_RINGBUF:
799 return DYNPTR_TYPE_RINGBUF;
800 case BPF_DYNPTR_TYPE_SKB:
801 return DYNPTR_TYPE_SKB;
802 case BPF_DYNPTR_TYPE_XDP:
803 return DYNPTR_TYPE_XDP;
809 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
811 return type == BPF_DYNPTR_TYPE_RINGBUF;
814 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
815 enum bpf_dynptr_type type,
816 bool first_slot, int dynptr_id);
818 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
819 struct bpf_reg_state *reg);
821 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
822 struct bpf_reg_state *sreg1,
823 struct bpf_reg_state *sreg2,
824 enum bpf_dynptr_type type)
826 int id = ++env->id_gen;
828 __mark_dynptr_reg(sreg1, type, true, id);
829 __mark_dynptr_reg(sreg2, type, false, id);
832 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
833 struct bpf_reg_state *reg,
834 enum bpf_dynptr_type type)
836 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
839 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
840 struct bpf_func_state *state, int spi);
842 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
843 enum bpf_arg_type arg_type, int insn_idx)
845 struct bpf_func_state *state = func(env, reg);
846 enum bpf_dynptr_type type;
849 spi = dynptr_get_spi(env, reg);
853 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
854 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
855 * to ensure that for the following example:
858 * So marking spi = 2 should lead to destruction of both d1 and d2. In
859 * case they do belong to same dynptr, second call won't see slot_type
860 * as STACK_DYNPTR and will simply skip destruction.
862 err = destroy_if_dynptr_stack_slot(env, state, spi);
865 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
869 for (i = 0; i < BPF_REG_SIZE; i++) {
870 state->stack[spi].slot_type[i] = STACK_DYNPTR;
871 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
874 type = arg_to_dynptr_type(arg_type);
875 if (type == BPF_DYNPTR_TYPE_INVALID)
878 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
879 &state->stack[spi - 1].spilled_ptr, type);
881 if (dynptr_type_refcounted(type)) {
882 /* The id is used to track proper releasing */
883 id = acquire_reference_state(env, insn_idx);
887 state->stack[spi].spilled_ptr.ref_obj_id = id;
888 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
891 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
892 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
897 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
899 struct bpf_func_state *state = func(env, reg);
902 spi = dynptr_get_spi(env, reg);
906 for (i = 0; i < BPF_REG_SIZE; i++) {
907 state->stack[spi].slot_type[i] = STACK_INVALID;
908 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
911 /* Invalidate any slices associated with this dynptr */
912 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
913 WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
915 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
916 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
918 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
920 * While we don't allow reading STACK_INVALID, it is still possible to
921 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
922 * helpers or insns can do partial read of that part without failing,
923 * but check_stack_range_initialized, check_stack_read_var_off, and
924 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
925 * the slot conservatively. Hence we need to prevent those liveness
928 * This was not a problem before because STACK_INVALID is only set by
929 * default (where the default reg state has its reg->parent as NULL), or
930 * in clean_live_states after REG_LIVE_DONE (at which point
931 * mark_reg_read won't walk reg->parent chain), but not randomly during
932 * verifier state exploration (like we did above). Hence, for our case
933 * parentage chain will still be live (i.e. reg->parent may be
934 * non-NULL), while earlier reg->parent was NULL, so we need
935 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
936 * done later on reads or by mark_dynptr_read as well to unnecessary
937 * mark registers in verifier state.
939 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
940 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
945 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
946 struct bpf_reg_state *reg);
948 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
950 if (!env->allow_ptr_leaks)
951 __mark_reg_not_init(env, reg);
953 __mark_reg_unknown(env, reg);
956 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
957 struct bpf_func_state *state, int spi)
959 struct bpf_func_state *fstate;
960 struct bpf_reg_state *dreg;
963 /* We always ensure that STACK_DYNPTR is never set partially,
964 * hence just checking for slot_type[0] is enough. This is
965 * different for STACK_SPILL, where it may be only set for
966 * 1 byte, so code has to use is_spilled_reg.
968 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
971 /* Reposition spi to first slot */
972 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
975 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
976 verbose(env, "cannot overwrite referenced dynptr\n");
980 mark_stack_slot_scratched(env, spi);
981 mark_stack_slot_scratched(env, spi - 1);
983 /* Writing partially to one dynptr stack slot destroys both. */
984 for (i = 0; i < BPF_REG_SIZE; i++) {
985 state->stack[spi].slot_type[i] = STACK_INVALID;
986 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
989 dynptr_id = state->stack[spi].spilled_ptr.id;
990 /* Invalidate any slices associated with this dynptr */
991 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
992 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
993 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
995 if (dreg->dynptr_id == dynptr_id)
996 mark_reg_invalid(env, dreg);
999 /* Do not release reference state, we are destroying dynptr on stack,
1000 * not using some helper to release it. Just reset register.
1002 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1003 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1005 /* Same reason as unmark_stack_slots_dynptr above */
1006 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1007 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1012 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1016 if (reg->type == CONST_PTR_TO_DYNPTR)
1019 spi = dynptr_get_spi(env, reg);
1021 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1022 * error because this just means the stack state hasn't been updated yet.
1023 * We will do check_mem_access to check and update stack bounds later.
1025 if (spi < 0 && spi != -ERANGE)
1028 /* We don't need to check if the stack slots are marked by previous
1029 * dynptr initializations because we allow overwriting existing unreferenced
1030 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1031 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1032 * touching are completely destructed before we reinitialize them for a new
1033 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1034 * instead of delaying it until the end where the user will get "Unreleased
1040 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1042 struct bpf_func_state *state = func(env, reg);
1045 /* This already represents first slot of initialized bpf_dynptr.
1047 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1048 * check_func_arg_reg_off's logic, so we don't need to check its
1049 * offset and alignment.
1051 if (reg->type == CONST_PTR_TO_DYNPTR)
1054 spi = dynptr_get_spi(env, reg);
1057 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1060 for (i = 0; i < BPF_REG_SIZE; i++) {
1061 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1062 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1069 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1070 enum bpf_arg_type arg_type)
1072 struct bpf_func_state *state = func(env, reg);
1073 enum bpf_dynptr_type dynptr_type;
1076 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1077 if (arg_type == ARG_PTR_TO_DYNPTR)
1080 dynptr_type = arg_to_dynptr_type(arg_type);
1081 if (reg->type == CONST_PTR_TO_DYNPTR) {
1082 return reg->dynptr.type == dynptr_type;
1084 spi = dynptr_get_spi(env, reg);
1087 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1091 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1093 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1094 struct bpf_reg_state *reg, int insn_idx,
1095 struct btf *btf, u32 btf_id, int nr_slots)
1097 struct bpf_func_state *state = func(env, reg);
1100 spi = iter_get_spi(env, reg, nr_slots);
1104 id = acquire_reference_state(env, insn_idx);
1108 for (i = 0; i < nr_slots; i++) {
1109 struct bpf_stack_state *slot = &state->stack[spi - i];
1110 struct bpf_reg_state *st = &slot->spilled_ptr;
1112 __mark_reg_known_zero(st);
1113 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1114 st->live |= REG_LIVE_WRITTEN;
1115 st->ref_obj_id = i == 0 ? id : 0;
1117 st->iter.btf_id = btf_id;
1118 st->iter.state = BPF_ITER_STATE_ACTIVE;
1121 for (j = 0; j < BPF_REG_SIZE; j++)
1122 slot->slot_type[j] = STACK_ITER;
1124 mark_stack_slot_scratched(env, spi - i);
1130 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1131 struct bpf_reg_state *reg, int nr_slots)
1133 struct bpf_func_state *state = func(env, reg);
1136 spi = iter_get_spi(env, reg, nr_slots);
1140 for (i = 0; i < nr_slots; i++) {
1141 struct bpf_stack_state *slot = &state->stack[spi - i];
1142 struct bpf_reg_state *st = &slot->spilled_ptr;
1145 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1147 __mark_reg_not_init(env, st);
1149 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1150 st->live |= REG_LIVE_WRITTEN;
1152 for (j = 0; j < BPF_REG_SIZE; j++)
1153 slot->slot_type[j] = STACK_INVALID;
1155 mark_stack_slot_scratched(env, spi - i);
1161 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1162 struct bpf_reg_state *reg, int nr_slots)
1164 struct bpf_func_state *state = func(env, reg);
1167 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1168 * will do check_mem_access to check and update stack bounds later, so
1169 * return true for that case.
1171 spi = iter_get_spi(env, reg, nr_slots);
1177 for (i = 0; i < nr_slots; i++) {
1178 struct bpf_stack_state *slot = &state->stack[spi - i];
1180 for (j = 0; j < BPF_REG_SIZE; j++)
1181 if (slot->slot_type[j] == STACK_ITER)
1188 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1189 struct btf *btf, u32 btf_id, int nr_slots)
1191 struct bpf_func_state *state = func(env, reg);
1194 spi = iter_get_spi(env, reg, nr_slots);
1198 for (i = 0; i < nr_slots; i++) {
1199 struct bpf_stack_state *slot = &state->stack[spi - i];
1200 struct bpf_reg_state *st = &slot->spilled_ptr;
1202 /* only main (first) slot has ref_obj_id set */
1203 if (i == 0 && !st->ref_obj_id)
1205 if (i != 0 && st->ref_obj_id)
1207 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1210 for (j = 0; j < BPF_REG_SIZE; j++)
1211 if (slot->slot_type[j] != STACK_ITER)
1218 /* Check if given stack slot is "special":
1219 * - spilled register state (STACK_SPILL);
1220 * - dynptr state (STACK_DYNPTR);
1221 * - iter state (STACK_ITER).
1223 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1225 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1237 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1242 /* The reg state of a pointer or a bounded scalar was saved when
1243 * it was spilled to the stack.
1245 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1247 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1250 static void scrub_spilled_slot(u8 *stype)
1252 if (*stype != STACK_INVALID)
1253 *stype = STACK_MISC;
1256 static void print_verifier_state(struct bpf_verifier_env *env,
1257 const struct bpf_func_state *state,
1260 const struct bpf_reg_state *reg;
1261 enum bpf_reg_type t;
1265 verbose(env, " frame%d:", state->frameno);
1266 for (i = 0; i < MAX_BPF_REG; i++) {
1267 reg = &state->regs[i];
1271 if (!print_all && !reg_scratched(env, i))
1273 verbose(env, " R%d", i);
1274 print_liveness(env, reg->live);
1276 if (t == SCALAR_VALUE && reg->precise)
1278 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1279 tnum_is_const(reg->var_off)) {
1280 /* reg->off should be 0 for SCALAR_VALUE */
1281 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1282 verbose(env, "%lld", reg->var_off.value + reg->off);
1284 const char *sep = "";
1286 verbose(env, "%s", reg_type_str(env, t));
1287 if (base_type(t) == PTR_TO_BTF_ID)
1288 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1291 * _a stands for append, was shortened to avoid multiline statements below.
1292 * This macro is used to output a comma separated list of attributes.
1294 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1297 verbose_a("id=%d", reg->id);
1298 if (reg->ref_obj_id)
1299 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1300 if (type_is_non_owning_ref(reg->type))
1301 verbose_a("%s", "non_own_ref");
1302 if (t != SCALAR_VALUE)
1303 verbose_a("off=%d", reg->off);
1304 if (type_is_pkt_pointer(t))
1305 verbose_a("r=%d", reg->range);
1306 else if (base_type(t) == CONST_PTR_TO_MAP ||
1307 base_type(t) == PTR_TO_MAP_KEY ||
1308 base_type(t) == PTR_TO_MAP_VALUE)
1309 verbose_a("ks=%d,vs=%d",
1310 reg->map_ptr->key_size,
1311 reg->map_ptr->value_size);
1312 if (tnum_is_const(reg->var_off)) {
1313 /* Typically an immediate SCALAR_VALUE, but
1314 * could be a pointer whose offset is too big
1317 verbose_a("imm=%llx", reg->var_off.value);
1319 if (reg->smin_value != reg->umin_value &&
1320 reg->smin_value != S64_MIN)
1321 verbose_a("smin=%lld", (long long)reg->smin_value);
1322 if (reg->smax_value != reg->umax_value &&
1323 reg->smax_value != S64_MAX)
1324 verbose_a("smax=%lld", (long long)reg->smax_value);
1325 if (reg->umin_value != 0)
1326 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1327 if (reg->umax_value != U64_MAX)
1328 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1329 if (!tnum_is_unknown(reg->var_off)) {
1332 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1333 verbose_a("var_off=%s", tn_buf);
1335 if (reg->s32_min_value != reg->smin_value &&
1336 reg->s32_min_value != S32_MIN)
1337 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1338 if (reg->s32_max_value != reg->smax_value &&
1339 reg->s32_max_value != S32_MAX)
1340 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1341 if (reg->u32_min_value != reg->umin_value &&
1342 reg->u32_min_value != U32_MIN)
1343 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1344 if (reg->u32_max_value != reg->umax_value &&
1345 reg->u32_max_value != U32_MAX)
1346 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1353 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1354 char types_buf[BPF_REG_SIZE + 1];
1358 for (j = 0; j < BPF_REG_SIZE; j++) {
1359 if (state->stack[i].slot_type[j] != STACK_INVALID)
1361 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1363 types_buf[BPF_REG_SIZE] = 0;
1366 if (!print_all && !stack_slot_scratched(env, i))
1368 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1370 reg = &state->stack[i].spilled_ptr;
1373 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1374 print_liveness(env, reg->live);
1375 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1376 if (t == SCALAR_VALUE && reg->precise)
1378 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1379 verbose(env, "%lld", reg->var_off.value + reg->off);
1382 i += BPF_DYNPTR_NR_SLOTS - 1;
1383 reg = &state->stack[i].spilled_ptr;
1385 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1386 print_liveness(env, reg->live);
1387 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1388 if (reg->ref_obj_id)
1389 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1392 /* only main slot has ref_obj_id set; skip others */
1393 reg = &state->stack[i].spilled_ptr;
1394 if (!reg->ref_obj_id)
1397 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1398 print_liveness(env, reg->live);
1399 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1400 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1401 reg->ref_obj_id, iter_state_str(reg->iter.state),
1407 reg = &state->stack[i].spilled_ptr;
1409 for (j = 0; j < BPF_REG_SIZE; j++)
1410 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1411 types_buf[BPF_REG_SIZE] = 0;
1413 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1414 print_liveness(env, reg->live);
1415 verbose(env, "=%s", types_buf);
1419 if (state->acquired_refs && state->refs[0].id) {
1420 verbose(env, " refs=%d", state->refs[0].id);
1421 for (i = 1; i < state->acquired_refs; i++)
1422 if (state->refs[i].id)
1423 verbose(env, ",%d", state->refs[i].id);
1425 if (state->in_callback_fn)
1426 verbose(env, " cb");
1427 if (state->in_async_callback_fn)
1428 verbose(env, " async_cb");
1430 mark_verifier_state_clean(env);
1433 static inline u32 vlog_alignment(u32 pos)
1435 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1436 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1439 static void print_insn_state(struct bpf_verifier_env *env,
1440 const struct bpf_func_state *state)
1442 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1443 /* remove new line character */
1444 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1445 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1447 verbose(env, "%d:", env->insn_idx);
1449 print_verifier_state(env, state, false);
1452 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1453 * small to hold src. This is different from krealloc since we don't want to preserve
1454 * the contents of dst.
1456 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1459 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1465 if (ZERO_OR_NULL_PTR(src))
1468 if (unlikely(check_mul_overflow(n, size, &bytes)))
1471 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1472 dst = krealloc(orig, alloc_bytes, flags);
1478 memcpy(dst, src, bytes);
1480 return dst ? dst : ZERO_SIZE_PTR;
1483 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1484 * small to hold new_n items. new items are zeroed out if the array grows.
1486 * Contrary to krealloc_array, does not free arr if new_n is zero.
1488 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1493 if (!new_n || old_n == new_n)
1496 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1497 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1505 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1508 return arr ? arr : ZERO_SIZE_PTR;
1511 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1513 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1514 sizeof(struct bpf_reference_state), GFP_KERNEL);
1518 dst->acquired_refs = src->acquired_refs;
1522 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1524 size_t n = src->allocated_stack / BPF_REG_SIZE;
1526 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1531 dst->allocated_stack = src->allocated_stack;
1535 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1537 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1538 sizeof(struct bpf_reference_state));
1542 state->acquired_refs = n;
1546 static int grow_stack_state(struct bpf_func_state *state, int size)
1548 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1553 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1557 state->allocated_stack = size;
1561 /* Acquire a pointer id from the env and update the state->refs to include
1562 * this new pointer reference.
1563 * On success, returns a valid pointer id to associate with the register
1564 * On failure, returns a negative errno.
1566 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1568 struct bpf_func_state *state = cur_func(env);
1569 int new_ofs = state->acquired_refs;
1572 err = resize_reference_state(state, state->acquired_refs + 1);
1576 state->refs[new_ofs].id = id;
1577 state->refs[new_ofs].insn_idx = insn_idx;
1578 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1583 /* release function corresponding to acquire_reference_state(). Idempotent. */
1584 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1588 last_idx = state->acquired_refs - 1;
1589 for (i = 0; i < state->acquired_refs; i++) {
1590 if (state->refs[i].id == ptr_id) {
1591 /* Cannot release caller references in callbacks */
1592 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1594 if (last_idx && i != last_idx)
1595 memcpy(&state->refs[i], &state->refs[last_idx],
1596 sizeof(*state->refs));
1597 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1598 state->acquired_refs--;
1605 static void free_func_state(struct bpf_func_state *state)
1610 kfree(state->stack);
1614 static void clear_jmp_history(struct bpf_verifier_state *state)
1616 kfree(state->jmp_history);
1617 state->jmp_history = NULL;
1618 state->jmp_history_cnt = 0;
1621 static void free_verifier_state(struct bpf_verifier_state *state,
1626 for (i = 0; i <= state->curframe; i++) {
1627 free_func_state(state->frame[i]);
1628 state->frame[i] = NULL;
1630 clear_jmp_history(state);
1635 /* copy verifier state from src to dst growing dst stack space
1636 * when necessary to accommodate larger src stack
1638 static int copy_func_state(struct bpf_func_state *dst,
1639 const struct bpf_func_state *src)
1643 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1644 err = copy_reference_state(dst, src);
1647 return copy_stack_state(dst, src);
1650 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1651 const struct bpf_verifier_state *src)
1653 struct bpf_func_state *dst;
1656 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1657 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1659 if (!dst_state->jmp_history)
1661 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1663 /* if dst has more stack frames then src frame, free them */
1664 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1665 free_func_state(dst_state->frame[i]);
1666 dst_state->frame[i] = NULL;
1668 dst_state->speculative = src->speculative;
1669 dst_state->active_rcu_lock = src->active_rcu_lock;
1670 dst_state->curframe = src->curframe;
1671 dst_state->active_lock.ptr = src->active_lock.ptr;
1672 dst_state->active_lock.id = src->active_lock.id;
1673 dst_state->branches = src->branches;
1674 dst_state->parent = src->parent;
1675 dst_state->first_insn_idx = src->first_insn_idx;
1676 dst_state->last_insn_idx = src->last_insn_idx;
1677 for (i = 0; i <= src->curframe; i++) {
1678 dst = dst_state->frame[i];
1680 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1683 dst_state->frame[i] = dst;
1685 err = copy_func_state(dst, src->frame[i]);
1692 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1695 u32 br = --st->branches;
1697 /* WARN_ON(br > 1) technically makes sense here,
1698 * but see comment in push_stack(), hence:
1700 WARN_ONCE((int)br < 0,
1701 "BUG update_branch_counts:branches_to_explore=%d\n",
1709 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1710 int *insn_idx, bool pop_log)
1712 struct bpf_verifier_state *cur = env->cur_state;
1713 struct bpf_verifier_stack_elem *elem, *head = env->head;
1716 if (env->head == NULL)
1720 err = copy_verifier_state(cur, &head->st);
1725 bpf_vlog_reset(&env->log, head->log_pos);
1727 *insn_idx = head->insn_idx;
1729 *prev_insn_idx = head->prev_insn_idx;
1731 free_verifier_state(&head->st, false);
1738 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1739 int insn_idx, int prev_insn_idx,
1742 struct bpf_verifier_state *cur = env->cur_state;
1743 struct bpf_verifier_stack_elem *elem;
1746 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1750 elem->insn_idx = insn_idx;
1751 elem->prev_insn_idx = prev_insn_idx;
1752 elem->next = env->head;
1753 elem->log_pos = env->log.end_pos;
1756 err = copy_verifier_state(&elem->st, cur);
1759 elem->st.speculative |= speculative;
1760 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1761 verbose(env, "The sequence of %d jumps is too complex.\n",
1765 if (elem->st.parent) {
1766 ++elem->st.parent->branches;
1767 /* WARN_ON(branches > 2) technically makes sense here,
1769 * 1. speculative states will bump 'branches' for non-branch
1771 * 2. is_state_visited() heuristics may decide not to create
1772 * a new state for a sequence of branches and all such current
1773 * and cloned states will be pointing to a single parent state
1774 * which might have large 'branches' count.
1779 free_verifier_state(env->cur_state, true);
1780 env->cur_state = NULL;
1781 /* pop all elements and return */
1782 while (!pop_stack(env, NULL, NULL, false));
1786 #define CALLER_SAVED_REGS 6
1787 static const int caller_saved[CALLER_SAVED_REGS] = {
1788 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1791 /* This helper doesn't clear reg->id */
1792 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1794 reg->var_off = tnum_const(imm);
1795 reg->smin_value = (s64)imm;
1796 reg->smax_value = (s64)imm;
1797 reg->umin_value = imm;
1798 reg->umax_value = imm;
1800 reg->s32_min_value = (s32)imm;
1801 reg->s32_max_value = (s32)imm;
1802 reg->u32_min_value = (u32)imm;
1803 reg->u32_max_value = (u32)imm;
1806 /* Mark the unknown part of a register (variable offset or scalar value) as
1807 * known to have the value @imm.
1809 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1811 /* Clear off and union(map_ptr, range) */
1812 memset(((u8 *)reg) + sizeof(reg->type), 0,
1813 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1815 reg->ref_obj_id = 0;
1816 ___mark_reg_known(reg, imm);
1819 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1821 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1822 reg->s32_min_value = (s32)imm;
1823 reg->s32_max_value = (s32)imm;
1824 reg->u32_min_value = (u32)imm;
1825 reg->u32_max_value = (u32)imm;
1828 /* Mark the 'variable offset' part of a register as zero. This should be
1829 * used only on registers holding a pointer type.
1831 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1833 __mark_reg_known(reg, 0);
1836 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1838 __mark_reg_known(reg, 0);
1839 reg->type = SCALAR_VALUE;
1842 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1843 struct bpf_reg_state *regs, u32 regno)
1845 if (WARN_ON(regno >= MAX_BPF_REG)) {
1846 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1847 /* Something bad happened, let's kill all regs */
1848 for (regno = 0; regno < MAX_BPF_REG; regno++)
1849 __mark_reg_not_init(env, regs + regno);
1852 __mark_reg_known_zero(regs + regno);
1855 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1856 bool first_slot, int dynptr_id)
1858 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1859 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1860 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1862 __mark_reg_known_zero(reg);
1863 reg->type = CONST_PTR_TO_DYNPTR;
1864 /* Give each dynptr a unique id to uniquely associate slices to it. */
1865 reg->id = dynptr_id;
1866 reg->dynptr.type = type;
1867 reg->dynptr.first_slot = first_slot;
1870 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1872 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1873 const struct bpf_map *map = reg->map_ptr;
1875 if (map->inner_map_meta) {
1876 reg->type = CONST_PTR_TO_MAP;
1877 reg->map_ptr = map->inner_map_meta;
1878 /* transfer reg's id which is unique for every map_lookup_elem
1879 * as UID of the inner map.
1881 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1882 reg->map_uid = reg->id;
1883 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1884 reg->type = PTR_TO_XDP_SOCK;
1885 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1886 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1887 reg->type = PTR_TO_SOCKET;
1889 reg->type = PTR_TO_MAP_VALUE;
1894 reg->type &= ~PTR_MAYBE_NULL;
1897 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1898 struct btf_field_graph_root *ds_head)
1900 __mark_reg_known_zero(®s[regno]);
1901 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1902 regs[regno].btf = ds_head->btf;
1903 regs[regno].btf_id = ds_head->value_btf_id;
1904 regs[regno].off = ds_head->node_offset;
1907 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1909 return type_is_pkt_pointer(reg->type);
1912 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1914 return reg_is_pkt_pointer(reg) ||
1915 reg->type == PTR_TO_PACKET_END;
1918 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1920 return base_type(reg->type) == PTR_TO_MEM &&
1921 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1924 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1925 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1926 enum bpf_reg_type which)
1928 /* The register can already have a range from prior markings.
1929 * This is fine as long as it hasn't been advanced from its
1932 return reg->type == which &&
1935 tnum_equals_const(reg->var_off, 0);
1938 /* Reset the min/max bounds of a register */
1939 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1941 reg->smin_value = S64_MIN;
1942 reg->smax_value = S64_MAX;
1943 reg->umin_value = 0;
1944 reg->umax_value = U64_MAX;
1946 reg->s32_min_value = S32_MIN;
1947 reg->s32_max_value = S32_MAX;
1948 reg->u32_min_value = 0;
1949 reg->u32_max_value = U32_MAX;
1952 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1954 reg->smin_value = S64_MIN;
1955 reg->smax_value = S64_MAX;
1956 reg->umin_value = 0;
1957 reg->umax_value = U64_MAX;
1960 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1962 reg->s32_min_value = S32_MIN;
1963 reg->s32_max_value = S32_MAX;
1964 reg->u32_min_value = 0;
1965 reg->u32_max_value = U32_MAX;
1968 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1970 struct tnum var32_off = tnum_subreg(reg->var_off);
1972 /* min signed is max(sign bit) | min(other bits) */
1973 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1974 var32_off.value | (var32_off.mask & S32_MIN));
1975 /* max signed is min(sign bit) | max(other bits) */
1976 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1977 var32_off.value | (var32_off.mask & S32_MAX));
1978 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1979 reg->u32_max_value = min(reg->u32_max_value,
1980 (u32)(var32_off.value | var32_off.mask));
1983 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1985 /* min signed is max(sign bit) | min(other bits) */
1986 reg->smin_value = max_t(s64, reg->smin_value,
1987 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1988 /* max signed is min(sign bit) | max(other bits) */
1989 reg->smax_value = min_t(s64, reg->smax_value,
1990 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1991 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1992 reg->umax_value = min(reg->umax_value,
1993 reg->var_off.value | reg->var_off.mask);
1996 static void __update_reg_bounds(struct bpf_reg_state *reg)
1998 __update_reg32_bounds(reg);
1999 __update_reg64_bounds(reg);
2002 /* Uses signed min/max values to inform unsigned, and vice-versa */
2003 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2005 /* Learn sign from signed bounds.
2006 * If we cannot cross the sign boundary, then signed and unsigned bounds
2007 * are the same, so combine. This works even in the negative case, e.g.
2008 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2010 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2011 reg->s32_min_value = reg->u32_min_value =
2012 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2013 reg->s32_max_value = reg->u32_max_value =
2014 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2017 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2018 * boundary, so we must be careful.
2020 if ((s32)reg->u32_max_value >= 0) {
2021 /* Positive. We can't learn anything from the smin, but smax
2022 * is positive, hence safe.
2024 reg->s32_min_value = reg->u32_min_value;
2025 reg->s32_max_value = reg->u32_max_value =
2026 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2027 } else if ((s32)reg->u32_min_value < 0) {
2028 /* Negative. We can't learn anything from the smax, but smin
2029 * is negative, hence safe.
2031 reg->s32_min_value = reg->u32_min_value =
2032 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2033 reg->s32_max_value = reg->u32_max_value;
2037 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2039 /* Learn sign from signed bounds.
2040 * If we cannot cross the sign boundary, then signed and unsigned bounds
2041 * are the same, so combine. This works even in the negative case, e.g.
2042 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2044 if (reg->smin_value >= 0 || reg->smax_value < 0) {
2045 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2047 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2051 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2052 * boundary, so we must be careful.
2054 if ((s64)reg->umax_value >= 0) {
2055 /* Positive. We can't learn anything from the smin, but smax
2056 * is positive, hence safe.
2058 reg->smin_value = reg->umin_value;
2059 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2061 } else if ((s64)reg->umin_value < 0) {
2062 /* Negative. We can't learn anything from the smax, but smin
2063 * is negative, hence safe.
2065 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2067 reg->smax_value = reg->umax_value;
2071 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2073 __reg32_deduce_bounds(reg);
2074 __reg64_deduce_bounds(reg);
2077 /* Attempts to improve var_off based on unsigned min/max information */
2078 static void __reg_bound_offset(struct bpf_reg_state *reg)
2080 struct tnum var64_off = tnum_intersect(reg->var_off,
2081 tnum_range(reg->umin_value,
2083 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2084 tnum_range(reg->u32_min_value,
2085 reg->u32_max_value));
2087 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2090 static void reg_bounds_sync(struct bpf_reg_state *reg)
2092 /* We might have learned new bounds from the var_off. */
2093 __update_reg_bounds(reg);
2094 /* We might have learned something about the sign bit. */
2095 __reg_deduce_bounds(reg);
2096 /* We might have learned some bits from the bounds. */
2097 __reg_bound_offset(reg);
2098 /* Intersecting with the old var_off might have improved our bounds
2099 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2100 * then new var_off is (0; 0x7f...fc) which improves our umax.
2102 __update_reg_bounds(reg);
2105 static bool __reg32_bound_s64(s32 a)
2107 return a >= 0 && a <= S32_MAX;
2110 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2112 reg->umin_value = reg->u32_min_value;
2113 reg->umax_value = reg->u32_max_value;
2115 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2116 * be positive otherwise set to worse case bounds and refine later
2119 if (__reg32_bound_s64(reg->s32_min_value) &&
2120 __reg32_bound_s64(reg->s32_max_value)) {
2121 reg->smin_value = reg->s32_min_value;
2122 reg->smax_value = reg->s32_max_value;
2124 reg->smin_value = 0;
2125 reg->smax_value = U32_MAX;
2129 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2131 /* special case when 64-bit register has upper 32-bit register
2132 * zeroed. Typically happens after zext or <<32, >>32 sequence
2133 * allowing us to use 32-bit bounds directly,
2135 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2136 __reg_assign_32_into_64(reg);
2138 /* Otherwise the best we can do is push lower 32bit known and
2139 * unknown bits into register (var_off set from jmp logic)
2140 * then learn as much as possible from the 64-bit tnum
2141 * known and unknown bits. The previous smin/smax bounds are
2142 * invalid here because of jmp32 compare so mark them unknown
2143 * so they do not impact tnum bounds calculation.
2145 __mark_reg64_unbounded(reg);
2147 reg_bounds_sync(reg);
2150 static bool __reg64_bound_s32(s64 a)
2152 return a >= S32_MIN && a <= S32_MAX;
2155 static bool __reg64_bound_u32(u64 a)
2157 return a >= U32_MIN && a <= U32_MAX;
2160 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2162 __mark_reg32_unbounded(reg);
2163 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2164 reg->s32_min_value = (s32)reg->smin_value;
2165 reg->s32_max_value = (s32)reg->smax_value;
2167 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2168 reg->u32_min_value = (u32)reg->umin_value;
2169 reg->u32_max_value = (u32)reg->umax_value;
2171 reg_bounds_sync(reg);
2174 /* Mark a register as having a completely unknown (scalar) value. */
2175 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2176 struct bpf_reg_state *reg)
2179 * Clear type, off, and union(map_ptr, range) and
2180 * padding between 'type' and union
2182 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2183 reg->type = SCALAR_VALUE;
2185 reg->ref_obj_id = 0;
2186 reg->var_off = tnum_unknown;
2188 reg->precise = !env->bpf_capable;
2189 __mark_reg_unbounded(reg);
2192 static void mark_reg_unknown(struct bpf_verifier_env *env,
2193 struct bpf_reg_state *regs, u32 regno)
2195 if (WARN_ON(regno >= MAX_BPF_REG)) {
2196 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2197 /* Something bad happened, let's kill all regs except FP */
2198 for (regno = 0; regno < BPF_REG_FP; regno++)
2199 __mark_reg_not_init(env, regs + regno);
2202 __mark_reg_unknown(env, regs + regno);
2205 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2206 struct bpf_reg_state *reg)
2208 __mark_reg_unknown(env, reg);
2209 reg->type = NOT_INIT;
2212 static void mark_reg_not_init(struct bpf_verifier_env *env,
2213 struct bpf_reg_state *regs, u32 regno)
2215 if (WARN_ON(regno >= MAX_BPF_REG)) {
2216 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2217 /* Something bad happened, let's kill all regs except FP */
2218 for (regno = 0; regno < BPF_REG_FP; regno++)
2219 __mark_reg_not_init(env, regs + regno);
2222 __mark_reg_not_init(env, regs + regno);
2225 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2226 struct bpf_reg_state *regs, u32 regno,
2227 enum bpf_reg_type reg_type,
2228 struct btf *btf, u32 btf_id,
2229 enum bpf_type_flag flag)
2231 if (reg_type == SCALAR_VALUE) {
2232 mark_reg_unknown(env, regs, regno);
2235 mark_reg_known_zero(env, regs, regno);
2236 regs[regno].type = PTR_TO_BTF_ID | flag;
2237 regs[regno].btf = btf;
2238 regs[regno].btf_id = btf_id;
2241 #define DEF_NOT_SUBREG (0)
2242 static void init_reg_state(struct bpf_verifier_env *env,
2243 struct bpf_func_state *state)
2245 struct bpf_reg_state *regs = state->regs;
2248 for (i = 0; i < MAX_BPF_REG; i++) {
2249 mark_reg_not_init(env, regs, i);
2250 regs[i].live = REG_LIVE_NONE;
2251 regs[i].parent = NULL;
2252 regs[i].subreg_def = DEF_NOT_SUBREG;
2256 regs[BPF_REG_FP].type = PTR_TO_STACK;
2257 mark_reg_known_zero(env, regs, BPF_REG_FP);
2258 regs[BPF_REG_FP].frameno = state->frameno;
2261 #define BPF_MAIN_FUNC (-1)
2262 static void init_func_state(struct bpf_verifier_env *env,
2263 struct bpf_func_state *state,
2264 int callsite, int frameno, int subprogno)
2266 state->callsite = callsite;
2267 state->frameno = frameno;
2268 state->subprogno = subprogno;
2269 state->callback_ret_range = tnum_range(0, 0);
2270 init_reg_state(env, state);
2271 mark_verifier_state_scratched(env);
2274 /* Similar to push_stack(), but for async callbacks */
2275 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2276 int insn_idx, int prev_insn_idx,
2279 struct bpf_verifier_stack_elem *elem;
2280 struct bpf_func_state *frame;
2282 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2286 elem->insn_idx = insn_idx;
2287 elem->prev_insn_idx = prev_insn_idx;
2288 elem->next = env->head;
2289 elem->log_pos = env->log.end_pos;
2292 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2294 "The sequence of %d jumps is too complex for async cb.\n",
2298 /* Unlike push_stack() do not copy_verifier_state().
2299 * The caller state doesn't matter.
2300 * This is async callback. It starts in a fresh stack.
2301 * Initialize it similar to do_check_common().
2303 elem->st.branches = 1;
2304 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2307 init_func_state(env, frame,
2308 BPF_MAIN_FUNC /* callsite */,
2309 0 /* frameno within this callchain */,
2310 subprog /* subprog number within this prog */);
2311 elem->st.frame[0] = frame;
2314 free_verifier_state(env->cur_state, true);
2315 env->cur_state = NULL;
2316 /* pop all elements and return */
2317 while (!pop_stack(env, NULL, NULL, false));
2323 SRC_OP, /* register is used as source operand */
2324 DST_OP, /* register is used as destination operand */
2325 DST_OP_NO_MARK /* same as above, check only, don't mark */
2328 static int cmp_subprogs(const void *a, const void *b)
2330 return ((struct bpf_subprog_info *)a)->start -
2331 ((struct bpf_subprog_info *)b)->start;
2334 static int find_subprog(struct bpf_verifier_env *env, int off)
2336 struct bpf_subprog_info *p;
2338 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2339 sizeof(env->subprog_info[0]), cmp_subprogs);
2342 return p - env->subprog_info;
2346 static int add_subprog(struct bpf_verifier_env *env, int off)
2348 int insn_cnt = env->prog->len;
2351 if (off >= insn_cnt || off < 0) {
2352 verbose(env, "call to invalid destination\n");
2355 ret = find_subprog(env, off);
2358 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2359 verbose(env, "too many subprograms\n");
2362 /* determine subprog starts. The end is one before the next starts */
2363 env->subprog_info[env->subprog_cnt++].start = off;
2364 sort(env->subprog_info, env->subprog_cnt,
2365 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2366 return env->subprog_cnt - 1;
2369 #define MAX_KFUNC_DESCS 256
2370 #define MAX_KFUNC_BTFS 256
2372 struct bpf_kfunc_desc {
2373 struct btf_func_model func_model;
2379 struct bpf_kfunc_btf {
2381 struct module *module;
2385 struct bpf_kfunc_desc_tab {
2386 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2390 struct bpf_kfunc_btf_tab {
2391 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2395 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2397 const struct bpf_kfunc_desc *d0 = a;
2398 const struct bpf_kfunc_desc *d1 = b;
2400 /* func_id is not greater than BTF_MAX_TYPE */
2401 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2404 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2406 const struct bpf_kfunc_btf *d0 = a;
2407 const struct bpf_kfunc_btf *d1 = b;
2409 return d0->offset - d1->offset;
2412 static const struct bpf_kfunc_desc *
2413 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2415 struct bpf_kfunc_desc desc = {
2419 struct bpf_kfunc_desc_tab *tab;
2421 tab = prog->aux->kfunc_tab;
2422 return bsearch(&desc, tab->descs, tab->nr_descs,
2423 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2426 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2429 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2430 struct bpf_kfunc_btf_tab *tab;
2431 struct bpf_kfunc_btf *b;
2436 tab = env->prog->aux->kfunc_btf_tab;
2437 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2438 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2440 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2441 verbose(env, "too many different module BTFs\n");
2442 return ERR_PTR(-E2BIG);
2445 if (bpfptr_is_null(env->fd_array)) {
2446 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2447 return ERR_PTR(-EPROTO);
2450 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2451 offset * sizeof(btf_fd),
2453 return ERR_PTR(-EFAULT);
2455 btf = btf_get_by_fd(btf_fd);
2457 verbose(env, "invalid module BTF fd specified\n");
2461 if (!btf_is_module(btf)) {
2462 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2464 return ERR_PTR(-EINVAL);
2467 mod = btf_try_get_module(btf);
2470 return ERR_PTR(-ENXIO);
2473 b = &tab->descs[tab->nr_descs++];
2478 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2479 kfunc_btf_cmp_by_off, NULL);
2484 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2489 while (tab->nr_descs--) {
2490 module_put(tab->descs[tab->nr_descs].module);
2491 btf_put(tab->descs[tab->nr_descs].btf);
2496 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2500 /* In the future, this can be allowed to increase limit
2501 * of fd index into fd_array, interpreted as u16.
2503 verbose(env, "negative offset disallowed for kernel module function call\n");
2504 return ERR_PTR(-EINVAL);
2507 return __find_kfunc_desc_btf(env, offset);
2509 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2512 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2514 const struct btf_type *func, *func_proto;
2515 struct bpf_kfunc_btf_tab *btf_tab;
2516 struct bpf_kfunc_desc_tab *tab;
2517 struct bpf_prog_aux *prog_aux;
2518 struct bpf_kfunc_desc *desc;
2519 const char *func_name;
2520 struct btf *desc_btf;
2521 unsigned long call_imm;
2525 prog_aux = env->prog->aux;
2526 tab = prog_aux->kfunc_tab;
2527 btf_tab = prog_aux->kfunc_btf_tab;
2530 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2534 if (!env->prog->jit_requested) {
2535 verbose(env, "JIT is required for calling kernel function\n");
2539 if (!bpf_jit_supports_kfunc_call()) {
2540 verbose(env, "JIT does not support calling kernel function\n");
2544 if (!env->prog->gpl_compatible) {
2545 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2549 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2552 prog_aux->kfunc_tab = tab;
2555 /* func_id == 0 is always invalid, but instead of returning an error, be
2556 * conservative and wait until the code elimination pass before returning
2557 * error, so that invalid calls that get pruned out can be in BPF programs
2558 * loaded from userspace. It is also required that offset be untouched
2561 if (!func_id && !offset)
2564 if (!btf_tab && offset) {
2565 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2568 prog_aux->kfunc_btf_tab = btf_tab;
2571 desc_btf = find_kfunc_desc_btf(env, offset);
2572 if (IS_ERR(desc_btf)) {
2573 verbose(env, "failed to find BTF for kernel function\n");
2574 return PTR_ERR(desc_btf);
2577 if (find_kfunc_desc(env->prog, func_id, offset))
2580 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2581 verbose(env, "too many different kernel function calls\n");
2585 func = btf_type_by_id(desc_btf, func_id);
2586 if (!func || !btf_type_is_func(func)) {
2587 verbose(env, "kernel btf_id %u is not a function\n",
2591 func_proto = btf_type_by_id(desc_btf, func->type);
2592 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2593 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2598 func_name = btf_name_by_offset(desc_btf, func->name_off);
2599 addr = kallsyms_lookup_name(func_name);
2601 verbose(env, "cannot find address for kernel function %s\n",
2606 call_imm = BPF_CALL_IMM(addr);
2607 /* Check whether or not the relative offset overflows desc->imm */
2608 if ((unsigned long)(s32)call_imm != call_imm) {
2609 verbose(env, "address of kernel function %s is out of range\n",
2614 if (bpf_dev_bound_kfunc_id(func_id)) {
2615 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2620 desc = &tab->descs[tab->nr_descs++];
2621 desc->func_id = func_id;
2622 desc->imm = call_imm;
2623 desc->offset = offset;
2624 err = btf_distill_func_proto(&env->log, desc_btf,
2625 func_proto, func_name,
2628 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2629 kfunc_desc_cmp_by_id_off, NULL);
2633 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2635 const struct bpf_kfunc_desc *d0 = a;
2636 const struct bpf_kfunc_desc *d1 = b;
2638 if (d0->imm > d1->imm)
2640 else if (d0->imm < d1->imm)
2645 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2647 struct bpf_kfunc_desc_tab *tab;
2649 tab = prog->aux->kfunc_tab;
2653 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2654 kfunc_desc_cmp_by_imm, NULL);
2657 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2659 return !!prog->aux->kfunc_tab;
2662 const struct btf_func_model *
2663 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2664 const struct bpf_insn *insn)
2666 const struct bpf_kfunc_desc desc = {
2669 const struct bpf_kfunc_desc *res;
2670 struct bpf_kfunc_desc_tab *tab;
2672 tab = prog->aux->kfunc_tab;
2673 res = bsearch(&desc, tab->descs, tab->nr_descs,
2674 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2676 return res ? &res->func_model : NULL;
2679 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2681 struct bpf_subprog_info *subprog = env->subprog_info;
2682 struct bpf_insn *insn = env->prog->insnsi;
2683 int i, ret, insn_cnt = env->prog->len;
2685 /* Add entry function. */
2686 ret = add_subprog(env, 0);
2690 for (i = 0; i < insn_cnt; i++, insn++) {
2691 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2692 !bpf_pseudo_kfunc_call(insn))
2695 if (!env->bpf_capable) {
2696 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2700 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2701 ret = add_subprog(env, i + insn->imm + 1);
2703 ret = add_kfunc_call(env, insn->imm, insn->off);
2709 /* Add a fake 'exit' subprog which could simplify subprog iteration
2710 * logic. 'subprog_cnt' should not be increased.
2712 subprog[env->subprog_cnt].start = insn_cnt;
2714 if (env->log.level & BPF_LOG_LEVEL2)
2715 for (i = 0; i < env->subprog_cnt; i++)
2716 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2721 static int check_subprogs(struct bpf_verifier_env *env)
2723 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2724 struct bpf_subprog_info *subprog = env->subprog_info;
2725 struct bpf_insn *insn = env->prog->insnsi;
2726 int insn_cnt = env->prog->len;
2728 /* now check that all jumps are within the same subprog */
2729 subprog_start = subprog[cur_subprog].start;
2730 subprog_end = subprog[cur_subprog + 1].start;
2731 for (i = 0; i < insn_cnt; i++) {
2732 u8 code = insn[i].code;
2734 if (code == (BPF_JMP | BPF_CALL) &&
2735 insn[i].src_reg == 0 &&
2736 insn[i].imm == BPF_FUNC_tail_call)
2737 subprog[cur_subprog].has_tail_call = true;
2738 if (BPF_CLASS(code) == BPF_LD &&
2739 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2740 subprog[cur_subprog].has_ld_abs = true;
2741 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2743 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2745 off = i + insn[i].off + 1;
2746 if (off < subprog_start || off >= subprog_end) {
2747 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2751 if (i == subprog_end - 1) {
2752 /* to avoid fall-through from one subprog into another
2753 * the last insn of the subprog should be either exit
2754 * or unconditional jump back
2756 if (code != (BPF_JMP | BPF_EXIT) &&
2757 code != (BPF_JMP | BPF_JA)) {
2758 verbose(env, "last insn is not an exit or jmp\n");
2761 subprog_start = subprog_end;
2763 if (cur_subprog < env->subprog_cnt)
2764 subprog_end = subprog[cur_subprog + 1].start;
2770 /* Parentage chain of this register (or stack slot) should take care of all
2771 * issues like callee-saved registers, stack slot allocation time, etc.
2773 static int mark_reg_read(struct bpf_verifier_env *env,
2774 const struct bpf_reg_state *state,
2775 struct bpf_reg_state *parent, u8 flag)
2777 bool writes = parent == state->parent; /* Observe write marks */
2781 /* if read wasn't screened by an earlier write ... */
2782 if (writes && state->live & REG_LIVE_WRITTEN)
2784 if (parent->live & REG_LIVE_DONE) {
2785 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2786 reg_type_str(env, parent->type),
2787 parent->var_off.value, parent->off);
2790 /* The first condition is more likely to be true than the
2791 * second, checked it first.
2793 if ((parent->live & REG_LIVE_READ) == flag ||
2794 parent->live & REG_LIVE_READ64)
2795 /* The parentage chain never changes and
2796 * this parent was already marked as LIVE_READ.
2797 * There is no need to keep walking the chain again and
2798 * keep re-marking all parents as LIVE_READ.
2799 * This case happens when the same register is read
2800 * multiple times without writes into it in-between.
2801 * Also, if parent has the stronger REG_LIVE_READ64 set,
2802 * then no need to set the weak REG_LIVE_READ32.
2805 /* ... then we depend on parent's value */
2806 parent->live |= flag;
2807 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2808 if (flag == REG_LIVE_READ64)
2809 parent->live &= ~REG_LIVE_READ32;
2811 parent = state->parent;
2816 if (env->longest_mark_read_walk < cnt)
2817 env->longest_mark_read_walk = cnt;
2821 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2823 struct bpf_func_state *state = func(env, reg);
2826 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2827 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2830 if (reg->type == CONST_PTR_TO_DYNPTR)
2832 spi = dynptr_get_spi(env, reg);
2835 /* Caller ensures dynptr is valid and initialized, which means spi is in
2836 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2839 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2840 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2843 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2844 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2847 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2848 int spi, int nr_slots)
2850 struct bpf_func_state *state = func(env, reg);
2853 for (i = 0; i < nr_slots; i++) {
2854 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2856 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2860 mark_stack_slot_scratched(env, spi - i);
2866 /* This function is supposed to be used by the following 32-bit optimization
2867 * code only. It returns TRUE if the source or destination register operates
2868 * on 64-bit, otherwise return FALSE.
2870 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2871 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2876 class = BPF_CLASS(code);
2878 if (class == BPF_JMP) {
2879 /* BPF_EXIT for "main" will reach here. Return TRUE
2884 if (op == BPF_CALL) {
2885 /* BPF to BPF call will reach here because of marking
2886 * caller saved clobber with DST_OP_NO_MARK for which we
2887 * don't care the register def because they are anyway
2888 * marked as NOT_INIT already.
2890 if (insn->src_reg == BPF_PSEUDO_CALL)
2892 /* Helper call will reach here because of arg type
2893 * check, conservatively return TRUE.
2902 if (class == BPF_ALU64 || class == BPF_JMP ||
2903 /* BPF_END always use BPF_ALU class. */
2904 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2907 if (class == BPF_ALU || class == BPF_JMP32)
2910 if (class == BPF_LDX) {
2912 return BPF_SIZE(code) == BPF_DW;
2913 /* LDX source must be ptr. */
2917 if (class == BPF_STX) {
2918 /* BPF_STX (including atomic variants) has multiple source
2919 * operands, one of which is a ptr. Check whether the caller is
2922 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2924 return BPF_SIZE(code) == BPF_DW;
2927 if (class == BPF_LD) {
2928 u8 mode = BPF_MODE(code);
2931 if (mode == BPF_IMM)
2934 /* Both LD_IND and LD_ABS return 32-bit data. */
2938 /* Implicit ctx ptr. */
2939 if (regno == BPF_REG_6)
2942 /* Explicit source could be any width. */
2946 if (class == BPF_ST)
2947 /* The only source register for BPF_ST is a ptr. */
2950 /* Conservatively return true at default. */
2954 /* Return the regno defined by the insn, or -1. */
2955 static int insn_def_regno(const struct bpf_insn *insn)
2957 switch (BPF_CLASS(insn->code)) {
2963 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2964 (insn->imm & BPF_FETCH)) {
2965 if (insn->imm == BPF_CMPXCHG)
2968 return insn->src_reg;
2973 return insn->dst_reg;
2977 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2978 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2980 int dst_reg = insn_def_regno(insn);
2985 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2988 static void mark_insn_zext(struct bpf_verifier_env *env,
2989 struct bpf_reg_state *reg)
2991 s32 def_idx = reg->subreg_def;
2993 if (def_idx == DEF_NOT_SUBREG)
2996 env->insn_aux_data[def_idx - 1].zext_dst = true;
2997 /* The dst will be zero extended, so won't be sub-register anymore. */
2998 reg->subreg_def = DEF_NOT_SUBREG;
3001 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3002 enum reg_arg_type t)
3004 struct bpf_verifier_state *vstate = env->cur_state;
3005 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3006 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3007 struct bpf_reg_state *reg, *regs = state->regs;
3010 if (regno >= MAX_BPF_REG) {
3011 verbose(env, "R%d is invalid\n", regno);
3015 mark_reg_scratched(env, regno);
3018 rw64 = is_reg64(env, insn, regno, reg, t);
3020 /* check whether register used as source operand can be read */
3021 if (reg->type == NOT_INIT) {
3022 verbose(env, "R%d !read_ok\n", regno);
3025 /* We don't need to worry about FP liveness because it's read-only */
3026 if (regno == BPF_REG_FP)
3030 mark_insn_zext(env, reg);
3032 return mark_reg_read(env, reg, reg->parent,
3033 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3035 /* check whether register used as dest operand can be written to */
3036 if (regno == BPF_REG_FP) {
3037 verbose(env, "frame pointer is read only\n");
3040 reg->live |= REG_LIVE_WRITTEN;
3041 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3043 mark_reg_unknown(env, regs, regno);
3048 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3050 env->insn_aux_data[idx].jmp_point = true;
3053 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3055 return env->insn_aux_data[insn_idx].jmp_point;
3058 /* for any branch, call, exit record the history of jmps in the given state */
3059 static int push_jmp_history(struct bpf_verifier_env *env,
3060 struct bpf_verifier_state *cur)
3062 u32 cnt = cur->jmp_history_cnt;
3063 struct bpf_idx_pair *p;
3066 if (!is_jmp_point(env, env->insn_idx))
3070 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3071 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3074 p[cnt - 1].idx = env->insn_idx;
3075 p[cnt - 1].prev_idx = env->prev_insn_idx;
3076 cur->jmp_history = p;
3077 cur->jmp_history_cnt = cnt;
3081 /* Backtrack one insn at a time. If idx is not at the top of recorded
3082 * history then previous instruction came from straight line execution.
3084 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3089 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3090 i = st->jmp_history[cnt - 1].prev_idx;
3098 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3100 const struct btf_type *func;
3101 struct btf *desc_btf;
3103 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3106 desc_btf = find_kfunc_desc_btf(data, insn->off);
3107 if (IS_ERR(desc_btf))
3110 func = btf_type_by_id(desc_btf, insn->imm);
3111 return btf_name_by_offset(desc_btf, func->name_off);
3114 /* For given verifier state backtrack_insn() is called from the last insn to
3115 * the first insn. Its purpose is to compute a bitmask of registers and
3116 * stack slots that needs precision in the parent verifier state.
3118 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
3119 u32 *reg_mask, u64 *stack_mask)
3121 const struct bpf_insn_cbs cbs = {
3122 .cb_call = disasm_kfunc_name,
3123 .cb_print = verbose,
3124 .private_data = env,
3126 struct bpf_insn *insn = env->prog->insnsi + idx;
3127 u8 class = BPF_CLASS(insn->code);
3128 u8 opcode = BPF_OP(insn->code);
3129 u8 mode = BPF_MODE(insn->code);
3130 u32 dreg = 1u << insn->dst_reg;
3131 u32 sreg = 1u << insn->src_reg;
3134 if (insn->code == 0)
3136 if (env->log.level & BPF_LOG_LEVEL2) {
3137 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
3138 verbose(env, "%d: ", idx);
3139 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3142 if (class == BPF_ALU || class == BPF_ALU64) {
3143 if (!(*reg_mask & dreg))
3145 if (opcode == BPF_MOV) {
3146 if (BPF_SRC(insn->code) == BPF_X) {
3148 * dreg needs precision after this insn
3149 * sreg needs precision before this insn
3155 * dreg needs precision after this insn.
3156 * Corresponding register is already marked
3157 * as precise=true in this verifier state.
3158 * No further markings in parent are necessary
3163 if (BPF_SRC(insn->code) == BPF_X) {
3165 * both dreg and sreg need precision
3170 * dreg still needs precision before this insn
3173 } else if (class == BPF_LDX) {
3174 if (!(*reg_mask & dreg))
3178 /* scalars can only be spilled into stack w/o losing precision.
3179 * Load from any other memory can be zero extended.
3180 * The desire to keep that precision is already indicated
3181 * by 'precise' mark in corresponding register of this state.
3182 * No further tracking necessary.
3184 if (insn->src_reg != BPF_REG_FP)
3187 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3188 * that [fp - off] slot contains scalar that needs to be
3189 * tracked with precision
3191 spi = (-insn->off - 1) / BPF_REG_SIZE;
3193 verbose(env, "BUG spi %d\n", spi);
3194 WARN_ONCE(1, "verifier backtracking bug");
3197 *stack_mask |= 1ull << spi;
3198 } else if (class == BPF_STX || class == BPF_ST) {
3199 if (*reg_mask & dreg)
3200 /* stx & st shouldn't be using _scalar_ dst_reg
3201 * to access memory. It means backtracking
3202 * encountered a case of pointer subtraction.
3205 /* scalars can only be spilled into stack */
3206 if (insn->dst_reg != BPF_REG_FP)
3208 spi = (-insn->off - 1) / BPF_REG_SIZE;
3210 verbose(env, "BUG spi %d\n", spi);
3211 WARN_ONCE(1, "verifier backtracking bug");
3214 if (!(*stack_mask & (1ull << spi)))
3216 *stack_mask &= ~(1ull << spi);
3217 if (class == BPF_STX)
3219 } else if (class == BPF_JMP || class == BPF_JMP32) {
3220 if (opcode == BPF_CALL) {
3221 if (insn->src_reg == BPF_PSEUDO_CALL)
3223 /* BPF helpers that invoke callback subprogs are
3224 * equivalent to BPF_PSEUDO_CALL above
3226 if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
3228 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3229 * catch this error later. Make backtracking conservative
3232 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3234 /* regular helper call sets R0 */
3236 if (*reg_mask & 0x3f) {
3237 /* if backtracing was looking for registers R1-R5
3238 * they should have been found already.
3240 verbose(env, "BUG regs %x\n", *reg_mask);
3241 WARN_ONCE(1, "verifier backtracking bug");
3244 } else if (opcode == BPF_EXIT) {
3246 } else if (BPF_SRC(insn->code) == BPF_X) {
3247 if (!(*reg_mask & (dreg | sreg)))
3250 * Both dreg and sreg need precision before
3251 * this insn. If only sreg was marked precise
3252 * before it would be equally necessary to
3253 * propagate it to dreg.
3255 *reg_mask |= (sreg | dreg);
3256 /* else dreg <cond> K
3257 * Only dreg still needs precision before
3258 * this insn, so for the K-based conditional
3259 * there is nothing new to be marked.
3262 } else if (class == BPF_LD) {
3263 if (!(*reg_mask & dreg))
3266 /* It's ld_imm64 or ld_abs or ld_ind.
3267 * For ld_imm64 no further tracking of precision
3268 * into parent is necessary
3270 if (mode == BPF_IND || mode == BPF_ABS)
3271 /* to be analyzed */
3277 /* the scalar precision tracking algorithm:
3278 * . at the start all registers have precise=false.
3279 * . scalar ranges are tracked as normal through alu and jmp insns.
3280 * . once precise value of the scalar register is used in:
3281 * . ptr + scalar alu
3282 * . if (scalar cond K|scalar)
3283 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3284 * backtrack through the verifier states and mark all registers and
3285 * stack slots with spilled constants that these scalar regisers
3286 * should be precise.
3287 * . during state pruning two registers (or spilled stack slots)
3288 * are equivalent if both are not precise.
3290 * Note the verifier cannot simply walk register parentage chain,
3291 * since many different registers and stack slots could have been
3292 * used to compute single precise scalar.
3294 * The approach of starting with precise=true for all registers and then
3295 * backtrack to mark a register as not precise when the verifier detects
3296 * that program doesn't care about specific value (e.g., when helper
3297 * takes register as ARG_ANYTHING parameter) is not safe.
3299 * It's ok to walk single parentage chain of the verifier states.
3300 * It's possible that this backtracking will go all the way till 1st insn.
3301 * All other branches will be explored for needing precision later.
3303 * The backtracking needs to deal with cases like:
3304 * 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)
3307 * if r5 > 0x79f goto pc+7
3308 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3311 * call bpf_perf_event_output#25
3312 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3316 * call foo // uses callee's r6 inside to compute r0
3320 * to track above reg_mask/stack_mask needs to be independent for each frame.
3322 * Also if parent's curframe > frame where backtracking started,
3323 * the verifier need to mark registers in both frames, otherwise callees
3324 * may incorrectly prune callers. This is similar to
3325 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3327 * For now backtracking falls back into conservative marking.
3329 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3330 struct bpf_verifier_state *st)
3332 struct bpf_func_state *func;
3333 struct bpf_reg_state *reg;
3336 /* big hammer: mark all scalars precise in this path.
3337 * pop_stack may still get !precise scalars.
3338 * We also skip current state and go straight to first parent state,
3339 * because precision markings in current non-checkpointed state are
3340 * not needed. See why in the comment in __mark_chain_precision below.
3342 for (st = st->parent; st; st = st->parent) {
3343 for (i = 0; i <= st->curframe; i++) {
3344 func = st->frame[i];
3345 for (j = 0; j < BPF_REG_FP; j++) {
3346 reg = &func->regs[j];
3347 if (reg->type != SCALAR_VALUE)
3349 reg->precise = true;
3351 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3352 if (!is_spilled_reg(&func->stack[j]))
3354 reg = &func->stack[j].spilled_ptr;
3355 if (reg->type != SCALAR_VALUE)
3357 reg->precise = true;
3363 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3365 struct bpf_func_state *func;
3366 struct bpf_reg_state *reg;
3369 for (i = 0; i <= st->curframe; i++) {
3370 func = st->frame[i];
3371 for (j = 0; j < BPF_REG_FP; j++) {
3372 reg = &func->regs[j];
3373 if (reg->type != SCALAR_VALUE)
3375 reg->precise = false;
3377 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3378 if (!is_spilled_reg(&func->stack[j]))
3380 reg = &func->stack[j].spilled_ptr;
3381 if (reg->type != SCALAR_VALUE)
3383 reg->precise = false;
3389 * __mark_chain_precision() backtracks BPF program instruction sequence and
3390 * chain of verifier states making sure that register *regno* (if regno >= 0)
3391 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3392 * SCALARS, as well as any other registers and slots that contribute to
3393 * a tracked state of given registers/stack slots, depending on specific BPF
3394 * assembly instructions (see backtrack_insns() for exact instruction handling
3395 * logic). This backtracking relies on recorded jmp_history and is able to
3396 * traverse entire chain of parent states. This process ends only when all the
3397 * necessary registers/slots and their transitive dependencies are marked as
3400 * One important and subtle aspect is that precise marks *do not matter* in
3401 * the currently verified state (current state). It is important to understand
3402 * why this is the case.
3404 * First, note that current state is the state that is not yet "checkpointed",
3405 * i.e., it is not yet put into env->explored_states, and it has no children
3406 * states as well. It's ephemeral, and can end up either a) being discarded if
3407 * compatible explored state is found at some point or BPF_EXIT instruction is
3408 * reached or b) checkpointed and put into env->explored_states, branching out
3409 * into one or more children states.
3411 * In the former case, precise markings in current state are completely
3412 * ignored by state comparison code (see regsafe() for details). Only
3413 * checkpointed ("old") state precise markings are important, and if old
3414 * state's register/slot is precise, regsafe() assumes current state's
3415 * register/slot as precise and checks value ranges exactly and precisely. If
3416 * states turn out to be compatible, current state's necessary precise
3417 * markings and any required parent states' precise markings are enforced
3418 * after the fact with propagate_precision() logic, after the fact. But it's
3419 * important to realize that in this case, even after marking current state
3420 * registers/slots as precise, we immediately discard current state. So what
3421 * actually matters is any of the precise markings propagated into current
3422 * state's parent states, which are always checkpointed (due to b) case above).
3423 * As such, for scenario a) it doesn't matter if current state has precise
3424 * markings set or not.
3426 * Now, for the scenario b), checkpointing and forking into child(ren)
3427 * state(s). Note that before current state gets to checkpointing step, any
3428 * processed instruction always assumes precise SCALAR register/slot
3429 * knowledge: if precise value or range is useful to prune jump branch, BPF
3430 * verifier takes this opportunity enthusiastically. Similarly, when
3431 * register's value is used to calculate offset or memory address, exact
3432 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3433 * what we mentioned above about state comparison ignoring precise markings
3434 * during state comparison, BPF verifier ignores and also assumes precise
3435 * markings *at will* during instruction verification process. But as verifier
3436 * assumes precision, it also propagates any precision dependencies across
3437 * parent states, which are not yet finalized, so can be further restricted
3438 * based on new knowledge gained from restrictions enforced by their children
3439 * states. This is so that once those parent states are finalized, i.e., when
3440 * they have no more active children state, state comparison logic in
3441 * is_state_visited() would enforce strict and precise SCALAR ranges, if
3442 * required for correctness.
3444 * To build a bit more intuition, note also that once a state is checkpointed,
3445 * the path we took to get to that state is not important. This is crucial
3446 * property for state pruning. When state is checkpointed and finalized at
3447 * some instruction index, it can be correctly and safely used to "short
3448 * circuit" any *compatible* state that reaches exactly the same instruction
3449 * index. I.e., if we jumped to that instruction from a completely different
3450 * code path than original finalized state was derived from, it doesn't
3451 * matter, current state can be discarded because from that instruction
3452 * forward having a compatible state will ensure we will safely reach the
3453 * exit. States describe preconditions for further exploration, but completely
3454 * forget the history of how we got here.
3456 * This also means that even if we needed precise SCALAR range to get to
3457 * finalized state, but from that point forward *that same* SCALAR register is
3458 * never used in a precise context (i.e., it's precise value is not needed for
3459 * correctness), it's correct and safe to mark such register as "imprecise"
3460 * (i.e., precise marking set to false). This is what we rely on when we do
3461 * not set precise marking in current state. If no child state requires
3462 * precision for any given SCALAR register, it's safe to dictate that it can
3463 * be imprecise. If any child state does require this register to be precise,
3464 * we'll mark it precise later retroactively during precise markings
3465 * propagation from child state to parent states.
3467 * Skipping precise marking setting in current state is a mild version of
3468 * relying on the above observation. But we can utilize this property even
3469 * more aggressively by proactively forgetting any precise marking in the
3470 * current state (which we inherited from the parent state), right before we
3471 * checkpoint it and branch off into new child state. This is done by
3472 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3473 * finalized states which help in short circuiting more future states.
3475 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
3478 struct bpf_verifier_state *st = env->cur_state;
3479 int first_idx = st->first_insn_idx;
3480 int last_idx = env->insn_idx;
3481 struct bpf_func_state *func;
3482 struct bpf_reg_state *reg;
3483 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
3484 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
3485 bool skip_first = true;
3486 bool new_marks = false;
3489 if (!env->bpf_capable)
3492 /* Do sanity checks against current state of register and/or stack
3493 * slot, but don't set precise flag in current state, as precision
3494 * tracking in the current state is unnecessary.
3496 func = st->frame[frame];
3498 reg = &func->regs[regno];
3499 if (reg->type != SCALAR_VALUE) {
3500 WARN_ONCE(1, "backtracing misuse");
3507 if (!is_spilled_reg(&func->stack[spi])) {
3511 reg = &func->stack[spi].spilled_ptr;
3512 if (reg->type != SCALAR_VALUE) {
3522 if (!reg_mask && !stack_mask)
3526 DECLARE_BITMAP(mask, 64);
3527 u32 history = st->jmp_history_cnt;
3529 if (env->log.level & BPF_LOG_LEVEL2)
3530 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3533 /* we are at the entry into subprog, which
3534 * is expected for global funcs, but only if
3535 * requested precise registers are R1-R5
3536 * (which are global func's input arguments)
3538 if (st->curframe == 0 &&
3539 st->frame[0]->subprogno > 0 &&
3540 st->frame[0]->callsite == BPF_MAIN_FUNC &&
3541 stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3542 bitmap_from_u64(mask, reg_mask);
3543 for_each_set_bit(i, mask, 32) {
3544 reg = &st->frame[0]->regs[i];
3545 if (reg->type != SCALAR_VALUE) {
3546 reg_mask &= ~(1u << i);
3549 reg->precise = true;
3554 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3555 st->frame[0]->subprogno, reg_mask, stack_mask);
3556 WARN_ONCE(1, "verifier backtracking bug");
3560 for (i = last_idx;;) {
3565 err = backtrack_insn(env, i, ®_mask, &stack_mask);
3567 if (err == -ENOTSUPP) {
3568 mark_all_scalars_precise(env, st);
3573 if (!reg_mask && !stack_mask)
3574 /* Found assignment(s) into tracked register in this state.
3575 * Since this state is already marked, just return.
3576 * Nothing to be tracked further in the parent state.
3581 i = get_prev_insn_idx(st, i, &history);
3582 if (i >= env->prog->len) {
3583 /* This can happen if backtracking reached insn 0
3584 * and there are still reg_mask or stack_mask
3586 * It means the backtracking missed the spot where
3587 * particular register was initialized with a constant.
3589 verbose(env, "BUG backtracking idx %d\n", i);
3590 WARN_ONCE(1, "verifier backtracking bug");
3599 func = st->frame[frame];
3600 bitmap_from_u64(mask, reg_mask);
3601 for_each_set_bit(i, mask, 32) {
3602 reg = &func->regs[i];
3603 if (reg->type != SCALAR_VALUE) {
3604 reg_mask &= ~(1u << i);
3609 reg->precise = true;
3612 bitmap_from_u64(mask, stack_mask);
3613 for_each_set_bit(i, mask, 64) {
3614 if (i >= func->allocated_stack / BPF_REG_SIZE) {
3615 /* the sequence of instructions:
3617 * 3: (7b) *(u64 *)(r3 -8) = r0
3618 * 4: (79) r4 = *(u64 *)(r10 -8)
3619 * doesn't contain jmps. It's backtracked
3620 * as a single block.
3621 * During backtracking insn 3 is not recognized as
3622 * stack access, so at the end of backtracking
3623 * stack slot fp-8 is still marked in stack_mask.
3624 * However the parent state may not have accessed
3625 * fp-8 and it's "unallocated" stack space.
3626 * In such case fallback to conservative.
3628 mark_all_scalars_precise(env, st);
3632 if (!is_spilled_reg(&func->stack[i])) {
3633 stack_mask &= ~(1ull << i);
3636 reg = &func->stack[i].spilled_ptr;
3637 if (reg->type != SCALAR_VALUE) {
3638 stack_mask &= ~(1ull << i);
3643 reg->precise = true;
3645 if (env->log.level & BPF_LOG_LEVEL2) {
3646 verbose(env, "parent %s regs=%x stack=%llx marks:",
3647 new_marks ? "didn't have" : "already had",
3648 reg_mask, stack_mask);
3649 print_verifier_state(env, func, true);
3652 if (!reg_mask && !stack_mask)
3657 last_idx = st->last_insn_idx;
3658 first_idx = st->first_insn_idx;
3663 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3665 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3668 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3670 return __mark_chain_precision(env, frame, regno, -1);
3673 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3675 return __mark_chain_precision(env, frame, -1, spi);
3678 static bool is_spillable_regtype(enum bpf_reg_type type)
3680 switch (base_type(type)) {
3681 case PTR_TO_MAP_VALUE:
3685 case PTR_TO_PACKET_META:
3686 case PTR_TO_PACKET_END:
3687 case PTR_TO_FLOW_KEYS:
3688 case CONST_PTR_TO_MAP:
3690 case PTR_TO_SOCK_COMMON:
3691 case PTR_TO_TCP_SOCK:
3692 case PTR_TO_XDP_SOCK:
3697 case PTR_TO_MAP_KEY:
3704 /* Does this register contain a constant zero? */
3705 static bool register_is_null(struct bpf_reg_state *reg)
3707 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3710 static bool register_is_const(struct bpf_reg_state *reg)
3712 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3715 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3717 return tnum_is_unknown(reg->var_off) &&
3718 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3719 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3720 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3721 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3724 static bool register_is_bounded(struct bpf_reg_state *reg)
3726 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3729 static bool __is_pointer_value(bool allow_ptr_leaks,
3730 const struct bpf_reg_state *reg)
3732 if (allow_ptr_leaks)
3735 return reg->type != SCALAR_VALUE;
3738 /* Copy src state preserving dst->parent and dst->live fields */
3739 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3741 struct bpf_reg_state *parent = dst->parent;
3742 enum bpf_reg_liveness live = dst->live;
3745 dst->parent = parent;
3749 static void save_register_state(struct bpf_func_state *state,
3750 int spi, struct bpf_reg_state *reg,
3755 copy_register_state(&state->stack[spi].spilled_ptr, reg);
3756 if (size == BPF_REG_SIZE)
3757 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3759 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3760 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3762 /* size < 8 bytes spill */
3764 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3767 static bool is_bpf_st_mem(struct bpf_insn *insn)
3769 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3772 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3773 * stack boundary and alignment are checked in check_mem_access()
3775 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3776 /* stack frame we're writing to */
3777 struct bpf_func_state *state,
3778 int off, int size, int value_regno,
3781 struct bpf_func_state *cur; /* state of the current function */
3782 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3783 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3784 struct bpf_reg_state *reg = NULL;
3785 u32 dst_reg = insn->dst_reg;
3787 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3790 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3791 * so it's aligned access and [off, off + size) are within stack limits
3793 if (!env->allow_ptr_leaks &&
3794 state->stack[spi].slot_type[0] == STACK_SPILL &&
3795 size != BPF_REG_SIZE) {
3796 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3800 cur = env->cur_state->frame[env->cur_state->curframe];
3801 if (value_regno >= 0)
3802 reg = &cur->regs[value_regno];
3803 if (!env->bypass_spec_v4) {
3804 bool sanitize = reg && is_spillable_regtype(reg->type);
3806 for (i = 0; i < size; i++) {
3807 u8 type = state->stack[spi].slot_type[i];
3809 if (type != STACK_MISC && type != STACK_ZERO) {
3816 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3819 err = destroy_if_dynptr_stack_slot(env, state, spi);
3823 mark_stack_slot_scratched(env, spi);
3824 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3825 !register_is_null(reg) && env->bpf_capable) {
3826 if (dst_reg != BPF_REG_FP) {
3827 /* The backtracking logic can only recognize explicit
3828 * stack slot address like [fp - 8]. Other spill of
3829 * scalar via different register has to be conservative.
3830 * Backtrack from here and mark all registers as precise
3831 * that contributed into 'reg' being a constant.
3833 err = mark_chain_precision(env, value_regno);
3837 save_register_state(state, spi, reg, size);
3838 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3839 insn->imm != 0 && env->bpf_capable) {
3840 struct bpf_reg_state fake_reg = {};
3842 __mark_reg_known(&fake_reg, (u32)insn->imm);
3843 fake_reg.type = SCALAR_VALUE;
3844 save_register_state(state, spi, &fake_reg, size);
3845 } else if (reg && is_spillable_regtype(reg->type)) {
3846 /* register containing pointer is being spilled into stack */
3847 if (size != BPF_REG_SIZE) {
3848 verbose_linfo(env, insn_idx, "; ");
3849 verbose(env, "invalid size of register spill\n");
3852 if (state != cur && reg->type == PTR_TO_STACK) {
3853 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3856 save_register_state(state, spi, reg, size);
3858 u8 type = STACK_MISC;
3860 /* regular write of data into stack destroys any spilled ptr */
3861 state->stack[spi].spilled_ptr.type = NOT_INIT;
3862 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
3863 if (is_stack_slot_special(&state->stack[spi]))
3864 for (i = 0; i < BPF_REG_SIZE; i++)
3865 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3867 /* only mark the slot as written if all 8 bytes were written
3868 * otherwise read propagation may incorrectly stop too soon
3869 * when stack slots are partially written.
3870 * This heuristic means that read propagation will be
3871 * conservative, since it will add reg_live_read marks
3872 * to stack slots all the way to first state when programs
3873 * writes+reads less than 8 bytes
3875 if (size == BPF_REG_SIZE)
3876 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3878 /* when we zero initialize stack slots mark them as such */
3879 if ((reg && register_is_null(reg)) ||
3880 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3881 /* backtracking doesn't work for STACK_ZERO yet. */
3882 err = mark_chain_precision(env, value_regno);
3888 /* Mark slots affected by this stack write. */
3889 for (i = 0; i < size; i++)
3890 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3896 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3897 * known to contain a variable offset.
3898 * This function checks whether the write is permitted and conservatively
3899 * tracks the effects of the write, considering that each stack slot in the
3900 * dynamic range is potentially written to.
3902 * 'off' includes 'regno->off'.
3903 * 'value_regno' can be -1, meaning that an unknown value is being written to
3906 * Spilled pointers in range are not marked as written because we don't know
3907 * what's going to be actually written. This means that read propagation for
3908 * future reads cannot be terminated by this write.
3910 * For privileged programs, uninitialized stack slots are considered
3911 * initialized by this write (even though we don't know exactly what offsets
3912 * are going to be written to). The idea is that we don't want the verifier to
3913 * reject future reads that access slots written to through variable offsets.
3915 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3916 /* func where register points to */
3917 struct bpf_func_state *state,
3918 int ptr_regno, int off, int size,
3919 int value_regno, int insn_idx)
3921 struct bpf_func_state *cur; /* state of the current function */
3922 int min_off, max_off;
3924 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3925 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3926 bool writing_zero = false;
3927 /* set if the fact that we're writing a zero is used to let any
3928 * stack slots remain STACK_ZERO
3930 bool zero_used = false;
3932 cur = env->cur_state->frame[env->cur_state->curframe];
3933 ptr_reg = &cur->regs[ptr_regno];
3934 min_off = ptr_reg->smin_value + off;
3935 max_off = ptr_reg->smax_value + off + size;
3936 if (value_regno >= 0)
3937 value_reg = &cur->regs[value_regno];
3938 if ((value_reg && register_is_null(value_reg)) ||
3939 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
3940 writing_zero = true;
3942 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3946 for (i = min_off; i < max_off; i++) {
3950 err = destroy_if_dynptr_stack_slot(env, state, spi);
3955 /* Variable offset writes destroy any spilled pointers in range. */
3956 for (i = min_off; i < max_off; i++) {
3957 u8 new_type, *stype;
3961 spi = slot / BPF_REG_SIZE;
3962 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3963 mark_stack_slot_scratched(env, spi);
3965 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3966 /* Reject the write if range we may write to has not
3967 * been initialized beforehand. If we didn't reject
3968 * here, the ptr status would be erased below (even
3969 * though not all slots are actually overwritten),
3970 * possibly opening the door to leaks.
3972 * We do however catch STACK_INVALID case below, and
3973 * only allow reading possibly uninitialized memory
3974 * later for CAP_PERFMON, as the write may not happen to
3977 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3982 /* Erase all spilled pointers. */
3983 state->stack[spi].spilled_ptr.type = NOT_INIT;
3985 /* Update the slot type. */
3986 new_type = STACK_MISC;
3987 if (writing_zero && *stype == STACK_ZERO) {
3988 new_type = STACK_ZERO;
3991 /* If the slot is STACK_INVALID, we check whether it's OK to
3992 * pretend that it will be initialized by this write. The slot
3993 * might not actually be written to, and so if we mark it as
3994 * initialized future reads might leak uninitialized memory.
3995 * For privileged programs, we will accept such reads to slots
3996 * that may or may not be written because, if we're reject
3997 * them, the error would be too confusing.
3999 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4000 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4007 /* backtracking doesn't work for STACK_ZERO yet. */
4008 err = mark_chain_precision(env, value_regno);
4015 /* When register 'dst_regno' is assigned some values from stack[min_off,
4016 * max_off), we set the register's type according to the types of the
4017 * respective stack slots. If all the stack values are known to be zeros, then
4018 * so is the destination reg. Otherwise, the register is considered to be
4019 * SCALAR. This function does not deal with register filling; the caller must
4020 * ensure that all spilled registers in the stack range have been marked as
4023 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4024 /* func where src register points to */
4025 struct bpf_func_state *ptr_state,
4026 int min_off, int max_off, int dst_regno)
4028 struct bpf_verifier_state *vstate = env->cur_state;
4029 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4034 for (i = min_off; i < max_off; i++) {
4036 spi = slot / BPF_REG_SIZE;
4037 stype = ptr_state->stack[spi].slot_type;
4038 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4042 if (zeros == max_off - min_off) {
4043 /* any access_size read into register is zero extended,
4044 * so the whole register == const_zero
4046 __mark_reg_const_zero(&state->regs[dst_regno]);
4047 /* backtracking doesn't support STACK_ZERO yet,
4048 * so mark it precise here, so that later
4049 * backtracking can stop here.
4050 * Backtracking may not need this if this register
4051 * doesn't participate in pointer adjustment.
4052 * Forward propagation of precise flag is not
4053 * necessary either. This mark is only to stop
4054 * backtracking. Any register that contributed
4055 * to const 0 was marked precise before spill.
4057 state->regs[dst_regno].precise = true;
4059 /* have read misc data from the stack */
4060 mark_reg_unknown(env, state->regs, dst_regno);
4062 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4065 /* Read the stack at 'off' and put the results into the register indicated by
4066 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4069 * 'dst_regno' can be -1, meaning that the read value is not going to a
4072 * The access is assumed to be within the current stack bounds.
4074 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4075 /* func where src register points to */
4076 struct bpf_func_state *reg_state,
4077 int off, int size, int dst_regno)
4079 struct bpf_verifier_state *vstate = env->cur_state;
4080 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4081 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4082 struct bpf_reg_state *reg;
4085 stype = reg_state->stack[spi].slot_type;
4086 reg = ®_state->stack[spi].spilled_ptr;
4088 if (is_spilled_reg(®_state->stack[spi])) {
4091 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4094 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4095 if (reg->type != SCALAR_VALUE) {
4096 verbose_linfo(env, env->insn_idx, "; ");
4097 verbose(env, "invalid size of register fill\n");
4101 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4105 if (!(off % BPF_REG_SIZE) && size == spill_size) {
4106 /* The earlier check_reg_arg() has decided the
4107 * subreg_def for this insn. Save it first.
4109 s32 subreg_def = state->regs[dst_regno].subreg_def;
4111 copy_register_state(&state->regs[dst_regno], reg);
4112 state->regs[dst_regno].subreg_def = subreg_def;
4114 for (i = 0; i < size; i++) {
4115 type = stype[(slot - i) % BPF_REG_SIZE];
4116 if (type == STACK_SPILL)
4118 if (type == STACK_MISC)
4120 if (type == STACK_INVALID && env->allow_uninit_stack)
4122 verbose(env, "invalid read from stack off %d+%d size %d\n",
4126 mark_reg_unknown(env, state->regs, dst_regno);
4128 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4132 if (dst_regno >= 0) {
4133 /* restore register state from stack */
4134 copy_register_state(&state->regs[dst_regno], reg);
4135 /* mark reg as written since spilled pointer state likely
4136 * has its liveness marks cleared by is_state_visited()
4137 * which resets stack/reg liveness for state transitions
4139 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4140 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4141 /* If dst_regno==-1, the caller is asking us whether
4142 * it is acceptable to use this value as a SCALAR_VALUE
4144 * We must not allow unprivileged callers to do that
4145 * with spilled pointers.
4147 verbose(env, "leaking pointer from stack off %d\n",
4151 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4153 for (i = 0; i < size; i++) {
4154 type = stype[(slot - i) % BPF_REG_SIZE];
4155 if (type == STACK_MISC)
4157 if (type == STACK_ZERO)
4159 if (type == STACK_INVALID && env->allow_uninit_stack)
4161 verbose(env, "invalid read from stack off %d+%d size %d\n",
4165 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4167 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4172 enum bpf_access_src {
4173 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4174 ACCESS_HELPER = 2, /* the access is performed by a helper */
4177 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4178 int regno, int off, int access_size,
4179 bool zero_size_allowed,
4180 enum bpf_access_src type,
4181 struct bpf_call_arg_meta *meta);
4183 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4185 return cur_regs(env) + regno;
4188 /* Read the stack at 'ptr_regno + off' and put the result into the register
4190 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4191 * but not its variable offset.
4192 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4194 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4195 * filling registers (i.e. reads of spilled register cannot be detected when
4196 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4197 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4198 * offset; for a fixed offset check_stack_read_fixed_off should be used
4201 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4202 int ptr_regno, int off, int size, int dst_regno)
4204 /* The state of the source register. */
4205 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4206 struct bpf_func_state *ptr_state = func(env, reg);
4208 int min_off, max_off;
4210 /* Note that we pass a NULL meta, so raw access will not be permitted.
4212 err = check_stack_range_initialized(env, ptr_regno, off, size,
4213 false, ACCESS_DIRECT, NULL);
4217 min_off = reg->smin_value + off;
4218 max_off = reg->smax_value + off;
4219 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4223 /* check_stack_read dispatches to check_stack_read_fixed_off or
4224 * check_stack_read_var_off.
4226 * The caller must ensure that the offset falls within the allocated stack
4229 * 'dst_regno' is a register which will receive the value from the stack. It
4230 * can be -1, meaning that the read value is not going to a register.
4232 static int check_stack_read(struct bpf_verifier_env *env,
4233 int ptr_regno, int off, int size,
4236 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4237 struct bpf_func_state *state = func(env, reg);
4239 /* Some accesses are only permitted with a static offset. */
4240 bool var_off = !tnum_is_const(reg->var_off);
4242 /* The offset is required to be static when reads don't go to a
4243 * register, in order to not leak pointers (see
4244 * check_stack_read_fixed_off).
4246 if (dst_regno < 0 && var_off) {
4249 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4250 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4254 /* Variable offset is prohibited for unprivileged mode for simplicity
4255 * since it requires corresponding support in Spectre masking for stack
4256 * ALU. See also retrieve_ptr_limit(). The check in
4257 * check_stack_access_for_ptr_arithmetic() called by
4258 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4259 * with variable offsets, therefore no check is required here. Further,
4260 * just checking it here would be insufficient as speculative stack
4261 * writes could still lead to unsafe speculative behaviour.
4264 off += reg->var_off.value;
4265 err = check_stack_read_fixed_off(env, state, off, size,
4268 /* Variable offset stack reads need more conservative handling
4269 * than fixed offset ones. Note that dst_regno >= 0 on this
4272 err = check_stack_read_var_off(env, ptr_regno, off, size,
4279 /* check_stack_write dispatches to check_stack_write_fixed_off or
4280 * check_stack_write_var_off.
4282 * 'ptr_regno' is the register used as a pointer into the stack.
4283 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4284 * 'value_regno' is the register whose value we're writing to the stack. It can
4285 * be -1, meaning that we're not writing from a register.
4287 * The caller must ensure that the offset falls within the maximum stack size.
4289 static int check_stack_write(struct bpf_verifier_env *env,
4290 int ptr_regno, int off, int size,
4291 int value_regno, int insn_idx)
4293 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4294 struct bpf_func_state *state = func(env, reg);
4297 if (tnum_is_const(reg->var_off)) {
4298 off += reg->var_off.value;
4299 err = check_stack_write_fixed_off(env, state, off, size,
4300 value_regno, insn_idx);
4302 /* Variable offset stack reads need more conservative handling
4303 * than fixed offset ones.
4305 err = check_stack_write_var_off(env, state,
4306 ptr_regno, off, size,
4307 value_regno, insn_idx);
4312 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4313 int off, int size, enum bpf_access_type type)
4315 struct bpf_reg_state *regs = cur_regs(env);
4316 struct bpf_map *map = regs[regno].map_ptr;
4317 u32 cap = bpf_map_flags_to_cap(map);
4319 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4320 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4321 map->value_size, off, size);
4325 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4326 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4327 map->value_size, off, size);
4334 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4335 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4336 int off, int size, u32 mem_size,
4337 bool zero_size_allowed)
4339 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4340 struct bpf_reg_state *reg;
4342 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4345 reg = &cur_regs(env)[regno];
4346 switch (reg->type) {
4347 case PTR_TO_MAP_KEY:
4348 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4349 mem_size, off, size);
4351 case PTR_TO_MAP_VALUE:
4352 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4353 mem_size, off, size);
4356 case PTR_TO_PACKET_META:
4357 case PTR_TO_PACKET_END:
4358 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4359 off, size, regno, reg->id, off, mem_size);
4363 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4364 mem_size, off, size);
4370 /* check read/write into a memory region with possible variable offset */
4371 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4372 int off, int size, u32 mem_size,
4373 bool zero_size_allowed)
4375 struct bpf_verifier_state *vstate = env->cur_state;
4376 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4377 struct bpf_reg_state *reg = &state->regs[regno];
4380 /* We may have adjusted the register pointing to memory region, so we
4381 * need to try adding each of min_value and max_value to off
4382 * to make sure our theoretical access will be safe.
4384 * The minimum value is only important with signed
4385 * comparisons where we can't assume the floor of a
4386 * value is 0. If we are using signed variables for our
4387 * index'es we need to make sure that whatever we use
4388 * will have a set floor within our range.
4390 if (reg->smin_value < 0 &&
4391 (reg->smin_value == S64_MIN ||
4392 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4393 reg->smin_value + off < 0)) {
4394 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4398 err = __check_mem_access(env, regno, reg->smin_value + off, size,
4399 mem_size, zero_size_allowed);
4401 verbose(env, "R%d min value is outside of the allowed memory range\n",
4406 /* If we haven't set a max value then we need to bail since we can't be
4407 * sure we won't do bad things.
4408 * If reg->umax_value + off could overflow, treat that as unbounded too.
4410 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4411 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4415 err = __check_mem_access(env, regno, reg->umax_value + off, size,
4416 mem_size, zero_size_allowed);
4418 verbose(env, "R%d max value is outside of the allowed memory range\n",
4426 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4427 const struct bpf_reg_state *reg, int regno,
4430 /* Access to this pointer-typed register or passing it to a helper
4431 * is only allowed in its original, unmodified form.
4435 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4436 reg_type_str(env, reg->type), regno, reg->off);
4440 if (!fixed_off_ok && reg->off) {
4441 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4442 reg_type_str(env, reg->type), regno, reg->off);
4446 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4449 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4450 verbose(env, "variable %s access var_off=%s disallowed\n",
4451 reg_type_str(env, reg->type), tn_buf);
4458 int check_ptr_off_reg(struct bpf_verifier_env *env,
4459 const struct bpf_reg_state *reg, int regno)
4461 return __check_ptr_off_reg(env, reg, regno, false);
4464 static int map_kptr_match_type(struct bpf_verifier_env *env,
4465 struct btf_field *kptr_field,
4466 struct bpf_reg_state *reg, u32 regno)
4468 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4469 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4470 const char *reg_name = "";
4472 /* Only unreferenced case accepts untrusted pointers */
4473 if (kptr_field->type == BPF_KPTR_UNREF)
4474 perm_flags |= PTR_UNTRUSTED;
4476 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4479 if (!btf_is_kernel(reg->btf)) {
4480 verbose(env, "R%d must point to kernel BTF\n", regno);
4483 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
4484 reg_name = btf_type_name(reg->btf, reg->btf_id);
4486 /* For ref_ptr case, release function check should ensure we get one
4487 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4488 * normal store of unreferenced kptr, we must ensure var_off is zero.
4489 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4490 * reg->off and reg->ref_obj_id are not needed here.
4492 if (__check_ptr_off_reg(env, reg, regno, true))
4495 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
4496 * we also need to take into account the reg->off.
4498 * We want to support cases like:
4506 * v = func(); // PTR_TO_BTF_ID
4507 * val->foo = v; // reg->off is zero, btf and btf_id match type
4508 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4509 * // first member type of struct after comparison fails
4510 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4513 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
4514 * is zero. We must also ensure that btf_struct_ids_match does not walk
4515 * the struct to match type against first member of struct, i.e. reject
4516 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4517 * strict mode to true for type match.
4519 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4520 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4521 kptr_field->type == BPF_KPTR_REF))
4525 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4526 reg_type_str(env, reg->type), reg_name);
4527 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4528 if (kptr_field->type == BPF_KPTR_UNREF)
4529 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4536 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4537 * can dereference RCU protected pointers and result is PTR_TRUSTED.
4539 static bool in_rcu_cs(struct bpf_verifier_env *env)
4541 return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
4544 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4545 BTF_SET_START(rcu_protected_types)
4546 BTF_ID(struct, prog_test_ref_kfunc)
4547 BTF_ID(struct, cgroup)
4548 BTF_ID(struct, bpf_cpumask)
4549 BTF_ID(struct, task_struct)
4550 BTF_SET_END(rcu_protected_types)
4552 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4554 if (!btf_is_kernel(btf))
4556 return btf_id_set_contains(&rcu_protected_types, btf_id);
4559 static bool rcu_safe_kptr(const struct btf_field *field)
4561 const struct btf_field_kptr *kptr = &field->kptr;
4563 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
4566 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4567 int value_regno, int insn_idx,
4568 struct btf_field *kptr_field)
4570 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4571 int class = BPF_CLASS(insn->code);
4572 struct bpf_reg_state *val_reg;
4574 /* Things we already checked for in check_map_access and caller:
4575 * - Reject cases where variable offset may touch kptr
4576 * - size of access (must be BPF_DW)
4577 * - tnum_is_const(reg->var_off)
4578 * - kptr_field->offset == off + reg->var_off.value
4580 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4581 if (BPF_MODE(insn->code) != BPF_MEM) {
4582 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4586 /* We only allow loading referenced kptr, since it will be marked as
4587 * untrusted, similar to unreferenced kptr.
4589 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4590 verbose(env, "store to referenced kptr disallowed\n");
4594 if (class == BPF_LDX) {
4595 val_reg = reg_state(env, value_regno);
4596 /* We can simply mark the value_regno receiving the pointer
4597 * value from map as PTR_TO_BTF_ID, with the correct type.
4599 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4600 kptr_field->kptr.btf_id,
4601 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
4602 PTR_MAYBE_NULL | MEM_RCU :
4603 PTR_MAYBE_NULL | PTR_UNTRUSTED);
4604 /* For mark_ptr_or_null_reg */
4605 val_reg->id = ++env->id_gen;
4606 } else if (class == BPF_STX) {
4607 val_reg = reg_state(env, value_regno);
4608 if (!register_is_null(val_reg) &&
4609 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4611 } else if (class == BPF_ST) {
4613 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4614 kptr_field->offset);
4618 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4624 /* check read/write into a map element with possible variable offset */
4625 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4626 int off, int size, bool zero_size_allowed,
4627 enum bpf_access_src src)
4629 struct bpf_verifier_state *vstate = env->cur_state;
4630 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4631 struct bpf_reg_state *reg = &state->regs[regno];
4632 struct bpf_map *map = reg->map_ptr;
4633 struct btf_record *rec;
4636 err = check_mem_region_access(env, regno, off, size, map->value_size,
4641 if (IS_ERR_OR_NULL(map->record))
4644 for (i = 0; i < rec->cnt; i++) {
4645 struct btf_field *field = &rec->fields[i];
4646 u32 p = field->offset;
4648 /* If any part of a field can be touched by load/store, reject
4649 * this program. To check that [x1, x2) overlaps with [y1, y2),
4650 * it is sufficient to check x1 < y2 && y1 < x2.
4652 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4653 p < reg->umax_value + off + size) {
4654 switch (field->type) {
4655 case BPF_KPTR_UNREF:
4657 if (src != ACCESS_DIRECT) {
4658 verbose(env, "kptr cannot be accessed indirectly by helper\n");
4661 if (!tnum_is_const(reg->var_off)) {
4662 verbose(env, "kptr access cannot have variable offset\n");
4665 if (p != off + reg->var_off.value) {
4666 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4667 p, off + reg->var_off.value);
4670 if (size != bpf_size_to_bytes(BPF_DW)) {
4671 verbose(env, "kptr access size must be BPF_DW\n");
4676 verbose(env, "%s cannot be accessed directly by load/store\n",
4677 btf_field_type_name(field->type));
4685 #define MAX_PACKET_OFF 0xffff
4687 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4688 const struct bpf_call_arg_meta *meta,
4689 enum bpf_access_type t)
4691 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4693 switch (prog_type) {
4694 /* Program types only with direct read access go here! */
4695 case BPF_PROG_TYPE_LWT_IN:
4696 case BPF_PROG_TYPE_LWT_OUT:
4697 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4698 case BPF_PROG_TYPE_SK_REUSEPORT:
4699 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4700 case BPF_PROG_TYPE_CGROUP_SKB:
4705 /* Program types with direct read + write access go here! */
4706 case BPF_PROG_TYPE_SCHED_CLS:
4707 case BPF_PROG_TYPE_SCHED_ACT:
4708 case BPF_PROG_TYPE_XDP:
4709 case BPF_PROG_TYPE_LWT_XMIT:
4710 case BPF_PROG_TYPE_SK_SKB:
4711 case BPF_PROG_TYPE_SK_MSG:
4713 return meta->pkt_access;
4715 env->seen_direct_write = true;
4718 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4720 env->seen_direct_write = true;
4729 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4730 int size, bool zero_size_allowed)
4732 struct bpf_reg_state *regs = cur_regs(env);
4733 struct bpf_reg_state *reg = ®s[regno];
4736 /* We may have added a variable offset to the packet pointer; but any
4737 * reg->range we have comes after that. We are only checking the fixed
4741 /* We don't allow negative numbers, because we aren't tracking enough
4742 * detail to prove they're safe.
4744 if (reg->smin_value < 0) {
4745 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4750 err = reg->range < 0 ? -EINVAL :
4751 __check_mem_access(env, regno, off, size, reg->range,
4754 verbose(env, "R%d offset is outside of the packet\n", regno);
4758 /* __check_mem_access has made sure "off + size - 1" is within u16.
4759 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4760 * otherwise find_good_pkt_pointers would have refused to set range info
4761 * that __check_mem_access would have rejected this pkt access.
4762 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4764 env->prog->aux->max_pkt_offset =
4765 max_t(u32, env->prog->aux->max_pkt_offset,
4766 off + reg->umax_value + size - 1);
4771 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
4772 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4773 enum bpf_access_type t, enum bpf_reg_type *reg_type,
4774 struct btf **btf, u32 *btf_id)
4776 struct bpf_insn_access_aux info = {
4777 .reg_type = *reg_type,
4781 if (env->ops->is_valid_access &&
4782 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4783 /* A non zero info.ctx_field_size indicates that this field is a
4784 * candidate for later verifier transformation to load the whole
4785 * field and then apply a mask when accessed with a narrower
4786 * access than actual ctx access size. A zero info.ctx_field_size
4787 * will only allow for whole field access and rejects any other
4788 * type of narrower access.
4790 *reg_type = info.reg_type;
4792 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4794 *btf_id = info.btf_id;
4796 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4798 /* remember the offset of last byte accessed in ctx */
4799 if (env->prog->aux->max_ctx_offset < off + size)
4800 env->prog->aux->max_ctx_offset = off + size;
4804 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4808 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4811 if (size < 0 || off < 0 ||
4812 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4813 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4820 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4821 u32 regno, int off, int size,
4822 enum bpf_access_type t)
4824 struct bpf_reg_state *regs = cur_regs(env);
4825 struct bpf_reg_state *reg = ®s[regno];
4826 struct bpf_insn_access_aux info = {};
4829 if (reg->smin_value < 0) {
4830 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4835 switch (reg->type) {
4836 case PTR_TO_SOCK_COMMON:
4837 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4840 valid = bpf_sock_is_valid_access(off, size, t, &info);
4842 case PTR_TO_TCP_SOCK:
4843 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4845 case PTR_TO_XDP_SOCK:
4846 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4854 env->insn_aux_data[insn_idx].ctx_field_size =
4855 info.ctx_field_size;
4859 verbose(env, "R%d invalid %s access off=%d size=%d\n",
4860 regno, reg_type_str(env, reg->type), off, size);
4865 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4867 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4870 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4872 const struct bpf_reg_state *reg = reg_state(env, regno);
4874 return reg->type == PTR_TO_CTX;
4877 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4879 const struct bpf_reg_state *reg = reg_state(env, regno);
4881 return type_is_sk_pointer(reg->type);
4884 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4886 const struct bpf_reg_state *reg = reg_state(env, regno);
4888 return type_is_pkt_pointer(reg->type);
4891 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4893 const struct bpf_reg_state *reg = reg_state(env, regno);
4895 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4896 return reg->type == PTR_TO_FLOW_KEYS;
4899 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4901 /* A referenced register is always trusted. */
4902 if (reg->ref_obj_id)
4905 /* If a register is not referenced, it is trusted if it has the
4906 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4907 * other type modifiers may be safe, but we elect to take an opt-in
4908 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4911 * Eventually, we should make PTR_TRUSTED the single source of truth
4912 * for whether a register is trusted.
4914 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4915 !bpf_type_has_unsafe_modifiers(reg->type);
4918 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4920 return reg->type & MEM_RCU;
4923 static void clear_trusted_flags(enum bpf_type_flag *flag)
4925 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
4928 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4929 const struct bpf_reg_state *reg,
4930 int off, int size, bool strict)
4932 struct tnum reg_off;
4935 /* Byte size accesses are always allowed. */
4936 if (!strict || size == 1)
4939 /* For platforms that do not have a Kconfig enabling
4940 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4941 * NET_IP_ALIGN is universally set to '2'. And on platforms
4942 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4943 * to this code only in strict mode where we want to emulate
4944 * the NET_IP_ALIGN==2 checking. Therefore use an
4945 * unconditional IP align value of '2'.
4949 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4950 if (!tnum_is_aligned(reg_off, size)) {
4953 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4955 "misaligned packet access off %d+%s+%d+%d size %d\n",
4956 ip_align, tn_buf, reg->off, off, size);
4963 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4964 const struct bpf_reg_state *reg,
4965 const char *pointer_desc,
4966 int off, int size, bool strict)
4968 struct tnum reg_off;
4970 /* Byte size accesses are always allowed. */
4971 if (!strict || size == 1)
4974 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4975 if (!tnum_is_aligned(reg_off, size)) {
4978 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4979 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4980 pointer_desc, tn_buf, reg->off, off, size);
4987 static int check_ptr_alignment(struct bpf_verifier_env *env,
4988 const struct bpf_reg_state *reg, int off,
4989 int size, bool strict_alignment_once)
4991 bool strict = env->strict_alignment || strict_alignment_once;
4992 const char *pointer_desc = "";
4994 switch (reg->type) {
4996 case PTR_TO_PACKET_META:
4997 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4998 * right in front, treat it the very same way.
5000 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5001 case PTR_TO_FLOW_KEYS:
5002 pointer_desc = "flow keys ";
5004 case PTR_TO_MAP_KEY:
5005 pointer_desc = "key ";
5007 case PTR_TO_MAP_VALUE:
5008 pointer_desc = "value ";
5011 pointer_desc = "context ";
5014 pointer_desc = "stack ";
5015 /* The stack spill tracking logic in check_stack_write_fixed_off()
5016 * and check_stack_read_fixed_off() relies on stack accesses being
5022 pointer_desc = "sock ";
5024 case PTR_TO_SOCK_COMMON:
5025 pointer_desc = "sock_common ";
5027 case PTR_TO_TCP_SOCK:
5028 pointer_desc = "tcp_sock ";
5030 case PTR_TO_XDP_SOCK:
5031 pointer_desc = "xdp_sock ";
5036 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5040 static int update_stack_depth(struct bpf_verifier_env *env,
5041 const struct bpf_func_state *func,
5044 u16 stack = env->subprog_info[func->subprogno].stack_depth;
5049 /* update known max for given subprogram */
5050 env->subprog_info[func->subprogno].stack_depth = -off;
5054 /* starting from main bpf function walk all instructions of the function
5055 * and recursively walk all callees that given function can call.
5056 * Ignore jump and exit insns.
5057 * Since recursion is prevented by check_cfg() this algorithm
5058 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5060 static int check_max_stack_depth(struct bpf_verifier_env *env)
5062 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
5063 struct bpf_subprog_info *subprog = env->subprog_info;
5064 struct bpf_insn *insn = env->prog->insnsi;
5065 bool tail_call_reachable = false;
5066 int ret_insn[MAX_CALL_FRAMES];
5067 int ret_prog[MAX_CALL_FRAMES];
5071 /* protect against potential stack overflow that might happen when
5072 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5073 * depth for such case down to 256 so that the worst case scenario
5074 * would result in 8k stack size (32 which is tailcall limit * 256 =
5077 * To get the idea what might happen, see an example:
5078 * func1 -> sub rsp, 128
5079 * subfunc1 -> sub rsp, 256
5080 * tailcall1 -> add rsp, 256
5081 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5082 * subfunc2 -> sub rsp, 64
5083 * subfunc22 -> sub rsp, 128
5084 * tailcall2 -> add rsp, 128
5085 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5087 * tailcall will unwind the current stack frame but it will not get rid
5088 * of caller's stack as shown on the example above.
5090 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5092 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5096 /* round up to 32-bytes, since this is granularity
5097 * of interpreter stack size
5099 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5100 if (depth > MAX_BPF_STACK) {
5101 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5106 subprog_end = subprog[idx + 1].start;
5107 for (; i < subprog_end; i++) {
5110 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5112 /* remember insn and function to return to */
5113 ret_insn[frame] = i + 1;
5114 ret_prog[frame] = idx;
5116 /* find the callee */
5117 next_insn = i + insn[i].imm + 1;
5118 idx = find_subprog(env, next_insn);
5120 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5124 if (subprog[idx].is_async_cb) {
5125 if (subprog[idx].has_tail_call) {
5126 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5129 /* async callbacks don't increase bpf prog stack size */
5134 if (subprog[idx].has_tail_call)
5135 tail_call_reachable = true;
5138 if (frame >= MAX_CALL_FRAMES) {
5139 verbose(env, "the call stack of %d frames is too deep !\n",
5145 /* if tail call got detected across bpf2bpf calls then mark each of the
5146 * currently present subprog frames as tail call reachable subprogs;
5147 * this info will be utilized by JIT so that we will be preserving the
5148 * tail call counter throughout bpf2bpf calls combined with tailcalls
5150 if (tail_call_reachable)
5151 for (j = 0; j < frame; j++)
5152 subprog[ret_prog[j]].tail_call_reachable = true;
5153 if (subprog[0].tail_call_reachable)
5154 env->prog->aux->tail_call_reachable = true;
5156 /* end of for() loop means the last insn of the 'subprog'
5157 * was reached. Doesn't matter whether it was JA or EXIT
5161 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5163 i = ret_insn[frame];
5164 idx = ret_prog[frame];
5168 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5169 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5170 const struct bpf_insn *insn, int idx)
5172 int start = idx + insn->imm + 1, subprog;
5174 subprog = find_subprog(env, start);
5176 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5180 return env->subprog_info[subprog].stack_depth;
5184 static int __check_buffer_access(struct bpf_verifier_env *env,
5185 const char *buf_info,
5186 const struct bpf_reg_state *reg,
5187 int regno, int off, int size)
5191 "R%d invalid %s buffer access: off=%d, size=%d\n",
5192 regno, buf_info, off, size);
5195 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5198 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5200 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5201 regno, off, tn_buf);
5208 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5209 const struct bpf_reg_state *reg,
5210 int regno, int off, int size)
5214 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5218 if (off + size > env->prog->aux->max_tp_access)
5219 env->prog->aux->max_tp_access = off + size;
5224 static int check_buffer_access(struct bpf_verifier_env *env,
5225 const struct bpf_reg_state *reg,
5226 int regno, int off, int size,
5227 bool zero_size_allowed,
5230 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5233 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5237 if (off + size > *max_access)
5238 *max_access = off + size;
5243 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5244 static void zext_32_to_64(struct bpf_reg_state *reg)
5246 reg->var_off = tnum_subreg(reg->var_off);
5247 __reg_assign_32_into_64(reg);
5250 /* truncate register to smaller size (in bytes)
5251 * must be called with size < BPF_REG_SIZE
5253 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5257 /* clear high bits in bit representation */
5258 reg->var_off = tnum_cast(reg->var_off, size);
5260 /* fix arithmetic bounds */
5261 mask = ((u64)1 << (size * 8)) - 1;
5262 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5263 reg->umin_value &= mask;
5264 reg->umax_value &= mask;
5266 reg->umin_value = 0;
5267 reg->umax_value = mask;
5269 reg->smin_value = reg->umin_value;
5270 reg->smax_value = reg->umax_value;
5272 /* If size is smaller than 32bit register the 32bit register
5273 * values are also truncated so we push 64-bit bounds into
5274 * 32-bit bounds. Above were truncated < 32-bits already.
5278 __reg_combine_64_into_32(reg);
5281 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5283 /* A map is considered read-only if the following condition are true:
5285 * 1) BPF program side cannot change any of the map content. The
5286 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5287 * and was set at map creation time.
5288 * 2) The map value(s) have been initialized from user space by a
5289 * loader and then "frozen", such that no new map update/delete
5290 * operations from syscall side are possible for the rest of
5291 * the map's lifetime from that point onwards.
5292 * 3) Any parallel/pending map update/delete operations from syscall
5293 * side have been completed. Only after that point, it's safe to
5294 * assume that map value(s) are immutable.
5296 return (map->map_flags & BPF_F_RDONLY_PROG) &&
5297 READ_ONCE(map->frozen) &&
5298 !bpf_map_write_active(map);
5301 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5307 err = map->ops->map_direct_value_addr(map, &addr, off);
5310 ptr = (void *)(long)addr + off;
5314 *val = (u64)*(u8 *)ptr;
5317 *val = (u64)*(u16 *)ptr;
5320 *val = (u64)*(u32 *)ptr;
5331 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
5332 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
5333 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
5336 * Allow list few fields as RCU trusted or full trusted.
5337 * This logic doesn't allow mix tagging and will be removed once GCC supports
5341 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5342 BTF_TYPE_SAFE_RCU(struct task_struct) {
5343 const cpumask_t *cpus_ptr;
5344 struct css_set __rcu *cgroups;
5345 struct task_struct __rcu *real_parent;
5346 struct task_struct *group_leader;
5349 BTF_TYPE_SAFE_RCU(struct cgroup) {
5350 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5351 struct kernfs_node *kn;
5354 BTF_TYPE_SAFE_RCU(struct css_set) {
5355 struct cgroup *dfl_cgrp;
5358 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5359 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5360 struct file __rcu *exe_file;
5363 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5364 * because bpf prog accessible sockets are SOCK_RCU_FREE.
5366 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5370 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5374 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5375 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5376 struct seq_file *seq;
5379 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5380 struct bpf_iter_meta *meta;
5381 struct task_struct *task;
5384 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5388 BTF_TYPE_SAFE_TRUSTED(struct file) {
5389 struct inode *f_inode;
5392 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5393 /* no negative dentry-s in places where bpf can see it */
5394 struct inode *d_inode;
5397 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5401 static bool type_is_rcu(struct bpf_verifier_env *env,
5402 struct bpf_reg_state *reg,
5403 const char *field_name, u32 btf_id)
5405 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5406 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5407 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5409 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5412 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5413 struct bpf_reg_state *reg,
5414 const char *field_name, u32 btf_id)
5416 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5417 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5418 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5420 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5423 static bool type_is_trusted(struct bpf_verifier_env *env,
5424 struct bpf_reg_state *reg,
5425 const char *field_name, u32 btf_id)
5427 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5428 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5429 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5430 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5431 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5432 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5434 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5437 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5438 struct bpf_reg_state *regs,
5439 int regno, int off, int size,
5440 enum bpf_access_type atype,
5443 struct bpf_reg_state *reg = regs + regno;
5444 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5445 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5446 const char *field_name = NULL;
5447 enum bpf_type_flag flag = 0;
5451 if (!env->allow_ptr_leaks) {
5453 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5457 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5459 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5465 "R%d is ptr_%s invalid negative access: off=%d\n",
5469 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5472 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5474 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5475 regno, tname, off, tn_buf);
5479 if (reg->type & MEM_USER) {
5481 "R%d is ptr_%s access user memory: off=%d\n",
5486 if (reg->type & MEM_PERCPU) {
5488 "R%d is ptr_%s access percpu memory: off=%d\n",
5493 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
5494 if (!btf_is_kernel(reg->btf)) {
5495 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5498 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
5500 /* Writes are permitted with default btf_struct_access for
5501 * program allocated objects (which always have ref_obj_id > 0),
5502 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5504 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
5505 verbose(env, "only read is supported\n");
5509 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5511 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5515 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
5521 if (ret != PTR_TO_BTF_ID) {
5524 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
5525 /* If this is an untrusted pointer, all pointers formed by walking it
5526 * also inherit the untrusted flag.
5528 flag = PTR_UNTRUSTED;
5530 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
5531 /* By default any pointer obtained from walking a trusted pointer is no
5532 * longer trusted, unless the field being accessed has explicitly been
5533 * marked as inheriting its parent's state of trust (either full or RCU).
5535 * 'cgroups' pointer is untrusted if task->cgroups dereference
5536 * happened in a sleepable program outside of bpf_rcu_read_lock()
5537 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
5538 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
5540 * A regular RCU-protected pointer with __rcu tag can also be deemed
5541 * trusted if we are in an RCU CS. Such pointer can be NULL.
5543 if (type_is_trusted(env, reg, field_name, btf_id)) {
5544 flag |= PTR_TRUSTED;
5545 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
5546 if (type_is_rcu(env, reg, field_name, btf_id)) {
5547 /* ignore __rcu tag and mark it MEM_RCU */
5549 } else if (flag & MEM_RCU ||
5550 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
5551 /* __rcu tagged pointers can be NULL */
5552 flag |= MEM_RCU | PTR_MAYBE_NULL;
5553 } else if (flag & (MEM_PERCPU | MEM_USER)) {
5556 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
5557 clear_trusted_flags(&flag);
5561 * If not in RCU CS or MEM_RCU pointer can be NULL then
5562 * aggressively mark as untrusted otherwise such
5563 * pointers will be plain PTR_TO_BTF_ID without flags
5564 * and will be allowed to be passed into helpers for
5567 flag = PTR_UNTRUSTED;
5570 /* Old compat. Deprecated */
5571 clear_trusted_flags(&flag);
5574 if (atype == BPF_READ && value_regno >= 0)
5575 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5580 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5581 struct bpf_reg_state *regs,
5582 int regno, int off, int size,
5583 enum bpf_access_type atype,
5586 struct bpf_reg_state *reg = regs + regno;
5587 struct bpf_map *map = reg->map_ptr;
5588 struct bpf_reg_state map_reg;
5589 enum bpf_type_flag flag = 0;
5590 const struct btf_type *t;
5596 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5600 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5601 verbose(env, "map_ptr access not supported for map type %d\n",
5606 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5607 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5609 if (!env->allow_ptr_leaks) {
5611 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5617 verbose(env, "R%d is %s invalid negative access: off=%d\n",
5622 if (atype != BPF_READ) {
5623 verbose(env, "only read from %s is supported\n", tname);
5627 /* Simulate access to a PTR_TO_BTF_ID */
5628 memset(&map_reg, 0, sizeof(map_reg));
5629 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
5630 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
5634 if (value_regno >= 0)
5635 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
5640 /* Check that the stack access at the given offset is within bounds. The
5641 * maximum valid offset is -1.
5643 * The minimum valid offset is -MAX_BPF_STACK for writes, and
5644 * -state->allocated_stack for reads.
5646 static int check_stack_slot_within_bounds(int off,
5647 struct bpf_func_state *state,
5648 enum bpf_access_type t)
5653 min_valid_off = -MAX_BPF_STACK;
5655 min_valid_off = -state->allocated_stack;
5657 if (off < min_valid_off || off > -1)
5662 /* Check that the stack access at 'regno + off' falls within the maximum stack
5665 * 'off' includes `regno->offset`, but not its dynamic part (if any).
5667 static int check_stack_access_within_bounds(
5668 struct bpf_verifier_env *env,
5669 int regno, int off, int access_size,
5670 enum bpf_access_src src, enum bpf_access_type type)
5672 struct bpf_reg_state *regs = cur_regs(env);
5673 struct bpf_reg_state *reg = regs + regno;
5674 struct bpf_func_state *state = func(env, reg);
5675 int min_off, max_off;
5679 if (src == ACCESS_HELPER)
5680 /* We don't know if helpers are reading or writing (or both). */
5681 err_extra = " indirect access to";
5682 else if (type == BPF_READ)
5683 err_extra = " read from";
5685 err_extra = " write to";
5687 if (tnum_is_const(reg->var_off)) {
5688 min_off = reg->var_off.value + off;
5689 if (access_size > 0)
5690 max_off = min_off + access_size - 1;
5694 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
5695 reg->smin_value <= -BPF_MAX_VAR_OFF) {
5696 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
5700 min_off = reg->smin_value + off;
5701 if (access_size > 0)
5702 max_off = reg->smax_value + off + access_size - 1;
5707 err = check_stack_slot_within_bounds(min_off, state, type);
5709 err = check_stack_slot_within_bounds(max_off, state, type);
5712 if (tnum_is_const(reg->var_off)) {
5713 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5714 err_extra, regno, off, access_size);
5718 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5719 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5720 err_extra, regno, tn_buf, access_size);
5726 /* check whether memory at (regno + off) is accessible for t = (read | write)
5727 * if t==write, value_regno is a register which value is stored into memory
5728 * if t==read, value_regno is a register which will receive the value from memory
5729 * if t==write && value_regno==-1, some unknown value is stored into memory
5730 * if t==read && value_regno==-1, don't care what we read from memory
5732 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5733 int off, int bpf_size, enum bpf_access_type t,
5734 int value_regno, bool strict_alignment_once)
5736 struct bpf_reg_state *regs = cur_regs(env);
5737 struct bpf_reg_state *reg = regs + regno;
5738 struct bpf_func_state *state;
5741 size = bpf_size_to_bytes(bpf_size);
5745 /* alignment checks will add in reg->off themselves */
5746 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5750 /* for access checks, reg->off is just part of off */
5753 if (reg->type == PTR_TO_MAP_KEY) {
5754 if (t == BPF_WRITE) {
5755 verbose(env, "write to change key R%d not allowed\n", regno);
5759 err = check_mem_region_access(env, regno, off, size,
5760 reg->map_ptr->key_size, false);
5763 if (value_regno >= 0)
5764 mark_reg_unknown(env, regs, value_regno);
5765 } else if (reg->type == PTR_TO_MAP_VALUE) {
5766 struct btf_field *kptr_field = NULL;
5768 if (t == BPF_WRITE && value_regno >= 0 &&
5769 is_pointer_value(env, value_regno)) {
5770 verbose(env, "R%d leaks addr into map\n", value_regno);
5773 err = check_map_access_type(env, regno, off, size, t);
5776 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5779 if (tnum_is_const(reg->var_off))
5780 kptr_field = btf_record_find(reg->map_ptr->record,
5781 off + reg->var_off.value, BPF_KPTR);
5783 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5784 } else if (t == BPF_READ && value_regno >= 0) {
5785 struct bpf_map *map = reg->map_ptr;
5787 /* if map is read-only, track its contents as scalars */
5788 if (tnum_is_const(reg->var_off) &&
5789 bpf_map_is_rdonly(map) &&
5790 map->ops->map_direct_value_addr) {
5791 int map_off = off + reg->var_off.value;
5794 err = bpf_map_direct_read(map, map_off, size,
5799 regs[value_regno].type = SCALAR_VALUE;
5800 __mark_reg_known(®s[value_regno], val);
5802 mark_reg_unknown(env, regs, value_regno);
5805 } else if (base_type(reg->type) == PTR_TO_MEM) {
5806 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5808 if (type_may_be_null(reg->type)) {
5809 verbose(env, "R%d invalid mem access '%s'\n", regno,
5810 reg_type_str(env, reg->type));
5814 if (t == BPF_WRITE && rdonly_mem) {
5815 verbose(env, "R%d cannot write into %s\n",
5816 regno, reg_type_str(env, reg->type));
5820 if (t == BPF_WRITE && value_regno >= 0 &&
5821 is_pointer_value(env, value_regno)) {
5822 verbose(env, "R%d leaks addr into mem\n", value_regno);
5826 err = check_mem_region_access(env, regno, off, size,
5827 reg->mem_size, false);
5828 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5829 mark_reg_unknown(env, regs, value_regno);
5830 } else if (reg->type == PTR_TO_CTX) {
5831 enum bpf_reg_type reg_type = SCALAR_VALUE;
5832 struct btf *btf = NULL;
5835 if (t == BPF_WRITE && value_regno >= 0 &&
5836 is_pointer_value(env, value_regno)) {
5837 verbose(env, "R%d leaks addr into ctx\n", value_regno);
5841 err = check_ptr_off_reg(env, reg, regno);
5845 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
5848 verbose_linfo(env, insn_idx, "; ");
5849 if (!err && t == BPF_READ && value_regno >= 0) {
5850 /* ctx access returns either a scalar, or a
5851 * PTR_TO_PACKET[_META,_END]. In the latter
5852 * case, we know the offset is zero.
5854 if (reg_type == SCALAR_VALUE) {
5855 mark_reg_unknown(env, regs, value_regno);
5857 mark_reg_known_zero(env, regs,
5859 if (type_may_be_null(reg_type))
5860 regs[value_regno].id = ++env->id_gen;
5861 /* A load of ctx field could have different
5862 * actual load size with the one encoded in the
5863 * insn. When the dst is PTR, it is for sure not
5866 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5867 if (base_type(reg_type) == PTR_TO_BTF_ID) {
5868 regs[value_regno].btf = btf;
5869 regs[value_regno].btf_id = btf_id;
5872 regs[value_regno].type = reg_type;
5875 } else if (reg->type == PTR_TO_STACK) {
5876 /* Basic bounds checks. */
5877 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5881 state = func(env, reg);
5882 err = update_stack_depth(env, state, off);
5887 err = check_stack_read(env, regno, off, size,
5890 err = check_stack_write(env, regno, off, size,
5891 value_regno, insn_idx);
5892 } else if (reg_is_pkt_pointer(reg)) {
5893 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5894 verbose(env, "cannot write into packet\n");
5897 if (t == BPF_WRITE && value_regno >= 0 &&
5898 is_pointer_value(env, value_regno)) {
5899 verbose(env, "R%d leaks addr into packet\n",
5903 err = check_packet_access(env, regno, off, size, false);
5904 if (!err && t == BPF_READ && value_regno >= 0)
5905 mark_reg_unknown(env, regs, value_regno);
5906 } else if (reg->type == PTR_TO_FLOW_KEYS) {
5907 if (t == BPF_WRITE && value_regno >= 0 &&
5908 is_pointer_value(env, value_regno)) {
5909 verbose(env, "R%d leaks addr into flow keys\n",
5914 err = check_flow_keys_access(env, off, size);
5915 if (!err && t == BPF_READ && value_regno >= 0)
5916 mark_reg_unknown(env, regs, value_regno);
5917 } else if (type_is_sk_pointer(reg->type)) {
5918 if (t == BPF_WRITE) {
5919 verbose(env, "R%d cannot write into %s\n",
5920 regno, reg_type_str(env, reg->type));
5923 err = check_sock_access(env, insn_idx, regno, off, size, t);
5924 if (!err && value_regno >= 0)
5925 mark_reg_unknown(env, regs, value_regno);
5926 } else if (reg->type == PTR_TO_TP_BUFFER) {
5927 err = check_tp_buffer_access(env, reg, regno, off, size);
5928 if (!err && t == BPF_READ && value_regno >= 0)
5929 mark_reg_unknown(env, regs, value_regno);
5930 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5931 !type_may_be_null(reg->type)) {
5932 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5934 } else if (reg->type == CONST_PTR_TO_MAP) {
5935 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5937 } else if (base_type(reg->type) == PTR_TO_BUF) {
5938 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5942 if (t == BPF_WRITE) {
5943 verbose(env, "R%d cannot write into %s\n",
5944 regno, reg_type_str(env, reg->type));
5947 max_access = &env->prog->aux->max_rdonly_access;
5949 max_access = &env->prog->aux->max_rdwr_access;
5952 err = check_buffer_access(env, reg, regno, off, size, false,
5955 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5956 mark_reg_unknown(env, regs, value_regno);
5958 verbose(env, "R%d invalid mem access '%s'\n", regno,
5959 reg_type_str(env, reg->type));
5963 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5964 regs[value_regno].type == SCALAR_VALUE) {
5965 /* b/h/w load zero-extends, mark upper bits as known 0 */
5966 coerce_reg_to_size(®s[value_regno], size);
5971 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5976 switch (insn->imm) {
5978 case BPF_ADD | BPF_FETCH:
5980 case BPF_AND | BPF_FETCH:
5982 case BPF_OR | BPF_FETCH:
5984 case BPF_XOR | BPF_FETCH:
5989 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5993 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5994 verbose(env, "invalid atomic operand size\n");
5998 /* check src1 operand */
5999 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6003 /* check src2 operand */
6004 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6008 if (insn->imm == BPF_CMPXCHG) {
6009 /* Check comparison of R0 with memory location */
6010 const u32 aux_reg = BPF_REG_0;
6012 err = check_reg_arg(env, aux_reg, SRC_OP);
6016 if (is_pointer_value(env, aux_reg)) {
6017 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6022 if (is_pointer_value(env, insn->src_reg)) {
6023 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6027 if (is_ctx_reg(env, insn->dst_reg) ||
6028 is_pkt_reg(env, insn->dst_reg) ||
6029 is_flow_key_reg(env, insn->dst_reg) ||
6030 is_sk_reg(env, insn->dst_reg)) {
6031 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6033 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6037 if (insn->imm & BPF_FETCH) {
6038 if (insn->imm == BPF_CMPXCHG)
6039 load_reg = BPF_REG_0;
6041 load_reg = insn->src_reg;
6043 /* check and record load of old value */
6044 err = check_reg_arg(env, load_reg, DST_OP);
6048 /* This instruction accesses a memory location but doesn't
6049 * actually load it into a register.
6054 /* Check whether we can read the memory, with second call for fetch
6055 * case to simulate the register fill.
6057 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6058 BPF_SIZE(insn->code), BPF_READ, -1, true);
6059 if (!err && load_reg >= 0)
6060 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6061 BPF_SIZE(insn->code), BPF_READ, load_reg,
6066 /* Check whether we can write into the same memory. */
6067 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6068 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
6075 /* When register 'regno' is used to read the stack (either directly or through
6076 * a helper function) make sure that it's within stack boundary and, depending
6077 * on the access type, that all elements of the stack are initialized.
6079 * 'off' includes 'regno->off', but not its dynamic part (if any).
6081 * All registers that have been spilled on the stack in the slots within the
6082 * read offsets are marked as read.
6084 static int check_stack_range_initialized(
6085 struct bpf_verifier_env *env, int regno, int off,
6086 int access_size, bool zero_size_allowed,
6087 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6089 struct bpf_reg_state *reg = reg_state(env, regno);
6090 struct bpf_func_state *state = func(env, reg);
6091 int err, min_off, max_off, i, j, slot, spi;
6092 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6093 enum bpf_access_type bounds_check_type;
6094 /* Some accesses can write anything into the stack, others are
6097 bool clobber = false;
6099 if (access_size == 0 && !zero_size_allowed) {
6100 verbose(env, "invalid zero-sized read\n");
6104 if (type == ACCESS_HELPER) {
6105 /* The bounds checks for writes are more permissive than for
6106 * reads. However, if raw_mode is not set, we'll do extra
6109 bounds_check_type = BPF_WRITE;
6112 bounds_check_type = BPF_READ;
6114 err = check_stack_access_within_bounds(env, regno, off, access_size,
6115 type, bounds_check_type);
6120 if (tnum_is_const(reg->var_off)) {
6121 min_off = max_off = reg->var_off.value + off;
6123 /* Variable offset is prohibited for unprivileged mode for
6124 * simplicity since it requires corresponding support in
6125 * Spectre masking for stack ALU.
6126 * See also retrieve_ptr_limit().
6128 if (!env->bypass_spec_v1) {
6131 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6132 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6133 regno, err_extra, tn_buf);
6136 /* Only initialized buffer on stack is allowed to be accessed
6137 * with variable offset. With uninitialized buffer it's hard to
6138 * guarantee that whole memory is marked as initialized on
6139 * helper return since specific bounds are unknown what may
6140 * cause uninitialized stack leaking.
6142 if (meta && meta->raw_mode)
6145 min_off = reg->smin_value + off;
6146 max_off = reg->smax_value + off;
6149 if (meta && meta->raw_mode) {
6150 /* Ensure we won't be overwriting dynptrs when simulating byte
6151 * by byte access in check_helper_call using meta.access_size.
6152 * This would be a problem if we have a helper in the future
6155 * helper(uninit_mem, len, dynptr)
6157 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6158 * may end up writing to dynptr itself when touching memory from
6159 * arg 1. This can be relaxed on a case by case basis for known
6160 * safe cases, but reject due to the possibilitiy of aliasing by
6163 for (i = min_off; i < max_off + access_size; i++) {
6164 int stack_off = -i - 1;
6167 /* raw_mode may write past allocated_stack */
6168 if (state->allocated_stack <= stack_off)
6170 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6171 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6175 meta->access_size = access_size;
6176 meta->regno = regno;
6180 for (i = min_off; i < max_off + access_size; i++) {
6184 spi = slot / BPF_REG_SIZE;
6185 if (state->allocated_stack <= slot)
6187 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6188 if (*stype == STACK_MISC)
6190 if ((*stype == STACK_ZERO) ||
6191 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6193 /* helper can write anything into the stack */
6194 *stype = STACK_MISC;
6199 if (is_spilled_reg(&state->stack[spi]) &&
6200 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6201 env->allow_ptr_leaks)) {
6203 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6204 for (j = 0; j < BPF_REG_SIZE; j++)
6205 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6211 if (tnum_is_const(reg->var_off)) {
6212 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6213 err_extra, regno, min_off, i - min_off, access_size);
6217 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6218 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6219 err_extra, regno, tn_buf, i - min_off, access_size);
6223 /* reading any byte out of 8-byte 'spill_slot' will cause
6224 * the whole slot to be marked as 'read'
6226 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6227 state->stack[spi].spilled_ptr.parent,
6229 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6230 * be sure that whether stack slot is written to or not. Hence,
6231 * we must still conservatively propagate reads upwards even if
6232 * helper may write to the entire memory range.
6235 return update_stack_depth(env, state, min_off);
6238 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6239 int access_size, bool zero_size_allowed,
6240 struct bpf_call_arg_meta *meta)
6242 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6245 switch (base_type(reg->type)) {
6247 case PTR_TO_PACKET_META:
6248 return check_packet_access(env, regno, reg->off, access_size,
6250 case PTR_TO_MAP_KEY:
6251 if (meta && meta->raw_mode) {
6252 verbose(env, "R%d cannot write into %s\n", regno,
6253 reg_type_str(env, reg->type));
6256 return check_mem_region_access(env, regno, reg->off, access_size,
6257 reg->map_ptr->key_size, false);
6258 case PTR_TO_MAP_VALUE:
6259 if (check_map_access_type(env, regno, reg->off, access_size,
6260 meta && meta->raw_mode ? BPF_WRITE :
6263 return check_map_access(env, regno, reg->off, access_size,
6264 zero_size_allowed, ACCESS_HELPER);
6266 if (type_is_rdonly_mem(reg->type)) {
6267 if (meta && meta->raw_mode) {
6268 verbose(env, "R%d cannot write into %s\n", regno,
6269 reg_type_str(env, reg->type));
6273 return check_mem_region_access(env, regno, reg->off,
6274 access_size, reg->mem_size,
6277 if (type_is_rdonly_mem(reg->type)) {
6278 if (meta && meta->raw_mode) {
6279 verbose(env, "R%d cannot write into %s\n", regno,
6280 reg_type_str(env, reg->type));
6284 max_access = &env->prog->aux->max_rdonly_access;
6286 max_access = &env->prog->aux->max_rdwr_access;
6288 return check_buffer_access(env, reg, regno, reg->off,
6289 access_size, zero_size_allowed,
6292 return check_stack_range_initialized(
6294 regno, reg->off, access_size,
6295 zero_size_allowed, ACCESS_HELPER, meta);
6297 return check_ptr_to_btf_access(env, regs, regno, reg->off,
6298 access_size, BPF_READ, -1);
6300 /* in case the function doesn't know how to access the context,
6301 * (because we are in a program of type SYSCALL for example), we
6302 * can not statically check its size.
6303 * Dynamically check it now.
6305 if (!env->ops->convert_ctx_access) {
6306 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6307 int offset = access_size - 1;
6309 /* Allow zero-byte read from PTR_TO_CTX */
6310 if (access_size == 0)
6311 return zero_size_allowed ? 0 : -EACCES;
6313 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6318 default: /* scalar_value or invalid ptr */
6319 /* Allow zero-byte read from NULL, regardless of pointer type */
6320 if (zero_size_allowed && access_size == 0 &&
6321 register_is_null(reg))
6324 verbose(env, "R%d type=%s ", regno,
6325 reg_type_str(env, reg->type));
6326 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6331 static int check_mem_size_reg(struct bpf_verifier_env *env,
6332 struct bpf_reg_state *reg, u32 regno,
6333 bool zero_size_allowed,
6334 struct bpf_call_arg_meta *meta)
6338 /* This is used to refine r0 return value bounds for helpers
6339 * that enforce this value as an upper bound on return values.
6340 * See do_refine_retval_range() for helpers that can refine
6341 * the return value. C type of helper is u32 so we pull register
6342 * bound from umax_value however, if negative verifier errors
6343 * out. Only upper bounds can be learned because retval is an
6344 * int type and negative retvals are allowed.
6346 meta->msize_max_value = reg->umax_value;
6348 /* The register is SCALAR_VALUE; the access check
6349 * happens using its boundaries.
6351 if (!tnum_is_const(reg->var_off))
6352 /* For unprivileged variable accesses, disable raw
6353 * mode so that the program is required to
6354 * initialize all the memory that the helper could
6355 * just partially fill up.
6359 if (reg->smin_value < 0) {
6360 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6365 if (reg->umin_value == 0) {
6366 err = check_helper_mem_access(env, regno - 1, 0,
6373 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6374 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6378 err = check_helper_mem_access(env, regno - 1,
6380 zero_size_allowed, meta);
6382 err = mark_chain_precision(env, regno);
6386 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6387 u32 regno, u32 mem_size)
6389 bool may_be_null = type_may_be_null(reg->type);
6390 struct bpf_reg_state saved_reg;
6391 struct bpf_call_arg_meta meta;
6394 if (register_is_null(reg))
6397 memset(&meta, 0, sizeof(meta));
6398 /* Assuming that the register contains a value check if the memory
6399 * access is safe. Temporarily save and restore the register's state as
6400 * the conversion shouldn't be visible to a caller.
6404 mark_ptr_not_null_reg(reg);
6407 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6408 /* Check access for BPF_WRITE */
6409 meta.raw_mode = true;
6410 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6418 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6421 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6422 bool may_be_null = type_may_be_null(mem_reg->type);
6423 struct bpf_reg_state saved_reg;
6424 struct bpf_call_arg_meta meta;
6427 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6429 memset(&meta, 0, sizeof(meta));
6432 saved_reg = *mem_reg;
6433 mark_ptr_not_null_reg(mem_reg);
6436 err = check_mem_size_reg(env, reg, regno, true, &meta);
6437 /* Check access for BPF_WRITE */
6438 meta.raw_mode = true;
6439 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6442 *mem_reg = saved_reg;
6446 /* Implementation details:
6447 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6448 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6449 * Two bpf_map_lookups (even with the same key) will have different reg->id.
6450 * Two separate bpf_obj_new will also have different reg->id.
6451 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6452 * clears reg->id after value_or_null->value transition, since the verifier only
6453 * cares about the range of access to valid map value pointer and doesn't care
6454 * about actual address of the map element.
6455 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6456 * reg->id > 0 after value_or_null->value transition. By doing so
6457 * two bpf_map_lookups will be considered two different pointers that
6458 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6459 * returned from bpf_obj_new.
6460 * The verifier allows taking only one bpf_spin_lock at a time to avoid
6462 * Since only one bpf_spin_lock is allowed the checks are simpler than
6463 * reg_is_refcounted() logic. The verifier needs to remember only
6464 * one spin_lock instead of array of acquired_refs.
6465 * cur_state->active_lock remembers which map value element or allocated
6466 * object got locked and clears it after bpf_spin_unlock.
6468 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6471 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6472 struct bpf_verifier_state *cur = env->cur_state;
6473 bool is_const = tnum_is_const(reg->var_off);
6474 u64 val = reg->var_off.value;
6475 struct bpf_map *map = NULL;
6476 struct btf *btf = NULL;
6477 struct btf_record *rec;
6481 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6485 if (reg->type == PTR_TO_MAP_VALUE) {
6489 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
6497 rec = reg_btf_record(reg);
6498 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6499 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6500 map ? map->name : "kptr");
6503 if (rec->spin_lock_off != val + reg->off) {
6504 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
6505 val + reg->off, rec->spin_lock_off);
6509 if (cur->active_lock.ptr) {
6511 "Locking two bpf_spin_locks are not allowed\n");
6515 cur->active_lock.ptr = map;
6517 cur->active_lock.ptr = btf;
6518 cur->active_lock.id = reg->id;
6527 if (!cur->active_lock.ptr) {
6528 verbose(env, "bpf_spin_unlock without taking a lock\n");
6531 if (cur->active_lock.ptr != ptr ||
6532 cur->active_lock.id != reg->id) {
6533 verbose(env, "bpf_spin_unlock of different lock\n");
6537 invalidate_non_owning_refs(env);
6539 cur->active_lock.ptr = NULL;
6540 cur->active_lock.id = 0;
6545 static int process_timer_func(struct bpf_verifier_env *env, int regno,
6546 struct bpf_call_arg_meta *meta)
6548 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6549 bool is_const = tnum_is_const(reg->var_off);
6550 struct bpf_map *map = reg->map_ptr;
6551 u64 val = reg->var_off.value;
6555 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6560 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6564 if (!btf_record_has_field(map->record, BPF_TIMER)) {
6565 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
6568 if (map->record->timer_off != val + reg->off) {
6569 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
6570 val + reg->off, map->record->timer_off);
6573 if (meta->map_ptr) {
6574 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6577 meta->map_uid = reg->map_uid;
6578 meta->map_ptr = map;
6582 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6583 struct bpf_call_arg_meta *meta)
6585 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6586 struct bpf_map *map_ptr = reg->map_ptr;
6587 struct btf_field *kptr_field;
6590 if (!tnum_is_const(reg->var_off)) {
6592 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6596 if (!map_ptr->btf) {
6597 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6601 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6602 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
6606 meta->map_ptr = map_ptr;
6607 kptr_off = reg->off + reg->var_off.value;
6608 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
6610 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
6613 if (kptr_field->type != BPF_KPTR_REF) {
6614 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
6617 meta->kptr_field = kptr_field;
6621 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6622 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6624 * In both cases we deal with the first 8 bytes, but need to mark the next 8
6625 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6626 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6628 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6629 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6630 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6631 * mutate the view of the dynptr and also possibly destroy it. In the latter
6632 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6633 * memory that dynptr points to.
6635 * The verifier will keep track both levels of mutation (bpf_dynptr's in
6636 * reg->type and the memory's in reg->dynptr.type), but there is no support for
6637 * readonly dynptr view yet, hence only the first case is tracked and checked.
6639 * This is consistent with how C applies the const modifier to a struct object,
6640 * where the pointer itself inside bpf_dynptr becomes const but not what it
6643 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6644 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6646 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
6647 enum bpf_arg_type arg_type)
6649 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6652 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6653 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6655 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6656 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6660 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
6661 * constructing a mutable bpf_dynptr object.
6663 * Currently, this is only possible with PTR_TO_STACK
6664 * pointing to a region of at least 16 bytes which doesn't
6665 * contain an existing bpf_dynptr.
6667 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6668 * mutated or destroyed. However, the memory it points to
6671 * None - Points to a initialized dynptr that can be mutated and
6672 * destroyed, including mutation of the memory it points
6675 if (arg_type & MEM_UNINIT) {
6678 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6679 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6683 /* we write BPF_DW bits (8 bytes) at a time */
6684 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
6685 err = check_mem_access(env, insn_idx, regno,
6686 i, BPF_DW, BPF_WRITE, -1, false);
6691 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx);
6692 } else /* MEM_RDONLY and None case from above */ {
6693 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6694 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6695 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6699 if (!is_dynptr_reg_valid_init(env, reg)) {
6701 "Expected an initialized dynptr as arg #%d\n",
6706 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6707 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6709 "Expected a dynptr of type %s as arg #%d\n",
6710 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
6714 err = mark_dynptr_read(env, reg);
6719 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
6721 struct bpf_func_state *state = func(env, reg);
6723 return state->stack[spi].spilled_ptr.ref_obj_id;
6726 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6728 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
6731 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6733 return meta->kfunc_flags & KF_ITER_NEW;
6736 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6738 return meta->kfunc_flags & KF_ITER_NEXT;
6741 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6743 return meta->kfunc_flags & KF_ITER_DESTROY;
6746 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
6748 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
6749 * kfunc is iter state pointer
6751 return arg == 0 && is_iter_kfunc(meta);
6754 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
6755 struct bpf_kfunc_call_arg_meta *meta)
6757 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6758 const struct btf_type *t;
6759 const struct btf_param *arg;
6760 int spi, err, i, nr_slots;
6763 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
6764 arg = &btf_params(meta->func_proto)[0];
6765 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
6766 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
6767 nr_slots = t->size / BPF_REG_SIZE;
6769 if (is_iter_new_kfunc(meta)) {
6770 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
6771 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
6772 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
6773 iter_type_str(meta->btf, btf_id), regno);
6777 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
6778 err = check_mem_access(env, insn_idx, regno,
6779 i, BPF_DW, BPF_WRITE, -1, false);
6784 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
6788 /* iter_next() or iter_destroy() expect initialized iter state*/
6789 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
6790 verbose(env, "expected an initialized iter_%s as arg #%d\n",
6791 iter_type_str(meta->btf, btf_id), regno);
6795 spi = iter_get_spi(env, reg, nr_slots);
6799 err = mark_iter_read(env, reg, spi, nr_slots);
6803 /* remember meta->iter info for process_iter_next_call() */
6804 meta->iter.spi = spi;
6805 meta->iter.frameno = reg->frameno;
6806 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
6808 if (is_iter_destroy_kfunc(meta)) {
6809 err = unmark_stack_slots_iter(env, reg, nr_slots);
6818 /* process_iter_next_call() is called when verifier gets to iterator's next
6819 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
6820 * to it as just "iter_next()" in comments below.
6822 * BPF verifier relies on a crucial contract for any iter_next()
6823 * implementation: it should *eventually* return NULL, and once that happens
6824 * it should keep returning NULL. That is, once iterator exhausts elements to
6825 * iterate, it should never reset or spuriously return new elements.
6827 * With the assumption of such contract, process_iter_next_call() simulates
6828 * a fork in the verifier state to validate loop logic correctness and safety
6829 * without having to simulate infinite amount of iterations.
6831 * In current state, we first assume that iter_next() returned NULL and
6832 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
6833 * conditions we should not form an infinite loop and should eventually reach
6836 * Besides that, we also fork current state and enqueue it for later
6837 * verification. In a forked state we keep iterator state as ACTIVE
6838 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
6839 * also bump iteration depth to prevent erroneous infinite loop detection
6840 * later on (see iter_active_depths_differ() comment for details). In this
6841 * state we assume that we'll eventually loop back to another iter_next()
6842 * calls (it could be in exactly same location or in some other instruction,
6843 * it doesn't matter, we don't make any unnecessary assumptions about this,
6844 * everything revolves around iterator state in a stack slot, not which
6845 * instruction is calling iter_next()). When that happens, we either will come
6846 * to iter_next() with equivalent state and can conclude that next iteration
6847 * will proceed in exactly the same way as we just verified, so it's safe to
6848 * assume that loop converges. If not, we'll go on another iteration
6849 * simulation with a different input state, until all possible starting states
6850 * are validated or we reach maximum number of instructions limit.
6852 * This way, we will either exhaustively discover all possible input states
6853 * that iterator loop can start with and eventually will converge, or we'll
6854 * effectively regress into bounded loop simulation logic and either reach
6855 * maximum number of instructions if loop is not provably convergent, or there
6856 * is some statically known limit on number of iterations (e.g., if there is
6857 * an explicit `if n > 100 then break;` statement somewhere in the loop).
6859 * One very subtle but very important aspect is that we *always* simulate NULL
6860 * condition first (as the current state) before we simulate non-NULL case.
6861 * This has to do with intricacies of scalar precision tracking. By simulating
6862 * "exit condition" of iter_next() returning NULL first, we make sure all the
6863 * relevant precision marks *that will be set **after** we exit iterator loop*
6864 * are propagated backwards to common parent state of NULL and non-NULL
6865 * branches. Thanks to that, state equivalence checks done later in forked
6866 * state, when reaching iter_next() for ACTIVE iterator, can assume that
6867 * precision marks are finalized and won't change. Because simulating another
6868 * ACTIVE iterator iteration won't change them (because given same input
6869 * states we'll end up with exactly same output states which we are currently
6870 * comparing; and verification after the loop already propagated back what
6871 * needs to be **additionally** tracked as precise). It's subtle, grok
6872 * precision tracking for more intuitive understanding.
6874 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
6875 struct bpf_kfunc_call_arg_meta *meta)
6877 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
6878 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
6879 struct bpf_reg_state *cur_iter, *queued_iter;
6880 int iter_frameno = meta->iter.frameno;
6881 int iter_spi = meta->iter.spi;
6883 BTF_TYPE_EMIT(struct bpf_iter);
6885 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
6887 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
6888 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
6889 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
6890 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
6894 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
6895 /* branch out active iter state */
6896 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
6900 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
6901 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
6902 queued_iter->iter.depth++;
6904 queued_fr = queued_st->frame[queued_st->curframe];
6905 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
6908 /* switch to DRAINED state, but keep the depth unchanged */
6909 /* mark current iter state as drained and assume returned NULL */
6910 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
6911 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
6916 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6918 return type == ARG_CONST_SIZE ||
6919 type == ARG_CONST_SIZE_OR_ZERO;
6922 static bool arg_type_is_release(enum bpf_arg_type type)
6924 return type & OBJ_RELEASE;
6927 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6929 return base_type(type) == ARG_PTR_TO_DYNPTR;
6932 static int int_ptr_type_to_size(enum bpf_arg_type type)
6934 if (type == ARG_PTR_TO_INT)
6936 else if (type == ARG_PTR_TO_LONG)
6942 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6943 const struct bpf_call_arg_meta *meta,
6944 enum bpf_arg_type *arg_type)
6946 if (!meta->map_ptr) {
6947 /* kernel subsystem misconfigured verifier */
6948 verbose(env, "invalid map_ptr to access map->type\n");
6952 switch (meta->map_ptr->map_type) {
6953 case BPF_MAP_TYPE_SOCKMAP:
6954 case BPF_MAP_TYPE_SOCKHASH:
6955 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6956 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6958 verbose(env, "invalid arg_type for sockmap/sockhash\n");
6962 case BPF_MAP_TYPE_BLOOM_FILTER:
6963 if (meta->func_id == BPF_FUNC_map_peek_elem)
6964 *arg_type = ARG_PTR_TO_MAP_VALUE;
6972 struct bpf_reg_types {
6973 const enum bpf_reg_type types[10];
6977 static const struct bpf_reg_types sock_types = {
6987 static const struct bpf_reg_types btf_id_sock_common_types = {
6994 PTR_TO_BTF_ID | PTR_TRUSTED,
6996 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7000 static const struct bpf_reg_types mem_types = {
7008 PTR_TO_MEM | MEM_RINGBUF,
7010 PTR_TO_BTF_ID | PTR_TRUSTED,
7014 static const struct bpf_reg_types int_ptr_types = {
7024 static const struct bpf_reg_types spin_lock_types = {
7027 PTR_TO_BTF_ID | MEM_ALLOC,
7031 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7032 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7033 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7034 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7035 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7036 static const struct bpf_reg_types btf_ptr_types = {
7039 PTR_TO_BTF_ID | PTR_TRUSTED,
7040 PTR_TO_BTF_ID | MEM_RCU,
7043 static const struct bpf_reg_types percpu_btf_ptr_types = {
7045 PTR_TO_BTF_ID | MEM_PERCPU,
7046 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7049 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7050 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7051 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7052 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7053 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7054 static const struct bpf_reg_types dynptr_types = {
7057 CONST_PTR_TO_DYNPTR,
7061 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7062 [ARG_PTR_TO_MAP_KEY] = &mem_types,
7063 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
7064 [ARG_CONST_SIZE] = &scalar_types,
7065 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
7066 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
7067 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
7068 [ARG_PTR_TO_CTX] = &context_types,
7069 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
7071 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7073 [ARG_PTR_TO_SOCKET] = &fullsock_types,
7074 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
7075 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
7076 [ARG_PTR_TO_MEM] = &mem_types,
7077 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
7078 [ARG_PTR_TO_INT] = &int_ptr_types,
7079 [ARG_PTR_TO_LONG] = &int_ptr_types,
7080 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
7081 [ARG_PTR_TO_FUNC] = &func_ptr_types,
7082 [ARG_PTR_TO_STACK] = &stack_ptr_types,
7083 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
7084 [ARG_PTR_TO_TIMER] = &timer_types,
7085 [ARG_PTR_TO_KPTR] = &kptr_types,
7086 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
7089 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7090 enum bpf_arg_type arg_type,
7091 const u32 *arg_btf_id,
7092 struct bpf_call_arg_meta *meta)
7094 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7095 enum bpf_reg_type expected, type = reg->type;
7096 const struct bpf_reg_types *compatible;
7099 compatible = compatible_reg_types[base_type(arg_type)];
7101 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7105 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7106 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7108 * Same for MAYBE_NULL:
7110 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7111 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7113 * Therefore we fold these flags depending on the arg_type before comparison.
7115 if (arg_type & MEM_RDONLY)
7116 type &= ~MEM_RDONLY;
7117 if (arg_type & PTR_MAYBE_NULL)
7118 type &= ~PTR_MAYBE_NULL;
7120 if (meta->func_id == BPF_FUNC_kptr_xchg && type & MEM_ALLOC)
7123 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7124 expected = compatible->types[i];
7125 if (expected == NOT_INIT)
7128 if (type == expected)
7132 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7133 for (j = 0; j + 1 < i; j++)
7134 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7135 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7139 if (base_type(reg->type) != PTR_TO_BTF_ID)
7142 if (compatible == &mem_types) {
7143 if (!(arg_type & MEM_RDONLY)) {
7145 "%s() may write into memory pointed by R%d type=%s\n",
7146 func_id_name(meta->func_id),
7147 regno, reg_type_str(env, reg->type));
7153 switch ((int)reg->type) {
7155 case PTR_TO_BTF_ID | PTR_TRUSTED:
7156 case PTR_TO_BTF_ID | MEM_RCU:
7157 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7158 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7160 /* For bpf_sk_release, it needs to match against first member
7161 * 'struct sock_common', hence make an exception for it. This
7162 * allows bpf_sk_release to work for multiple socket types.
7164 bool strict_type_match = arg_type_is_release(arg_type) &&
7165 meta->func_id != BPF_FUNC_sk_release;
7167 if (type_may_be_null(reg->type) &&
7168 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7169 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7174 if (!compatible->btf_id) {
7175 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7178 arg_btf_id = compatible->btf_id;
7181 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7182 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7185 if (arg_btf_id == BPF_PTR_POISON) {
7186 verbose(env, "verifier internal error:");
7187 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7192 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7193 btf_vmlinux, *arg_btf_id,
7194 strict_type_match)) {
7195 verbose(env, "R%d is of type %s but %s is expected\n",
7196 regno, btf_type_name(reg->btf, reg->btf_id),
7197 btf_type_name(btf_vmlinux, *arg_btf_id));
7203 case PTR_TO_BTF_ID | MEM_ALLOC:
7204 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7205 meta->func_id != BPF_FUNC_kptr_xchg) {
7206 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7209 /* Handled by helper specific checks */
7211 case PTR_TO_BTF_ID | MEM_PERCPU:
7212 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7213 /* Handled by helper specific checks */
7216 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7222 static struct btf_field *
7223 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7225 struct btf_field *field;
7226 struct btf_record *rec;
7228 rec = reg_btf_record(reg);
7232 field = btf_record_find(rec, off, fields);
7239 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7240 const struct bpf_reg_state *reg, int regno,
7241 enum bpf_arg_type arg_type)
7243 u32 type = reg->type;
7245 /* When referenced register is passed to release function, its fixed
7248 * We will check arg_type_is_release reg has ref_obj_id when storing
7249 * meta->release_regno.
7251 if (arg_type_is_release(arg_type)) {
7252 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7253 * may not directly point to the object being released, but to
7254 * dynptr pointing to such object, which might be at some offset
7255 * on the stack. In that case, we simply to fallback to the
7258 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7261 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7262 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7263 return __check_ptr_off_reg(env, reg, regno, true);
7265 verbose(env, "R%d must have zero offset when passed to release func\n",
7267 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7268 btf_type_name(reg->btf, reg->btf_id), reg->off);
7272 /* Doing check_ptr_off_reg check for the offset will catch this
7273 * because fixed_off_ok is false, but checking here allows us
7274 * to give the user a better error message.
7277 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7281 return __check_ptr_off_reg(env, reg, regno, false);
7285 /* Pointer types where both fixed and variable offset is explicitly allowed: */
7288 case PTR_TO_PACKET_META:
7289 case PTR_TO_MAP_KEY:
7290 case PTR_TO_MAP_VALUE:
7292 case PTR_TO_MEM | MEM_RDONLY:
7293 case PTR_TO_MEM | MEM_RINGBUF:
7295 case PTR_TO_BUF | MEM_RDONLY:
7298 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7302 case PTR_TO_BTF_ID | MEM_ALLOC:
7303 case PTR_TO_BTF_ID | PTR_TRUSTED:
7304 case PTR_TO_BTF_ID | MEM_RCU:
7305 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7306 /* When referenced PTR_TO_BTF_ID is passed to release function,
7307 * its fixed offset must be 0. In the other cases, fixed offset
7308 * can be non-zero. This was already checked above. So pass
7309 * fixed_off_ok as true to allow fixed offset for all other
7310 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7311 * still need to do checks instead of returning.
7313 return __check_ptr_off_reg(env, reg, regno, true);
7315 return __check_ptr_off_reg(env, reg, regno, false);
7319 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7320 const struct bpf_func_proto *fn,
7321 struct bpf_reg_state *regs)
7323 struct bpf_reg_state *state = NULL;
7326 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7327 if (arg_type_is_dynptr(fn->arg_type[i])) {
7329 verbose(env, "verifier internal error: multiple dynptr args\n");
7332 state = ®s[BPF_REG_1 + i];
7336 verbose(env, "verifier internal error: no dynptr arg found\n");
7341 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7343 struct bpf_func_state *state = func(env, reg);
7346 if (reg->type == CONST_PTR_TO_DYNPTR)
7348 spi = dynptr_get_spi(env, reg);
7351 return state->stack[spi].spilled_ptr.id;
7354 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7356 struct bpf_func_state *state = func(env, reg);
7359 if (reg->type == CONST_PTR_TO_DYNPTR)
7360 return reg->ref_obj_id;
7361 spi = dynptr_get_spi(env, reg);
7364 return state->stack[spi].spilled_ptr.ref_obj_id;
7367 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
7368 struct bpf_reg_state *reg)
7370 struct bpf_func_state *state = func(env, reg);
7373 if (reg->type == CONST_PTR_TO_DYNPTR)
7374 return reg->dynptr.type;
7376 spi = __get_spi(reg->off);
7378 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
7379 return BPF_DYNPTR_TYPE_INVALID;
7382 return state->stack[spi].spilled_ptr.dynptr.type;
7385 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
7386 struct bpf_call_arg_meta *meta,
7387 const struct bpf_func_proto *fn,
7390 u32 regno = BPF_REG_1 + arg;
7391 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7392 enum bpf_arg_type arg_type = fn->arg_type[arg];
7393 enum bpf_reg_type type = reg->type;
7394 u32 *arg_btf_id = NULL;
7397 if (arg_type == ARG_DONTCARE)
7400 err = check_reg_arg(env, regno, SRC_OP);
7404 if (arg_type == ARG_ANYTHING) {
7405 if (is_pointer_value(env, regno)) {
7406 verbose(env, "R%d leaks addr into helper function\n",
7413 if (type_is_pkt_pointer(type) &&
7414 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
7415 verbose(env, "helper access to the packet is not allowed\n");
7419 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
7420 err = resolve_map_arg_type(env, meta, &arg_type);
7425 if (register_is_null(reg) && type_may_be_null(arg_type))
7426 /* A NULL register has a SCALAR_VALUE type, so skip
7429 goto skip_type_check;
7431 /* arg_btf_id and arg_size are in a union. */
7432 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7433 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
7434 arg_btf_id = fn->arg_btf_id[arg];
7436 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7440 err = check_func_arg_reg_off(env, reg, regno, arg_type);
7445 if (arg_type_is_release(arg_type)) {
7446 if (arg_type_is_dynptr(arg_type)) {
7447 struct bpf_func_state *state = func(env, reg);
7450 /* Only dynptr created on stack can be released, thus
7451 * the get_spi and stack state checks for spilled_ptr
7452 * should only be done before process_dynptr_func for
7455 if (reg->type == PTR_TO_STACK) {
7456 spi = dynptr_get_spi(env, reg);
7457 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7458 verbose(env, "arg %d is an unacquired reference\n", regno);
7462 verbose(env, "cannot release unowned const bpf_dynptr\n");
7465 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
7466 verbose(env, "R%d must be referenced when passed to release function\n",
7470 if (meta->release_regno) {
7471 verbose(env, "verifier internal error: more than one release argument\n");
7474 meta->release_regno = regno;
7477 if (reg->ref_obj_id) {
7478 if (meta->ref_obj_id) {
7479 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
7480 regno, reg->ref_obj_id,
7484 meta->ref_obj_id = reg->ref_obj_id;
7487 switch (base_type(arg_type)) {
7488 case ARG_CONST_MAP_PTR:
7489 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
7490 if (meta->map_ptr) {
7491 /* Use map_uid (which is unique id of inner map) to reject:
7492 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
7493 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
7494 * if (inner_map1 && inner_map2) {
7495 * timer = bpf_map_lookup_elem(inner_map1);
7497 * // mismatch would have been allowed
7498 * bpf_timer_init(timer, inner_map2);
7501 * Comparing map_ptr is enough to distinguish normal and outer maps.
7503 if (meta->map_ptr != reg->map_ptr ||
7504 meta->map_uid != reg->map_uid) {
7506 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
7507 meta->map_uid, reg->map_uid);
7511 meta->map_ptr = reg->map_ptr;
7512 meta->map_uid = reg->map_uid;
7514 case ARG_PTR_TO_MAP_KEY:
7515 /* bpf_map_xxx(..., map_ptr, ..., key) call:
7516 * check that [key, key + map->key_size) are within
7517 * stack limits and initialized
7519 if (!meta->map_ptr) {
7520 /* in function declaration map_ptr must come before
7521 * map_key, so that it's verified and known before
7522 * we have to check map_key here. Otherwise it means
7523 * that kernel subsystem misconfigured verifier
7525 verbose(env, "invalid map_ptr to access map->key\n");
7528 err = check_helper_mem_access(env, regno,
7529 meta->map_ptr->key_size, false,
7532 case ARG_PTR_TO_MAP_VALUE:
7533 if (type_may_be_null(arg_type) && register_is_null(reg))
7536 /* bpf_map_xxx(..., map_ptr, ..., value) call:
7537 * check [value, value + map->value_size) validity
7539 if (!meta->map_ptr) {
7540 /* kernel subsystem misconfigured verifier */
7541 verbose(env, "invalid map_ptr to access map->value\n");
7544 meta->raw_mode = arg_type & MEM_UNINIT;
7545 err = check_helper_mem_access(env, regno,
7546 meta->map_ptr->value_size, false,
7549 case ARG_PTR_TO_PERCPU_BTF_ID:
7551 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
7554 meta->ret_btf = reg->btf;
7555 meta->ret_btf_id = reg->btf_id;
7557 case ARG_PTR_TO_SPIN_LOCK:
7558 if (in_rbtree_lock_required_cb(env)) {
7559 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
7562 if (meta->func_id == BPF_FUNC_spin_lock) {
7563 err = process_spin_lock(env, regno, true);
7566 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
7567 err = process_spin_lock(env, regno, false);
7571 verbose(env, "verifier internal error\n");
7575 case ARG_PTR_TO_TIMER:
7576 err = process_timer_func(env, regno, meta);
7580 case ARG_PTR_TO_FUNC:
7581 meta->subprogno = reg->subprogno;
7583 case ARG_PTR_TO_MEM:
7584 /* The access to this pointer is only checked when we hit the
7585 * next is_mem_size argument below.
7587 meta->raw_mode = arg_type & MEM_UNINIT;
7588 if (arg_type & MEM_FIXED_SIZE) {
7589 err = check_helper_mem_access(env, regno,
7590 fn->arg_size[arg], false,
7594 case ARG_CONST_SIZE:
7595 err = check_mem_size_reg(env, reg, regno, false, meta);
7597 case ARG_CONST_SIZE_OR_ZERO:
7598 err = check_mem_size_reg(env, reg, regno, true, meta);
7600 case ARG_PTR_TO_DYNPTR:
7601 err = process_dynptr_func(env, regno, insn_idx, arg_type);
7605 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
7606 if (!tnum_is_const(reg->var_off)) {
7607 verbose(env, "R%d is not a known constant'\n",
7611 meta->mem_size = reg->var_off.value;
7612 err = mark_chain_precision(env, regno);
7616 case ARG_PTR_TO_INT:
7617 case ARG_PTR_TO_LONG:
7619 int size = int_ptr_type_to_size(arg_type);
7621 err = check_helper_mem_access(env, regno, size, false, meta);
7624 err = check_ptr_alignment(env, reg, 0, size, true);
7627 case ARG_PTR_TO_CONST_STR:
7629 struct bpf_map *map = reg->map_ptr;
7634 if (!bpf_map_is_rdonly(map)) {
7635 verbose(env, "R%d does not point to a readonly map'\n", regno);
7639 if (!tnum_is_const(reg->var_off)) {
7640 verbose(env, "R%d is not a constant address'\n", regno);
7644 if (!map->ops->map_direct_value_addr) {
7645 verbose(env, "no direct value access support for this map type\n");
7649 err = check_map_access(env, regno, reg->off,
7650 map->value_size - reg->off, false,
7655 map_off = reg->off + reg->var_off.value;
7656 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
7658 verbose(env, "direct value access on string failed\n");
7662 str_ptr = (char *)(long)(map_addr);
7663 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
7664 verbose(env, "string is not zero-terminated\n");
7669 case ARG_PTR_TO_KPTR:
7670 err = process_kptr_func(env, regno, meta);
7679 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
7681 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7682 enum bpf_prog_type type = resolve_prog_type(env->prog);
7684 if (func_id != BPF_FUNC_map_update_elem)
7687 /* It's not possible to get access to a locked struct sock in these
7688 * contexts, so updating is safe.
7691 case BPF_PROG_TYPE_TRACING:
7692 if (eatype == BPF_TRACE_ITER)
7695 case BPF_PROG_TYPE_SOCKET_FILTER:
7696 case BPF_PROG_TYPE_SCHED_CLS:
7697 case BPF_PROG_TYPE_SCHED_ACT:
7698 case BPF_PROG_TYPE_XDP:
7699 case BPF_PROG_TYPE_SK_REUSEPORT:
7700 case BPF_PROG_TYPE_FLOW_DISSECTOR:
7701 case BPF_PROG_TYPE_SK_LOOKUP:
7707 verbose(env, "cannot update sockmap in this context\n");
7711 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
7713 return env->prog->jit_requested &&
7714 bpf_jit_supports_subprog_tailcalls();
7717 static int check_map_func_compatibility(struct bpf_verifier_env *env,
7718 struct bpf_map *map, int func_id)
7723 /* We need a two way check, first is from map perspective ... */
7724 switch (map->map_type) {
7725 case BPF_MAP_TYPE_PROG_ARRAY:
7726 if (func_id != BPF_FUNC_tail_call)
7729 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
7730 if (func_id != BPF_FUNC_perf_event_read &&
7731 func_id != BPF_FUNC_perf_event_output &&
7732 func_id != BPF_FUNC_skb_output &&
7733 func_id != BPF_FUNC_perf_event_read_value &&
7734 func_id != BPF_FUNC_xdp_output)
7737 case BPF_MAP_TYPE_RINGBUF:
7738 if (func_id != BPF_FUNC_ringbuf_output &&
7739 func_id != BPF_FUNC_ringbuf_reserve &&
7740 func_id != BPF_FUNC_ringbuf_query &&
7741 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
7742 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
7743 func_id != BPF_FUNC_ringbuf_discard_dynptr)
7746 case BPF_MAP_TYPE_USER_RINGBUF:
7747 if (func_id != BPF_FUNC_user_ringbuf_drain)
7750 case BPF_MAP_TYPE_STACK_TRACE:
7751 if (func_id != BPF_FUNC_get_stackid)
7754 case BPF_MAP_TYPE_CGROUP_ARRAY:
7755 if (func_id != BPF_FUNC_skb_under_cgroup &&
7756 func_id != BPF_FUNC_current_task_under_cgroup)
7759 case BPF_MAP_TYPE_CGROUP_STORAGE:
7760 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
7761 if (func_id != BPF_FUNC_get_local_storage)
7764 case BPF_MAP_TYPE_DEVMAP:
7765 case BPF_MAP_TYPE_DEVMAP_HASH:
7766 if (func_id != BPF_FUNC_redirect_map &&
7767 func_id != BPF_FUNC_map_lookup_elem)
7770 /* Restrict bpf side of cpumap and xskmap, open when use-cases
7773 case BPF_MAP_TYPE_CPUMAP:
7774 if (func_id != BPF_FUNC_redirect_map)
7777 case BPF_MAP_TYPE_XSKMAP:
7778 if (func_id != BPF_FUNC_redirect_map &&
7779 func_id != BPF_FUNC_map_lookup_elem)
7782 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
7783 case BPF_MAP_TYPE_HASH_OF_MAPS:
7784 if (func_id != BPF_FUNC_map_lookup_elem)
7787 case BPF_MAP_TYPE_SOCKMAP:
7788 if (func_id != BPF_FUNC_sk_redirect_map &&
7789 func_id != BPF_FUNC_sock_map_update &&
7790 func_id != BPF_FUNC_map_delete_elem &&
7791 func_id != BPF_FUNC_msg_redirect_map &&
7792 func_id != BPF_FUNC_sk_select_reuseport &&
7793 func_id != BPF_FUNC_map_lookup_elem &&
7794 !may_update_sockmap(env, func_id))
7797 case BPF_MAP_TYPE_SOCKHASH:
7798 if (func_id != BPF_FUNC_sk_redirect_hash &&
7799 func_id != BPF_FUNC_sock_hash_update &&
7800 func_id != BPF_FUNC_map_delete_elem &&
7801 func_id != BPF_FUNC_msg_redirect_hash &&
7802 func_id != BPF_FUNC_sk_select_reuseport &&
7803 func_id != BPF_FUNC_map_lookup_elem &&
7804 !may_update_sockmap(env, func_id))
7807 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
7808 if (func_id != BPF_FUNC_sk_select_reuseport)
7811 case BPF_MAP_TYPE_QUEUE:
7812 case BPF_MAP_TYPE_STACK:
7813 if (func_id != BPF_FUNC_map_peek_elem &&
7814 func_id != BPF_FUNC_map_pop_elem &&
7815 func_id != BPF_FUNC_map_push_elem)
7818 case BPF_MAP_TYPE_SK_STORAGE:
7819 if (func_id != BPF_FUNC_sk_storage_get &&
7820 func_id != BPF_FUNC_sk_storage_delete &&
7821 func_id != BPF_FUNC_kptr_xchg)
7824 case BPF_MAP_TYPE_INODE_STORAGE:
7825 if (func_id != BPF_FUNC_inode_storage_get &&
7826 func_id != BPF_FUNC_inode_storage_delete &&
7827 func_id != BPF_FUNC_kptr_xchg)
7830 case BPF_MAP_TYPE_TASK_STORAGE:
7831 if (func_id != BPF_FUNC_task_storage_get &&
7832 func_id != BPF_FUNC_task_storage_delete &&
7833 func_id != BPF_FUNC_kptr_xchg)
7836 case BPF_MAP_TYPE_CGRP_STORAGE:
7837 if (func_id != BPF_FUNC_cgrp_storage_get &&
7838 func_id != BPF_FUNC_cgrp_storage_delete &&
7839 func_id != BPF_FUNC_kptr_xchg)
7842 case BPF_MAP_TYPE_BLOOM_FILTER:
7843 if (func_id != BPF_FUNC_map_peek_elem &&
7844 func_id != BPF_FUNC_map_push_elem)
7851 /* ... and second from the function itself. */
7853 case BPF_FUNC_tail_call:
7854 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
7856 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
7857 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
7861 case BPF_FUNC_perf_event_read:
7862 case BPF_FUNC_perf_event_output:
7863 case BPF_FUNC_perf_event_read_value:
7864 case BPF_FUNC_skb_output:
7865 case BPF_FUNC_xdp_output:
7866 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
7869 case BPF_FUNC_ringbuf_output:
7870 case BPF_FUNC_ringbuf_reserve:
7871 case BPF_FUNC_ringbuf_query:
7872 case BPF_FUNC_ringbuf_reserve_dynptr:
7873 case BPF_FUNC_ringbuf_submit_dynptr:
7874 case BPF_FUNC_ringbuf_discard_dynptr:
7875 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
7878 case BPF_FUNC_user_ringbuf_drain:
7879 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
7882 case BPF_FUNC_get_stackid:
7883 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
7886 case BPF_FUNC_current_task_under_cgroup:
7887 case BPF_FUNC_skb_under_cgroup:
7888 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
7891 case BPF_FUNC_redirect_map:
7892 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
7893 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
7894 map->map_type != BPF_MAP_TYPE_CPUMAP &&
7895 map->map_type != BPF_MAP_TYPE_XSKMAP)
7898 case BPF_FUNC_sk_redirect_map:
7899 case BPF_FUNC_msg_redirect_map:
7900 case BPF_FUNC_sock_map_update:
7901 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
7904 case BPF_FUNC_sk_redirect_hash:
7905 case BPF_FUNC_msg_redirect_hash:
7906 case BPF_FUNC_sock_hash_update:
7907 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
7910 case BPF_FUNC_get_local_storage:
7911 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
7912 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
7915 case BPF_FUNC_sk_select_reuseport:
7916 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
7917 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
7918 map->map_type != BPF_MAP_TYPE_SOCKHASH)
7921 case BPF_FUNC_map_pop_elem:
7922 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7923 map->map_type != BPF_MAP_TYPE_STACK)
7926 case BPF_FUNC_map_peek_elem:
7927 case BPF_FUNC_map_push_elem:
7928 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7929 map->map_type != BPF_MAP_TYPE_STACK &&
7930 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
7933 case BPF_FUNC_map_lookup_percpu_elem:
7934 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
7935 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7936 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
7939 case BPF_FUNC_sk_storage_get:
7940 case BPF_FUNC_sk_storage_delete:
7941 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
7944 case BPF_FUNC_inode_storage_get:
7945 case BPF_FUNC_inode_storage_delete:
7946 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
7949 case BPF_FUNC_task_storage_get:
7950 case BPF_FUNC_task_storage_delete:
7951 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
7954 case BPF_FUNC_cgrp_storage_get:
7955 case BPF_FUNC_cgrp_storage_delete:
7956 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
7965 verbose(env, "cannot pass map_type %d into func %s#%d\n",
7966 map->map_type, func_id_name(func_id), func_id);
7970 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
7974 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
7976 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
7978 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
7980 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
7982 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
7985 /* We only support one arg being in raw mode at the moment,
7986 * which is sufficient for the helper functions we have
7992 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
7994 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
7995 bool has_size = fn->arg_size[arg] != 0;
7996 bool is_next_size = false;
7998 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
7999 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8001 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8002 return is_next_size;
8004 return has_size == is_next_size || is_next_size == is_fixed;
8007 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8009 /* bpf_xxx(..., buf, len) call will access 'len'
8010 * bytes from memory 'buf'. Both arg types need
8011 * to be paired, so make sure there's no buggy
8012 * helper function specification.
8014 if (arg_type_is_mem_size(fn->arg1_type) ||
8015 check_args_pair_invalid(fn, 0) ||
8016 check_args_pair_invalid(fn, 1) ||
8017 check_args_pair_invalid(fn, 2) ||
8018 check_args_pair_invalid(fn, 3) ||
8019 check_args_pair_invalid(fn, 4))
8025 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8029 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8030 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8031 return !!fn->arg_btf_id[i];
8032 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8033 return fn->arg_btf_id[i] == BPF_PTR_POISON;
8034 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8035 /* arg_btf_id and arg_size are in a union. */
8036 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8037 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8044 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8046 return check_raw_mode_ok(fn) &&
8047 check_arg_pair_ok(fn) &&
8048 check_btf_id_ok(fn) ? 0 : -EINVAL;
8051 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8052 * are now invalid, so turn them into unknown SCALAR_VALUE.
8054 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8055 * since these slices point to packet data.
8057 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8059 struct bpf_func_state *state;
8060 struct bpf_reg_state *reg;
8062 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8063 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8064 mark_reg_invalid(env, reg);
8070 BEYOND_PKT_END = -2,
8073 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8075 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8076 struct bpf_reg_state *reg = &state->regs[regn];
8078 if (reg->type != PTR_TO_PACKET)
8079 /* PTR_TO_PACKET_META is not supported yet */
8082 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8083 * How far beyond pkt_end it goes is unknown.
8084 * if (!range_open) it's the case of pkt >= pkt_end
8085 * if (range_open) it's the case of pkt > pkt_end
8086 * hence this pointer is at least 1 byte bigger than pkt_end
8089 reg->range = BEYOND_PKT_END;
8091 reg->range = AT_PKT_END;
8094 /* The pointer with the specified id has released its reference to kernel
8095 * resources. Identify all copies of the same pointer and clear the reference.
8097 static int release_reference(struct bpf_verifier_env *env,
8100 struct bpf_func_state *state;
8101 struct bpf_reg_state *reg;
8104 err = release_reference_state(cur_func(env), ref_obj_id);
8108 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8109 if (reg->ref_obj_id == ref_obj_id)
8110 mark_reg_invalid(env, reg);
8116 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8118 struct bpf_func_state *unused;
8119 struct bpf_reg_state *reg;
8121 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8122 if (type_is_non_owning_ref(reg->type))
8123 mark_reg_invalid(env, reg);
8127 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8128 struct bpf_reg_state *regs)
8132 /* after the call registers r0 - r5 were scratched */
8133 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8134 mark_reg_not_init(env, regs, caller_saved[i]);
8135 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8139 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8140 struct bpf_func_state *caller,
8141 struct bpf_func_state *callee,
8144 static int set_callee_state(struct bpf_verifier_env *env,
8145 struct bpf_func_state *caller,
8146 struct bpf_func_state *callee, int insn_idx);
8148 static bool is_callback_calling_kfunc(u32 btf_id);
8150 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8151 int *insn_idx, int subprog,
8152 set_callee_state_fn set_callee_state_cb)
8154 struct bpf_verifier_state *state = env->cur_state;
8155 struct bpf_func_info_aux *func_info_aux;
8156 struct bpf_func_state *caller, *callee;
8158 bool is_global = false;
8160 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8161 verbose(env, "the call stack of %d frames is too deep\n",
8162 state->curframe + 2);
8166 caller = state->frame[state->curframe];
8167 if (state->frame[state->curframe + 1]) {
8168 verbose(env, "verifier bug. Frame %d already allocated\n",
8169 state->curframe + 1);
8173 func_info_aux = env->prog->aux->func_info_aux;
8175 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
8176 err = btf_check_subprog_call(env, subprog, caller->regs);
8181 verbose(env, "Caller passes invalid args into func#%d\n",
8185 if (env->log.level & BPF_LOG_LEVEL)
8187 "Func#%d is global and valid. Skipping.\n",
8189 clear_caller_saved_regs(env, caller->regs);
8191 /* All global functions return a 64-bit SCALAR_VALUE */
8192 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8193 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8195 /* continue with next insn after call */
8200 /* set_callee_state is used for direct subprog calls, but we are
8201 * interested in validating only BPF helpers that can call subprogs as
8204 if (set_callee_state_cb != set_callee_state) {
8205 if (bpf_pseudo_kfunc_call(insn) &&
8206 !is_callback_calling_kfunc(insn->imm)) {
8207 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8208 func_id_name(insn->imm), insn->imm);
8210 } else if (!bpf_pseudo_kfunc_call(insn) &&
8211 !is_callback_calling_function(insn->imm)) { /* helper */
8212 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8213 func_id_name(insn->imm), insn->imm);
8218 if (insn->code == (BPF_JMP | BPF_CALL) &&
8219 insn->src_reg == 0 &&
8220 insn->imm == BPF_FUNC_timer_set_callback) {
8221 struct bpf_verifier_state *async_cb;
8223 /* there is no real recursion here. timer callbacks are async */
8224 env->subprog_info[subprog].is_async_cb = true;
8225 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8226 *insn_idx, subprog);
8229 callee = async_cb->frame[0];
8230 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8232 /* Convert bpf_timer_set_callback() args into timer callback args */
8233 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8237 clear_caller_saved_regs(env, caller->regs);
8238 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8239 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8240 /* continue with next insn after call */
8244 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8247 state->frame[state->curframe + 1] = callee;
8249 /* callee cannot access r0, r6 - r9 for reading and has to write
8250 * into its own stack before reading from it.
8251 * callee can read/write into caller's stack
8253 init_func_state(env, callee,
8254 /* remember the callsite, it will be used by bpf_exit */
8255 *insn_idx /* callsite */,
8256 state->curframe + 1 /* frameno within this callchain */,
8257 subprog /* subprog number within this prog */);
8259 /* Transfer references to the callee */
8260 err = copy_reference_state(callee, caller);
8264 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8268 clear_caller_saved_regs(env, caller->regs);
8270 /* only increment it after check_reg_arg() finished */
8273 /* and go analyze first insn of the callee */
8274 *insn_idx = env->subprog_info[subprog].start - 1;
8276 if (env->log.level & BPF_LOG_LEVEL) {
8277 verbose(env, "caller:\n");
8278 print_verifier_state(env, caller, true);
8279 verbose(env, "callee:\n");
8280 print_verifier_state(env, callee, true);
8285 free_func_state(callee);
8286 state->frame[state->curframe + 1] = NULL;
8290 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8291 struct bpf_func_state *caller,
8292 struct bpf_func_state *callee)
8294 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8295 * void *callback_ctx, u64 flags);
8296 * callback_fn(struct bpf_map *map, void *key, void *value,
8297 * void *callback_ctx);
8299 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8301 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8302 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8303 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8305 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8306 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8307 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8309 /* pointer to stack or null */
8310 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8313 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8317 static int set_callee_state(struct bpf_verifier_env *env,
8318 struct bpf_func_state *caller,
8319 struct bpf_func_state *callee, int insn_idx)
8323 /* copy r1 - r5 args that callee can access. The copy includes parent
8324 * pointers, which connects us up to the liveness chain
8326 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8327 callee->regs[i] = caller->regs[i];
8331 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8334 int subprog, target_insn;
8336 target_insn = *insn_idx + insn->imm + 1;
8337 subprog = find_subprog(env, target_insn);
8339 verbose(env, "verifier bug. No program starts at insn %d\n",
8344 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8347 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8348 struct bpf_func_state *caller,
8349 struct bpf_func_state *callee,
8352 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8353 struct bpf_map *map;
8356 if (bpf_map_ptr_poisoned(insn_aux)) {
8357 verbose(env, "tail_call abusing map_ptr\n");
8361 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8362 if (!map->ops->map_set_for_each_callback_args ||
8363 !map->ops->map_for_each_callback) {
8364 verbose(env, "callback function not allowed for map\n");
8368 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
8372 callee->in_callback_fn = true;
8373 callee->callback_ret_range = tnum_range(0, 1);
8377 static int set_loop_callback_state(struct bpf_verifier_env *env,
8378 struct bpf_func_state *caller,
8379 struct bpf_func_state *callee,
8382 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
8384 * callback_fn(u32 index, void *callback_ctx);
8386 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
8387 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8390 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8391 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8392 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8394 callee->in_callback_fn = true;
8395 callee->callback_ret_range = tnum_range(0, 1);
8399 static int set_timer_callback_state(struct bpf_verifier_env *env,
8400 struct bpf_func_state *caller,
8401 struct bpf_func_state *callee,
8404 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
8406 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
8407 * callback_fn(struct bpf_map *map, void *key, void *value);
8409 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
8410 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
8411 callee->regs[BPF_REG_1].map_ptr = map_ptr;
8413 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8414 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8415 callee->regs[BPF_REG_2].map_ptr = map_ptr;
8417 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8418 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8419 callee->regs[BPF_REG_3].map_ptr = map_ptr;
8422 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8423 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8424 callee->in_async_callback_fn = true;
8425 callee->callback_ret_range = tnum_range(0, 1);
8429 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
8430 struct bpf_func_state *caller,
8431 struct bpf_func_state *callee,
8434 /* bpf_find_vma(struct task_struct *task, u64 addr,
8435 * void *callback_fn, void *callback_ctx, u64 flags)
8436 * (callback_fn)(struct task_struct *task,
8437 * struct vm_area_struct *vma, void *callback_ctx);
8439 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8441 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8442 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8443 callee->regs[BPF_REG_2].btf = btf_vmlinux;
8444 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8446 /* pointer to stack or null */
8447 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8450 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8451 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8452 callee->in_callback_fn = true;
8453 callee->callback_ret_range = tnum_range(0, 1);
8457 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8458 struct bpf_func_state *caller,
8459 struct bpf_func_state *callee,
8462 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8463 * callback_ctx, u64 flags);
8464 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8466 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
8467 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
8468 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8471 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8472 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8473 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8475 callee->in_callback_fn = true;
8476 callee->callback_ret_range = tnum_range(0, 1);
8480 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
8481 struct bpf_func_state *caller,
8482 struct bpf_func_state *callee,
8485 /* void bpf_rbtree_add(struct bpf_rb_root *root, struct bpf_rb_node *node,
8486 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
8488 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add is the same PTR_TO_BTF_ID w/ offset
8489 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
8490 * by this point, so look at 'root'
8492 struct btf_field *field;
8494 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
8496 if (!field || !field->graph_root.value_btf_id)
8499 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
8500 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
8501 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
8502 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
8504 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8505 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8506 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8507 callee->in_callback_fn = true;
8508 callee->callback_ret_range = tnum_range(0, 1);
8512 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
8514 /* Are we currently verifying the callback for a rbtree helper that must
8515 * be called with lock held? If so, no need to complain about unreleased
8518 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
8520 struct bpf_verifier_state *state = env->cur_state;
8521 struct bpf_insn *insn = env->prog->insnsi;
8522 struct bpf_func_state *callee;
8525 if (!state->curframe)
8528 callee = state->frame[state->curframe];
8530 if (!callee->in_callback_fn)
8533 kfunc_btf_id = insn[callee->callsite].imm;
8534 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
8537 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
8539 struct bpf_verifier_state *state = env->cur_state;
8540 struct bpf_func_state *caller, *callee;
8541 struct bpf_reg_state *r0;
8544 callee = state->frame[state->curframe];
8545 r0 = &callee->regs[BPF_REG_0];
8546 if (r0->type == PTR_TO_STACK) {
8547 /* technically it's ok to return caller's stack pointer
8548 * (or caller's caller's pointer) back to the caller,
8549 * since these pointers are valid. Only current stack
8550 * pointer will be invalid as soon as function exits,
8551 * but let's be conservative
8553 verbose(env, "cannot return stack pointer to the caller\n");
8557 caller = state->frame[state->curframe - 1];
8558 if (callee->in_callback_fn) {
8559 /* enforce R0 return value range [0, 1]. */
8560 struct tnum range = callee->callback_ret_range;
8562 if (r0->type != SCALAR_VALUE) {
8563 verbose(env, "R0 not a scalar value\n");
8566 if (!tnum_in(range, r0->var_off)) {
8567 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
8571 /* return to the caller whatever r0 had in the callee */
8572 caller->regs[BPF_REG_0] = *r0;
8575 /* callback_fn frame should have released its own additions to parent's
8576 * reference state at this point, or check_reference_leak would
8577 * complain, hence it must be the same as the caller. There is no need
8580 if (!callee->in_callback_fn) {
8581 /* Transfer references to the caller */
8582 err = copy_reference_state(caller, callee);
8587 *insn_idx = callee->callsite + 1;
8588 if (env->log.level & BPF_LOG_LEVEL) {
8589 verbose(env, "returning from callee:\n");
8590 print_verifier_state(env, callee, true);
8591 verbose(env, "to caller at %d:\n", *insn_idx);
8592 print_verifier_state(env, caller, true);
8594 /* clear everything in the callee */
8595 free_func_state(callee);
8596 state->frame[state->curframe--] = NULL;
8600 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
8602 struct bpf_call_arg_meta *meta)
8604 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
8606 if (ret_type != RET_INTEGER ||
8607 (func_id != BPF_FUNC_get_stack &&
8608 func_id != BPF_FUNC_get_task_stack &&
8609 func_id != BPF_FUNC_probe_read_str &&
8610 func_id != BPF_FUNC_probe_read_kernel_str &&
8611 func_id != BPF_FUNC_probe_read_user_str))
8614 ret_reg->smax_value = meta->msize_max_value;
8615 ret_reg->s32_max_value = meta->msize_max_value;
8616 ret_reg->smin_value = -MAX_ERRNO;
8617 ret_reg->s32_min_value = -MAX_ERRNO;
8618 reg_bounds_sync(ret_reg);
8622 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8623 int func_id, int insn_idx)
8625 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8626 struct bpf_map *map = meta->map_ptr;
8628 if (func_id != BPF_FUNC_tail_call &&
8629 func_id != BPF_FUNC_map_lookup_elem &&
8630 func_id != BPF_FUNC_map_update_elem &&
8631 func_id != BPF_FUNC_map_delete_elem &&
8632 func_id != BPF_FUNC_map_push_elem &&
8633 func_id != BPF_FUNC_map_pop_elem &&
8634 func_id != BPF_FUNC_map_peek_elem &&
8635 func_id != BPF_FUNC_for_each_map_elem &&
8636 func_id != BPF_FUNC_redirect_map &&
8637 func_id != BPF_FUNC_map_lookup_percpu_elem)
8641 verbose(env, "kernel subsystem misconfigured verifier\n");
8645 /* In case of read-only, some additional restrictions
8646 * need to be applied in order to prevent altering the
8647 * state of the map from program side.
8649 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
8650 (func_id == BPF_FUNC_map_delete_elem ||
8651 func_id == BPF_FUNC_map_update_elem ||
8652 func_id == BPF_FUNC_map_push_elem ||
8653 func_id == BPF_FUNC_map_pop_elem)) {
8654 verbose(env, "write into map forbidden\n");
8658 if (!BPF_MAP_PTR(aux->map_ptr_state))
8659 bpf_map_ptr_store(aux, meta->map_ptr,
8660 !meta->map_ptr->bypass_spec_v1);
8661 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
8662 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
8663 !meta->map_ptr->bypass_spec_v1);
8668 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8669 int func_id, int insn_idx)
8671 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8672 struct bpf_reg_state *regs = cur_regs(env), *reg;
8673 struct bpf_map *map = meta->map_ptr;
8677 if (func_id != BPF_FUNC_tail_call)
8679 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
8680 verbose(env, "kernel subsystem misconfigured verifier\n");
8684 reg = ®s[BPF_REG_3];
8685 val = reg->var_off.value;
8686 max = map->max_entries;
8688 if (!(register_is_const(reg) && val < max)) {
8689 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8693 err = mark_chain_precision(env, BPF_REG_3);
8696 if (bpf_map_key_unseen(aux))
8697 bpf_map_key_store(aux, val);
8698 else if (!bpf_map_key_poisoned(aux) &&
8699 bpf_map_key_immediate(aux) != val)
8700 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8704 static int check_reference_leak(struct bpf_verifier_env *env)
8706 struct bpf_func_state *state = cur_func(env);
8707 bool refs_lingering = false;
8710 if (state->frameno && !state->in_callback_fn)
8713 for (i = 0; i < state->acquired_refs; i++) {
8714 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
8716 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
8717 state->refs[i].id, state->refs[i].insn_idx);
8718 refs_lingering = true;
8720 return refs_lingering ? -EINVAL : 0;
8723 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
8724 struct bpf_reg_state *regs)
8726 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
8727 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
8728 struct bpf_map *fmt_map = fmt_reg->map_ptr;
8729 struct bpf_bprintf_data data = {};
8730 int err, fmt_map_off, num_args;
8734 /* data must be an array of u64 */
8735 if (data_len_reg->var_off.value % 8)
8737 num_args = data_len_reg->var_off.value / 8;
8739 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
8740 * and map_direct_value_addr is set.
8742 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
8743 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
8746 verbose(env, "verifier bug\n");
8749 fmt = (char *)(long)fmt_addr + fmt_map_off;
8751 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
8752 * can focus on validating the format specifiers.
8754 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
8756 verbose(env, "Invalid format string\n");
8761 static int check_get_func_ip(struct bpf_verifier_env *env)
8763 enum bpf_prog_type type = resolve_prog_type(env->prog);
8764 int func_id = BPF_FUNC_get_func_ip;
8766 if (type == BPF_PROG_TYPE_TRACING) {
8767 if (!bpf_prog_has_trampoline(env->prog)) {
8768 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
8769 func_id_name(func_id), func_id);
8773 } else if (type == BPF_PROG_TYPE_KPROBE) {
8777 verbose(env, "func %s#%d not supported for program type %d\n",
8778 func_id_name(func_id), func_id, type);
8782 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
8784 return &env->insn_aux_data[env->insn_idx];
8787 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
8789 struct bpf_reg_state *regs = cur_regs(env);
8790 struct bpf_reg_state *reg = ®s[BPF_REG_4];
8791 bool reg_is_null = register_is_null(reg);
8794 mark_chain_precision(env, BPF_REG_4);
8799 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
8801 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
8803 if (!state->initialized) {
8804 state->initialized = 1;
8805 state->fit_for_inline = loop_flag_is_zero(env);
8806 state->callback_subprogno = subprogno;
8810 if (!state->fit_for_inline)
8813 state->fit_for_inline = (loop_flag_is_zero(env) &&
8814 state->callback_subprogno == subprogno);
8817 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8820 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8821 const struct bpf_func_proto *fn = NULL;
8822 enum bpf_return_type ret_type;
8823 enum bpf_type_flag ret_flag;
8824 struct bpf_reg_state *regs;
8825 struct bpf_call_arg_meta meta;
8826 int insn_idx = *insn_idx_p;
8828 int i, err, func_id;
8830 /* find function prototype */
8831 func_id = insn->imm;
8832 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
8833 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
8838 if (env->ops->get_func_proto)
8839 fn = env->ops->get_func_proto(func_id, env->prog);
8841 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
8846 /* eBPF programs must be GPL compatible to use GPL-ed functions */
8847 if (!env->prog->gpl_compatible && fn->gpl_only) {
8848 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
8852 if (fn->allowed && !fn->allowed(env->prog)) {
8853 verbose(env, "helper call is not allowed in probe\n");
8857 if (!env->prog->aux->sleepable && fn->might_sleep) {
8858 verbose(env, "helper call might sleep in a non-sleepable prog\n");
8862 /* With LD_ABS/IND some JITs save/restore skb from r1. */
8863 changes_data = bpf_helper_changes_pkt_data(fn->func);
8864 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
8865 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
8866 func_id_name(func_id), func_id);
8870 memset(&meta, 0, sizeof(meta));
8871 meta.pkt_access = fn->pkt_access;
8873 err = check_func_proto(fn, func_id);
8875 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
8876 func_id_name(func_id), func_id);
8880 if (env->cur_state->active_rcu_lock) {
8881 if (fn->might_sleep) {
8882 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
8883 func_id_name(func_id), func_id);
8887 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
8888 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
8891 meta.func_id = func_id;
8893 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8894 err = check_func_arg(env, i, &meta, fn, insn_idx);
8899 err = record_func_map(env, &meta, func_id, insn_idx);
8903 err = record_func_key(env, &meta, func_id, insn_idx);
8907 /* Mark slots with STACK_MISC in case of raw mode, stack offset
8908 * is inferred from register state.
8910 for (i = 0; i < meta.access_size; i++) {
8911 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
8912 BPF_WRITE, -1, false);
8917 regs = cur_regs(env);
8919 if (meta.release_regno) {
8921 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8922 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
8923 * is safe to do directly.
8925 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
8926 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
8927 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
8930 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
8931 } else if (meta.ref_obj_id) {
8932 err = release_reference(env, meta.ref_obj_id);
8933 } else if (register_is_null(®s[meta.release_regno])) {
8934 /* meta.ref_obj_id can only be 0 if register that is meant to be
8935 * released is NULL, which must be > R0.
8940 verbose(env, "func %s#%d reference has not been acquired before\n",
8941 func_id_name(func_id), func_id);
8947 case BPF_FUNC_tail_call:
8948 err = check_reference_leak(env);
8950 verbose(env, "tail_call would lead to reference leak\n");
8954 case BPF_FUNC_get_local_storage:
8955 /* check that flags argument in get_local_storage(map, flags) is 0,
8956 * this is required because get_local_storage() can't return an error.
8958 if (!register_is_null(®s[BPF_REG_2])) {
8959 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
8963 case BPF_FUNC_for_each_map_elem:
8964 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8965 set_map_elem_callback_state);
8967 case BPF_FUNC_timer_set_callback:
8968 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8969 set_timer_callback_state);
8971 case BPF_FUNC_find_vma:
8972 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8973 set_find_vma_callback_state);
8975 case BPF_FUNC_snprintf:
8976 err = check_bpf_snprintf_call(env, regs);
8979 update_loop_inline_state(env, meta.subprogno);
8980 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8981 set_loop_callback_state);
8983 case BPF_FUNC_dynptr_from_mem:
8984 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
8985 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
8986 reg_type_str(env, regs[BPF_REG_1].type));
8990 case BPF_FUNC_set_retval:
8991 if (prog_type == BPF_PROG_TYPE_LSM &&
8992 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
8993 if (!env->prog->aux->attach_func_proto->type) {
8994 /* Make sure programs that attach to void
8995 * hooks don't try to modify return value.
8997 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9002 case BPF_FUNC_dynptr_data:
9004 struct bpf_reg_state *reg;
9007 reg = get_dynptr_arg_reg(env, fn, regs);
9012 if (meta.dynptr_id) {
9013 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9016 if (meta.ref_obj_id) {
9017 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9021 id = dynptr_id(env, reg);
9023 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9027 ref_obj_id = dynptr_ref_obj_id(env, reg);
9028 if (ref_obj_id < 0) {
9029 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9033 meta.dynptr_id = id;
9034 meta.ref_obj_id = ref_obj_id;
9038 case BPF_FUNC_dynptr_write:
9040 enum bpf_dynptr_type dynptr_type;
9041 struct bpf_reg_state *reg;
9043 reg = get_dynptr_arg_reg(env, fn, regs);
9047 dynptr_type = dynptr_get_type(env, reg);
9048 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9051 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9052 /* this will trigger clear_all_pkt_pointers(), which will
9053 * invalidate all dynptr slices associated with the skb
9055 changes_data = true;
9059 case BPF_FUNC_user_ringbuf_drain:
9060 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9061 set_user_ringbuf_callback_state);
9068 /* reset caller saved regs */
9069 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9070 mark_reg_not_init(env, regs, caller_saved[i]);
9071 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9074 /* helper call returns 64-bit value. */
9075 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9077 /* update return register (already marked as written above) */
9078 ret_type = fn->ret_type;
9079 ret_flag = type_flag(ret_type);
9081 switch (base_type(ret_type)) {
9083 /* sets type to SCALAR_VALUE */
9084 mark_reg_unknown(env, regs, BPF_REG_0);
9087 regs[BPF_REG_0].type = NOT_INIT;
9089 case RET_PTR_TO_MAP_VALUE:
9090 /* There is no offset yet applied, variable or fixed */
9091 mark_reg_known_zero(env, regs, BPF_REG_0);
9092 /* remember map_ptr, so that check_map_access()
9093 * can check 'value_size' boundary of memory access
9094 * to map element returned from bpf_map_lookup_elem()
9096 if (meta.map_ptr == NULL) {
9098 "kernel subsystem misconfigured verifier\n");
9101 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9102 regs[BPF_REG_0].map_uid = meta.map_uid;
9103 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9104 if (!type_may_be_null(ret_type) &&
9105 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9106 regs[BPF_REG_0].id = ++env->id_gen;
9109 case RET_PTR_TO_SOCKET:
9110 mark_reg_known_zero(env, regs, BPF_REG_0);
9111 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9113 case RET_PTR_TO_SOCK_COMMON:
9114 mark_reg_known_zero(env, regs, BPF_REG_0);
9115 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9117 case RET_PTR_TO_TCP_SOCK:
9118 mark_reg_known_zero(env, regs, BPF_REG_0);
9119 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9121 case RET_PTR_TO_MEM:
9122 mark_reg_known_zero(env, regs, BPF_REG_0);
9123 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9124 regs[BPF_REG_0].mem_size = meta.mem_size;
9126 case RET_PTR_TO_MEM_OR_BTF_ID:
9128 const struct btf_type *t;
9130 mark_reg_known_zero(env, regs, BPF_REG_0);
9131 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9132 if (!btf_type_is_struct(t)) {
9134 const struct btf_type *ret;
9137 /* resolve the type size of ksym. */
9138 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9140 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9141 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9142 tname, PTR_ERR(ret));
9145 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9146 regs[BPF_REG_0].mem_size = tsize;
9148 /* MEM_RDONLY may be carried from ret_flag, but it
9149 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9150 * it will confuse the check of PTR_TO_BTF_ID in
9151 * check_mem_access().
9153 ret_flag &= ~MEM_RDONLY;
9155 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9156 regs[BPF_REG_0].btf = meta.ret_btf;
9157 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9161 case RET_PTR_TO_BTF_ID:
9163 struct btf *ret_btf;
9166 mark_reg_known_zero(env, regs, BPF_REG_0);
9167 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9168 if (func_id == BPF_FUNC_kptr_xchg) {
9169 ret_btf = meta.kptr_field->kptr.btf;
9170 ret_btf_id = meta.kptr_field->kptr.btf_id;
9171 if (!btf_is_kernel(ret_btf))
9172 regs[BPF_REG_0].type |= MEM_ALLOC;
9174 if (fn->ret_btf_id == BPF_PTR_POISON) {
9175 verbose(env, "verifier internal error:");
9176 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9177 func_id_name(func_id));
9180 ret_btf = btf_vmlinux;
9181 ret_btf_id = *fn->ret_btf_id;
9183 if (ret_btf_id == 0) {
9184 verbose(env, "invalid return type %u of func %s#%d\n",
9185 base_type(ret_type), func_id_name(func_id),
9189 regs[BPF_REG_0].btf = ret_btf;
9190 regs[BPF_REG_0].btf_id = ret_btf_id;
9194 verbose(env, "unknown return type %u of func %s#%d\n",
9195 base_type(ret_type), func_id_name(func_id), func_id);
9199 if (type_may_be_null(regs[BPF_REG_0].type))
9200 regs[BPF_REG_0].id = ++env->id_gen;
9202 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9203 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9204 func_id_name(func_id), func_id);
9208 if (is_dynptr_ref_function(func_id))
9209 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9211 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9212 /* For release_reference() */
9213 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9214 } else if (is_acquire_function(func_id, meta.map_ptr)) {
9215 int id = acquire_reference_state(env, insn_idx);
9219 /* For mark_ptr_or_null_reg() */
9220 regs[BPF_REG_0].id = id;
9221 /* For release_reference() */
9222 regs[BPF_REG_0].ref_obj_id = id;
9225 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9227 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9231 if ((func_id == BPF_FUNC_get_stack ||
9232 func_id == BPF_FUNC_get_task_stack) &&
9233 !env->prog->has_callchain_buf) {
9234 const char *err_str;
9236 #ifdef CONFIG_PERF_EVENTS
9237 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9238 err_str = "cannot get callchain buffer for func %s#%d\n";
9241 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9244 verbose(env, err_str, func_id_name(func_id), func_id);
9248 env->prog->has_callchain_buf = true;
9251 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9252 env->prog->call_get_stack = true;
9254 if (func_id == BPF_FUNC_get_func_ip) {
9255 if (check_get_func_ip(env))
9257 env->prog->call_get_func_ip = true;
9261 clear_all_pkt_pointers(env);
9265 /* mark_btf_func_reg_size() is used when the reg size is determined by
9266 * the BTF func_proto's return value size and argument.
9268 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9271 struct bpf_reg_state *reg = &cur_regs(env)[regno];
9273 if (regno == BPF_REG_0) {
9274 /* Function return value */
9275 reg->live |= REG_LIVE_WRITTEN;
9276 reg->subreg_def = reg_size == sizeof(u64) ?
9277 DEF_NOT_SUBREG : env->insn_idx + 1;
9279 /* Function argument */
9280 if (reg_size == sizeof(u64)) {
9281 mark_insn_zext(env, reg);
9282 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9284 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9289 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9291 return meta->kfunc_flags & KF_ACQUIRE;
9294 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
9296 return meta->kfunc_flags & KF_RET_NULL;
9299 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9301 return meta->kfunc_flags & KF_RELEASE;
9304 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9306 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
9309 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9311 return meta->kfunc_flags & KF_SLEEPABLE;
9314 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9316 return meta->kfunc_flags & KF_DESTRUCTIVE;
9319 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9321 return meta->kfunc_flags & KF_RCU;
9324 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
9326 return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
9329 static bool __kfunc_param_match_suffix(const struct btf *btf,
9330 const struct btf_param *arg,
9333 int suffix_len = strlen(suffix), len;
9334 const char *param_name;
9336 /* In the future, this can be ported to use BTF tagging */
9337 param_name = btf_name_by_offset(btf, arg->name_off);
9338 if (str_is_empty(param_name))
9340 len = strlen(param_name);
9341 if (len < suffix_len)
9343 param_name += len - suffix_len;
9344 return !strncmp(param_name, suffix, suffix_len);
9347 static bool is_kfunc_arg_mem_size(const struct btf *btf,
9348 const struct btf_param *arg,
9349 const struct bpf_reg_state *reg)
9351 const struct btf_type *t;
9353 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9354 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9357 return __kfunc_param_match_suffix(btf, arg, "__sz");
9360 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9361 const struct btf_param *arg,
9362 const struct bpf_reg_state *reg)
9364 const struct btf_type *t;
9366 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9367 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9370 return __kfunc_param_match_suffix(btf, arg, "__szk");
9373 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
9375 return __kfunc_param_match_suffix(btf, arg, "__k");
9378 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
9380 return __kfunc_param_match_suffix(btf, arg, "__ign");
9383 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
9385 return __kfunc_param_match_suffix(btf, arg, "__alloc");
9388 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
9390 return __kfunc_param_match_suffix(btf, arg, "__uninit");
9393 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9394 const struct btf_param *arg,
9397 int len, target_len = strlen(name);
9398 const char *param_name;
9400 param_name = btf_name_by_offset(btf, arg->name_off);
9401 if (str_is_empty(param_name))
9403 len = strlen(param_name);
9404 if (len != target_len)
9406 if (strcmp(param_name, name))
9414 KF_ARG_LIST_HEAD_ID,
9415 KF_ARG_LIST_NODE_ID,
9420 BTF_ID_LIST(kf_arg_btf_ids)
9421 BTF_ID(struct, bpf_dynptr_kern)
9422 BTF_ID(struct, bpf_list_head)
9423 BTF_ID(struct, bpf_list_node)
9424 BTF_ID(struct, bpf_rb_root)
9425 BTF_ID(struct, bpf_rb_node)
9427 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
9428 const struct btf_param *arg, int type)
9430 const struct btf_type *t;
9433 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9436 if (!btf_type_is_ptr(t))
9438 t = btf_type_skip_modifiers(btf, t->type, &res_id);
9441 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9444 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9446 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9449 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9451 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9454 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
9456 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
9459 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9461 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9464 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
9466 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
9469 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
9470 const struct btf_param *arg)
9472 const struct btf_type *t;
9474 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
9481 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
9482 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
9483 const struct btf *btf,
9484 const struct btf_type *t, int rec)
9486 const struct btf_type *member_type;
9487 const struct btf_member *member;
9490 if (!btf_type_is_struct(t))
9493 for_each_member(i, t, member) {
9494 const struct btf_array *array;
9496 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
9497 if (btf_type_is_struct(member_type)) {
9499 verbose(env, "max struct nesting depth exceeded\n");
9502 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
9506 if (btf_type_is_array(member_type)) {
9507 array = btf_array(member_type);
9510 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
9511 if (!btf_type_is_scalar(member_type))
9515 if (!btf_type_is_scalar(member_type))
9522 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
9524 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
9525 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9526 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
9530 enum kfunc_ptr_arg_type {
9532 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
9533 KF_ARG_PTR_TO_KPTR, /* PTR_TO_KPTR but type specific */
9534 KF_ARG_PTR_TO_DYNPTR,
9536 KF_ARG_PTR_TO_LIST_HEAD,
9537 KF_ARG_PTR_TO_LIST_NODE,
9538 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
9540 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
9541 KF_ARG_PTR_TO_CALLBACK,
9542 KF_ARG_PTR_TO_RB_ROOT,
9543 KF_ARG_PTR_TO_RB_NODE,
9546 enum special_kfunc_type {
9547 KF_bpf_obj_new_impl,
9548 KF_bpf_obj_drop_impl,
9549 KF_bpf_list_push_front,
9550 KF_bpf_list_push_back,
9551 KF_bpf_list_pop_front,
9552 KF_bpf_list_pop_back,
9553 KF_bpf_cast_to_kern_ctx,
9555 KF_bpf_rcu_read_lock,
9556 KF_bpf_rcu_read_unlock,
9557 KF_bpf_rbtree_remove,
9559 KF_bpf_rbtree_first,
9560 KF_bpf_dynptr_from_skb,
9561 KF_bpf_dynptr_from_xdp,
9562 KF_bpf_dynptr_slice,
9563 KF_bpf_dynptr_slice_rdwr,
9566 BTF_SET_START(special_kfunc_set)
9567 BTF_ID(func, bpf_obj_new_impl)
9568 BTF_ID(func, bpf_obj_drop_impl)
9569 BTF_ID(func, bpf_list_push_front)
9570 BTF_ID(func, bpf_list_push_back)
9571 BTF_ID(func, bpf_list_pop_front)
9572 BTF_ID(func, bpf_list_pop_back)
9573 BTF_ID(func, bpf_cast_to_kern_ctx)
9574 BTF_ID(func, bpf_rdonly_cast)
9575 BTF_ID(func, bpf_rbtree_remove)
9576 BTF_ID(func, bpf_rbtree_add)
9577 BTF_ID(func, bpf_rbtree_first)
9578 BTF_ID(func, bpf_dynptr_from_skb)
9579 BTF_ID(func, bpf_dynptr_from_xdp)
9580 BTF_ID(func, bpf_dynptr_slice)
9581 BTF_ID(func, bpf_dynptr_slice_rdwr)
9582 BTF_SET_END(special_kfunc_set)
9584 BTF_ID_LIST(special_kfunc_list)
9585 BTF_ID(func, bpf_obj_new_impl)
9586 BTF_ID(func, bpf_obj_drop_impl)
9587 BTF_ID(func, bpf_list_push_front)
9588 BTF_ID(func, bpf_list_push_back)
9589 BTF_ID(func, bpf_list_pop_front)
9590 BTF_ID(func, bpf_list_pop_back)
9591 BTF_ID(func, bpf_cast_to_kern_ctx)
9592 BTF_ID(func, bpf_rdonly_cast)
9593 BTF_ID(func, bpf_rcu_read_lock)
9594 BTF_ID(func, bpf_rcu_read_unlock)
9595 BTF_ID(func, bpf_rbtree_remove)
9596 BTF_ID(func, bpf_rbtree_add)
9597 BTF_ID(func, bpf_rbtree_first)
9598 BTF_ID(func, bpf_dynptr_from_skb)
9599 BTF_ID(func, bpf_dynptr_from_xdp)
9600 BTF_ID(func, bpf_dynptr_slice)
9601 BTF_ID(func, bpf_dynptr_slice_rdwr)
9603 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
9605 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
9608 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
9610 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
9613 static enum kfunc_ptr_arg_type
9614 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
9615 struct bpf_kfunc_call_arg_meta *meta,
9616 const struct btf_type *t, const struct btf_type *ref_t,
9617 const char *ref_tname, const struct btf_param *args,
9618 int argno, int nargs)
9620 u32 regno = argno + 1;
9621 struct bpf_reg_state *regs = cur_regs(env);
9622 struct bpf_reg_state *reg = ®s[regno];
9623 bool arg_mem_size = false;
9625 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
9626 return KF_ARG_PTR_TO_CTX;
9628 /* In this function, we verify the kfunc's BTF as per the argument type,
9629 * leaving the rest of the verification with respect to the register
9630 * type to our caller. When a set of conditions hold in the BTF type of
9631 * arguments, we resolve it to a known kfunc_ptr_arg_type.
9633 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
9634 return KF_ARG_PTR_TO_CTX;
9636 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
9637 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
9639 if (is_kfunc_arg_kptr_get(meta, argno)) {
9640 if (!btf_type_is_ptr(ref_t)) {
9641 verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
9644 ref_t = btf_type_by_id(meta->btf, ref_t->type);
9645 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
9646 if (!btf_type_is_struct(ref_t)) {
9647 verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
9648 meta->func_name, btf_type_str(ref_t), ref_tname);
9651 return KF_ARG_PTR_TO_KPTR;
9654 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
9655 return KF_ARG_PTR_TO_DYNPTR;
9657 if (is_kfunc_arg_iter(meta, argno))
9658 return KF_ARG_PTR_TO_ITER;
9660 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
9661 return KF_ARG_PTR_TO_LIST_HEAD;
9663 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
9664 return KF_ARG_PTR_TO_LIST_NODE;
9666 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
9667 return KF_ARG_PTR_TO_RB_ROOT;
9669 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
9670 return KF_ARG_PTR_TO_RB_NODE;
9672 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
9673 if (!btf_type_is_struct(ref_t)) {
9674 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
9675 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9678 return KF_ARG_PTR_TO_BTF_ID;
9681 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
9682 return KF_ARG_PTR_TO_CALLBACK;
9685 if (argno + 1 < nargs &&
9686 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
9687 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
9688 arg_mem_size = true;
9690 /* This is the catch all argument type of register types supported by
9691 * check_helper_mem_access. However, we only allow when argument type is
9692 * pointer to scalar, or struct composed (recursively) of scalars. When
9693 * arg_mem_size is true, the pointer can be void *.
9695 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
9696 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
9697 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
9698 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
9701 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
9704 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
9705 struct bpf_reg_state *reg,
9706 const struct btf_type *ref_t,
9707 const char *ref_tname, u32 ref_id,
9708 struct bpf_kfunc_call_arg_meta *meta,
9711 const struct btf_type *reg_ref_t;
9712 bool strict_type_match = false;
9713 const struct btf *reg_btf;
9714 const char *reg_ref_tname;
9717 if (base_type(reg->type) == PTR_TO_BTF_ID) {
9719 reg_ref_id = reg->btf_id;
9721 reg_btf = btf_vmlinux;
9722 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
9725 /* Enforce strict type matching for calls to kfuncs that are acquiring
9726 * or releasing a reference, or are no-cast aliases. We do _not_
9727 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
9728 * as we want to enable BPF programs to pass types that are bitwise
9729 * equivalent without forcing them to explicitly cast with something
9730 * like bpf_cast_to_kern_ctx().
9732 * For example, say we had a type like the following:
9734 * struct bpf_cpumask {
9735 * cpumask_t cpumask;
9739 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
9740 * to a struct cpumask, so it would be safe to pass a struct
9741 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
9743 * The philosophy here is similar to how we allow scalars of different
9744 * types to be passed to kfuncs as long as the size is the same. The
9745 * only difference here is that we're simply allowing
9746 * btf_struct_ids_match() to walk the struct at the 0th offset, and
9749 if (is_kfunc_acquire(meta) ||
9750 (is_kfunc_release(meta) && reg->ref_obj_id) ||
9751 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
9752 strict_type_match = true;
9754 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
9756 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
9757 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
9758 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
9759 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
9760 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
9761 btf_type_str(reg_ref_t), reg_ref_tname);
9767 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
9768 struct bpf_reg_state *reg,
9769 const struct btf_type *ref_t,
9770 const char *ref_tname,
9771 struct bpf_kfunc_call_arg_meta *meta,
9774 struct btf_field *kptr_field;
9776 /* check_func_arg_reg_off allows var_off for
9777 * PTR_TO_MAP_VALUE, but we need fixed offset to find
9780 if (!tnum_is_const(reg->var_off)) {
9781 verbose(env, "arg#0 must have constant offset\n");
9785 kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
9786 if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
9787 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
9788 reg->off + reg->var_off.value);
9792 if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
9793 kptr_field->kptr.btf_id, true)) {
9794 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
9795 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9801 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9803 struct bpf_verifier_state *state = env->cur_state;
9805 if (!state->active_lock.ptr) {
9806 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
9810 if (type_flag(reg->type) & NON_OWN_REF) {
9811 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
9815 reg->type |= NON_OWN_REF;
9819 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
9821 struct bpf_func_state *state, *unused;
9822 struct bpf_reg_state *reg;
9825 state = cur_func(env);
9828 verbose(env, "verifier internal error: ref_obj_id is zero for "
9829 "owning -> non-owning conversion\n");
9833 for (i = 0; i < state->acquired_refs; i++) {
9834 if (state->refs[i].id != ref_obj_id)
9837 /* Clear ref_obj_id here so release_reference doesn't clobber
9840 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9841 if (reg->ref_obj_id == ref_obj_id) {
9842 reg->ref_obj_id = 0;
9843 ref_set_non_owning(env, reg);
9849 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
9853 /* Implementation details:
9855 * Each register points to some region of memory, which we define as an
9856 * allocation. Each allocation may embed a bpf_spin_lock which protects any
9857 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
9858 * allocation. The lock and the data it protects are colocated in the same
9861 * Hence, everytime a register holds a pointer value pointing to such
9862 * allocation, the verifier preserves a unique reg->id for it.
9864 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
9865 * bpf_spin_lock is called.
9867 * To enable this, lock state in the verifier captures two values:
9868 * active_lock.ptr = Register's type specific pointer
9869 * active_lock.id = A unique ID for each register pointer value
9871 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
9872 * supported register types.
9874 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
9875 * allocated objects is the reg->btf pointer.
9877 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
9878 * can establish the provenance of the map value statically for each distinct
9879 * lookup into such maps. They always contain a single map value hence unique
9880 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
9882 * So, in case of global variables, they use array maps with max_entries = 1,
9883 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
9884 * into the same map value as max_entries is 1, as described above).
9886 * In case of inner map lookups, the inner map pointer has same map_ptr as the
9887 * outer map pointer (in verifier context), but each lookup into an inner map
9888 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
9889 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
9890 * will get different reg->id assigned to each lookup, hence different
9893 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
9894 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
9895 * returned from bpf_obj_new. Each allocation receives a new reg->id.
9897 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9902 switch ((int)reg->type) {
9903 case PTR_TO_MAP_VALUE:
9906 case PTR_TO_BTF_ID | MEM_ALLOC:
9910 verbose(env, "verifier internal error: unknown reg type for lock check\n");
9915 if (!env->cur_state->active_lock.ptr)
9917 if (env->cur_state->active_lock.ptr != ptr ||
9918 env->cur_state->active_lock.id != id) {
9919 verbose(env, "held lock and object are not in the same allocation\n");
9925 static bool is_bpf_list_api_kfunc(u32 btf_id)
9927 return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9928 btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
9929 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9930 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
9933 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
9935 return btf_id == special_kfunc_list[KF_bpf_rbtree_add] ||
9936 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9937 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
9940 static bool is_bpf_graph_api_kfunc(u32 btf_id)
9942 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id);
9945 static bool is_callback_calling_kfunc(u32 btf_id)
9947 return btf_id == special_kfunc_list[KF_bpf_rbtree_add];
9950 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
9952 return is_bpf_rbtree_api_kfunc(btf_id);
9955 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
9956 enum btf_field_type head_field_type,
9961 switch (head_field_type) {
9963 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
9966 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
9969 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
9970 btf_field_type_name(head_field_type));
9975 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
9976 btf_field_type_name(head_field_type));
9980 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
9981 enum btf_field_type node_field_type,
9986 switch (node_field_type) {
9988 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9989 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back]);
9992 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9993 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add]);
9996 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
9997 btf_field_type_name(node_field_type));
10002 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10003 btf_field_type_name(node_field_type));
10008 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10009 struct bpf_reg_state *reg, u32 regno,
10010 struct bpf_kfunc_call_arg_meta *meta,
10011 enum btf_field_type head_field_type,
10012 struct btf_field **head_field)
10014 const char *head_type_name;
10015 struct btf_field *field;
10016 struct btf_record *rec;
10019 if (meta->btf != btf_vmlinux) {
10020 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10024 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10027 head_type_name = btf_field_type_name(head_field_type);
10028 if (!tnum_is_const(reg->var_off)) {
10030 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10031 regno, head_type_name);
10035 rec = reg_btf_record(reg);
10036 head_off = reg->off + reg->var_off.value;
10037 field = btf_record_find(rec, head_off, head_field_type);
10039 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10043 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10044 if (check_reg_allocation_locked(env, reg)) {
10045 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10046 rec->spin_lock_off, head_type_name);
10051 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10054 *head_field = field;
10058 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10059 struct bpf_reg_state *reg, u32 regno,
10060 struct bpf_kfunc_call_arg_meta *meta)
10062 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10063 &meta->arg_list_head.field);
10066 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10067 struct bpf_reg_state *reg, u32 regno,
10068 struct bpf_kfunc_call_arg_meta *meta)
10070 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10071 &meta->arg_rbtree_root.field);
10075 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10076 struct bpf_reg_state *reg, u32 regno,
10077 struct bpf_kfunc_call_arg_meta *meta,
10078 enum btf_field_type head_field_type,
10079 enum btf_field_type node_field_type,
10080 struct btf_field **node_field)
10082 const char *node_type_name;
10083 const struct btf_type *et, *t;
10084 struct btf_field *field;
10087 if (meta->btf != btf_vmlinux) {
10088 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10092 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10095 node_type_name = btf_field_type_name(node_field_type);
10096 if (!tnum_is_const(reg->var_off)) {
10098 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10099 regno, node_type_name);
10103 node_off = reg->off + reg->var_off.value;
10104 field = reg_find_field_offset(reg, node_off, node_field_type);
10105 if (!field || field->offset != node_off) {
10106 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10110 field = *node_field;
10112 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10113 t = btf_type_by_id(reg->btf, reg->btf_id);
10114 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10115 field->graph_root.value_btf_id, true)) {
10116 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10117 "in struct %s, but arg is at offset=%d in struct %s\n",
10118 btf_field_type_name(head_field_type),
10119 btf_field_type_name(node_field_type),
10120 field->graph_root.node_offset,
10121 btf_name_by_offset(field->graph_root.btf, et->name_off),
10122 node_off, btf_name_by_offset(reg->btf, t->name_off));
10126 if (node_off != field->graph_root.node_offset) {
10127 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10128 node_off, btf_field_type_name(node_field_type),
10129 field->graph_root.node_offset,
10130 btf_name_by_offset(field->graph_root.btf, et->name_off));
10137 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10138 struct bpf_reg_state *reg, u32 regno,
10139 struct bpf_kfunc_call_arg_meta *meta)
10141 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10142 BPF_LIST_HEAD, BPF_LIST_NODE,
10143 &meta->arg_list_head.field);
10146 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10147 struct bpf_reg_state *reg, u32 regno,
10148 struct bpf_kfunc_call_arg_meta *meta)
10150 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10151 BPF_RB_ROOT, BPF_RB_NODE,
10152 &meta->arg_rbtree_root.field);
10155 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10158 const char *func_name = meta->func_name, *ref_tname;
10159 const struct btf *btf = meta->btf;
10160 const struct btf_param *args;
10164 args = (const struct btf_param *)(meta->func_proto + 1);
10165 nargs = btf_type_vlen(meta->func_proto);
10166 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10167 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10168 MAX_BPF_FUNC_REG_ARGS);
10172 /* Check that BTF function arguments match actual types that the
10175 for (i = 0; i < nargs; i++) {
10176 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
10177 const struct btf_type *t, *ref_t, *resolve_ret;
10178 enum bpf_arg_type arg_type = ARG_DONTCARE;
10179 u32 regno = i + 1, ref_id, type_size;
10180 bool is_ret_buf_sz = false;
10183 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10185 if (is_kfunc_arg_ignore(btf, &args[i]))
10188 if (btf_type_is_scalar(t)) {
10189 if (reg->type != SCALAR_VALUE) {
10190 verbose(env, "R%d is not a scalar\n", regno);
10194 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10195 if (meta->arg_constant.found) {
10196 verbose(env, "verifier internal error: only one constant argument permitted\n");
10199 if (!tnum_is_const(reg->var_off)) {
10200 verbose(env, "R%d must be a known constant\n", regno);
10203 ret = mark_chain_precision(env, regno);
10206 meta->arg_constant.found = true;
10207 meta->arg_constant.value = reg->var_off.value;
10208 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10209 meta->r0_rdonly = true;
10210 is_ret_buf_sz = true;
10211 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10212 is_ret_buf_sz = true;
10215 if (is_ret_buf_sz) {
10216 if (meta->r0_size) {
10217 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10221 if (!tnum_is_const(reg->var_off)) {
10222 verbose(env, "R%d is not a const\n", regno);
10226 meta->r0_size = reg->var_off.value;
10227 ret = mark_chain_precision(env, regno);
10234 if (!btf_type_is_ptr(t)) {
10235 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10239 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10240 (register_is_null(reg) || type_may_be_null(reg->type))) {
10241 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10245 if (reg->ref_obj_id) {
10246 if (is_kfunc_release(meta) && meta->ref_obj_id) {
10247 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10248 regno, reg->ref_obj_id,
10252 meta->ref_obj_id = reg->ref_obj_id;
10253 if (is_kfunc_release(meta))
10254 meta->release_regno = regno;
10257 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10258 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10260 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10261 if (kf_arg_type < 0)
10262 return kf_arg_type;
10264 switch (kf_arg_type) {
10265 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10266 case KF_ARG_PTR_TO_BTF_ID:
10267 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10270 if (!is_trusted_reg(reg)) {
10271 if (!is_kfunc_rcu(meta)) {
10272 verbose(env, "R%d must be referenced or trusted\n", regno);
10275 if (!is_rcu_reg(reg)) {
10276 verbose(env, "R%d must be a rcu pointer\n", regno);
10282 case KF_ARG_PTR_TO_CTX:
10283 /* Trusted arguments have the same offset checks as release arguments */
10284 arg_type |= OBJ_RELEASE;
10286 case KF_ARG_PTR_TO_KPTR:
10287 case KF_ARG_PTR_TO_DYNPTR:
10288 case KF_ARG_PTR_TO_ITER:
10289 case KF_ARG_PTR_TO_LIST_HEAD:
10290 case KF_ARG_PTR_TO_LIST_NODE:
10291 case KF_ARG_PTR_TO_RB_ROOT:
10292 case KF_ARG_PTR_TO_RB_NODE:
10293 case KF_ARG_PTR_TO_MEM:
10294 case KF_ARG_PTR_TO_MEM_SIZE:
10295 case KF_ARG_PTR_TO_CALLBACK:
10296 /* Trusted by default */
10303 if (is_kfunc_release(meta) && reg->ref_obj_id)
10304 arg_type |= OBJ_RELEASE;
10305 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10309 switch (kf_arg_type) {
10310 case KF_ARG_PTR_TO_CTX:
10311 if (reg->type != PTR_TO_CTX) {
10312 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10316 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10317 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10320 meta->ret_btf_id = ret;
10323 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10324 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10325 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10328 if (!reg->ref_obj_id) {
10329 verbose(env, "allocated object must be referenced\n");
10332 if (meta->btf == btf_vmlinux &&
10333 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10334 meta->arg_obj_drop.btf = reg->btf;
10335 meta->arg_obj_drop.btf_id = reg->btf_id;
10338 case KF_ARG_PTR_TO_KPTR:
10339 if (reg->type != PTR_TO_MAP_VALUE) {
10340 verbose(env, "arg#0 expected pointer to map value\n");
10343 ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
10347 case KF_ARG_PTR_TO_DYNPTR:
10349 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
10351 if (reg->type != PTR_TO_STACK &&
10352 reg->type != CONST_PTR_TO_DYNPTR) {
10353 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
10357 if (reg->type == CONST_PTR_TO_DYNPTR)
10358 dynptr_arg_type |= MEM_RDONLY;
10360 if (is_kfunc_arg_uninit(btf, &args[i]))
10361 dynptr_arg_type |= MEM_UNINIT;
10363 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb])
10364 dynptr_arg_type |= DYNPTR_TYPE_SKB;
10365 else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp])
10366 dynptr_arg_type |= DYNPTR_TYPE_XDP;
10368 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type);
10372 if (!(dynptr_arg_type & MEM_UNINIT)) {
10373 int id = dynptr_id(env, reg);
10376 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10379 meta->initialized_dynptr.id = id;
10380 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
10385 case KF_ARG_PTR_TO_ITER:
10386 ret = process_iter_arg(env, regno, insn_idx, meta);
10390 case KF_ARG_PTR_TO_LIST_HEAD:
10391 if (reg->type != PTR_TO_MAP_VALUE &&
10392 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10393 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10396 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10397 verbose(env, "allocated object must be referenced\n");
10400 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
10404 case KF_ARG_PTR_TO_RB_ROOT:
10405 if (reg->type != PTR_TO_MAP_VALUE &&
10406 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10407 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10410 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10411 verbose(env, "allocated object must be referenced\n");
10414 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
10418 case KF_ARG_PTR_TO_LIST_NODE:
10419 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10420 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10423 if (!reg->ref_obj_id) {
10424 verbose(env, "allocated object must be referenced\n");
10427 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
10431 case KF_ARG_PTR_TO_RB_NODE:
10432 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
10433 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
10434 verbose(env, "rbtree_remove node input must be non-owning ref\n");
10437 if (in_rbtree_lock_required_cb(env)) {
10438 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
10442 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10443 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10446 if (!reg->ref_obj_id) {
10447 verbose(env, "allocated object must be referenced\n");
10452 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10456 case KF_ARG_PTR_TO_BTF_ID:
10457 /* Only base_type is checked, further checks are done here */
10458 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10459 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10460 !reg2btf_ids[base_type(reg->type)]) {
10461 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10462 verbose(env, "expected %s or socket\n",
10463 reg_type_str(env, base_type(reg->type) |
10464 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10467 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10471 case KF_ARG_PTR_TO_MEM:
10472 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10473 if (IS_ERR(resolve_ret)) {
10474 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10475 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10478 ret = check_mem_reg(env, reg, regno, type_size);
10482 case KF_ARG_PTR_TO_MEM_SIZE:
10484 struct bpf_reg_state *size_reg = ®s[regno + 1];
10485 const struct btf_param *size_arg = &args[i + 1];
10487 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
10489 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
10493 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
10494 if (meta->arg_constant.found) {
10495 verbose(env, "verifier internal error: only one constant argument permitted\n");
10498 if (!tnum_is_const(size_reg->var_off)) {
10499 verbose(env, "R%d must be a known constant\n", regno + 1);
10502 meta->arg_constant.found = true;
10503 meta->arg_constant.value = size_reg->var_off.value;
10506 /* Skip next '__sz' or '__szk' argument */
10510 case KF_ARG_PTR_TO_CALLBACK:
10511 meta->subprogno = reg->subprogno;
10516 if (is_kfunc_release(meta) && !meta->release_regno) {
10517 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
10525 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
10526 struct bpf_insn *insn,
10527 struct bpf_kfunc_call_arg_meta *meta,
10528 const char **kfunc_name)
10530 const struct btf_type *func, *func_proto;
10531 u32 func_id, *kfunc_flags;
10532 const char *func_name;
10533 struct btf *desc_btf;
10536 *kfunc_name = NULL;
10541 desc_btf = find_kfunc_desc_btf(env, insn->off);
10542 if (IS_ERR(desc_btf))
10543 return PTR_ERR(desc_btf);
10545 func_id = insn->imm;
10546 func = btf_type_by_id(desc_btf, func_id);
10547 func_name = btf_name_by_offset(desc_btf, func->name_off);
10549 *kfunc_name = func_name;
10550 func_proto = btf_type_by_id(desc_btf, func->type);
10552 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
10553 if (!kfunc_flags) {
10557 memset(meta, 0, sizeof(*meta));
10558 meta->btf = desc_btf;
10559 meta->func_id = func_id;
10560 meta->kfunc_flags = *kfunc_flags;
10561 meta->func_proto = func_proto;
10562 meta->func_name = func_name;
10567 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10570 const struct btf_type *t, *ptr_type;
10571 u32 i, nargs, ptr_type_id, release_ref_obj_id;
10572 struct bpf_reg_state *regs = cur_regs(env);
10573 const char *func_name, *ptr_type_name;
10574 bool sleepable, rcu_lock, rcu_unlock;
10575 struct bpf_kfunc_call_arg_meta meta;
10576 struct bpf_insn_aux_data *insn_aux;
10577 int err, insn_idx = *insn_idx_p;
10578 const struct btf_param *args;
10579 const struct btf_type *ret_t;
10580 struct btf *desc_btf;
10582 /* skip for now, but return error when we find this in fixup_kfunc_call */
10586 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
10587 if (err == -EACCES && func_name)
10588 verbose(env, "calling kernel function %s is not allowed\n", func_name);
10591 desc_btf = meta.btf;
10592 insn_aux = &env->insn_aux_data[insn_idx];
10594 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
10596 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
10597 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
10601 sleepable = is_kfunc_sleepable(&meta);
10602 if (sleepable && !env->prog->aux->sleepable) {
10603 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
10607 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
10608 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
10610 if (env->cur_state->active_rcu_lock) {
10611 struct bpf_func_state *state;
10612 struct bpf_reg_state *reg;
10615 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
10617 } else if (rcu_unlock) {
10618 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10619 if (reg->type & MEM_RCU) {
10620 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
10621 reg->type |= PTR_UNTRUSTED;
10624 env->cur_state->active_rcu_lock = false;
10625 } else if (sleepable) {
10626 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
10629 } else if (rcu_lock) {
10630 env->cur_state->active_rcu_lock = true;
10631 } else if (rcu_unlock) {
10632 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
10636 /* Check the arguments */
10637 err = check_kfunc_args(env, &meta, insn_idx);
10640 /* In case of release function, we get register number of refcounted
10641 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
10643 if (meta.release_regno) {
10644 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
10646 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10647 func_name, meta.func_id);
10652 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front] ||
10653 meta.func_id == special_kfunc_list[KF_bpf_list_push_back] ||
10654 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
10655 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
10656 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
10658 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
10659 func_name, meta.func_id);
10663 err = release_reference(env, release_ref_obj_id);
10665 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10666 func_name, meta.func_id);
10671 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
10672 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10673 set_rbtree_add_callback_state);
10675 verbose(env, "kfunc %s#%d failed callback verification\n",
10676 func_name, meta.func_id);
10681 for (i = 0; i < CALLER_SAVED_REGS; i++)
10682 mark_reg_not_init(env, regs, caller_saved[i]);
10684 /* Check return type */
10685 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
10687 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
10688 /* Only exception is bpf_obj_new_impl */
10689 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
10690 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
10695 if (btf_type_is_scalar(t)) {
10696 mark_reg_unknown(env, regs, BPF_REG_0);
10697 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
10698 } else if (btf_type_is_ptr(t)) {
10699 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
10701 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
10702 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
10703 struct btf *ret_btf;
10706 if (unlikely(!bpf_global_ma_set))
10709 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
10710 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
10714 ret_btf = env->prog->aux->btf;
10715 ret_btf_id = meta.arg_constant.value;
10717 /* This may be NULL due to user not supplying a BTF */
10719 verbose(env, "bpf_obj_new requires prog BTF\n");
10723 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
10724 if (!ret_t || !__btf_type_is_struct(ret_t)) {
10725 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
10729 mark_reg_known_zero(env, regs, BPF_REG_0);
10730 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
10731 regs[BPF_REG_0].btf = ret_btf;
10732 regs[BPF_REG_0].btf_id = ret_btf_id;
10734 insn_aux->obj_new_size = ret_t->size;
10735 insn_aux->kptr_struct_meta =
10736 btf_find_struct_meta(ret_btf, ret_btf_id);
10737 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10738 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
10739 struct btf_field *field = meta.arg_list_head.field;
10741 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10742 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10743 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10744 struct btf_field *field = meta.arg_rbtree_root.field;
10746 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10747 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10748 mark_reg_known_zero(env, regs, BPF_REG_0);
10749 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
10750 regs[BPF_REG_0].btf = desc_btf;
10751 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10752 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
10753 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
10754 if (!ret_t || !btf_type_is_struct(ret_t)) {
10756 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
10760 mark_reg_known_zero(env, regs, BPF_REG_0);
10761 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
10762 regs[BPF_REG_0].btf = desc_btf;
10763 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
10764 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
10765 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
10766 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
10768 mark_reg_known_zero(env, regs, BPF_REG_0);
10770 if (!meta.arg_constant.found) {
10771 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
10775 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
10777 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
10778 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
10780 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
10781 regs[BPF_REG_0].type |= MEM_RDONLY;
10783 /* this will set env->seen_direct_write to true */
10784 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
10785 verbose(env, "the prog does not allow writes to packet data\n");
10790 if (!meta.initialized_dynptr.id) {
10791 verbose(env, "verifier internal error: no dynptr id\n");
10794 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
10796 /* we don't need to set BPF_REG_0's ref obj id
10797 * because packet slices are not refcounted (see
10798 * dynptr_type_refcounted)
10801 verbose(env, "kernel function %s unhandled dynamic return type\n",
10805 } else if (!__btf_type_is_struct(ptr_type)) {
10806 if (!meta.r0_size) {
10809 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
10811 meta.r0_rdonly = true;
10814 if (!meta.r0_size) {
10815 ptr_type_name = btf_name_by_offset(desc_btf,
10816 ptr_type->name_off);
10818 "kernel function %s returns pointer type %s %s is not supported\n",
10820 btf_type_str(ptr_type),
10825 mark_reg_known_zero(env, regs, BPF_REG_0);
10826 regs[BPF_REG_0].type = PTR_TO_MEM;
10827 regs[BPF_REG_0].mem_size = meta.r0_size;
10829 if (meta.r0_rdonly)
10830 regs[BPF_REG_0].type |= MEM_RDONLY;
10832 /* Ensures we don't access the memory after a release_reference() */
10833 if (meta.ref_obj_id)
10834 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10836 mark_reg_known_zero(env, regs, BPF_REG_0);
10837 regs[BPF_REG_0].btf = desc_btf;
10838 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
10839 regs[BPF_REG_0].btf_id = ptr_type_id;
10842 if (is_kfunc_ret_null(&meta)) {
10843 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
10844 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
10845 regs[BPF_REG_0].id = ++env->id_gen;
10847 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
10848 if (is_kfunc_acquire(&meta)) {
10849 int id = acquire_reference_state(env, insn_idx);
10853 if (is_kfunc_ret_null(&meta))
10854 regs[BPF_REG_0].id = id;
10855 regs[BPF_REG_0].ref_obj_id = id;
10856 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10857 ref_set_non_owning(env, ®s[BPF_REG_0]);
10860 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove])
10861 invalidate_non_owning_refs(env);
10863 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
10864 regs[BPF_REG_0].id = ++env->id_gen;
10865 } else if (btf_type_is_void(t)) {
10866 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
10867 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10868 insn_aux->kptr_struct_meta =
10869 btf_find_struct_meta(meta.arg_obj_drop.btf,
10870 meta.arg_obj_drop.btf_id);
10875 nargs = btf_type_vlen(meta.func_proto);
10876 args = (const struct btf_param *)(meta.func_proto + 1);
10877 for (i = 0; i < nargs; i++) {
10880 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
10881 if (btf_type_is_ptr(t))
10882 mark_btf_func_reg_size(env, regno, sizeof(void *));
10884 /* scalar. ensured by btf_check_kfunc_arg_match() */
10885 mark_btf_func_reg_size(env, regno, t->size);
10888 if (is_iter_next_kfunc(&meta)) {
10889 err = process_iter_next_call(env, insn_idx, &meta);
10897 static bool signed_add_overflows(s64 a, s64 b)
10899 /* Do the add in u64, where overflow is well-defined */
10900 s64 res = (s64)((u64)a + (u64)b);
10907 static bool signed_add32_overflows(s32 a, s32 b)
10909 /* Do the add in u32, where overflow is well-defined */
10910 s32 res = (s32)((u32)a + (u32)b);
10917 static bool signed_sub_overflows(s64 a, s64 b)
10919 /* Do the sub in u64, where overflow is well-defined */
10920 s64 res = (s64)((u64)a - (u64)b);
10927 static bool signed_sub32_overflows(s32 a, s32 b)
10929 /* Do the sub in u32, where overflow is well-defined */
10930 s32 res = (s32)((u32)a - (u32)b);
10937 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
10938 const struct bpf_reg_state *reg,
10939 enum bpf_reg_type type)
10941 bool known = tnum_is_const(reg->var_off);
10942 s64 val = reg->var_off.value;
10943 s64 smin = reg->smin_value;
10945 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
10946 verbose(env, "math between %s pointer and %lld is not allowed\n",
10947 reg_type_str(env, type), val);
10951 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
10952 verbose(env, "%s pointer offset %d is not allowed\n",
10953 reg_type_str(env, type), reg->off);
10957 if (smin == S64_MIN) {
10958 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
10959 reg_type_str(env, type));
10963 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
10964 verbose(env, "value %lld makes %s pointer be out of bounds\n",
10965 smin, reg_type_str(env, type));
10973 REASON_BOUNDS = -1,
10980 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
10981 u32 *alu_limit, bool mask_to_left)
10983 u32 max = 0, ptr_limit = 0;
10985 switch (ptr_reg->type) {
10987 /* Offset 0 is out-of-bounds, but acceptable start for the
10988 * left direction, see BPF_REG_FP. Also, unknown scalar
10989 * offset where we would need to deal with min/max bounds is
10990 * currently prohibited for unprivileged.
10992 max = MAX_BPF_STACK + mask_to_left;
10993 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
10995 case PTR_TO_MAP_VALUE:
10996 max = ptr_reg->map_ptr->value_size;
10997 ptr_limit = (mask_to_left ?
10998 ptr_reg->smin_value :
10999 ptr_reg->umax_value) + ptr_reg->off;
11002 return REASON_TYPE;
11005 if (ptr_limit >= max)
11006 return REASON_LIMIT;
11007 *alu_limit = ptr_limit;
11011 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11012 const struct bpf_insn *insn)
11014 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11017 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11018 u32 alu_state, u32 alu_limit)
11020 /* If we arrived here from different branches with different
11021 * state or limits to sanitize, then this won't work.
11023 if (aux->alu_state &&
11024 (aux->alu_state != alu_state ||
11025 aux->alu_limit != alu_limit))
11026 return REASON_PATHS;
11028 /* Corresponding fixup done in do_misc_fixups(). */
11029 aux->alu_state = alu_state;
11030 aux->alu_limit = alu_limit;
11034 static int sanitize_val_alu(struct bpf_verifier_env *env,
11035 struct bpf_insn *insn)
11037 struct bpf_insn_aux_data *aux = cur_aux(env);
11039 if (can_skip_alu_sanitation(env, insn))
11042 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11045 static bool sanitize_needed(u8 opcode)
11047 return opcode == BPF_ADD || opcode == BPF_SUB;
11050 struct bpf_sanitize_info {
11051 struct bpf_insn_aux_data aux;
11055 static struct bpf_verifier_state *
11056 sanitize_speculative_path(struct bpf_verifier_env *env,
11057 const struct bpf_insn *insn,
11058 u32 next_idx, u32 curr_idx)
11060 struct bpf_verifier_state *branch;
11061 struct bpf_reg_state *regs;
11063 branch = push_stack(env, next_idx, curr_idx, true);
11064 if (branch && insn) {
11065 regs = branch->frame[branch->curframe]->regs;
11066 if (BPF_SRC(insn->code) == BPF_K) {
11067 mark_reg_unknown(env, regs, insn->dst_reg);
11068 } else if (BPF_SRC(insn->code) == BPF_X) {
11069 mark_reg_unknown(env, regs, insn->dst_reg);
11070 mark_reg_unknown(env, regs, insn->src_reg);
11076 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11077 struct bpf_insn *insn,
11078 const struct bpf_reg_state *ptr_reg,
11079 const struct bpf_reg_state *off_reg,
11080 struct bpf_reg_state *dst_reg,
11081 struct bpf_sanitize_info *info,
11082 const bool commit_window)
11084 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11085 struct bpf_verifier_state *vstate = env->cur_state;
11086 bool off_is_imm = tnum_is_const(off_reg->var_off);
11087 bool off_is_neg = off_reg->smin_value < 0;
11088 bool ptr_is_dst_reg = ptr_reg == dst_reg;
11089 u8 opcode = BPF_OP(insn->code);
11090 u32 alu_state, alu_limit;
11091 struct bpf_reg_state tmp;
11095 if (can_skip_alu_sanitation(env, insn))
11098 /* We already marked aux for masking from non-speculative
11099 * paths, thus we got here in the first place. We only care
11100 * to explore bad access from here.
11102 if (vstate->speculative)
11105 if (!commit_window) {
11106 if (!tnum_is_const(off_reg->var_off) &&
11107 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11108 return REASON_BOUNDS;
11110 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
11111 (opcode == BPF_SUB && !off_is_neg);
11114 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11118 if (commit_window) {
11119 /* In commit phase we narrow the masking window based on
11120 * the observed pointer move after the simulated operation.
11122 alu_state = info->aux.alu_state;
11123 alu_limit = abs(info->aux.alu_limit - alu_limit);
11125 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11126 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11127 alu_state |= ptr_is_dst_reg ?
11128 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11130 /* Limit pruning on unknown scalars to enable deep search for
11131 * potential masking differences from other program paths.
11134 env->explore_alu_limits = true;
11137 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11141 /* If we're in commit phase, we're done here given we already
11142 * pushed the truncated dst_reg into the speculative verification
11145 * Also, when register is a known constant, we rewrite register-based
11146 * operation to immediate-based, and thus do not need masking (and as
11147 * a consequence, do not need to simulate the zero-truncation either).
11149 if (commit_window || off_is_imm)
11152 /* Simulate and find potential out-of-bounds access under
11153 * speculative execution from truncation as a result of
11154 * masking when off was not within expected range. If off
11155 * sits in dst, then we temporarily need to move ptr there
11156 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11157 * for cases where we use K-based arithmetic in one direction
11158 * and truncated reg-based in the other in order to explore
11161 if (!ptr_is_dst_reg) {
11163 copy_register_state(dst_reg, ptr_reg);
11165 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11167 if (!ptr_is_dst_reg && ret)
11169 return !ret ? REASON_STACK : 0;
11172 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11174 struct bpf_verifier_state *vstate = env->cur_state;
11176 /* If we simulate paths under speculation, we don't update the
11177 * insn as 'seen' such that when we verify unreachable paths in
11178 * the non-speculative domain, sanitize_dead_code() can still
11179 * rewrite/sanitize them.
11181 if (!vstate->speculative)
11182 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11185 static int sanitize_err(struct bpf_verifier_env *env,
11186 const struct bpf_insn *insn, int reason,
11187 const struct bpf_reg_state *off_reg,
11188 const struct bpf_reg_state *dst_reg)
11190 static const char *err = "pointer arithmetic with it prohibited for !root";
11191 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11192 u32 dst = insn->dst_reg, src = insn->src_reg;
11195 case REASON_BOUNDS:
11196 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11197 off_reg == dst_reg ? dst : src, err);
11200 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11201 off_reg == dst_reg ? src : dst, err);
11204 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11208 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11212 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11216 verbose(env, "verifier internal error: unknown reason (%d)\n",
11224 /* check that stack access falls within stack limits and that 'reg' doesn't
11225 * have a variable offset.
11227 * Variable offset is prohibited for unprivileged mode for simplicity since it
11228 * requires corresponding support in Spectre masking for stack ALU. See also
11229 * retrieve_ptr_limit().
11232 * 'off' includes 'reg->off'.
11234 static int check_stack_access_for_ptr_arithmetic(
11235 struct bpf_verifier_env *env,
11237 const struct bpf_reg_state *reg,
11240 if (!tnum_is_const(reg->var_off)) {
11243 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11244 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11245 regno, tn_buf, off);
11249 if (off >= 0 || off < -MAX_BPF_STACK) {
11250 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11251 "prohibited for !root; off=%d\n", regno, off);
11258 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11259 const struct bpf_insn *insn,
11260 const struct bpf_reg_state *dst_reg)
11262 u32 dst = insn->dst_reg;
11264 /* For unprivileged we require that resulting offset must be in bounds
11265 * in order to be able to sanitize access later on.
11267 if (env->bypass_spec_v1)
11270 switch (dst_reg->type) {
11272 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11273 dst_reg->off + dst_reg->var_off.value))
11276 case PTR_TO_MAP_VALUE:
11277 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
11278 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11279 "prohibited for !root\n", dst);
11290 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
11291 * Caller should also handle BPF_MOV case separately.
11292 * If we return -EACCES, caller may want to try again treating pointer as a
11293 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
11295 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11296 struct bpf_insn *insn,
11297 const struct bpf_reg_state *ptr_reg,
11298 const struct bpf_reg_state *off_reg)
11300 struct bpf_verifier_state *vstate = env->cur_state;
11301 struct bpf_func_state *state = vstate->frame[vstate->curframe];
11302 struct bpf_reg_state *regs = state->regs, *dst_reg;
11303 bool known = tnum_is_const(off_reg->var_off);
11304 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11305 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11306 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11307 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
11308 struct bpf_sanitize_info info = {};
11309 u8 opcode = BPF_OP(insn->code);
11310 u32 dst = insn->dst_reg;
11313 dst_reg = ®s[dst];
11315 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11316 smin_val > smax_val || umin_val > umax_val) {
11317 /* Taint dst register if offset had invalid bounds derived from
11318 * e.g. dead branches.
11320 __mark_reg_unknown(env, dst_reg);
11324 if (BPF_CLASS(insn->code) != BPF_ALU64) {
11325 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
11326 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11327 __mark_reg_unknown(env, dst_reg);
11332 "R%d 32-bit pointer arithmetic prohibited\n",
11337 if (ptr_reg->type & PTR_MAYBE_NULL) {
11338 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
11339 dst, reg_type_str(env, ptr_reg->type));
11343 switch (base_type(ptr_reg->type)) {
11344 case CONST_PTR_TO_MAP:
11345 /* smin_val represents the known value */
11346 if (known && smin_val == 0 && opcode == BPF_ADD)
11349 case PTR_TO_PACKET_END:
11350 case PTR_TO_SOCKET:
11351 case PTR_TO_SOCK_COMMON:
11352 case PTR_TO_TCP_SOCK:
11353 case PTR_TO_XDP_SOCK:
11354 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
11355 dst, reg_type_str(env, ptr_reg->type));
11361 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
11362 * The id may be overwritten later if we create a new variable offset.
11364 dst_reg->type = ptr_reg->type;
11365 dst_reg->id = ptr_reg->id;
11367 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
11368 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
11371 /* pointer types do not carry 32-bit bounds at the moment. */
11372 __mark_reg32_unbounded(dst_reg);
11374 if (sanitize_needed(opcode)) {
11375 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
11378 return sanitize_err(env, insn, ret, off_reg, dst_reg);
11383 /* We can take a fixed offset as long as it doesn't overflow
11384 * the s32 'off' field
11386 if (known && (ptr_reg->off + smin_val ==
11387 (s64)(s32)(ptr_reg->off + smin_val))) {
11388 /* pointer += K. Accumulate it into fixed offset */
11389 dst_reg->smin_value = smin_ptr;
11390 dst_reg->smax_value = smax_ptr;
11391 dst_reg->umin_value = umin_ptr;
11392 dst_reg->umax_value = umax_ptr;
11393 dst_reg->var_off = ptr_reg->var_off;
11394 dst_reg->off = ptr_reg->off + smin_val;
11395 dst_reg->raw = ptr_reg->raw;
11398 /* A new variable offset is created. Note that off_reg->off
11399 * == 0, since it's a scalar.
11400 * dst_reg gets the pointer type and since some positive
11401 * integer value was added to the pointer, give it a new 'id'
11402 * if it's a PTR_TO_PACKET.
11403 * this creates a new 'base' pointer, off_reg (variable) gets
11404 * added into the variable offset, and we copy the fixed offset
11407 if (signed_add_overflows(smin_ptr, smin_val) ||
11408 signed_add_overflows(smax_ptr, smax_val)) {
11409 dst_reg->smin_value = S64_MIN;
11410 dst_reg->smax_value = S64_MAX;
11412 dst_reg->smin_value = smin_ptr + smin_val;
11413 dst_reg->smax_value = smax_ptr + smax_val;
11415 if (umin_ptr + umin_val < umin_ptr ||
11416 umax_ptr + umax_val < umax_ptr) {
11417 dst_reg->umin_value = 0;
11418 dst_reg->umax_value = U64_MAX;
11420 dst_reg->umin_value = umin_ptr + umin_val;
11421 dst_reg->umax_value = umax_ptr + umax_val;
11423 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
11424 dst_reg->off = ptr_reg->off;
11425 dst_reg->raw = ptr_reg->raw;
11426 if (reg_is_pkt_pointer(ptr_reg)) {
11427 dst_reg->id = ++env->id_gen;
11428 /* something was added to pkt_ptr, set range to zero */
11429 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11433 if (dst_reg == off_reg) {
11434 /* scalar -= pointer. Creates an unknown scalar */
11435 verbose(env, "R%d tried to subtract pointer from scalar\n",
11439 /* We don't allow subtraction from FP, because (according to
11440 * test_verifier.c test "invalid fp arithmetic", JITs might not
11441 * be able to deal with it.
11443 if (ptr_reg->type == PTR_TO_STACK) {
11444 verbose(env, "R%d subtraction from stack pointer prohibited\n",
11448 if (known && (ptr_reg->off - smin_val ==
11449 (s64)(s32)(ptr_reg->off - smin_val))) {
11450 /* pointer -= K. Subtract it from fixed offset */
11451 dst_reg->smin_value = smin_ptr;
11452 dst_reg->smax_value = smax_ptr;
11453 dst_reg->umin_value = umin_ptr;
11454 dst_reg->umax_value = umax_ptr;
11455 dst_reg->var_off = ptr_reg->var_off;
11456 dst_reg->id = ptr_reg->id;
11457 dst_reg->off = ptr_reg->off - smin_val;
11458 dst_reg->raw = ptr_reg->raw;
11461 /* A new variable offset is created. If the subtrahend is known
11462 * nonnegative, then any reg->range we had before is still good.
11464 if (signed_sub_overflows(smin_ptr, smax_val) ||
11465 signed_sub_overflows(smax_ptr, smin_val)) {
11466 /* Overflow possible, we know nothing */
11467 dst_reg->smin_value = S64_MIN;
11468 dst_reg->smax_value = S64_MAX;
11470 dst_reg->smin_value = smin_ptr - smax_val;
11471 dst_reg->smax_value = smax_ptr - smin_val;
11473 if (umin_ptr < umax_val) {
11474 /* Overflow possible, we know nothing */
11475 dst_reg->umin_value = 0;
11476 dst_reg->umax_value = U64_MAX;
11478 /* Cannot overflow (as long as bounds are consistent) */
11479 dst_reg->umin_value = umin_ptr - umax_val;
11480 dst_reg->umax_value = umax_ptr - umin_val;
11482 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
11483 dst_reg->off = ptr_reg->off;
11484 dst_reg->raw = ptr_reg->raw;
11485 if (reg_is_pkt_pointer(ptr_reg)) {
11486 dst_reg->id = ++env->id_gen;
11487 /* something was added to pkt_ptr, set range to zero */
11489 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11495 /* bitwise ops on pointers are troublesome, prohibit. */
11496 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
11497 dst, bpf_alu_string[opcode >> 4]);
11500 /* other operators (e.g. MUL,LSH) produce non-pointer results */
11501 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
11502 dst, bpf_alu_string[opcode >> 4]);
11506 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
11508 reg_bounds_sync(dst_reg);
11509 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
11511 if (sanitize_needed(opcode)) {
11512 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
11515 return sanitize_err(env, insn, ret, off_reg, dst_reg);
11521 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
11522 struct bpf_reg_state *src_reg)
11524 s32 smin_val = src_reg->s32_min_value;
11525 s32 smax_val = src_reg->s32_max_value;
11526 u32 umin_val = src_reg->u32_min_value;
11527 u32 umax_val = src_reg->u32_max_value;
11529 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
11530 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
11531 dst_reg->s32_min_value = S32_MIN;
11532 dst_reg->s32_max_value = S32_MAX;
11534 dst_reg->s32_min_value += smin_val;
11535 dst_reg->s32_max_value += smax_val;
11537 if (dst_reg->u32_min_value + umin_val < umin_val ||
11538 dst_reg->u32_max_value + umax_val < umax_val) {
11539 dst_reg->u32_min_value = 0;
11540 dst_reg->u32_max_value = U32_MAX;
11542 dst_reg->u32_min_value += umin_val;
11543 dst_reg->u32_max_value += umax_val;
11547 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
11548 struct bpf_reg_state *src_reg)
11550 s64 smin_val = src_reg->smin_value;
11551 s64 smax_val = src_reg->smax_value;
11552 u64 umin_val = src_reg->umin_value;
11553 u64 umax_val = src_reg->umax_value;
11555 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
11556 signed_add_overflows(dst_reg->smax_value, smax_val)) {
11557 dst_reg->smin_value = S64_MIN;
11558 dst_reg->smax_value = S64_MAX;
11560 dst_reg->smin_value += smin_val;
11561 dst_reg->smax_value += smax_val;
11563 if (dst_reg->umin_value + umin_val < umin_val ||
11564 dst_reg->umax_value + umax_val < umax_val) {
11565 dst_reg->umin_value = 0;
11566 dst_reg->umax_value = U64_MAX;
11568 dst_reg->umin_value += umin_val;
11569 dst_reg->umax_value += umax_val;
11573 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
11574 struct bpf_reg_state *src_reg)
11576 s32 smin_val = src_reg->s32_min_value;
11577 s32 smax_val = src_reg->s32_max_value;
11578 u32 umin_val = src_reg->u32_min_value;
11579 u32 umax_val = src_reg->u32_max_value;
11581 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
11582 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
11583 /* Overflow possible, we know nothing */
11584 dst_reg->s32_min_value = S32_MIN;
11585 dst_reg->s32_max_value = S32_MAX;
11587 dst_reg->s32_min_value -= smax_val;
11588 dst_reg->s32_max_value -= smin_val;
11590 if (dst_reg->u32_min_value < umax_val) {
11591 /* Overflow possible, we know nothing */
11592 dst_reg->u32_min_value = 0;
11593 dst_reg->u32_max_value = U32_MAX;
11595 /* Cannot overflow (as long as bounds are consistent) */
11596 dst_reg->u32_min_value -= umax_val;
11597 dst_reg->u32_max_value -= umin_val;
11601 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
11602 struct bpf_reg_state *src_reg)
11604 s64 smin_val = src_reg->smin_value;
11605 s64 smax_val = src_reg->smax_value;
11606 u64 umin_val = src_reg->umin_value;
11607 u64 umax_val = src_reg->umax_value;
11609 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
11610 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
11611 /* Overflow possible, we know nothing */
11612 dst_reg->smin_value = S64_MIN;
11613 dst_reg->smax_value = S64_MAX;
11615 dst_reg->smin_value -= smax_val;
11616 dst_reg->smax_value -= smin_val;
11618 if (dst_reg->umin_value < umax_val) {
11619 /* Overflow possible, we know nothing */
11620 dst_reg->umin_value = 0;
11621 dst_reg->umax_value = U64_MAX;
11623 /* Cannot overflow (as long as bounds are consistent) */
11624 dst_reg->umin_value -= umax_val;
11625 dst_reg->umax_value -= umin_val;
11629 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
11630 struct bpf_reg_state *src_reg)
11632 s32 smin_val = src_reg->s32_min_value;
11633 u32 umin_val = src_reg->u32_min_value;
11634 u32 umax_val = src_reg->u32_max_value;
11636 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
11637 /* Ain't nobody got time to multiply that sign */
11638 __mark_reg32_unbounded(dst_reg);
11641 /* Both values are positive, so we can work with unsigned and
11642 * copy the result to signed (unless it exceeds S32_MAX).
11644 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
11645 /* Potential overflow, we know nothing */
11646 __mark_reg32_unbounded(dst_reg);
11649 dst_reg->u32_min_value *= umin_val;
11650 dst_reg->u32_max_value *= umax_val;
11651 if (dst_reg->u32_max_value > S32_MAX) {
11652 /* Overflow possible, we know nothing */
11653 dst_reg->s32_min_value = S32_MIN;
11654 dst_reg->s32_max_value = S32_MAX;
11656 dst_reg->s32_min_value = dst_reg->u32_min_value;
11657 dst_reg->s32_max_value = dst_reg->u32_max_value;
11661 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
11662 struct bpf_reg_state *src_reg)
11664 s64 smin_val = src_reg->smin_value;
11665 u64 umin_val = src_reg->umin_value;
11666 u64 umax_val = src_reg->umax_value;
11668 if (smin_val < 0 || dst_reg->smin_value < 0) {
11669 /* Ain't nobody got time to multiply that sign */
11670 __mark_reg64_unbounded(dst_reg);
11673 /* Both values are positive, so we can work with unsigned and
11674 * copy the result to signed (unless it exceeds S64_MAX).
11676 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
11677 /* Potential overflow, we know nothing */
11678 __mark_reg64_unbounded(dst_reg);
11681 dst_reg->umin_value *= umin_val;
11682 dst_reg->umax_value *= umax_val;
11683 if (dst_reg->umax_value > S64_MAX) {
11684 /* Overflow possible, we know nothing */
11685 dst_reg->smin_value = S64_MIN;
11686 dst_reg->smax_value = S64_MAX;
11688 dst_reg->smin_value = dst_reg->umin_value;
11689 dst_reg->smax_value = dst_reg->umax_value;
11693 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
11694 struct bpf_reg_state *src_reg)
11696 bool src_known = tnum_subreg_is_const(src_reg->var_off);
11697 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11698 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11699 s32 smin_val = src_reg->s32_min_value;
11700 u32 umax_val = src_reg->u32_max_value;
11702 if (src_known && dst_known) {
11703 __mark_reg32_known(dst_reg, var32_off.value);
11707 /* We get our minimum from the var_off, since that's inherently
11708 * bitwise. Our maximum is the minimum of the operands' maxima.
11710 dst_reg->u32_min_value = var32_off.value;
11711 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
11712 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11713 /* Lose signed bounds when ANDing negative numbers,
11714 * ain't nobody got time for that.
11716 dst_reg->s32_min_value = S32_MIN;
11717 dst_reg->s32_max_value = S32_MAX;
11719 /* ANDing two positives gives a positive, so safe to
11720 * cast result into s64.
11722 dst_reg->s32_min_value = dst_reg->u32_min_value;
11723 dst_reg->s32_max_value = dst_reg->u32_max_value;
11727 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
11728 struct bpf_reg_state *src_reg)
11730 bool src_known = tnum_is_const(src_reg->var_off);
11731 bool dst_known = tnum_is_const(dst_reg->var_off);
11732 s64 smin_val = src_reg->smin_value;
11733 u64 umax_val = src_reg->umax_value;
11735 if (src_known && dst_known) {
11736 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11740 /* We get our minimum from the var_off, since that's inherently
11741 * bitwise. Our maximum is the minimum of the operands' maxima.
11743 dst_reg->umin_value = dst_reg->var_off.value;
11744 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
11745 if (dst_reg->smin_value < 0 || smin_val < 0) {
11746 /* Lose signed bounds when ANDing negative numbers,
11747 * ain't nobody got time for that.
11749 dst_reg->smin_value = S64_MIN;
11750 dst_reg->smax_value = S64_MAX;
11752 /* ANDing two positives gives a positive, so safe to
11753 * cast result into s64.
11755 dst_reg->smin_value = dst_reg->umin_value;
11756 dst_reg->smax_value = dst_reg->umax_value;
11758 /* We may learn something more from the var_off */
11759 __update_reg_bounds(dst_reg);
11762 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
11763 struct bpf_reg_state *src_reg)
11765 bool src_known = tnum_subreg_is_const(src_reg->var_off);
11766 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11767 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11768 s32 smin_val = src_reg->s32_min_value;
11769 u32 umin_val = src_reg->u32_min_value;
11771 if (src_known && dst_known) {
11772 __mark_reg32_known(dst_reg, var32_off.value);
11776 /* We get our maximum from the var_off, and our minimum is the
11777 * maximum of the operands' minima
11779 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
11780 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11781 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11782 /* Lose signed bounds when ORing negative numbers,
11783 * ain't nobody got time for that.
11785 dst_reg->s32_min_value = S32_MIN;
11786 dst_reg->s32_max_value = S32_MAX;
11788 /* ORing two positives gives a positive, so safe to
11789 * cast result into s64.
11791 dst_reg->s32_min_value = dst_reg->u32_min_value;
11792 dst_reg->s32_max_value = dst_reg->u32_max_value;
11796 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
11797 struct bpf_reg_state *src_reg)
11799 bool src_known = tnum_is_const(src_reg->var_off);
11800 bool dst_known = tnum_is_const(dst_reg->var_off);
11801 s64 smin_val = src_reg->smin_value;
11802 u64 umin_val = src_reg->umin_value;
11804 if (src_known && dst_known) {
11805 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11809 /* We get our maximum from the var_off, and our minimum is the
11810 * maximum of the operands' minima
11812 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
11813 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11814 if (dst_reg->smin_value < 0 || smin_val < 0) {
11815 /* Lose signed bounds when ORing negative numbers,
11816 * ain't nobody got time for that.
11818 dst_reg->smin_value = S64_MIN;
11819 dst_reg->smax_value = S64_MAX;
11821 /* ORing two positives gives a positive, so safe to
11822 * cast result into s64.
11824 dst_reg->smin_value = dst_reg->umin_value;
11825 dst_reg->smax_value = dst_reg->umax_value;
11827 /* We may learn something more from the var_off */
11828 __update_reg_bounds(dst_reg);
11831 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
11832 struct bpf_reg_state *src_reg)
11834 bool src_known = tnum_subreg_is_const(src_reg->var_off);
11835 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11836 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11837 s32 smin_val = src_reg->s32_min_value;
11839 if (src_known && dst_known) {
11840 __mark_reg32_known(dst_reg, var32_off.value);
11844 /* We get both minimum and maximum from the var32_off. */
11845 dst_reg->u32_min_value = var32_off.value;
11846 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11848 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
11849 /* XORing two positive sign numbers gives a positive,
11850 * so safe to cast u32 result into s32.
11852 dst_reg->s32_min_value = dst_reg->u32_min_value;
11853 dst_reg->s32_max_value = dst_reg->u32_max_value;
11855 dst_reg->s32_min_value = S32_MIN;
11856 dst_reg->s32_max_value = S32_MAX;
11860 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
11861 struct bpf_reg_state *src_reg)
11863 bool src_known = tnum_is_const(src_reg->var_off);
11864 bool dst_known = tnum_is_const(dst_reg->var_off);
11865 s64 smin_val = src_reg->smin_value;
11867 if (src_known && dst_known) {
11868 /* dst_reg->var_off.value has been updated earlier */
11869 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11873 /* We get both minimum and maximum from the var_off. */
11874 dst_reg->umin_value = dst_reg->var_off.value;
11875 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11877 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
11878 /* XORing two positive sign numbers gives a positive,
11879 * so safe to cast u64 result into s64.
11881 dst_reg->smin_value = dst_reg->umin_value;
11882 dst_reg->smax_value = dst_reg->umax_value;
11884 dst_reg->smin_value = S64_MIN;
11885 dst_reg->smax_value = S64_MAX;
11888 __update_reg_bounds(dst_reg);
11891 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11892 u64 umin_val, u64 umax_val)
11894 /* We lose all sign bit information (except what we can pick
11897 dst_reg->s32_min_value = S32_MIN;
11898 dst_reg->s32_max_value = S32_MAX;
11899 /* If we might shift our top bit out, then we know nothing */
11900 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
11901 dst_reg->u32_min_value = 0;
11902 dst_reg->u32_max_value = U32_MAX;
11904 dst_reg->u32_min_value <<= umin_val;
11905 dst_reg->u32_max_value <<= umax_val;
11909 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11910 struct bpf_reg_state *src_reg)
11912 u32 umax_val = src_reg->u32_max_value;
11913 u32 umin_val = src_reg->u32_min_value;
11914 /* u32 alu operation will zext upper bits */
11915 struct tnum subreg = tnum_subreg(dst_reg->var_off);
11917 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11918 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
11919 /* Not required but being careful mark reg64 bounds as unknown so
11920 * that we are forced to pick them up from tnum and zext later and
11921 * if some path skips this step we are still safe.
11923 __mark_reg64_unbounded(dst_reg);
11924 __update_reg32_bounds(dst_reg);
11927 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
11928 u64 umin_val, u64 umax_val)
11930 /* Special case <<32 because it is a common compiler pattern to sign
11931 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
11932 * positive we know this shift will also be positive so we can track
11933 * bounds correctly. Otherwise we lose all sign bit information except
11934 * what we can pick up from var_off. Perhaps we can generalize this
11935 * later to shifts of any length.
11937 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
11938 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
11940 dst_reg->smax_value = S64_MAX;
11942 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
11943 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
11945 dst_reg->smin_value = S64_MIN;
11947 /* If we might shift our top bit out, then we know nothing */
11948 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
11949 dst_reg->umin_value = 0;
11950 dst_reg->umax_value = U64_MAX;
11952 dst_reg->umin_value <<= umin_val;
11953 dst_reg->umax_value <<= umax_val;
11957 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
11958 struct bpf_reg_state *src_reg)
11960 u64 umax_val = src_reg->umax_value;
11961 u64 umin_val = src_reg->umin_value;
11963 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
11964 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
11965 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11967 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
11968 /* We may learn something more from the var_off */
11969 __update_reg_bounds(dst_reg);
11972 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
11973 struct bpf_reg_state *src_reg)
11975 struct tnum subreg = tnum_subreg(dst_reg->var_off);
11976 u32 umax_val = src_reg->u32_max_value;
11977 u32 umin_val = src_reg->u32_min_value;
11979 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
11980 * be negative, then either:
11981 * 1) src_reg might be zero, so the sign bit of the result is
11982 * unknown, so we lose our signed bounds
11983 * 2) it's known negative, thus the unsigned bounds capture the
11985 * 3) the signed bounds cross zero, so they tell us nothing
11987 * If the value in dst_reg is known nonnegative, then again the
11988 * unsigned bounds capture the signed bounds.
11989 * Thus, in all cases it suffices to blow away our signed bounds
11990 * and rely on inferring new ones from the unsigned bounds and
11991 * var_off of the result.
11993 dst_reg->s32_min_value = S32_MIN;
11994 dst_reg->s32_max_value = S32_MAX;
11996 dst_reg->var_off = tnum_rshift(subreg, umin_val);
11997 dst_reg->u32_min_value >>= umax_val;
11998 dst_reg->u32_max_value >>= umin_val;
12000 __mark_reg64_unbounded(dst_reg);
12001 __update_reg32_bounds(dst_reg);
12004 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12005 struct bpf_reg_state *src_reg)
12007 u64 umax_val = src_reg->umax_value;
12008 u64 umin_val = src_reg->umin_value;
12010 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12011 * be negative, then either:
12012 * 1) src_reg might be zero, so the sign bit of the result is
12013 * unknown, so we lose our signed bounds
12014 * 2) it's known negative, thus the unsigned bounds capture the
12016 * 3) the signed bounds cross zero, so they tell us nothing
12018 * If the value in dst_reg is known nonnegative, then again the
12019 * unsigned bounds capture the signed bounds.
12020 * Thus, in all cases it suffices to blow away our signed bounds
12021 * and rely on inferring new ones from the unsigned bounds and
12022 * var_off of the result.
12024 dst_reg->smin_value = S64_MIN;
12025 dst_reg->smax_value = S64_MAX;
12026 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12027 dst_reg->umin_value >>= umax_val;
12028 dst_reg->umax_value >>= umin_val;
12030 /* Its not easy to operate on alu32 bounds here because it depends
12031 * on bits being shifted in. Take easy way out and mark unbounded
12032 * so we can recalculate later from tnum.
12034 __mark_reg32_unbounded(dst_reg);
12035 __update_reg_bounds(dst_reg);
12038 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12039 struct bpf_reg_state *src_reg)
12041 u64 umin_val = src_reg->u32_min_value;
12043 /* Upon reaching here, src_known is true and
12044 * umax_val is equal to umin_val.
12046 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12047 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12049 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12051 /* blow away the dst_reg umin_value/umax_value and rely on
12052 * dst_reg var_off to refine the result.
12054 dst_reg->u32_min_value = 0;
12055 dst_reg->u32_max_value = U32_MAX;
12057 __mark_reg64_unbounded(dst_reg);
12058 __update_reg32_bounds(dst_reg);
12061 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12062 struct bpf_reg_state *src_reg)
12064 u64 umin_val = src_reg->umin_value;
12066 /* Upon reaching here, src_known is true and umax_val is equal
12069 dst_reg->smin_value >>= umin_val;
12070 dst_reg->smax_value >>= umin_val;
12072 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12074 /* blow away the dst_reg umin_value/umax_value and rely on
12075 * dst_reg var_off to refine the result.
12077 dst_reg->umin_value = 0;
12078 dst_reg->umax_value = U64_MAX;
12080 /* Its not easy to operate on alu32 bounds here because it depends
12081 * on bits being shifted in from upper 32-bits. Take easy way out
12082 * and mark unbounded so we can recalculate later from tnum.
12084 __mark_reg32_unbounded(dst_reg);
12085 __update_reg_bounds(dst_reg);
12088 /* WARNING: This function does calculations on 64-bit values, but the actual
12089 * execution may occur on 32-bit values. Therefore, things like bitshifts
12090 * need extra checks in the 32-bit case.
12092 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12093 struct bpf_insn *insn,
12094 struct bpf_reg_state *dst_reg,
12095 struct bpf_reg_state src_reg)
12097 struct bpf_reg_state *regs = cur_regs(env);
12098 u8 opcode = BPF_OP(insn->code);
12100 s64 smin_val, smax_val;
12101 u64 umin_val, umax_val;
12102 s32 s32_min_val, s32_max_val;
12103 u32 u32_min_val, u32_max_val;
12104 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12105 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12108 smin_val = src_reg.smin_value;
12109 smax_val = src_reg.smax_value;
12110 umin_val = src_reg.umin_value;
12111 umax_val = src_reg.umax_value;
12113 s32_min_val = src_reg.s32_min_value;
12114 s32_max_val = src_reg.s32_max_value;
12115 u32_min_val = src_reg.u32_min_value;
12116 u32_max_val = src_reg.u32_max_value;
12119 src_known = tnum_subreg_is_const(src_reg.var_off);
12121 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12122 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12123 /* Taint dst register if offset had invalid bounds
12124 * derived from e.g. dead branches.
12126 __mark_reg_unknown(env, dst_reg);
12130 src_known = tnum_is_const(src_reg.var_off);
12132 (smin_val != smax_val || umin_val != umax_val)) ||
12133 smin_val > smax_val || umin_val > umax_val) {
12134 /* Taint dst register if offset had invalid bounds
12135 * derived from e.g. dead branches.
12137 __mark_reg_unknown(env, dst_reg);
12143 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12144 __mark_reg_unknown(env, dst_reg);
12148 if (sanitize_needed(opcode)) {
12149 ret = sanitize_val_alu(env, insn);
12151 return sanitize_err(env, insn, ret, NULL, NULL);
12154 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12155 * There are two classes of instructions: The first class we track both
12156 * alu32 and alu64 sign/unsigned bounds independently this provides the
12157 * greatest amount of precision when alu operations are mixed with jmp32
12158 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12159 * and BPF_OR. This is possible because these ops have fairly easy to
12160 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12161 * See alu32 verifier tests for examples. The second class of
12162 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12163 * with regards to tracking sign/unsigned bounds because the bits may
12164 * cross subreg boundaries in the alu64 case. When this happens we mark
12165 * the reg unbounded in the subreg bound space and use the resulting
12166 * tnum to calculate an approximation of the sign/unsigned bounds.
12170 scalar32_min_max_add(dst_reg, &src_reg);
12171 scalar_min_max_add(dst_reg, &src_reg);
12172 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12175 scalar32_min_max_sub(dst_reg, &src_reg);
12176 scalar_min_max_sub(dst_reg, &src_reg);
12177 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12180 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12181 scalar32_min_max_mul(dst_reg, &src_reg);
12182 scalar_min_max_mul(dst_reg, &src_reg);
12185 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12186 scalar32_min_max_and(dst_reg, &src_reg);
12187 scalar_min_max_and(dst_reg, &src_reg);
12190 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12191 scalar32_min_max_or(dst_reg, &src_reg);
12192 scalar_min_max_or(dst_reg, &src_reg);
12195 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12196 scalar32_min_max_xor(dst_reg, &src_reg);
12197 scalar_min_max_xor(dst_reg, &src_reg);
12200 if (umax_val >= insn_bitness) {
12201 /* Shifts greater than 31 or 63 are undefined.
12202 * This includes shifts by a negative number.
12204 mark_reg_unknown(env, regs, insn->dst_reg);
12208 scalar32_min_max_lsh(dst_reg, &src_reg);
12210 scalar_min_max_lsh(dst_reg, &src_reg);
12213 if (umax_val >= insn_bitness) {
12214 /* Shifts greater than 31 or 63 are undefined.
12215 * This includes shifts by a negative number.
12217 mark_reg_unknown(env, regs, insn->dst_reg);
12221 scalar32_min_max_rsh(dst_reg, &src_reg);
12223 scalar_min_max_rsh(dst_reg, &src_reg);
12226 if (umax_val >= insn_bitness) {
12227 /* Shifts greater than 31 or 63 are undefined.
12228 * This includes shifts by a negative number.
12230 mark_reg_unknown(env, regs, insn->dst_reg);
12234 scalar32_min_max_arsh(dst_reg, &src_reg);
12236 scalar_min_max_arsh(dst_reg, &src_reg);
12239 mark_reg_unknown(env, regs, insn->dst_reg);
12243 /* ALU32 ops are zero extended into 64bit register */
12245 zext_32_to_64(dst_reg);
12246 reg_bounds_sync(dst_reg);
12250 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12253 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12254 struct bpf_insn *insn)
12256 struct bpf_verifier_state *vstate = env->cur_state;
12257 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12258 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12259 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12260 u8 opcode = BPF_OP(insn->code);
12263 dst_reg = ®s[insn->dst_reg];
12265 if (dst_reg->type != SCALAR_VALUE)
12268 /* Make sure ID is cleared otherwise dst_reg min/max could be
12269 * incorrectly propagated into other registers by find_equal_scalars()
12272 if (BPF_SRC(insn->code) == BPF_X) {
12273 src_reg = ®s[insn->src_reg];
12274 if (src_reg->type != SCALAR_VALUE) {
12275 if (dst_reg->type != SCALAR_VALUE) {
12276 /* Combining two pointers by any ALU op yields
12277 * an arbitrary scalar. Disallow all math except
12278 * pointer subtraction
12280 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12281 mark_reg_unknown(env, regs, insn->dst_reg);
12284 verbose(env, "R%d pointer %s pointer prohibited\n",
12286 bpf_alu_string[opcode >> 4]);
12289 /* scalar += pointer
12290 * This is legal, but we have to reverse our
12291 * src/dest handling in computing the range
12293 err = mark_chain_precision(env, insn->dst_reg);
12296 return adjust_ptr_min_max_vals(env, insn,
12299 } else if (ptr_reg) {
12300 /* pointer += scalar */
12301 err = mark_chain_precision(env, insn->src_reg);
12304 return adjust_ptr_min_max_vals(env, insn,
12306 } else if (dst_reg->precise) {
12307 /* if dst_reg is precise, src_reg should be precise as well */
12308 err = mark_chain_precision(env, insn->src_reg);
12313 /* Pretend the src is a reg with a known value, since we only
12314 * need to be able to read from this state.
12316 off_reg.type = SCALAR_VALUE;
12317 __mark_reg_known(&off_reg, insn->imm);
12318 src_reg = &off_reg;
12319 if (ptr_reg) /* pointer += K */
12320 return adjust_ptr_min_max_vals(env, insn,
12324 /* Got here implies adding two SCALAR_VALUEs */
12325 if (WARN_ON_ONCE(ptr_reg)) {
12326 print_verifier_state(env, state, true);
12327 verbose(env, "verifier internal error: unexpected ptr_reg\n");
12330 if (WARN_ON(!src_reg)) {
12331 print_verifier_state(env, state, true);
12332 verbose(env, "verifier internal error: no src_reg\n");
12335 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
12338 /* check validity of 32-bit and 64-bit arithmetic operations */
12339 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
12341 struct bpf_reg_state *regs = cur_regs(env);
12342 u8 opcode = BPF_OP(insn->code);
12345 if (opcode == BPF_END || opcode == BPF_NEG) {
12346 if (opcode == BPF_NEG) {
12347 if (BPF_SRC(insn->code) != BPF_K ||
12348 insn->src_reg != BPF_REG_0 ||
12349 insn->off != 0 || insn->imm != 0) {
12350 verbose(env, "BPF_NEG uses reserved fields\n");
12354 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
12355 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
12356 BPF_CLASS(insn->code) == BPF_ALU64) {
12357 verbose(env, "BPF_END uses reserved fields\n");
12362 /* check src operand */
12363 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12367 if (is_pointer_value(env, insn->dst_reg)) {
12368 verbose(env, "R%d pointer arithmetic prohibited\n",
12373 /* check dest operand */
12374 err = check_reg_arg(env, insn->dst_reg, DST_OP);
12378 } else if (opcode == BPF_MOV) {
12380 if (BPF_SRC(insn->code) == BPF_X) {
12381 if (insn->imm != 0 || insn->off != 0) {
12382 verbose(env, "BPF_MOV uses reserved fields\n");
12386 /* check src operand */
12387 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12391 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12392 verbose(env, "BPF_MOV uses reserved fields\n");
12397 /* check dest operand, mark as required later */
12398 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12402 if (BPF_SRC(insn->code) == BPF_X) {
12403 struct bpf_reg_state *src_reg = regs + insn->src_reg;
12404 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
12406 if (BPF_CLASS(insn->code) == BPF_ALU64) {
12408 * copy register state to dest reg
12410 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
12411 /* Assign src and dst registers the same ID
12412 * that will be used by find_equal_scalars()
12413 * to propagate min/max range.
12415 src_reg->id = ++env->id_gen;
12416 copy_register_state(dst_reg, src_reg);
12417 dst_reg->live |= REG_LIVE_WRITTEN;
12418 dst_reg->subreg_def = DEF_NOT_SUBREG;
12420 /* R1 = (u32) R2 */
12421 if (is_pointer_value(env, insn->src_reg)) {
12423 "R%d partial copy of pointer\n",
12426 } else if (src_reg->type == SCALAR_VALUE) {
12427 copy_register_state(dst_reg, src_reg);
12428 /* Make sure ID is cleared otherwise
12429 * dst_reg min/max could be incorrectly
12430 * propagated into src_reg by find_equal_scalars()
12433 dst_reg->live |= REG_LIVE_WRITTEN;
12434 dst_reg->subreg_def = env->insn_idx + 1;
12436 mark_reg_unknown(env, regs,
12439 zext_32_to_64(dst_reg);
12440 reg_bounds_sync(dst_reg);
12444 * remember the value we stored into this reg
12446 /* clear any state __mark_reg_known doesn't set */
12447 mark_reg_unknown(env, regs, insn->dst_reg);
12448 regs[insn->dst_reg].type = SCALAR_VALUE;
12449 if (BPF_CLASS(insn->code) == BPF_ALU64) {
12450 __mark_reg_known(regs + insn->dst_reg,
12453 __mark_reg_known(regs + insn->dst_reg,
12458 } else if (opcode > BPF_END) {
12459 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
12462 } else { /* all other ALU ops: and, sub, xor, add, ... */
12464 if (BPF_SRC(insn->code) == BPF_X) {
12465 if (insn->imm != 0 || insn->off != 0) {
12466 verbose(env, "BPF_ALU uses reserved fields\n");
12469 /* check src1 operand */
12470 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12474 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12475 verbose(env, "BPF_ALU uses reserved fields\n");
12480 /* check src2 operand */
12481 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12485 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
12486 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
12487 verbose(env, "div by zero\n");
12491 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
12492 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
12493 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
12495 if (insn->imm < 0 || insn->imm >= size) {
12496 verbose(env, "invalid shift %d\n", insn->imm);
12501 /* check dest operand */
12502 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12506 return adjust_reg_min_max_vals(env, insn);
12512 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
12513 struct bpf_reg_state *dst_reg,
12514 enum bpf_reg_type type,
12515 bool range_right_open)
12517 struct bpf_func_state *state;
12518 struct bpf_reg_state *reg;
12521 if (dst_reg->off < 0 ||
12522 (dst_reg->off == 0 && range_right_open))
12523 /* This doesn't give us any range */
12526 if (dst_reg->umax_value > MAX_PACKET_OFF ||
12527 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
12528 /* Risk of overflow. For instance, ptr + (1<<63) may be less
12529 * than pkt_end, but that's because it's also less than pkt.
12533 new_range = dst_reg->off;
12534 if (range_right_open)
12537 /* Examples for register markings:
12539 * pkt_data in dst register:
12543 * if (r2 > pkt_end) goto <handle exception>
12548 * if (r2 < pkt_end) goto <access okay>
12549 * <handle exception>
12552 * r2 == dst_reg, pkt_end == src_reg
12553 * r2=pkt(id=n,off=8,r=0)
12554 * r3=pkt(id=n,off=0,r=0)
12556 * pkt_data in src register:
12560 * if (pkt_end >= r2) goto <access okay>
12561 * <handle exception>
12565 * if (pkt_end <= r2) goto <handle exception>
12569 * pkt_end == dst_reg, r2 == src_reg
12570 * r2=pkt(id=n,off=8,r=0)
12571 * r3=pkt(id=n,off=0,r=0)
12573 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
12574 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
12575 * and [r3, r3 + 8-1) respectively is safe to access depending on
12579 /* If our ids match, then we must have the same max_value. And we
12580 * don't care about the other reg's fixed offset, since if it's too big
12581 * the range won't allow anything.
12582 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
12584 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12585 if (reg->type == type && reg->id == dst_reg->id)
12586 /* keep the maximum range already checked */
12587 reg->range = max(reg->range, new_range);
12591 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
12593 struct tnum subreg = tnum_subreg(reg->var_off);
12594 s32 sval = (s32)val;
12598 if (tnum_is_const(subreg))
12599 return !!tnum_equals_const(subreg, val);
12600 else if (val < reg->u32_min_value || val > reg->u32_max_value)
12604 if (tnum_is_const(subreg))
12605 return !tnum_equals_const(subreg, val);
12606 else if (val < reg->u32_min_value || val > reg->u32_max_value)
12610 if ((~subreg.mask & subreg.value) & val)
12612 if (!((subreg.mask | subreg.value) & val))
12616 if (reg->u32_min_value > val)
12618 else if (reg->u32_max_value <= val)
12622 if (reg->s32_min_value > sval)
12624 else if (reg->s32_max_value <= sval)
12628 if (reg->u32_max_value < val)
12630 else if (reg->u32_min_value >= val)
12634 if (reg->s32_max_value < sval)
12636 else if (reg->s32_min_value >= sval)
12640 if (reg->u32_min_value >= val)
12642 else if (reg->u32_max_value < val)
12646 if (reg->s32_min_value >= sval)
12648 else if (reg->s32_max_value < sval)
12652 if (reg->u32_max_value <= val)
12654 else if (reg->u32_min_value > val)
12658 if (reg->s32_max_value <= sval)
12660 else if (reg->s32_min_value > sval)
12669 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
12671 s64 sval = (s64)val;
12675 if (tnum_is_const(reg->var_off))
12676 return !!tnum_equals_const(reg->var_off, val);
12677 else if (val < reg->umin_value || val > reg->umax_value)
12681 if (tnum_is_const(reg->var_off))
12682 return !tnum_equals_const(reg->var_off, val);
12683 else if (val < reg->umin_value || val > reg->umax_value)
12687 if ((~reg->var_off.mask & reg->var_off.value) & val)
12689 if (!((reg->var_off.mask | reg->var_off.value) & val))
12693 if (reg->umin_value > val)
12695 else if (reg->umax_value <= val)
12699 if (reg->smin_value > sval)
12701 else if (reg->smax_value <= sval)
12705 if (reg->umax_value < val)
12707 else if (reg->umin_value >= val)
12711 if (reg->smax_value < sval)
12713 else if (reg->smin_value >= sval)
12717 if (reg->umin_value >= val)
12719 else if (reg->umax_value < val)
12723 if (reg->smin_value >= sval)
12725 else if (reg->smax_value < sval)
12729 if (reg->umax_value <= val)
12731 else if (reg->umin_value > val)
12735 if (reg->smax_value <= sval)
12737 else if (reg->smin_value > sval)
12745 /* compute branch direction of the expression "if (reg opcode val) goto target;"
12747 * 1 - branch will be taken and "goto target" will be executed
12748 * 0 - branch will not be taken and fall-through to next insn
12749 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
12752 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
12755 if (__is_pointer_value(false, reg)) {
12756 if (!reg_type_not_null(reg->type))
12759 /* If pointer is valid tests against zero will fail so we can
12760 * use this to direct branch taken.
12776 return is_branch32_taken(reg, val, opcode);
12777 return is_branch64_taken(reg, val, opcode);
12780 static int flip_opcode(u32 opcode)
12782 /* How can we transform "a <op> b" into "b <op> a"? */
12783 static const u8 opcode_flip[16] = {
12784 /* these stay the same */
12785 [BPF_JEQ >> 4] = BPF_JEQ,
12786 [BPF_JNE >> 4] = BPF_JNE,
12787 [BPF_JSET >> 4] = BPF_JSET,
12788 /* these swap "lesser" and "greater" (L and G in the opcodes) */
12789 [BPF_JGE >> 4] = BPF_JLE,
12790 [BPF_JGT >> 4] = BPF_JLT,
12791 [BPF_JLE >> 4] = BPF_JGE,
12792 [BPF_JLT >> 4] = BPF_JGT,
12793 [BPF_JSGE >> 4] = BPF_JSLE,
12794 [BPF_JSGT >> 4] = BPF_JSLT,
12795 [BPF_JSLE >> 4] = BPF_JSGE,
12796 [BPF_JSLT >> 4] = BPF_JSGT
12798 return opcode_flip[opcode >> 4];
12801 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
12802 struct bpf_reg_state *src_reg,
12805 struct bpf_reg_state *pkt;
12807 if (src_reg->type == PTR_TO_PACKET_END) {
12809 } else if (dst_reg->type == PTR_TO_PACKET_END) {
12811 opcode = flip_opcode(opcode);
12816 if (pkt->range >= 0)
12821 /* pkt <= pkt_end */
12824 /* pkt > pkt_end */
12825 if (pkt->range == BEYOND_PKT_END)
12826 /* pkt has at last one extra byte beyond pkt_end */
12827 return opcode == BPF_JGT;
12830 /* pkt < pkt_end */
12833 /* pkt >= pkt_end */
12834 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
12835 return opcode == BPF_JGE;
12841 /* Adjusts the register min/max values in the case that the dst_reg is the
12842 * variable register that we are working on, and src_reg is a constant or we're
12843 * simply doing a BPF_K check.
12844 * In JEQ/JNE cases we also adjust the var_off values.
12846 static void reg_set_min_max(struct bpf_reg_state *true_reg,
12847 struct bpf_reg_state *false_reg,
12848 u64 val, u32 val32,
12849 u8 opcode, bool is_jmp32)
12851 struct tnum false_32off = tnum_subreg(false_reg->var_off);
12852 struct tnum false_64off = false_reg->var_off;
12853 struct tnum true_32off = tnum_subreg(true_reg->var_off);
12854 struct tnum true_64off = true_reg->var_off;
12855 s64 sval = (s64)val;
12856 s32 sval32 = (s32)val32;
12858 /* If the dst_reg is a pointer, we can't learn anything about its
12859 * variable offset from the compare (unless src_reg were a pointer into
12860 * the same object, but we don't bother with that.
12861 * Since false_reg and true_reg have the same type by construction, we
12862 * only need to check one of them for pointerness.
12864 if (__is_pointer_value(false, false_reg))
12868 /* JEQ/JNE comparison doesn't change the register equivalence.
12871 * if (r1 == 42) goto label;
12873 * label: // here both r1 and r2 are known to be 42.
12875 * Hence when marking register as known preserve it's ID.
12879 __mark_reg32_known(true_reg, val32);
12880 true_32off = tnum_subreg(true_reg->var_off);
12882 ___mark_reg_known(true_reg, val);
12883 true_64off = true_reg->var_off;
12888 __mark_reg32_known(false_reg, val32);
12889 false_32off = tnum_subreg(false_reg->var_off);
12891 ___mark_reg_known(false_reg, val);
12892 false_64off = false_reg->var_off;
12897 false_32off = tnum_and(false_32off, tnum_const(~val32));
12898 if (is_power_of_2(val32))
12899 true_32off = tnum_or(true_32off,
12900 tnum_const(val32));
12902 false_64off = tnum_and(false_64off, tnum_const(~val));
12903 if (is_power_of_2(val))
12904 true_64off = tnum_or(true_64off,
12912 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
12913 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
12915 false_reg->u32_max_value = min(false_reg->u32_max_value,
12917 true_reg->u32_min_value = max(true_reg->u32_min_value,
12920 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
12921 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
12923 false_reg->umax_value = min(false_reg->umax_value, false_umax);
12924 true_reg->umin_value = max(true_reg->umin_value, true_umin);
12932 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
12933 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
12935 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
12936 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
12938 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
12939 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
12941 false_reg->smax_value = min(false_reg->smax_value, false_smax);
12942 true_reg->smin_value = max(true_reg->smin_value, true_smin);
12950 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
12951 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
12953 false_reg->u32_min_value = max(false_reg->u32_min_value,
12955 true_reg->u32_max_value = min(true_reg->u32_max_value,
12958 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
12959 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
12961 false_reg->umin_value = max(false_reg->umin_value, false_umin);
12962 true_reg->umax_value = min(true_reg->umax_value, true_umax);
12970 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
12971 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
12973 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
12974 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
12976 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
12977 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
12979 false_reg->smin_value = max(false_reg->smin_value, false_smin);
12980 true_reg->smax_value = min(true_reg->smax_value, true_smax);
12989 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
12990 tnum_subreg(false_32off));
12991 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
12992 tnum_subreg(true_32off));
12993 __reg_combine_32_into_64(false_reg);
12994 __reg_combine_32_into_64(true_reg);
12996 false_reg->var_off = false_64off;
12997 true_reg->var_off = true_64off;
12998 __reg_combine_64_into_32(false_reg);
12999 __reg_combine_64_into_32(true_reg);
13003 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13004 * the variable reg.
13006 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13007 struct bpf_reg_state *false_reg,
13008 u64 val, u32 val32,
13009 u8 opcode, bool is_jmp32)
13011 opcode = flip_opcode(opcode);
13012 /* This uses zero as "not present in table"; luckily the zero opcode,
13013 * BPF_JA, can't get here.
13016 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13019 /* Regs are known to be equal, so intersect their min/max/var_off */
13020 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13021 struct bpf_reg_state *dst_reg)
13023 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13024 dst_reg->umin_value);
13025 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13026 dst_reg->umax_value);
13027 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13028 dst_reg->smin_value);
13029 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13030 dst_reg->smax_value);
13031 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13033 reg_bounds_sync(src_reg);
13034 reg_bounds_sync(dst_reg);
13037 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13038 struct bpf_reg_state *true_dst,
13039 struct bpf_reg_state *false_src,
13040 struct bpf_reg_state *false_dst,
13045 __reg_combine_min_max(true_src, true_dst);
13048 __reg_combine_min_max(false_src, false_dst);
13053 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13054 struct bpf_reg_state *reg, u32 id,
13057 if (type_may_be_null(reg->type) && reg->id == id &&
13058 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13059 /* Old offset (both fixed and variable parts) should have been
13060 * known-zero, because we don't allow pointer arithmetic on
13061 * pointers that might be NULL. If we see this happening, don't
13062 * convert the register.
13064 * But in some cases, some helpers that return local kptrs
13065 * advance offset for the returned pointer. In those cases, it
13066 * is fine to expect to see reg->off.
13068 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13070 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13071 WARN_ON_ONCE(reg->off))
13075 reg->type = SCALAR_VALUE;
13076 /* We don't need id and ref_obj_id from this point
13077 * onwards anymore, thus we should better reset it,
13078 * so that state pruning has chances to take effect.
13081 reg->ref_obj_id = 0;
13086 mark_ptr_not_null_reg(reg);
13088 if (!reg_may_point_to_spin_lock(reg)) {
13089 /* For not-NULL ptr, reg->ref_obj_id will be reset
13090 * in release_reference().
13092 * reg->id is still used by spin_lock ptr. Other
13093 * than spin_lock ptr type, reg->id can be reset.
13100 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13101 * be folded together at some point.
13103 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13106 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13107 struct bpf_reg_state *regs = state->regs, *reg;
13108 u32 ref_obj_id = regs[regno].ref_obj_id;
13109 u32 id = regs[regno].id;
13111 if (ref_obj_id && ref_obj_id == id && is_null)
13112 /* regs[regno] is in the " == NULL" branch.
13113 * No one could have freed the reference state before
13114 * doing the NULL check.
13116 WARN_ON_ONCE(release_reference_state(state, id));
13118 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13119 mark_ptr_or_null_reg(state, reg, id, is_null);
13123 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13124 struct bpf_reg_state *dst_reg,
13125 struct bpf_reg_state *src_reg,
13126 struct bpf_verifier_state *this_branch,
13127 struct bpf_verifier_state *other_branch)
13129 if (BPF_SRC(insn->code) != BPF_X)
13132 /* Pointers are always 64-bit. */
13133 if (BPF_CLASS(insn->code) == BPF_JMP32)
13136 switch (BPF_OP(insn->code)) {
13138 if ((dst_reg->type == PTR_TO_PACKET &&
13139 src_reg->type == PTR_TO_PACKET_END) ||
13140 (dst_reg->type == PTR_TO_PACKET_META &&
13141 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13142 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13143 find_good_pkt_pointers(this_branch, dst_reg,
13144 dst_reg->type, false);
13145 mark_pkt_end(other_branch, insn->dst_reg, true);
13146 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13147 src_reg->type == PTR_TO_PACKET) ||
13148 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13149 src_reg->type == PTR_TO_PACKET_META)) {
13150 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13151 find_good_pkt_pointers(other_branch, src_reg,
13152 src_reg->type, true);
13153 mark_pkt_end(this_branch, insn->src_reg, false);
13159 if ((dst_reg->type == PTR_TO_PACKET &&
13160 src_reg->type == PTR_TO_PACKET_END) ||
13161 (dst_reg->type == PTR_TO_PACKET_META &&
13162 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13163 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13164 find_good_pkt_pointers(other_branch, dst_reg,
13165 dst_reg->type, true);
13166 mark_pkt_end(this_branch, insn->dst_reg, false);
13167 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13168 src_reg->type == PTR_TO_PACKET) ||
13169 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13170 src_reg->type == PTR_TO_PACKET_META)) {
13171 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13172 find_good_pkt_pointers(this_branch, src_reg,
13173 src_reg->type, false);
13174 mark_pkt_end(other_branch, insn->src_reg, true);
13180 if ((dst_reg->type == PTR_TO_PACKET &&
13181 src_reg->type == PTR_TO_PACKET_END) ||
13182 (dst_reg->type == PTR_TO_PACKET_META &&
13183 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13184 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13185 find_good_pkt_pointers(this_branch, dst_reg,
13186 dst_reg->type, true);
13187 mark_pkt_end(other_branch, insn->dst_reg, false);
13188 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13189 src_reg->type == PTR_TO_PACKET) ||
13190 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13191 src_reg->type == PTR_TO_PACKET_META)) {
13192 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13193 find_good_pkt_pointers(other_branch, src_reg,
13194 src_reg->type, false);
13195 mark_pkt_end(this_branch, insn->src_reg, true);
13201 if ((dst_reg->type == PTR_TO_PACKET &&
13202 src_reg->type == PTR_TO_PACKET_END) ||
13203 (dst_reg->type == PTR_TO_PACKET_META &&
13204 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13205 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13206 find_good_pkt_pointers(other_branch, dst_reg,
13207 dst_reg->type, false);
13208 mark_pkt_end(this_branch, insn->dst_reg, true);
13209 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13210 src_reg->type == PTR_TO_PACKET) ||
13211 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13212 src_reg->type == PTR_TO_PACKET_META)) {
13213 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13214 find_good_pkt_pointers(this_branch, src_reg,
13215 src_reg->type, true);
13216 mark_pkt_end(other_branch, insn->src_reg, false);
13228 static void find_equal_scalars(struct bpf_verifier_state *vstate,
13229 struct bpf_reg_state *known_reg)
13231 struct bpf_func_state *state;
13232 struct bpf_reg_state *reg;
13234 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13235 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
13236 copy_register_state(reg, known_reg);
13240 static int check_cond_jmp_op(struct bpf_verifier_env *env,
13241 struct bpf_insn *insn, int *insn_idx)
13243 struct bpf_verifier_state *this_branch = env->cur_state;
13244 struct bpf_verifier_state *other_branch;
13245 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
13246 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
13247 struct bpf_reg_state *eq_branch_regs;
13248 u8 opcode = BPF_OP(insn->code);
13253 /* Only conditional jumps are expected to reach here. */
13254 if (opcode == BPF_JA || opcode > BPF_JSLE) {
13255 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
13259 if (BPF_SRC(insn->code) == BPF_X) {
13260 if (insn->imm != 0) {
13261 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13265 /* check src1 operand */
13266 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13270 if (is_pointer_value(env, insn->src_reg)) {
13271 verbose(env, "R%d pointer comparison prohibited\n",
13275 src_reg = ®s[insn->src_reg];
13277 if (insn->src_reg != BPF_REG_0) {
13278 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13283 /* check src2 operand */
13284 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13288 dst_reg = ®s[insn->dst_reg];
13289 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
13291 if (BPF_SRC(insn->code) == BPF_K) {
13292 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13293 } else if (src_reg->type == SCALAR_VALUE &&
13294 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13295 pred = is_branch_taken(dst_reg,
13296 tnum_subreg(src_reg->var_off).value,
13299 } else if (src_reg->type == SCALAR_VALUE &&
13300 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13301 pred = is_branch_taken(dst_reg,
13302 src_reg->var_off.value,
13305 } else if (dst_reg->type == SCALAR_VALUE &&
13306 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
13307 pred = is_branch_taken(src_reg,
13308 tnum_subreg(dst_reg->var_off).value,
13309 flip_opcode(opcode),
13311 } else if (dst_reg->type == SCALAR_VALUE &&
13312 !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
13313 pred = is_branch_taken(src_reg,
13314 dst_reg->var_off.value,
13315 flip_opcode(opcode),
13317 } else if (reg_is_pkt_pointer_any(dst_reg) &&
13318 reg_is_pkt_pointer_any(src_reg) &&
13320 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
13324 /* If we get here with a dst_reg pointer type it is because
13325 * above is_branch_taken() special cased the 0 comparison.
13327 if (!__is_pointer_value(false, dst_reg))
13328 err = mark_chain_precision(env, insn->dst_reg);
13329 if (BPF_SRC(insn->code) == BPF_X && !err &&
13330 !__is_pointer_value(false, src_reg))
13331 err = mark_chain_precision(env, insn->src_reg);
13337 /* Only follow the goto, ignore fall-through. If needed, push
13338 * the fall-through branch for simulation under speculative
13341 if (!env->bypass_spec_v1 &&
13342 !sanitize_speculative_path(env, insn, *insn_idx + 1,
13345 *insn_idx += insn->off;
13347 } else if (pred == 0) {
13348 /* Only follow the fall-through branch, since that's where the
13349 * program will go. If needed, push the goto branch for
13350 * simulation under speculative execution.
13352 if (!env->bypass_spec_v1 &&
13353 !sanitize_speculative_path(env, insn,
13354 *insn_idx + insn->off + 1,
13360 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
13364 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
13366 /* detect if we are comparing against a constant value so we can adjust
13367 * our min/max values for our dst register.
13368 * this is only legit if both are scalars (or pointers to the same
13369 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
13370 * because otherwise the different base pointers mean the offsets aren't
13373 if (BPF_SRC(insn->code) == BPF_X) {
13374 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
13376 if (dst_reg->type == SCALAR_VALUE &&
13377 src_reg->type == SCALAR_VALUE) {
13378 if (tnum_is_const(src_reg->var_off) ||
13380 tnum_is_const(tnum_subreg(src_reg->var_off))))
13381 reg_set_min_max(&other_branch_regs[insn->dst_reg],
13383 src_reg->var_off.value,
13384 tnum_subreg(src_reg->var_off).value,
13386 else if (tnum_is_const(dst_reg->var_off) ||
13388 tnum_is_const(tnum_subreg(dst_reg->var_off))))
13389 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
13391 dst_reg->var_off.value,
13392 tnum_subreg(dst_reg->var_off).value,
13394 else if (!is_jmp32 &&
13395 (opcode == BPF_JEQ || opcode == BPF_JNE))
13396 /* Comparing for equality, we can combine knowledge */
13397 reg_combine_min_max(&other_branch_regs[insn->src_reg],
13398 &other_branch_regs[insn->dst_reg],
13399 src_reg, dst_reg, opcode);
13401 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
13402 find_equal_scalars(this_branch, src_reg);
13403 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
13407 } else if (dst_reg->type == SCALAR_VALUE) {
13408 reg_set_min_max(&other_branch_regs[insn->dst_reg],
13409 dst_reg, insn->imm, (u32)insn->imm,
13413 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
13414 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
13415 find_equal_scalars(this_branch, dst_reg);
13416 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
13419 /* if one pointer register is compared to another pointer
13420 * register check if PTR_MAYBE_NULL could be lifted.
13421 * E.g. register A - maybe null
13422 * register B - not null
13423 * for JNE A, B, ... - A is not null in the false branch;
13424 * for JEQ A, B, ... - A is not null in the true branch.
13426 * Since PTR_TO_BTF_ID points to a kernel struct that does
13427 * not need to be null checked by the BPF program, i.e.,
13428 * could be null even without PTR_MAYBE_NULL marking, so
13429 * only propagate nullness when neither reg is that type.
13431 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
13432 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
13433 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
13434 base_type(src_reg->type) != PTR_TO_BTF_ID &&
13435 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
13436 eq_branch_regs = NULL;
13439 eq_branch_regs = other_branch_regs;
13442 eq_branch_regs = regs;
13448 if (eq_branch_regs) {
13449 if (type_may_be_null(src_reg->type))
13450 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
13452 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
13456 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
13457 * NOTE: these optimizations below are related with pointer comparison
13458 * which will never be JMP32.
13460 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
13461 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
13462 type_may_be_null(dst_reg->type)) {
13463 /* Mark all identical registers in each branch as either
13464 * safe or unknown depending R == 0 or R != 0 conditional.
13466 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
13467 opcode == BPF_JNE);
13468 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
13469 opcode == BPF_JEQ);
13470 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
13471 this_branch, other_branch) &&
13472 is_pointer_value(env, insn->dst_reg)) {
13473 verbose(env, "R%d pointer comparison prohibited\n",
13477 if (env->log.level & BPF_LOG_LEVEL)
13478 print_insn_state(env, this_branch->frame[this_branch->curframe]);
13482 /* verify BPF_LD_IMM64 instruction */
13483 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
13485 struct bpf_insn_aux_data *aux = cur_aux(env);
13486 struct bpf_reg_state *regs = cur_regs(env);
13487 struct bpf_reg_state *dst_reg;
13488 struct bpf_map *map;
13491 if (BPF_SIZE(insn->code) != BPF_DW) {
13492 verbose(env, "invalid BPF_LD_IMM insn\n");
13495 if (insn->off != 0) {
13496 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
13500 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13504 dst_reg = ®s[insn->dst_reg];
13505 if (insn->src_reg == 0) {
13506 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
13508 dst_reg->type = SCALAR_VALUE;
13509 __mark_reg_known(®s[insn->dst_reg], imm);
13513 /* All special src_reg cases are listed below. From this point onwards
13514 * we either succeed and assign a corresponding dst_reg->type after
13515 * zeroing the offset, or fail and reject the program.
13517 mark_reg_known_zero(env, regs, insn->dst_reg);
13519 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
13520 dst_reg->type = aux->btf_var.reg_type;
13521 switch (base_type(dst_reg->type)) {
13523 dst_reg->mem_size = aux->btf_var.mem_size;
13525 case PTR_TO_BTF_ID:
13526 dst_reg->btf = aux->btf_var.btf;
13527 dst_reg->btf_id = aux->btf_var.btf_id;
13530 verbose(env, "bpf verifier is misconfigured\n");
13536 if (insn->src_reg == BPF_PSEUDO_FUNC) {
13537 struct bpf_prog_aux *aux = env->prog->aux;
13538 u32 subprogno = find_subprog(env,
13539 env->insn_idx + insn->imm + 1);
13541 if (!aux->func_info) {
13542 verbose(env, "missing btf func_info\n");
13545 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
13546 verbose(env, "callback function not static\n");
13550 dst_reg->type = PTR_TO_FUNC;
13551 dst_reg->subprogno = subprogno;
13555 map = env->used_maps[aux->map_index];
13556 dst_reg->map_ptr = map;
13558 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
13559 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
13560 dst_reg->type = PTR_TO_MAP_VALUE;
13561 dst_reg->off = aux->map_off;
13562 WARN_ON_ONCE(map->max_entries != 1);
13563 /* We want reg->id to be same (0) as map_value is not distinct */
13564 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
13565 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
13566 dst_reg->type = CONST_PTR_TO_MAP;
13568 verbose(env, "bpf verifier is misconfigured\n");
13575 static bool may_access_skb(enum bpf_prog_type type)
13578 case BPF_PROG_TYPE_SOCKET_FILTER:
13579 case BPF_PROG_TYPE_SCHED_CLS:
13580 case BPF_PROG_TYPE_SCHED_ACT:
13587 /* verify safety of LD_ABS|LD_IND instructions:
13588 * - they can only appear in the programs where ctx == skb
13589 * - since they are wrappers of function calls, they scratch R1-R5 registers,
13590 * preserve R6-R9, and store return value into R0
13593 * ctx == skb == R6 == CTX
13596 * SRC == any register
13597 * IMM == 32-bit immediate
13600 * R0 - 8/16/32-bit skb data converted to cpu endianness
13602 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
13604 struct bpf_reg_state *regs = cur_regs(env);
13605 static const int ctx_reg = BPF_REG_6;
13606 u8 mode = BPF_MODE(insn->code);
13609 if (!may_access_skb(resolve_prog_type(env->prog))) {
13610 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
13614 if (!env->ops->gen_ld_abs) {
13615 verbose(env, "bpf verifier is misconfigured\n");
13619 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
13620 BPF_SIZE(insn->code) == BPF_DW ||
13621 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
13622 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
13626 /* check whether implicit source operand (register R6) is readable */
13627 err = check_reg_arg(env, ctx_reg, SRC_OP);
13631 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
13632 * gen_ld_abs() may terminate the program at runtime, leading to
13635 err = check_reference_leak(env);
13637 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
13641 if (env->cur_state->active_lock.ptr) {
13642 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
13646 if (env->cur_state->active_rcu_lock) {
13647 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
13651 if (regs[ctx_reg].type != PTR_TO_CTX) {
13653 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
13657 if (mode == BPF_IND) {
13658 /* check explicit source operand */
13659 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13664 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
13668 /* reset caller saved regs to unreadable */
13669 for (i = 0; i < CALLER_SAVED_REGS; i++) {
13670 mark_reg_not_init(env, regs, caller_saved[i]);
13671 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
13674 /* mark destination R0 register as readable, since it contains
13675 * the value fetched from the packet.
13676 * Already marked as written above.
13678 mark_reg_unknown(env, regs, BPF_REG_0);
13679 /* ld_abs load up to 32-bit skb data. */
13680 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
13684 static int check_return_code(struct bpf_verifier_env *env)
13686 struct tnum enforce_attach_type_range = tnum_unknown;
13687 const struct bpf_prog *prog = env->prog;
13688 struct bpf_reg_state *reg;
13689 struct tnum range = tnum_range(0, 1);
13690 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13692 struct bpf_func_state *frame = env->cur_state->frame[0];
13693 const bool is_subprog = frame->subprogno;
13695 /* LSM and struct_ops func-ptr's return type could be "void" */
13697 switch (prog_type) {
13698 case BPF_PROG_TYPE_LSM:
13699 if (prog->expected_attach_type == BPF_LSM_CGROUP)
13700 /* See below, can be 0 or 0-1 depending on hook. */
13703 case BPF_PROG_TYPE_STRUCT_OPS:
13704 if (!prog->aux->attach_func_proto->type)
13712 /* eBPF calling convention is such that R0 is used
13713 * to return the value from eBPF program.
13714 * Make sure that it's readable at this time
13715 * of bpf_exit, which means that program wrote
13716 * something into it earlier
13718 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
13722 if (is_pointer_value(env, BPF_REG_0)) {
13723 verbose(env, "R0 leaks addr as return value\n");
13727 reg = cur_regs(env) + BPF_REG_0;
13729 if (frame->in_async_callback_fn) {
13730 /* enforce return zero from async callbacks like timer */
13731 if (reg->type != SCALAR_VALUE) {
13732 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
13733 reg_type_str(env, reg->type));
13737 if (!tnum_in(tnum_const(0), reg->var_off)) {
13738 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
13745 if (reg->type != SCALAR_VALUE) {
13746 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
13747 reg_type_str(env, reg->type));
13753 switch (prog_type) {
13754 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
13755 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
13756 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
13757 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
13758 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
13759 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
13760 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
13761 range = tnum_range(1, 1);
13762 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
13763 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
13764 range = tnum_range(0, 3);
13766 case BPF_PROG_TYPE_CGROUP_SKB:
13767 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
13768 range = tnum_range(0, 3);
13769 enforce_attach_type_range = tnum_range(2, 3);
13772 case BPF_PROG_TYPE_CGROUP_SOCK:
13773 case BPF_PROG_TYPE_SOCK_OPS:
13774 case BPF_PROG_TYPE_CGROUP_DEVICE:
13775 case BPF_PROG_TYPE_CGROUP_SYSCTL:
13776 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
13778 case BPF_PROG_TYPE_RAW_TRACEPOINT:
13779 if (!env->prog->aux->attach_btf_id)
13781 range = tnum_const(0);
13783 case BPF_PROG_TYPE_TRACING:
13784 switch (env->prog->expected_attach_type) {
13785 case BPF_TRACE_FENTRY:
13786 case BPF_TRACE_FEXIT:
13787 range = tnum_const(0);
13789 case BPF_TRACE_RAW_TP:
13790 case BPF_MODIFY_RETURN:
13792 case BPF_TRACE_ITER:
13798 case BPF_PROG_TYPE_SK_LOOKUP:
13799 range = tnum_range(SK_DROP, SK_PASS);
13802 case BPF_PROG_TYPE_LSM:
13803 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
13804 /* Regular BPF_PROG_TYPE_LSM programs can return
13809 if (!env->prog->aux->attach_func_proto->type) {
13810 /* Make sure programs that attach to void
13811 * hooks don't try to modify return value.
13813 range = tnum_range(1, 1);
13817 case BPF_PROG_TYPE_EXT:
13818 /* freplace program can return anything as its return value
13819 * depends on the to-be-replaced kernel func or bpf program.
13825 if (reg->type != SCALAR_VALUE) {
13826 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
13827 reg_type_str(env, reg->type));
13831 if (!tnum_in(range, reg->var_off)) {
13832 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
13833 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
13834 prog_type == BPF_PROG_TYPE_LSM &&
13835 !prog->aux->attach_func_proto->type)
13836 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
13840 if (!tnum_is_unknown(enforce_attach_type_range) &&
13841 tnum_in(enforce_attach_type_range, reg->var_off))
13842 env->prog->enforce_expected_attach_type = 1;
13846 /* non-recursive DFS pseudo code
13847 * 1 procedure DFS-iterative(G,v):
13848 * 2 label v as discovered
13849 * 3 let S be a stack
13851 * 5 while S is not empty
13853 * 7 if t is what we're looking for:
13855 * 9 for all edges e in G.adjacentEdges(t) do
13856 * 10 if edge e is already labelled
13857 * 11 continue with the next edge
13858 * 12 w <- G.adjacentVertex(t,e)
13859 * 13 if vertex w is not discovered and not explored
13860 * 14 label e as tree-edge
13861 * 15 label w as discovered
13864 * 18 else if vertex w is discovered
13865 * 19 label e as back-edge
13867 * 21 // vertex w is explored
13868 * 22 label e as forward- or cross-edge
13869 * 23 label t as explored
13873 * 0x10 - discovered
13874 * 0x11 - discovered and fall-through edge labelled
13875 * 0x12 - discovered and fall-through and branch edges labelled
13886 static u32 state_htab_size(struct bpf_verifier_env *env)
13888 return env->prog->len;
13891 static struct bpf_verifier_state_list **explored_state(
13892 struct bpf_verifier_env *env,
13895 struct bpf_verifier_state *cur = env->cur_state;
13896 struct bpf_func_state *state = cur->frame[cur->curframe];
13898 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
13901 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
13903 env->insn_aux_data[idx].prune_point = true;
13906 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
13908 return env->insn_aux_data[insn_idx].prune_point;
13911 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
13913 env->insn_aux_data[idx].force_checkpoint = true;
13916 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
13918 return env->insn_aux_data[insn_idx].force_checkpoint;
13923 DONE_EXPLORING = 0,
13924 KEEP_EXPLORING = 1,
13927 /* t, w, e - match pseudo-code above:
13928 * t - index of current instruction
13929 * w - next instruction
13932 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
13935 int *insn_stack = env->cfg.insn_stack;
13936 int *insn_state = env->cfg.insn_state;
13938 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
13939 return DONE_EXPLORING;
13941 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
13942 return DONE_EXPLORING;
13944 if (w < 0 || w >= env->prog->len) {
13945 verbose_linfo(env, t, "%d: ", t);
13946 verbose(env, "jump out of range from insn %d to %d\n", t, w);
13951 /* mark branch target for state pruning */
13952 mark_prune_point(env, w);
13953 mark_jmp_point(env, w);
13956 if (insn_state[w] == 0) {
13958 insn_state[t] = DISCOVERED | e;
13959 insn_state[w] = DISCOVERED;
13960 if (env->cfg.cur_stack >= env->prog->len)
13962 insn_stack[env->cfg.cur_stack++] = w;
13963 return KEEP_EXPLORING;
13964 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
13965 if (loop_ok && env->bpf_capable)
13966 return DONE_EXPLORING;
13967 verbose_linfo(env, t, "%d: ", t);
13968 verbose_linfo(env, w, "%d: ", w);
13969 verbose(env, "back-edge from insn %d to %d\n", t, w);
13971 } else if (insn_state[w] == EXPLORED) {
13972 /* forward- or cross-edge */
13973 insn_state[t] = DISCOVERED | e;
13975 verbose(env, "insn state internal bug\n");
13978 return DONE_EXPLORING;
13981 static int visit_func_call_insn(int t, struct bpf_insn *insns,
13982 struct bpf_verifier_env *env,
13987 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
13991 mark_prune_point(env, t + 1);
13992 /* when we exit from subprog, we need to record non-linear history */
13993 mark_jmp_point(env, t + 1);
13995 if (visit_callee) {
13996 mark_prune_point(env, t);
13997 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
13998 /* It's ok to allow recursion from CFG point of
13999 * view. __check_func_call() will do the actual
14002 bpf_pseudo_func(insns + t));
14007 /* Visits the instruction at index t and returns one of the following:
14008 * < 0 - an error occurred
14009 * DONE_EXPLORING - the instruction was fully explored
14010 * KEEP_EXPLORING - there is still work to be done before it is fully explored
14012 static int visit_insn(int t, struct bpf_verifier_env *env)
14014 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14017 if (bpf_pseudo_func(insn))
14018 return visit_func_call_insn(t, insns, env, true);
14020 /* All non-branch instructions have a single fall-through edge. */
14021 if (BPF_CLASS(insn->code) != BPF_JMP &&
14022 BPF_CLASS(insn->code) != BPF_JMP32)
14023 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14025 switch (BPF_OP(insn->code)) {
14027 return DONE_EXPLORING;
14030 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14031 /* Mark this call insn as a prune point to trigger
14032 * is_state_visited() check before call itself is
14033 * processed by __check_func_call(). Otherwise new
14034 * async state will be pushed for further exploration.
14036 mark_prune_point(env, t);
14037 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14038 struct bpf_kfunc_call_arg_meta meta;
14040 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14041 if (ret == 0 && is_iter_next_kfunc(&meta)) {
14042 mark_prune_point(env, t);
14043 /* Checking and saving state checkpoints at iter_next() call
14044 * is crucial for fast convergence of open-coded iterator loop
14045 * logic, so we need to force it. If we don't do that,
14046 * is_state_visited() might skip saving a checkpoint, causing
14047 * unnecessarily long sequence of not checkpointed
14048 * instructions and jumps, leading to exhaustion of jump
14049 * history buffer, and potentially other undesired outcomes.
14050 * It is expected that with correct open-coded iterators
14051 * convergence will happen quickly, so we don't run a risk of
14052 * exhausting memory.
14054 mark_force_checkpoint(env, t);
14057 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14060 if (BPF_SRC(insn->code) != BPF_K)
14063 /* unconditional jump with single edge */
14064 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14069 mark_prune_point(env, t + insn->off + 1);
14070 mark_jmp_point(env, t + insn->off + 1);
14075 /* conditional jump with two edges */
14076 mark_prune_point(env, t);
14078 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14082 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14086 /* non-recursive depth-first-search to detect loops in BPF program
14087 * loop == back-edge in directed graph
14089 static int check_cfg(struct bpf_verifier_env *env)
14091 int insn_cnt = env->prog->len;
14092 int *insn_stack, *insn_state;
14096 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14100 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14102 kvfree(insn_state);
14106 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14107 insn_stack[0] = 0; /* 0 is the first instruction */
14108 env->cfg.cur_stack = 1;
14110 while (env->cfg.cur_stack > 0) {
14111 int t = insn_stack[env->cfg.cur_stack - 1];
14113 ret = visit_insn(t, env);
14115 case DONE_EXPLORING:
14116 insn_state[t] = EXPLORED;
14117 env->cfg.cur_stack--;
14119 case KEEP_EXPLORING:
14123 verbose(env, "visit_insn internal bug\n");
14130 if (env->cfg.cur_stack < 0) {
14131 verbose(env, "pop stack internal bug\n");
14136 for (i = 0; i < insn_cnt; i++) {
14137 if (insn_state[i] != EXPLORED) {
14138 verbose(env, "unreachable insn %d\n", i);
14143 ret = 0; /* cfg looks good */
14146 kvfree(insn_state);
14147 kvfree(insn_stack);
14148 env->cfg.insn_state = env->cfg.insn_stack = NULL;
14152 static int check_abnormal_return(struct bpf_verifier_env *env)
14156 for (i = 1; i < env->subprog_cnt; i++) {
14157 if (env->subprog_info[i].has_ld_abs) {
14158 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14161 if (env->subprog_info[i].has_tail_call) {
14162 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14169 /* The minimum supported BTF func info size */
14170 #define MIN_BPF_FUNCINFO_SIZE 8
14171 #define MAX_FUNCINFO_REC_SIZE 252
14173 static int check_btf_func(struct bpf_verifier_env *env,
14174 const union bpf_attr *attr,
14177 const struct btf_type *type, *func_proto, *ret_type;
14178 u32 i, nfuncs, urec_size, min_size;
14179 u32 krec_size = sizeof(struct bpf_func_info);
14180 struct bpf_func_info *krecord;
14181 struct bpf_func_info_aux *info_aux = NULL;
14182 struct bpf_prog *prog;
14183 const struct btf *btf;
14185 u32 prev_offset = 0;
14186 bool scalar_return;
14189 nfuncs = attr->func_info_cnt;
14191 if (check_abnormal_return(env))
14196 if (nfuncs != env->subprog_cnt) {
14197 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14201 urec_size = attr->func_info_rec_size;
14202 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14203 urec_size > MAX_FUNCINFO_REC_SIZE ||
14204 urec_size % sizeof(u32)) {
14205 verbose(env, "invalid func info rec size %u\n", urec_size);
14210 btf = prog->aux->btf;
14212 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14213 min_size = min_t(u32, krec_size, urec_size);
14215 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14218 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14222 for (i = 0; i < nfuncs; i++) {
14223 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14225 if (ret == -E2BIG) {
14226 verbose(env, "nonzero tailing record in func info");
14227 /* set the size kernel expects so loader can zero
14228 * out the rest of the record.
14230 if (copy_to_bpfptr_offset(uattr,
14231 offsetof(union bpf_attr, func_info_rec_size),
14232 &min_size, sizeof(min_size)))
14238 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
14243 /* check insn_off */
14246 if (krecord[i].insn_off) {
14248 "nonzero insn_off %u for the first func info record",
14249 krecord[i].insn_off);
14252 } else if (krecord[i].insn_off <= prev_offset) {
14254 "same or smaller insn offset (%u) than previous func info record (%u)",
14255 krecord[i].insn_off, prev_offset);
14259 if (env->subprog_info[i].start != krecord[i].insn_off) {
14260 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
14264 /* check type_id */
14265 type = btf_type_by_id(btf, krecord[i].type_id);
14266 if (!type || !btf_type_is_func(type)) {
14267 verbose(env, "invalid type id %d in func info",
14268 krecord[i].type_id);
14271 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
14273 func_proto = btf_type_by_id(btf, type->type);
14274 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14275 /* btf_func_check() already verified it during BTF load */
14277 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14279 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
14280 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14281 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14284 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14285 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14289 prev_offset = krecord[i].insn_off;
14290 bpfptr_add(&urecord, urec_size);
14293 prog->aux->func_info = krecord;
14294 prog->aux->func_info_cnt = nfuncs;
14295 prog->aux->func_info_aux = info_aux;
14304 static void adjust_btf_func(struct bpf_verifier_env *env)
14306 struct bpf_prog_aux *aux = env->prog->aux;
14309 if (!aux->func_info)
14312 for (i = 0; i < env->subprog_cnt; i++)
14313 aux->func_info[i].insn_off = env->subprog_info[i].start;
14316 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
14317 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
14319 static int check_btf_line(struct bpf_verifier_env *env,
14320 const union bpf_attr *attr,
14323 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14324 struct bpf_subprog_info *sub;
14325 struct bpf_line_info *linfo;
14326 struct bpf_prog *prog;
14327 const struct btf *btf;
14331 nr_linfo = attr->line_info_cnt;
14334 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
14337 rec_size = attr->line_info_rec_size;
14338 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
14339 rec_size > MAX_LINEINFO_REC_SIZE ||
14340 rec_size & (sizeof(u32) - 1))
14343 /* Need to zero it in case the userspace may
14344 * pass in a smaller bpf_line_info object.
14346 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
14347 GFP_KERNEL | __GFP_NOWARN);
14352 btf = prog->aux->btf;
14355 sub = env->subprog_info;
14356 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
14357 expected_size = sizeof(struct bpf_line_info);
14358 ncopy = min_t(u32, expected_size, rec_size);
14359 for (i = 0; i < nr_linfo; i++) {
14360 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
14362 if (err == -E2BIG) {
14363 verbose(env, "nonzero tailing record in line_info");
14364 if (copy_to_bpfptr_offset(uattr,
14365 offsetof(union bpf_attr, line_info_rec_size),
14366 &expected_size, sizeof(expected_size)))
14372 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
14378 * Check insn_off to ensure
14379 * 1) strictly increasing AND
14380 * 2) bounded by prog->len
14382 * The linfo[0].insn_off == 0 check logically falls into
14383 * the later "missing bpf_line_info for func..." case
14384 * because the first linfo[0].insn_off must be the
14385 * first sub also and the first sub must have
14386 * subprog_info[0].start == 0.
14388 if ((i && linfo[i].insn_off <= prev_offset) ||
14389 linfo[i].insn_off >= prog->len) {
14390 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
14391 i, linfo[i].insn_off, prev_offset,
14397 if (!prog->insnsi[linfo[i].insn_off].code) {
14399 "Invalid insn code at line_info[%u].insn_off\n",
14405 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
14406 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
14407 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
14412 if (s != env->subprog_cnt) {
14413 if (linfo[i].insn_off == sub[s].start) {
14414 sub[s].linfo_idx = i;
14416 } else if (sub[s].start < linfo[i].insn_off) {
14417 verbose(env, "missing bpf_line_info for func#%u\n", s);
14423 prev_offset = linfo[i].insn_off;
14424 bpfptr_add(&ulinfo, rec_size);
14427 if (s != env->subprog_cnt) {
14428 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
14429 env->subprog_cnt - s, s);
14434 prog->aux->linfo = linfo;
14435 prog->aux->nr_linfo = nr_linfo;
14444 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
14445 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
14447 static int check_core_relo(struct bpf_verifier_env *env,
14448 const union bpf_attr *attr,
14451 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
14452 struct bpf_core_relo core_relo = {};
14453 struct bpf_prog *prog = env->prog;
14454 const struct btf *btf = prog->aux->btf;
14455 struct bpf_core_ctx ctx = {
14459 bpfptr_t u_core_relo;
14462 nr_core_relo = attr->core_relo_cnt;
14465 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
14468 rec_size = attr->core_relo_rec_size;
14469 if (rec_size < MIN_CORE_RELO_SIZE ||
14470 rec_size > MAX_CORE_RELO_SIZE ||
14471 rec_size % sizeof(u32))
14474 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
14475 expected_size = sizeof(struct bpf_core_relo);
14476 ncopy = min_t(u32, expected_size, rec_size);
14478 /* Unlike func_info and line_info, copy and apply each CO-RE
14479 * relocation record one at a time.
14481 for (i = 0; i < nr_core_relo; i++) {
14482 /* future proofing when sizeof(bpf_core_relo) changes */
14483 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
14485 if (err == -E2BIG) {
14486 verbose(env, "nonzero tailing record in core_relo");
14487 if (copy_to_bpfptr_offset(uattr,
14488 offsetof(union bpf_attr, core_relo_rec_size),
14489 &expected_size, sizeof(expected_size)))
14495 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
14500 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
14501 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
14502 i, core_relo.insn_off, prog->len);
14507 err = bpf_core_apply(&ctx, &core_relo, i,
14508 &prog->insnsi[core_relo.insn_off / 8]);
14511 bpfptr_add(&u_core_relo, rec_size);
14516 static int check_btf_info(struct bpf_verifier_env *env,
14517 const union bpf_attr *attr,
14523 if (!attr->func_info_cnt && !attr->line_info_cnt) {
14524 if (check_abnormal_return(env))
14529 btf = btf_get_by_fd(attr->prog_btf_fd);
14531 return PTR_ERR(btf);
14532 if (btf_is_kernel(btf)) {
14536 env->prog->aux->btf = btf;
14538 err = check_btf_func(env, attr, uattr);
14542 err = check_btf_line(env, attr, uattr);
14546 err = check_core_relo(env, attr, uattr);
14553 /* check %cur's range satisfies %old's */
14554 static bool range_within(struct bpf_reg_state *old,
14555 struct bpf_reg_state *cur)
14557 return old->umin_value <= cur->umin_value &&
14558 old->umax_value >= cur->umax_value &&
14559 old->smin_value <= cur->smin_value &&
14560 old->smax_value >= cur->smax_value &&
14561 old->u32_min_value <= cur->u32_min_value &&
14562 old->u32_max_value >= cur->u32_max_value &&
14563 old->s32_min_value <= cur->s32_min_value &&
14564 old->s32_max_value >= cur->s32_max_value;
14567 /* If in the old state two registers had the same id, then they need to have
14568 * the same id in the new state as well. But that id could be different from
14569 * the old state, so we need to track the mapping from old to new ids.
14570 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
14571 * regs with old id 5 must also have new id 9 for the new state to be safe. But
14572 * regs with a different old id could still have new id 9, we don't care about
14574 * So we look through our idmap to see if this old id has been seen before. If
14575 * so, we require the new id to match; otherwise, we add the id pair to the map.
14577 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
14581 /* either both IDs should be set or both should be zero */
14582 if (!!old_id != !!cur_id)
14585 if (old_id == 0) /* cur_id == 0 as well */
14588 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
14589 if (!idmap[i].old) {
14590 /* Reached an empty slot; haven't seen this id before */
14591 idmap[i].old = old_id;
14592 idmap[i].cur = cur_id;
14595 if (idmap[i].old == old_id)
14596 return idmap[i].cur == cur_id;
14598 /* We ran out of idmap slots, which should be impossible */
14603 static void clean_func_state(struct bpf_verifier_env *env,
14604 struct bpf_func_state *st)
14606 enum bpf_reg_liveness live;
14609 for (i = 0; i < BPF_REG_FP; i++) {
14610 live = st->regs[i].live;
14611 /* liveness must not touch this register anymore */
14612 st->regs[i].live |= REG_LIVE_DONE;
14613 if (!(live & REG_LIVE_READ))
14614 /* since the register is unused, clear its state
14615 * to make further comparison simpler
14617 __mark_reg_not_init(env, &st->regs[i]);
14620 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
14621 live = st->stack[i].spilled_ptr.live;
14622 /* liveness must not touch this stack slot anymore */
14623 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
14624 if (!(live & REG_LIVE_READ)) {
14625 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
14626 for (j = 0; j < BPF_REG_SIZE; j++)
14627 st->stack[i].slot_type[j] = STACK_INVALID;
14632 static void clean_verifier_state(struct bpf_verifier_env *env,
14633 struct bpf_verifier_state *st)
14637 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
14638 /* all regs in this state in all frames were already marked */
14641 for (i = 0; i <= st->curframe; i++)
14642 clean_func_state(env, st->frame[i]);
14645 /* the parentage chains form a tree.
14646 * the verifier states are added to state lists at given insn and
14647 * pushed into state stack for future exploration.
14648 * when the verifier reaches bpf_exit insn some of the verifer states
14649 * stored in the state lists have their final liveness state already,
14650 * but a lot of states will get revised from liveness point of view when
14651 * the verifier explores other branches.
14654 * 2: if r1 == 100 goto pc+1
14657 * when the verifier reaches exit insn the register r0 in the state list of
14658 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
14659 * of insn 2 and goes exploring further. At the insn 4 it will walk the
14660 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
14662 * Since the verifier pushes the branch states as it sees them while exploring
14663 * the program the condition of walking the branch instruction for the second
14664 * time means that all states below this branch were already explored and
14665 * their final liveness marks are already propagated.
14666 * Hence when the verifier completes the search of state list in is_state_visited()
14667 * we can call this clean_live_states() function to mark all liveness states
14668 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
14669 * will not be used.
14670 * This function also clears the registers and stack for states that !READ
14671 * to simplify state merging.
14673 * Important note here that walking the same branch instruction in the callee
14674 * doesn't meant that the states are DONE. The verifier has to compare
14677 static void clean_live_states(struct bpf_verifier_env *env, int insn,
14678 struct bpf_verifier_state *cur)
14680 struct bpf_verifier_state_list *sl;
14683 sl = *explored_state(env, insn);
14685 if (sl->state.branches)
14687 if (sl->state.insn_idx != insn ||
14688 sl->state.curframe != cur->curframe)
14690 for (i = 0; i <= cur->curframe; i++)
14691 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
14693 clean_verifier_state(env, &sl->state);
14699 static bool regs_exact(const struct bpf_reg_state *rold,
14700 const struct bpf_reg_state *rcur,
14701 struct bpf_id_pair *idmap)
14703 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
14704 check_ids(rold->id, rcur->id, idmap) &&
14705 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
14708 /* Returns true if (rold safe implies rcur safe) */
14709 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
14710 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
14712 if (!(rold->live & REG_LIVE_READ))
14713 /* explored state didn't use this */
14715 if (rold->type == NOT_INIT)
14716 /* explored state can't have used this */
14718 if (rcur->type == NOT_INIT)
14721 /* Enforce that register types have to match exactly, including their
14722 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
14725 * One can make a point that using a pointer register as unbounded
14726 * SCALAR would be technically acceptable, but this could lead to
14727 * pointer leaks because scalars are allowed to leak while pointers
14728 * are not. We could make this safe in special cases if root is
14729 * calling us, but it's probably not worth the hassle.
14731 * Also, register types that are *not* MAYBE_NULL could technically be
14732 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
14733 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
14734 * to the same map).
14735 * However, if the old MAYBE_NULL register then got NULL checked,
14736 * doing so could have affected others with the same id, and we can't
14737 * check for that because we lost the id when we converted to
14738 * a non-MAYBE_NULL variant.
14739 * So, as a general rule we don't allow mixing MAYBE_NULL and
14740 * non-MAYBE_NULL registers as well.
14742 if (rold->type != rcur->type)
14745 switch (base_type(rold->type)) {
14747 if (regs_exact(rold, rcur, idmap))
14749 if (env->explore_alu_limits)
14751 if (!rold->precise)
14753 /* new val must satisfy old val knowledge */
14754 return range_within(rold, rcur) &&
14755 tnum_in(rold->var_off, rcur->var_off);
14756 case PTR_TO_MAP_KEY:
14757 case PTR_TO_MAP_VALUE:
14760 case PTR_TO_TP_BUFFER:
14761 /* If the new min/max/var_off satisfy the old ones and
14762 * everything else matches, we are OK.
14764 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
14765 range_within(rold, rcur) &&
14766 tnum_in(rold->var_off, rcur->var_off) &&
14767 check_ids(rold->id, rcur->id, idmap) &&
14768 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
14769 case PTR_TO_PACKET_META:
14770 case PTR_TO_PACKET:
14771 /* We must have at least as much range as the old ptr
14772 * did, so that any accesses which were safe before are
14773 * still safe. This is true even if old range < old off,
14774 * since someone could have accessed through (ptr - k), or
14775 * even done ptr -= k in a register, to get a safe access.
14777 if (rold->range > rcur->range)
14779 /* If the offsets don't match, we can't trust our alignment;
14780 * nor can we be sure that we won't fall out of range.
14782 if (rold->off != rcur->off)
14784 /* id relations must be preserved */
14785 if (!check_ids(rold->id, rcur->id, idmap))
14787 /* new val must satisfy old val knowledge */
14788 return range_within(rold, rcur) &&
14789 tnum_in(rold->var_off, rcur->var_off);
14791 /* two stack pointers are equal only if they're pointing to
14792 * the same stack frame, since fp-8 in foo != fp-8 in bar
14794 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
14796 return regs_exact(rold, rcur, idmap);
14800 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
14801 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
14805 /* walk slots of the explored stack and ignore any additional
14806 * slots in the current stack, since explored(safe) state
14809 for (i = 0; i < old->allocated_stack; i++) {
14810 struct bpf_reg_state *old_reg, *cur_reg;
14812 spi = i / BPF_REG_SIZE;
14814 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
14815 i += BPF_REG_SIZE - 1;
14816 /* explored state didn't use this */
14820 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
14823 if (env->allow_uninit_stack &&
14824 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
14827 /* explored stack has more populated slots than current stack
14828 * and these slots were used
14830 if (i >= cur->allocated_stack)
14833 /* if old state was safe with misc data in the stack
14834 * it will be safe with zero-initialized stack.
14835 * The opposite is not true
14837 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
14838 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
14840 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
14841 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
14842 /* Ex: old explored (safe) state has STACK_SPILL in
14843 * this stack slot, but current has STACK_MISC ->
14844 * this verifier states are not equivalent,
14845 * return false to continue verification of this path
14848 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
14850 /* Both old and cur are having same slot_type */
14851 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
14853 /* when explored and current stack slot are both storing
14854 * spilled registers, check that stored pointers types
14855 * are the same as well.
14856 * Ex: explored safe path could have stored
14857 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
14858 * but current path has stored:
14859 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
14860 * such verifier states are not equivalent.
14861 * return false to continue verification of this path
14863 if (!regsafe(env, &old->stack[spi].spilled_ptr,
14864 &cur->stack[spi].spilled_ptr, idmap))
14868 old_reg = &old->stack[spi].spilled_ptr;
14869 cur_reg = &cur->stack[spi].spilled_ptr;
14870 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
14871 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
14872 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
14876 old_reg = &old->stack[spi].spilled_ptr;
14877 cur_reg = &cur->stack[spi].spilled_ptr;
14878 /* iter.depth is not compared between states as it
14879 * doesn't matter for correctness and would otherwise
14880 * prevent convergence; we maintain it only to prevent
14881 * infinite loop check triggering, see
14882 * iter_active_depths_differ()
14884 if (old_reg->iter.btf != cur_reg->iter.btf ||
14885 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
14886 old_reg->iter.state != cur_reg->iter.state ||
14887 /* ignore {old_reg,cur_reg}->iter.depth, see above */
14888 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
14893 case STACK_INVALID:
14895 /* Ensure that new unhandled slot types return false by default */
14903 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
14904 struct bpf_id_pair *idmap)
14908 if (old->acquired_refs != cur->acquired_refs)
14911 for (i = 0; i < old->acquired_refs; i++) {
14912 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
14919 /* compare two verifier states
14921 * all states stored in state_list are known to be valid, since
14922 * verifier reached 'bpf_exit' instruction through them
14924 * this function is called when verifier exploring different branches of
14925 * execution popped from the state stack. If it sees an old state that has
14926 * more strict register state and more strict stack state then this execution
14927 * branch doesn't need to be explored further, since verifier already
14928 * concluded that more strict state leads to valid finish.
14930 * Therefore two states are equivalent if register state is more conservative
14931 * and explored stack state is more conservative than the current one.
14934 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
14935 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
14937 * In other words if current stack state (one being explored) has more
14938 * valid slots than old one that already passed validation, it means
14939 * the verifier can stop exploring and conclude that current state is valid too
14941 * Similarly with registers. If explored state has register type as invalid
14942 * whereas register type in current state is meaningful, it means that
14943 * the current state will reach 'bpf_exit' instruction safely
14945 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
14946 struct bpf_func_state *cur)
14950 for (i = 0; i < MAX_BPF_REG; i++)
14951 if (!regsafe(env, &old->regs[i], &cur->regs[i],
14952 env->idmap_scratch))
14955 if (!stacksafe(env, old, cur, env->idmap_scratch))
14958 if (!refsafe(old, cur, env->idmap_scratch))
14964 static bool states_equal(struct bpf_verifier_env *env,
14965 struct bpf_verifier_state *old,
14966 struct bpf_verifier_state *cur)
14970 if (old->curframe != cur->curframe)
14973 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
14975 /* Verification state from speculative execution simulation
14976 * must never prune a non-speculative execution one.
14978 if (old->speculative && !cur->speculative)
14981 if (old->active_lock.ptr != cur->active_lock.ptr)
14984 /* Old and cur active_lock's have to be either both present
14987 if (!!old->active_lock.id != !!cur->active_lock.id)
14990 if (old->active_lock.id &&
14991 !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
14994 if (old->active_rcu_lock != cur->active_rcu_lock)
14997 /* for states to be equal callsites have to be the same
14998 * and all frame states need to be equivalent
15000 for (i = 0; i <= old->curframe; i++) {
15001 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15003 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15009 /* Return 0 if no propagation happened. Return negative error code if error
15010 * happened. Otherwise, return the propagated bit.
15012 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15013 struct bpf_reg_state *reg,
15014 struct bpf_reg_state *parent_reg)
15016 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15017 u8 flag = reg->live & REG_LIVE_READ;
15020 /* When comes here, read flags of PARENT_REG or REG could be any of
15021 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15022 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15024 if (parent_flag == REG_LIVE_READ64 ||
15025 /* Or if there is no read flag from REG. */
15027 /* Or if the read flag from REG is the same as PARENT_REG. */
15028 parent_flag == flag)
15031 err = mark_reg_read(env, reg, parent_reg, flag);
15038 /* A write screens off any subsequent reads; but write marks come from the
15039 * straight-line code between a state and its parent. When we arrive at an
15040 * equivalent state (jump target or such) we didn't arrive by the straight-line
15041 * code, so read marks in the state must propagate to the parent regardless
15042 * of the state's write marks. That's what 'parent == state->parent' comparison
15043 * in mark_reg_read() is for.
15045 static int propagate_liveness(struct bpf_verifier_env *env,
15046 const struct bpf_verifier_state *vstate,
15047 struct bpf_verifier_state *vparent)
15049 struct bpf_reg_state *state_reg, *parent_reg;
15050 struct bpf_func_state *state, *parent;
15051 int i, frame, err = 0;
15053 if (vparent->curframe != vstate->curframe) {
15054 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15055 vparent->curframe, vstate->curframe);
15058 /* Propagate read liveness of registers... */
15059 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15060 for (frame = 0; frame <= vstate->curframe; frame++) {
15061 parent = vparent->frame[frame];
15062 state = vstate->frame[frame];
15063 parent_reg = parent->regs;
15064 state_reg = state->regs;
15065 /* We don't need to worry about FP liveness, it's read-only */
15066 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15067 err = propagate_liveness_reg(env, &state_reg[i],
15071 if (err == REG_LIVE_READ64)
15072 mark_insn_zext(env, &parent_reg[i]);
15075 /* Propagate stack slots. */
15076 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15077 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15078 parent_reg = &parent->stack[i].spilled_ptr;
15079 state_reg = &state->stack[i].spilled_ptr;
15080 err = propagate_liveness_reg(env, state_reg,
15089 /* find precise scalars in the previous equivalent state and
15090 * propagate them into the current state
15092 static int propagate_precision(struct bpf_verifier_env *env,
15093 const struct bpf_verifier_state *old)
15095 struct bpf_reg_state *state_reg;
15096 struct bpf_func_state *state;
15097 int i, err = 0, fr;
15099 for (fr = old->curframe; fr >= 0; fr--) {
15100 state = old->frame[fr];
15101 state_reg = state->regs;
15102 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15103 if (state_reg->type != SCALAR_VALUE ||
15104 !state_reg->precise ||
15105 !(state_reg->live & REG_LIVE_READ))
15107 if (env->log.level & BPF_LOG_LEVEL2)
15108 verbose(env, "frame %d: propagating r%d\n", fr, i);
15109 err = mark_chain_precision_frame(env, fr, i);
15114 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15115 if (!is_spilled_reg(&state->stack[i]))
15117 state_reg = &state->stack[i].spilled_ptr;
15118 if (state_reg->type != SCALAR_VALUE ||
15119 !state_reg->precise ||
15120 !(state_reg->live & REG_LIVE_READ))
15122 if (env->log.level & BPF_LOG_LEVEL2)
15123 verbose(env, "frame %d: propagating fp%d\n",
15124 fr, (-i - 1) * BPF_REG_SIZE);
15125 err = mark_chain_precision_stack_frame(env, fr, i);
15133 static bool states_maybe_looping(struct bpf_verifier_state *old,
15134 struct bpf_verifier_state *cur)
15136 struct bpf_func_state *fold, *fcur;
15137 int i, fr = cur->curframe;
15139 if (old->curframe != fr)
15142 fold = old->frame[fr];
15143 fcur = cur->frame[fr];
15144 for (i = 0; i < MAX_BPF_REG; i++)
15145 if (memcmp(&fold->regs[i], &fcur->regs[i],
15146 offsetof(struct bpf_reg_state, parent)))
15151 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15153 return env->insn_aux_data[insn_idx].is_iter_next;
15156 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15157 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15158 * states to match, which otherwise would look like an infinite loop. So while
15159 * iter_next() calls are taken care of, we still need to be careful and
15160 * prevent erroneous and too eager declaration of "ininite loop", when
15161 * iterators are involved.
15163 * Here's a situation in pseudo-BPF assembly form:
15165 * 0: again: ; set up iter_next() call args
15166 * 1: r1 = &it ; <CHECKPOINT HERE>
15167 * 2: call bpf_iter_num_next ; this is iter_next() call
15168 * 3: if r0 == 0 goto done
15169 * 4: ... something useful here ...
15170 * 5: goto again ; another iteration
15173 * 8: call bpf_iter_num_destroy ; clean up iter state
15176 * This is a typical loop. Let's assume that we have a prune point at 1:,
15177 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15178 * again`, assuming other heuristics don't get in a way).
15180 * When we first time come to 1:, let's say we have some state X. We proceed
15181 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15182 * Now we come back to validate that forked ACTIVE state. We proceed through
15183 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15184 * are converging. But the problem is that we don't know that yet, as this
15185 * convergence has to happen at iter_next() call site only. So if nothing is
15186 * done, at 1: verifier will use bounded loop logic and declare infinite
15187 * looping (and would be *technically* correct, if not for iterator's
15188 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15189 * don't want that. So what we do in process_iter_next_call() when we go on
15190 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15191 * a different iteration. So when we suspect an infinite loop, we additionally
15192 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15193 * pretend we are not looping and wait for next iter_next() call.
15195 * This only applies to ACTIVE state. In DRAINED state we don't expect to
15196 * loop, because that would actually mean infinite loop, as DRAINED state is
15197 * "sticky", and so we'll keep returning into the same instruction with the
15198 * same state (at least in one of possible code paths).
15200 * This approach allows to keep infinite loop heuristic even in the face of
15201 * active iterator. E.g., C snippet below is and will be detected as
15202 * inifintely looping:
15204 * struct bpf_iter_num it;
15207 * bpf_iter_num_new(&it, 0, 10);
15208 * while ((p = bpf_iter_num_next(&t))) {
15210 * while (x--) {} // <<-- infinite loop here
15214 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15216 struct bpf_reg_state *slot, *cur_slot;
15217 struct bpf_func_state *state;
15220 for (fr = old->curframe; fr >= 0; fr--) {
15221 state = old->frame[fr];
15222 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15223 if (state->stack[i].slot_type[0] != STACK_ITER)
15226 slot = &state->stack[i].spilled_ptr;
15227 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15230 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15231 if (cur_slot->iter.depth != slot->iter.depth)
15238 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
15240 struct bpf_verifier_state_list *new_sl;
15241 struct bpf_verifier_state_list *sl, **pprev;
15242 struct bpf_verifier_state *cur = env->cur_state, *new;
15243 int i, j, err, states_cnt = 0;
15244 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15245 bool add_new_state = force_new_state;
15247 /* bpf progs typically have pruning point every 4 instructions
15248 * http://vger.kernel.org/bpfconf2019.html#session-1
15249 * Do not add new state for future pruning if the verifier hasn't seen
15250 * at least 2 jumps and at least 8 instructions.
15251 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15252 * In tests that amounts to up to 50% reduction into total verifier
15253 * memory consumption and 20% verifier time speedup.
15255 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15256 env->insn_processed - env->prev_insn_processed >= 8)
15257 add_new_state = true;
15259 pprev = explored_state(env, insn_idx);
15262 clean_live_states(env, insn_idx, cur);
15266 if (sl->state.insn_idx != insn_idx)
15269 if (sl->state.branches) {
15270 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15272 if (frame->in_async_callback_fn &&
15273 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
15274 /* Different async_entry_cnt means that the verifier is
15275 * processing another entry into async callback.
15276 * Seeing the same state is not an indication of infinite
15277 * loop or infinite recursion.
15278 * But finding the same state doesn't mean that it's safe
15279 * to stop processing the current state. The previous state
15280 * hasn't yet reached bpf_exit, since state.branches > 0.
15281 * Checking in_async_callback_fn alone is not enough either.
15282 * Since the verifier still needs to catch infinite loops
15283 * inside async callbacks.
15285 goto skip_inf_loop_check;
15287 /* BPF open-coded iterators loop detection is special.
15288 * states_maybe_looping() logic is too simplistic in detecting
15289 * states that *might* be equivalent, because it doesn't know
15290 * about ID remapping, so don't even perform it.
15291 * See process_iter_next_call() and iter_active_depths_differ()
15292 * for overview of the logic. When current and one of parent
15293 * states are detected as equivalent, it's a good thing: we prove
15294 * convergence and can stop simulating further iterations.
15295 * It's safe to assume that iterator loop will finish, taking into
15296 * account iter_next() contract of eventually returning
15297 * sticky NULL result.
15299 if (is_iter_next_insn(env, insn_idx)) {
15300 if (states_equal(env, &sl->state, cur)) {
15301 struct bpf_func_state *cur_frame;
15302 struct bpf_reg_state *iter_state, *iter_reg;
15305 cur_frame = cur->frame[cur->curframe];
15306 /* btf_check_iter_kfuncs() enforces that
15307 * iter state pointer is always the first arg
15309 iter_reg = &cur_frame->regs[BPF_REG_1];
15310 /* current state is valid due to states_equal(),
15311 * so we can assume valid iter and reg state,
15312 * no need for extra (re-)validations
15314 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
15315 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
15316 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
15319 goto skip_inf_loop_check;
15321 /* attempt to detect infinite loop to avoid unnecessary doomed work */
15322 if (states_maybe_looping(&sl->state, cur) &&
15323 states_equal(env, &sl->state, cur) &&
15324 !iter_active_depths_differ(&sl->state, cur)) {
15325 verbose_linfo(env, insn_idx, "; ");
15326 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
15329 /* if the verifier is processing a loop, avoid adding new state
15330 * too often, since different loop iterations have distinct
15331 * states and may not help future pruning.
15332 * This threshold shouldn't be too low to make sure that
15333 * a loop with large bound will be rejected quickly.
15334 * The most abusive loop will be:
15336 * if r1 < 1000000 goto pc-2
15337 * 1M insn_procssed limit / 100 == 10k peak states.
15338 * This threshold shouldn't be too high either, since states
15339 * at the end of the loop are likely to be useful in pruning.
15341 skip_inf_loop_check:
15342 if (!force_new_state &&
15343 env->jmps_processed - env->prev_jmps_processed < 20 &&
15344 env->insn_processed - env->prev_insn_processed < 100)
15345 add_new_state = false;
15348 if (states_equal(env, &sl->state, cur)) {
15351 /* reached equivalent register/stack state,
15352 * prune the search.
15353 * Registers read by the continuation are read by us.
15354 * If we have any write marks in env->cur_state, they
15355 * will prevent corresponding reads in the continuation
15356 * from reaching our parent (an explored_state). Our
15357 * own state will get the read marks recorded, but
15358 * they'll be immediately forgotten as we're pruning
15359 * this state and will pop a new one.
15361 err = propagate_liveness(env, &sl->state, cur);
15363 /* if previous state reached the exit with precision and
15364 * current state is equivalent to it (except precsion marks)
15365 * the precision needs to be propagated back in
15366 * the current state.
15368 err = err ? : push_jmp_history(env, cur);
15369 err = err ? : propagate_precision(env, &sl->state);
15375 /* when new state is not going to be added do not increase miss count.
15376 * Otherwise several loop iterations will remove the state
15377 * recorded earlier. The goal of these heuristics is to have
15378 * states from some iterations of the loop (some in the beginning
15379 * and some at the end) to help pruning.
15383 /* heuristic to determine whether this state is beneficial
15384 * to keep checking from state equivalence point of view.
15385 * Higher numbers increase max_states_per_insn and verification time,
15386 * but do not meaningfully decrease insn_processed.
15388 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
15389 /* the state is unlikely to be useful. Remove it to
15390 * speed up verification
15393 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
15394 u32 br = sl->state.branches;
15397 "BUG live_done but branches_to_explore %d\n",
15399 free_verifier_state(&sl->state, false);
15401 env->peak_states--;
15403 /* cannot free this state, since parentage chain may
15404 * walk it later. Add it for free_list instead to
15405 * be freed at the end of verification
15407 sl->next = env->free_list;
15408 env->free_list = sl;
15418 if (env->max_states_per_insn < states_cnt)
15419 env->max_states_per_insn = states_cnt;
15421 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
15424 if (!add_new_state)
15427 /* There were no equivalent states, remember the current one.
15428 * Technically the current state is not proven to be safe yet,
15429 * but it will either reach outer most bpf_exit (which means it's safe)
15430 * or it will be rejected. When there are no loops the verifier won't be
15431 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
15432 * again on the way to bpf_exit.
15433 * When looping the sl->state.branches will be > 0 and this state
15434 * will not be considered for equivalence until branches == 0.
15436 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
15439 env->total_states++;
15440 env->peak_states++;
15441 env->prev_jmps_processed = env->jmps_processed;
15442 env->prev_insn_processed = env->insn_processed;
15444 /* forget precise markings we inherited, see __mark_chain_precision */
15445 if (env->bpf_capable)
15446 mark_all_scalars_imprecise(env, cur);
15448 /* add new state to the head of linked list */
15449 new = &new_sl->state;
15450 err = copy_verifier_state(new, cur);
15452 free_verifier_state(new, false);
15456 new->insn_idx = insn_idx;
15457 WARN_ONCE(new->branches != 1,
15458 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
15461 cur->first_insn_idx = insn_idx;
15462 clear_jmp_history(cur);
15463 new_sl->next = *explored_state(env, insn_idx);
15464 *explored_state(env, insn_idx) = new_sl;
15465 /* connect new state to parentage chain. Current frame needs all
15466 * registers connected. Only r6 - r9 of the callers are alive (pushed
15467 * to the stack implicitly by JITs) so in callers' frames connect just
15468 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
15469 * the state of the call instruction (with WRITTEN set), and r0 comes
15470 * from callee with its full parentage chain, anyway.
15472 /* clear write marks in current state: the writes we did are not writes
15473 * our child did, so they don't screen off its reads from us.
15474 * (There are no read marks in current state, because reads always mark
15475 * their parent and current state never has children yet. Only
15476 * explored_states can get read marks.)
15478 for (j = 0; j <= cur->curframe; j++) {
15479 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
15480 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
15481 for (i = 0; i < BPF_REG_FP; i++)
15482 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
15485 /* all stack frames are accessible from callee, clear them all */
15486 for (j = 0; j <= cur->curframe; j++) {
15487 struct bpf_func_state *frame = cur->frame[j];
15488 struct bpf_func_state *newframe = new->frame[j];
15490 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
15491 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
15492 frame->stack[i].spilled_ptr.parent =
15493 &newframe->stack[i].spilled_ptr;
15499 /* Return true if it's OK to have the same insn return a different type. */
15500 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
15502 switch (base_type(type)) {
15504 case PTR_TO_SOCKET:
15505 case PTR_TO_SOCK_COMMON:
15506 case PTR_TO_TCP_SOCK:
15507 case PTR_TO_XDP_SOCK:
15508 case PTR_TO_BTF_ID:
15515 /* If an instruction was previously used with particular pointer types, then we
15516 * need to be careful to avoid cases such as the below, where it may be ok
15517 * for one branch accessing the pointer, but not ok for the other branch:
15522 * R1 = some_other_valid_ptr;
15525 * R2 = *(u32 *)(R1 + 0);
15527 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
15529 return src != prev && (!reg_type_mismatch_ok(src) ||
15530 !reg_type_mismatch_ok(prev));
15533 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
15534 bool allow_trust_missmatch)
15536 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
15538 if (*prev_type == NOT_INIT) {
15539 /* Saw a valid insn
15540 * dst_reg = *(u32 *)(src_reg + off)
15541 * save type to validate intersecting paths
15544 } else if (reg_type_mismatch(type, *prev_type)) {
15545 /* Abuser program is trying to use the same insn
15546 * dst_reg = *(u32*) (src_reg + off)
15547 * with different pointer types:
15548 * src_reg == ctx in one branch and
15549 * src_reg == stack|map in some other branch.
15552 if (allow_trust_missmatch &&
15553 base_type(type) == PTR_TO_BTF_ID &&
15554 base_type(*prev_type) == PTR_TO_BTF_ID) {
15556 * Have to support a use case when one path through
15557 * the program yields TRUSTED pointer while another
15558 * is UNTRUSTED. Fallback to UNTRUSTED to generate
15561 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
15563 verbose(env, "same insn cannot be used with different pointers\n");
15571 static int do_check(struct bpf_verifier_env *env)
15573 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
15574 struct bpf_verifier_state *state = env->cur_state;
15575 struct bpf_insn *insns = env->prog->insnsi;
15576 struct bpf_reg_state *regs;
15577 int insn_cnt = env->prog->len;
15578 bool do_print_state = false;
15579 int prev_insn_idx = -1;
15582 struct bpf_insn *insn;
15586 env->prev_insn_idx = prev_insn_idx;
15587 if (env->insn_idx >= insn_cnt) {
15588 verbose(env, "invalid insn idx %d insn_cnt %d\n",
15589 env->insn_idx, insn_cnt);
15593 insn = &insns[env->insn_idx];
15594 class = BPF_CLASS(insn->code);
15596 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
15598 "BPF program is too large. Processed %d insn\n",
15599 env->insn_processed);
15603 state->last_insn_idx = env->prev_insn_idx;
15605 if (is_prune_point(env, env->insn_idx)) {
15606 err = is_state_visited(env, env->insn_idx);
15610 /* found equivalent state, can prune the search */
15611 if (env->log.level & BPF_LOG_LEVEL) {
15612 if (do_print_state)
15613 verbose(env, "\nfrom %d to %d%s: safe\n",
15614 env->prev_insn_idx, env->insn_idx,
15615 env->cur_state->speculative ?
15616 " (speculative execution)" : "");
15618 verbose(env, "%d: safe\n", env->insn_idx);
15620 goto process_bpf_exit;
15624 if (is_jmp_point(env, env->insn_idx)) {
15625 err = push_jmp_history(env, state);
15630 if (signal_pending(current))
15633 if (need_resched())
15636 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
15637 verbose(env, "\nfrom %d to %d%s:",
15638 env->prev_insn_idx, env->insn_idx,
15639 env->cur_state->speculative ?
15640 " (speculative execution)" : "");
15641 print_verifier_state(env, state->frame[state->curframe], true);
15642 do_print_state = false;
15645 if (env->log.level & BPF_LOG_LEVEL) {
15646 const struct bpf_insn_cbs cbs = {
15647 .cb_call = disasm_kfunc_name,
15648 .cb_print = verbose,
15649 .private_data = env,
15652 if (verifier_state_scratched(env))
15653 print_insn_state(env, state->frame[state->curframe]);
15655 verbose_linfo(env, env->insn_idx, "; ");
15656 env->prev_log_pos = env->log.end_pos;
15657 verbose(env, "%d: ", env->insn_idx);
15658 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
15659 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
15660 env->prev_log_pos = env->log.end_pos;
15663 if (bpf_prog_is_offloaded(env->prog->aux)) {
15664 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
15665 env->prev_insn_idx);
15670 regs = cur_regs(env);
15671 sanitize_mark_insn_seen(env);
15672 prev_insn_idx = env->insn_idx;
15674 if (class == BPF_ALU || class == BPF_ALU64) {
15675 err = check_alu_op(env, insn);
15679 } else if (class == BPF_LDX) {
15680 enum bpf_reg_type src_reg_type;
15682 /* check for reserved fields is already done */
15684 /* check src operand */
15685 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15689 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15693 src_reg_type = regs[insn->src_reg].type;
15695 /* check that memory (src_reg + off) is readable,
15696 * the state of dst_reg will be updated by this func
15698 err = check_mem_access(env, env->insn_idx, insn->src_reg,
15699 insn->off, BPF_SIZE(insn->code),
15700 BPF_READ, insn->dst_reg, false);
15704 err = save_aux_ptr_type(env, src_reg_type, true);
15707 } else if (class == BPF_STX) {
15708 enum bpf_reg_type dst_reg_type;
15710 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
15711 err = check_atomic(env, env->insn_idx, insn);
15718 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
15719 verbose(env, "BPF_STX uses reserved fields\n");
15723 /* check src1 operand */
15724 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15727 /* check src2 operand */
15728 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15732 dst_reg_type = regs[insn->dst_reg].type;
15734 /* check that memory (dst_reg + off) is writeable */
15735 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15736 insn->off, BPF_SIZE(insn->code),
15737 BPF_WRITE, insn->src_reg, false);
15741 err = save_aux_ptr_type(env, dst_reg_type, false);
15744 } else if (class == BPF_ST) {
15745 enum bpf_reg_type dst_reg_type;
15747 if (BPF_MODE(insn->code) != BPF_MEM ||
15748 insn->src_reg != BPF_REG_0) {
15749 verbose(env, "BPF_ST uses reserved fields\n");
15752 /* check src operand */
15753 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15757 dst_reg_type = regs[insn->dst_reg].type;
15759 /* check that memory (dst_reg + off) is writeable */
15760 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15761 insn->off, BPF_SIZE(insn->code),
15762 BPF_WRITE, -1, false);
15766 err = save_aux_ptr_type(env, dst_reg_type, false);
15769 } else if (class == BPF_JMP || class == BPF_JMP32) {
15770 u8 opcode = BPF_OP(insn->code);
15772 env->jmps_processed++;
15773 if (opcode == BPF_CALL) {
15774 if (BPF_SRC(insn->code) != BPF_K ||
15775 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
15776 && insn->off != 0) ||
15777 (insn->src_reg != BPF_REG_0 &&
15778 insn->src_reg != BPF_PSEUDO_CALL &&
15779 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
15780 insn->dst_reg != BPF_REG_0 ||
15781 class == BPF_JMP32) {
15782 verbose(env, "BPF_CALL uses reserved fields\n");
15786 if (env->cur_state->active_lock.ptr) {
15787 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
15788 (insn->src_reg == BPF_PSEUDO_CALL) ||
15789 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
15790 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
15791 verbose(env, "function calls are not allowed while holding a lock\n");
15795 if (insn->src_reg == BPF_PSEUDO_CALL)
15796 err = check_func_call(env, insn, &env->insn_idx);
15797 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
15798 err = check_kfunc_call(env, insn, &env->insn_idx);
15800 err = check_helper_call(env, insn, &env->insn_idx);
15804 mark_reg_scratched(env, BPF_REG_0);
15805 } else if (opcode == BPF_JA) {
15806 if (BPF_SRC(insn->code) != BPF_K ||
15808 insn->src_reg != BPF_REG_0 ||
15809 insn->dst_reg != BPF_REG_0 ||
15810 class == BPF_JMP32) {
15811 verbose(env, "BPF_JA uses reserved fields\n");
15815 env->insn_idx += insn->off + 1;
15818 } else if (opcode == BPF_EXIT) {
15819 if (BPF_SRC(insn->code) != BPF_K ||
15821 insn->src_reg != BPF_REG_0 ||
15822 insn->dst_reg != BPF_REG_0 ||
15823 class == BPF_JMP32) {
15824 verbose(env, "BPF_EXIT uses reserved fields\n");
15828 if (env->cur_state->active_lock.ptr &&
15829 !in_rbtree_lock_required_cb(env)) {
15830 verbose(env, "bpf_spin_unlock is missing\n");
15834 if (env->cur_state->active_rcu_lock) {
15835 verbose(env, "bpf_rcu_read_unlock is missing\n");
15839 /* We must do check_reference_leak here before
15840 * prepare_func_exit to handle the case when
15841 * state->curframe > 0, it may be a callback
15842 * function, for which reference_state must
15843 * match caller reference state when it exits.
15845 err = check_reference_leak(env);
15849 if (state->curframe) {
15850 /* exit from nested function */
15851 err = prepare_func_exit(env, &env->insn_idx);
15854 do_print_state = true;
15858 err = check_return_code(env);
15862 mark_verifier_state_scratched(env);
15863 update_branch_counts(env, env->cur_state);
15864 err = pop_stack(env, &prev_insn_idx,
15865 &env->insn_idx, pop_log);
15867 if (err != -ENOENT)
15871 do_print_state = true;
15875 err = check_cond_jmp_op(env, insn, &env->insn_idx);
15879 } else if (class == BPF_LD) {
15880 u8 mode = BPF_MODE(insn->code);
15882 if (mode == BPF_ABS || mode == BPF_IND) {
15883 err = check_ld_abs(env, insn);
15887 } else if (mode == BPF_IMM) {
15888 err = check_ld_imm(env, insn);
15893 sanitize_mark_insn_seen(env);
15895 verbose(env, "invalid BPF_LD mode\n");
15899 verbose(env, "unknown insn class %d\n", class);
15909 static int find_btf_percpu_datasec(struct btf *btf)
15911 const struct btf_type *t;
15916 * Both vmlinux and module each have their own ".data..percpu"
15917 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
15918 * types to look at only module's own BTF types.
15920 n = btf_nr_types(btf);
15921 if (btf_is_module(btf))
15922 i = btf_nr_types(btf_vmlinux);
15926 for(; i < n; i++) {
15927 t = btf_type_by_id(btf, i);
15928 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
15931 tname = btf_name_by_offset(btf, t->name_off);
15932 if (!strcmp(tname, ".data..percpu"))
15939 /* replace pseudo btf_id with kernel symbol address */
15940 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
15941 struct bpf_insn *insn,
15942 struct bpf_insn_aux_data *aux)
15944 const struct btf_var_secinfo *vsi;
15945 const struct btf_type *datasec;
15946 struct btf_mod_pair *btf_mod;
15947 const struct btf_type *t;
15948 const char *sym_name;
15949 bool percpu = false;
15950 u32 type, id = insn->imm;
15954 int i, btf_fd, err;
15956 btf_fd = insn[1].imm;
15958 btf = btf_get_by_fd(btf_fd);
15960 verbose(env, "invalid module BTF object FD specified.\n");
15964 if (!btf_vmlinux) {
15965 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
15972 t = btf_type_by_id(btf, id);
15974 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
15979 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
15980 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
15985 sym_name = btf_name_by_offset(btf, t->name_off);
15986 addr = kallsyms_lookup_name(sym_name);
15988 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
15993 insn[0].imm = (u32)addr;
15994 insn[1].imm = addr >> 32;
15996 if (btf_type_is_func(t)) {
15997 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
15998 aux->btf_var.mem_size = 0;
16002 datasec_id = find_btf_percpu_datasec(btf);
16003 if (datasec_id > 0) {
16004 datasec = btf_type_by_id(btf, datasec_id);
16005 for_each_vsi(i, datasec, vsi) {
16006 if (vsi->type == id) {
16014 t = btf_type_skip_modifiers(btf, type, NULL);
16016 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16017 aux->btf_var.btf = btf;
16018 aux->btf_var.btf_id = type;
16019 } else if (!btf_type_is_struct(t)) {
16020 const struct btf_type *ret;
16024 /* resolve the type size of ksym. */
16025 ret = btf_resolve_size(btf, t, &tsize);
16027 tname = btf_name_by_offset(btf, t->name_off);
16028 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16029 tname, PTR_ERR(ret));
16033 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16034 aux->btf_var.mem_size = tsize;
16036 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16037 aux->btf_var.btf = btf;
16038 aux->btf_var.btf_id = type;
16041 /* check whether we recorded this BTF (and maybe module) already */
16042 for (i = 0; i < env->used_btf_cnt; i++) {
16043 if (env->used_btfs[i].btf == btf) {
16049 if (env->used_btf_cnt >= MAX_USED_BTFS) {
16054 btf_mod = &env->used_btfs[env->used_btf_cnt];
16055 btf_mod->btf = btf;
16056 btf_mod->module = NULL;
16058 /* if we reference variables from kernel module, bump its refcount */
16059 if (btf_is_module(btf)) {
16060 btf_mod->module = btf_try_get_module(btf);
16061 if (!btf_mod->module) {
16067 env->used_btf_cnt++;
16075 static bool is_tracing_prog_type(enum bpf_prog_type type)
16078 case BPF_PROG_TYPE_KPROBE:
16079 case BPF_PROG_TYPE_TRACEPOINT:
16080 case BPF_PROG_TYPE_PERF_EVENT:
16081 case BPF_PROG_TYPE_RAW_TRACEPOINT:
16082 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16089 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16090 struct bpf_map *map,
16091 struct bpf_prog *prog)
16094 enum bpf_prog_type prog_type = resolve_prog_type(prog);
16096 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16097 btf_record_has_field(map->record, BPF_RB_ROOT)) {
16098 if (is_tracing_prog_type(prog_type)) {
16099 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16104 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16105 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16106 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16110 if (is_tracing_prog_type(prog_type)) {
16111 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16115 if (prog->aux->sleepable) {
16116 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16121 if (btf_record_has_field(map->record, BPF_TIMER)) {
16122 if (is_tracing_prog_type(prog_type)) {
16123 verbose(env, "tracing progs cannot use bpf_timer yet\n");
16128 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16129 !bpf_offload_prog_map_match(prog, map)) {
16130 verbose(env, "offload device mismatch between prog and map\n");
16134 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16135 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16139 if (prog->aux->sleepable)
16140 switch (map->map_type) {
16141 case BPF_MAP_TYPE_HASH:
16142 case BPF_MAP_TYPE_LRU_HASH:
16143 case BPF_MAP_TYPE_ARRAY:
16144 case BPF_MAP_TYPE_PERCPU_HASH:
16145 case BPF_MAP_TYPE_PERCPU_ARRAY:
16146 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16147 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16148 case BPF_MAP_TYPE_HASH_OF_MAPS:
16149 case BPF_MAP_TYPE_RINGBUF:
16150 case BPF_MAP_TYPE_USER_RINGBUF:
16151 case BPF_MAP_TYPE_INODE_STORAGE:
16152 case BPF_MAP_TYPE_SK_STORAGE:
16153 case BPF_MAP_TYPE_TASK_STORAGE:
16154 case BPF_MAP_TYPE_CGRP_STORAGE:
16158 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16165 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16167 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16168 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16171 /* find and rewrite pseudo imm in ld_imm64 instructions:
16173 * 1. if it accesses map FD, replace it with actual map pointer.
16174 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16176 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
16178 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
16180 struct bpf_insn *insn = env->prog->insnsi;
16181 int insn_cnt = env->prog->len;
16184 err = bpf_prog_calc_tag(env->prog);
16188 for (i = 0; i < insn_cnt; i++, insn++) {
16189 if (BPF_CLASS(insn->code) == BPF_LDX &&
16190 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
16191 verbose(env, "BPF_LDX uses reserved fields\n");
16195 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
16196 struct bpf_insn_aux_data *aux;
16197 struct bpf_map *map;
16202 if (i == insn_cnt - 1 || insn[1].code != 0 ||
16203 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16204 insn[1].off != 0) {
16205 verbose(env, "invalid bpf_ld_imm64 insn\n");
16209 if (insn[0].src_reg == 0)
16210 /* valid generic load 64-bit imm */
16213 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16214 aux = &env->insn_aux_data[i];
16215 err = check_pseudo_btf_id(env, insn, aux);
16221 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16222 aux = &env->insn_aux_data[i];
16223 aux->ptr_type = PTR_TO_FUNC;
16227 /* In final convert_pseudo_ld_imm64() step, this is
16228 * converted into regular 64-bit imm load insn.
16230 switch (insn[0].src_reg) {
16231 case BPF_PSEUDO_MAP_VALUE:
16232 case BPF_PSEUDO_MAP_IDX_VALUE:
16234 case BPF_PSEUDO_MAP_FD:
16235 case BPF_PSEUDO_MAP_IDX:
16236 if (insn[1].imm == 0)
16240 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
16244 switch (insn[0].src_reg) {
16245 case BPF_PSEUDO_MAP_IDX_VALUE:
16246 case BPF_PSEUDO_MAP_IDX:
16247 if (bpfptr_is_null(env->fd_array)) {
16248 verbose(env, "fd_idx without fd_array is invalid\n");
16251 if (copy_from_bpfptr_offset(&fd, env->fd_array,
16252 insn[0].imm * sizeof(fd),
16262 map = __bpf_map_get(f);
16264 verbose(env, "fd %d is not pointing to valid bpf_map\n",
16266 return PTR_ERR(map);
16269 err = check_map_prog_compatibility(env, map, env->prog);
16275 aux = &env->insn_aux_data[i];
16276 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
16277 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
16278 addr = (unsigned long)map;
16280 u32 off = insn[1].imm;
16282 if (off >= BPF_MAX_VAR_OFF) {
16283 verbose(env, "direct value offset of %u is not allowed\n", off);
16288 if (!map->ops->map_direct_value_addr) {
16289 verbose(env, "no direct value access support for this map type\n");
16294 err = map->ops->map_direct_value_addr(map, &addr, off);
16296 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
16297 map->value_size, off);
16302 aux->map_off = off;
16306 insn[0].imm = (u32)addr;
16307 insn[1].imm = addr >> 32;
16309 /* check whether we recorded this map already */
16310 for (j = 0; j < env->used_map_cnt; j++) {
16311 if (env->used_maps[j] == map) {
16312 aux->map_index = j;
16318 if (env->used_map_cnt >= MAX_USED_MAPS) {
16323 /* hold the map. If the program is rejected by verifier,
16324 * the map will be released by release_maps() or it
16325 * will be used by the valid program until it's unloaded
16326 * and all maps are released in free_used_maps()
16330 aux->map_index = env->used_map_cnt;
16331 env->used_maps[env->used_map_cnt++] = map;
16333 if (bpf_map_is_cgroup_storage(map) &&
16334 bpf_cgroup_storage_assign(env->prog->aux, map)) {
16335 verbose(env, "only one cgroup storage of each type is allowed\n");
16347 /* Basic sanity check before we invest more work here. */
16348 if (!bpf_opcode_in_insntable(insn->code)) {
16349 verbose(env, "unknown opcode %02x\n", insn->code);
16354 /* now all pseudo BPF_LD_IMM64 instructions load valid
16355 * 'struct bpf_map *' into a register instead of user map_fd.
16356 * These pointers will be used later by verifier to validate map access.
16361 /* drop refcnt of maps used by the rejected program */
16362 static void release_maps(struct bpf_verifier_env *env)
16364 __bpf_free_used_maps(env->prog->aux, env->used_maps,
16365 env->used_map_cnt);
16368 /* drop refcnt of maps used by the rejected program */
16369 static void release_btfs(struct bpf_verifier_env *env)
16371 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
16372 env->used_btf_cnt);
16375 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
16376 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
16378 struct bpf_insn *insn = env->prog->insnsi;
16379 int insn_cnt = env->prog->len;
16382 for (i = 0; i < insn_cnt; i++, insn++) {
16383 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
16385 if (insn->src_reg == BPF_PSEUDO_FUNC)
16391 /* single env->prog->insni[off] instruction was replaced with the range
16392 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
16393 * [0, off) and [off, end) to new locations, so the patched range stays zero
16395 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
16396 struct bpf_insn_aux_data *new_data,
16397 struct bpf_prog *new_prog, u32 off, u32 cnt)
16399 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
16400 struct bpf_insn *insn = new_prog->insnsi;
16401 u32 old_seen = old_data[off].seen;
16405 /* aux info at OFF always needs adjustment, no matter fast path
16406 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
16407 * original insn at old prog.
16409 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
16413 prog_len = new_prog->len;
16415 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
16416 memcpy(new_data + off + cnt - 1, old_data + off,
16417 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
16418 for (i = off; i < off + cnt - 1; i++) {
16419 /* Expand insni[off]'s seen count to the patched range. */
16420 new_data[i].seen = old_seen;
16421 new_data[i].zext_dst = insn_has_def32(env, insn + i);
16423 env->insn_aux_data = new_data;
16427 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
16433 /* NOTE: fake 'exit' subprog should be updated as well. */
16434 for (i = 0; i <= env->subprog_cnt; i++) {
16435 if (env->subprog_info[i].start <= off)
16437 env->subprog_info[i].start += len - 1;
16441 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
16443 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
16444 int i, sz = prog->aux->size_poke_tab;
16445 struct bpf_jit_poke_descriptor *desc;
16447 for (i = 0; i < sz; i++) {
16449 if (desc->insn_idx <= off)
16451 desc->insn_idx += len - 1;
16455 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
16456 const struct bpf_insn *patch, u32 len)
16458 struct bpf_prog *new_prog;
16459 struct bpf_insn_aux_data *new_data = NULL;
16462 new_data = vzalloc(array_size(env->prog->len + len - 1,
16463 sizeof(struct bpf_insn_aux_data)));
16468 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
16469 if (IS_ERR(new_prog)) {
16470 if (PTR_ERR(new_prog) == -ERANGE)
16472 "insn %d cannot be patched due to 16-bit range\n",
16473 env->insn_aux_data[off].orig_idx);
16477 adjust_insn_aux_data(env, new_data, new_prog, off, len);
16478 adjust_subprog_starts(env, off, len);
16479 adjust_poke_descs(new_prog, off, len);
16483 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
16488 /* find first prog starting at or after off (first to remove) */
16489 for (i = 0; i < env->subprog_cnt; i++)
16490 if (env->subprog_info[i].start >= off)
16492 /* find first prog starting at or after off + cnt (first to stay) */
16493 for (j = i; j < env->subprog_cnt; j++)
16494 if (env->subprog_info[j].start >= off + cnt)
16496 /* if j doesn't start exactly at off + cnt, we are just removing
16497 * the front of previous prog
16499 if (env->subprog_info[j].start != off + cnt)
16503 struct bpf_prog_aux *aux = env->prog->aux;
16506 /* move fake 'exit' subprog as well */
16507 move = env->subprog_cnt + 1 - j;
16509 memmove(env->subprog_info + i,
16510 env->subprog_info + j,
16511 sizeof(*env->subprog_info) * move);
16512 env->subprog_cnt -= j - i;
16514 /* remove func_info */
16515 if (aux->func_info) {
16516 move = aux->func_info_cnt - j;
16518 memmove(aux->func_info + i,
16519 aux->func_info + j,
16520 sizeof(*aux->func_info) * move);
16521 aux->func_info_cnt -= j - i;
16522 /* func_info->insn_off is set after all code rewrites,
16523 * in adjust_btf_func() - no need to adjust
16527 /* convert i from "first prog to remove" to "first to adjust" */
16528 if (env->subprog_info[i].start == off)
16532 /* update fake 'exit' subprog as well */
16533 for (; i <= env->subprog_cnt; i++)
16534 env->subprog_info[i].start -= cnt;
16539 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
16542 struct bpf_prog *prog = env->prog;
16543 u32 i, l_off, l_cnt, nr_linfo;
16544 struct bpf_line_info *linfo;
16546 nr_linfo = prog->aux->nr_linfo;
16550 linfo = prog->aux->linfo;
16552 /* find first line info to remove, count lines to be removed */
16553 for (i = 0; i < nr_linfo; i++)
16554 if (linfo[i].insn_off >= off)
16559 for (; i < nr_linfo; i++)
16560 if (linfo[i].insn_off < off + cnt)
16565 /* First live insn doesn't match first live linfo, it needs to "inherit"
16566 * last removed linfo. prog is already modified, so prog->len == off
16567 * means no live instructions after (tail of the program was removed).
16569 if (prog->len != off && l_cnt &&
16570 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
16572 linfo[--i].insn_off = off + cnt;
16575 /* remove the line info which refer to the removed instructions */
16577 memmove(linfo + l_off, linfo + i,
16578 sizeof(*linfo) * (nr_linfo - i));
16580 prog->aux->nr_linfo -= l_cnt;
16581 nr_linfo = prog->aux->nr_linfo;
16584 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
16585 for (i = l_off; i < nr_linfo; i++)
16586 linfo[i].insn_off -= cnt;
16588 /* fix up all subprogs (incl. 'exit') which start >= off */
16589 for (i = 0; i <= env->subprog_cnt; i++)
16590 if (env->subprog_info[i].linfo_idx > l_off) {
16591 /* program may have started in the removed region but
16592 * may not be fully removed
16594 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
16595 env->subprog_info[i].linfo_idx -= l_cnt;
16597 env->subprog_info[i].linfo_idx = l_off;
16603 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
16605 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16606 unsigned int orig_prog_len = env->prog->len;
16609 if (bpf_prog_is_offloaded(env->prog->aux))
16610 bpf_prog_offload_remove_insns(env, off, cnt);
16612 err = bpf_remove_insns(env->prog, off, cnt);
16616 err = adjust_subprog_starts_after_remove(env, off, cnt);
16620 err = bpf_adj_linfo_after_remove(env, off, cnt);
16624 memmove(aux_data + off, aux_data + off + cnt,
16625 sizeof(*aux_data) * (orig_prog_len - off - cnt));
16630 /* The verifier does more data flow analysis than llvm and will not
16631 * explore branches that are dead at run time. Malicious programs can
16632 * have dead code too. Therefore replace all dead at-run-time code
16635 * Just nops are not optimal, e.g. if they would sit at the end of the
16636 * program and through another bug we would manage to jump there, then
16637 * we'd execute beyond program memory otherwise. Returning exception
16638 * code also wouldn't work since we can have subprogs where the dead
16639 * code could be located.
16641 static void sanitize_dead_code(struct bpf_verifier_env *env)
16643 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16644 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
16645 struct bpf_insn *insn = env->prog->insnsi;
16646 const int insn_cnt = env->prog->len;
16649 for (i = 0; i < insn_cnt; i++) {
16650 if (aux_data[i].seen)
16652 memcpy(insn + i, &trap, sizeof(trap));
16653 aux_data[i].zext_dst = false;
16657 static bool insn_is_cond_jump(u8 code)
16661 if (BPF_CLASS(code) == BPF_JMP32)
16664 if (BPF_CLASS(code) != BPF_JMP)
16668 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
16671 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
16673 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16674 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
16675 struct bpf_insn *insn = env->prog->insnsi;
16676 const int insn_cnt = env->prog->len;
16679 for (i = 0; i < insn_cnt; i++, insn++) {
16680 if (!insn_is_cond_jump(insn->code))
16683 if (!aux_data[i + 1].seen)
16684 ja.off = insn->off;
16685 else if (!aux_data[i + 1 + insn->off].seen)
16690 if (bpf_prog_is_offloaded(env->prog->aux))
16691 bpf_prog_offload_replace_insn(env, i, &ja);
16693 memcpy(insn, &ja, sizeof(ja));
16697 static int opt_remove_dead_code(struct bpf_verifier_env *env)
16699 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16700 int insn_cnt = env->prog->len;
16703 for (i = 0; i < insn_cnt; i++) {
16707 while (i + j < insn_cnt && !aux_data[i + j].seen)
16712 err = verifier_remove_insns(env, i, j);
16715 insn_cnt = env->prog->len;
16721 static int opt_remove_nops(struct bpf_verifier_env *env)
16723 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
16724 struct bpf_insn *insn = env->prog->insnsi;
16725 int insn_cnt = env->prog->len;
16728 for (i = 0; i < insn_cnt; i++) {
16729 if (memcmp(&insn[i], &ja, sizeof(ja)))
16732 err = verifier_remove_insns(env, i, 1);
16742 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
16743 const union bpf_attr *attr)
16745 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
16746 struct bpf_insn_aux_data *aux = env->insn_aux_data;
16747 int i, patch_len, delta = 0, len = env->prog->len;
16748 struct bpf_insn *insns = env->prog->insnsi;
16749 struct bpf_prog *new_prog;
16752 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
16753 zext_patch[1] = BPF_ZEXT_REG(0);
16754 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
16755 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
16756 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
16757 for (i = 0; i < len; i++) {
16758 int adj_idx = i + delta;
16759 struct bpf_insn insn;
16762 insn = insns[adj_idx];
16763 load_reg = insn_def_regno(&insn);
16764 if (!aux[adj_idx].zext_dst) {
16772 class = BPF_CLASS(code);
16773 if (load_reg == -1)
16776 /* NOTE: arg "reg" (the fourth one) is only used for
16777 * BPF_STX + SRC_OP, so it is safe to pass NULL
16780 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
16781 if (class == BPF_LD &&
16782 BPF_MODE(code) == BPF_IMM)
16787 /* ctx load could be transformed into wider load. */
16788 if (class == BPF_LDX &&
16789 aux[adj_idx].ptr_type == PTR_TO_CTX)
16792 imm_rnd = get_random_u32();
16793 rnd_hi32_patch[0] = insn;
16794 rnd_hi32_patch[1].imm = imm_rnd;
16795 rnd_hi32_patch[3].dst_reg = load_reg;
16796 patch = rnd_hi32_patch;
16798 goto apply_patch_buffer;
16801 /* Add in an zero-extend instruction if a) the JIT has requested
16802 * it or b) it's a CMPXCHG.
16804 * The latter is because: BPF_CMPXCHG always loads a value into
16805 * R0, therefore always zero-extends. However some archs'
16806 * equivalent instruction only does this load when the
16807 * comparison is successful. This detail of CMPXCHG is
16808 * orthogonal to the general zero-extension behaviour of the
16809 * CPU, so it's treated independently of bpf_jit_needs_zext.
16811 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
16814 /* Zero-extension is done by the caller. */
16815 if (bpf_pseudo_kfunc_call(&insn))
16818 if (WARN_ON(load_reg == -1)) {
16819 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
16823 zext_patch[0] = insn;
16824 zext_patch[1].dst_reg = load_reg;
16825 zext_patch[1].src_reg = load_reg;
16826 patch = zext_patch;
16828 apply_patch_buffer:
16829 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
16832 env->prog = new_prog;
16833 insns = new_prog->insnsi;
16834 aux = env->insn_aux_data;
16835 delta += patch_len - 1;
16841 /* convert load instructions that access fields of a context type into a
16842 * sequence of instructions that access fields of the underlying structure:
16843 * struct __sk_buff -> struct sk_buff
16844 * struct bpf_sock_ops -> struct sock
16846 static int convert_ctx_accesses(struct bpf_verifier_env *env)
16848 const struct bpf_verifier_ops *ops = env->ops;
16849 int i, cnt, size, ctx_field_size, delta = 0;
16850 const int insn_cnt = env->prog->len;
16851 struct bpf_insn insn_buf[16], *insn;
16852 u32 target_size, size_default, off;
16853 struct bpf_prog *new_prog;
16854 enum bpf_access_type type;
16855 bool is_narrower_load;
16857 if (ops->gen_prologue || env->seen_direct_write) {
16858 if (!ops->gen_prologue) {
16859 verbose(env, "bpf verifier is misconfigured\n");
16862 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
16864 if (cnt >= ARRAY_SIZE(insn_buf)) {
16865 verbose(env, "bpf verifier is misconfigured\n");
16868 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
16872 env->prog = new_prog;
16877 if (bpf_prog_is_offloaded(env->prog->aux))
16880 insn = env->prog->insnsi + delta;
16882 for (i = 0; i < insn_cnt; i++, insn++) {
16883 bpf_convert_ctx_access_t convert_ctx_access;
16885 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
16886 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
16887 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
16888 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
16890 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
16891 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
16892 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
16893 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
16894 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
16895 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
16896 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
16897 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
16903 if (type == BPF_WRITE &&
16904 env->insn_aux_data[i + delta].sanitize_stack_spill) {
16905 struct bpf_insn patch[] = {
16910 cnt = ARRAY_SIZE(patch);
16911 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
16916 env->prog = new_prog;
16917 insn = new_prog->insnsi + i + delta;
16921 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
16923 if (!ops->convert_ctx_access)
16925 convert_ctx_access = ops->convert_ctx_access;
16927 case PTR_TO_SOCKET:
16928 case PTR_TO_SOCK_COMMON:
16929 convert_ctx_access = bpf_sock_convert_ctx_access;
16931 case PTR_TO_TCP_SOCK:
16932 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
16934 case PTR_TO_XDP_SOCK:
16935 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
16937 case PTR_TO_BTF_ID:
16938 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
16939 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
16940 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
16941 * be said once it is marked PTR_UNTRUSTED, hence we must handle
16942 * any faults for loads into such types. BPF_WRITE is disallowed
16945 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
16946 if (type == BPF_READ) {
16947 insn->code = BPF_LDX | BPF_PROBE_MEM |
16948 BPF_SIZE((insn)->code);
16949 env->prog->aux->num_exentries++;
16956 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
16957 size = BPF_LDST_BYTES(insn);
16959 /* If the read access is a narrower load of the field,
16960 * convert to a 4/8-byte load, to minimum program type specific
16961 * convert_ctx_access changes. If conversion is successful,
16962 * we will apply proper mask to the result.
16964 is_narrower_load = size < ctx_field_size;
16965 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
16967 if (is_narrower_load) {
16970 if (type == BPF_WRITE) {
16971 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
16976 if (ctx_field_size == 4)
16978 else if (ctx_field_size == 8)
16979 size_code = BPF_DW;
16981 insn->off = off & ~(size_default - 1);
16982 insn->code = BPF_LDX | BPF_MEM | size_code;
16986 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
16988 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
16989 (ctx_field_size && !target_size)) {
16990 verbose(env, "bpf verifier is misconfigured\n");
16994 if (is_narrower_load && size < target_size) {
16995 u8 shift = bpf_ctx_narrow_access_offset(
16996 off, size, size_default) * 8;
16997 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
16998 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17001 if (ctx_field_size <= 4) {
17003 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17006 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17007 (1 << size * 8) - 1);
17010 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17013 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
17014 (1ULL << size * 8) - 1);
17018 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17024 /* keep walking new program and skip insns we just inserted */
17025 env->prog = new_prog;
17026 insn = new_prog->insnsi + i + delta;
17032 static int jit_subprogs(struct bpf_verifier_env *env)
17034 struct bpf_prog *prog = env->prog, **func, *tmp;
17035 int i, j, subprog_start, subprog_end = 0, len, subprog;
17036 struct bpf_map *map_ptr;
17037 struct bpf_insn *insn;
17038 void *old_bpf_func;
17039 int err, num_exentries;
17041 if (env->subprog_cnt <= 1)
17044 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17045 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17048 /* Upon error here we cannot fall back to interpreter but
17049 * need a hard reject of the program. Thus -EFAULT is
17050 * propagated in any case.
17052 subprog = find_subprog(env, i + insn->imm + 1);
17054 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17055 i + insn->imm + 1);
17058 /* temporarily remember subprog id inside insn instead of
17059 * aux_data, since next loop will split up all insns into funcs
17061 insn->off = subprog;
17062 /* remember original imm in case JIT fails and fallback
17063 * to interpreter will be needed
17065 env->insn_aux_data[i].call_imm = insn->imm;
17066 /* point imm to __bpf_call_base+1 from JITs point of view */
17068 if (bpf_pseudo_func(insn))
17069 /* jit (e.g. x86_64) may emit fewer instructions
17070 * if it learns a u32 imm is the same as a u64 imm.
17071 * Force a non zero here.
17076 err = bpf_prog_alloc_jited_linfo(prog);
17078 goto out_undo_insn;
17081 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17083 goto out_undo_insn;
17085 for (i = 0; i < env->subprog_cnt; i++) {
17086 subprog_start = subprog_end;
17087 subprog_end = env->subprog_info[i + 1].start;
17089 len = subprog_end - subprog_start;
17090 /* bpf_prog_run() doesn't call subprogs directly,
17091 * hence main prog stats include the runtime of subprogs.
17092 * subprogs don't have IDs and not reachable via prog_get_next_id
17093 * func[i]->stats will never be accessed and stays NULL
17095 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17098 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17099 len * sizeof(struct bpf_insn));
17100 func[i]->type = prog->type;
17101 func[i]->len = len;
17102 if (bpf_prog_calc_tag(func[i]))
17104 func[i]->is_func = 1;
17105 func[i]->aux->func_idx = i;
17106 /* Below members will be freed only at prog->aux */
17107 func[i]->aux->btf = prog->aux->btf;
17108 func[i]->aux->func_info = prog->aux->func_info;
17109 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17110 func[i]->aux->poke_tab = prog->aux->poke_tab;
17111 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17113 for (j = 0; j < prog->aux->size_poke_tab; j++) {
17114 struct bpf_jit_poke_descriptor *poke;
17116 poke = &prog->aux->poke_tab[j];
17117 if (poke->insn_idx < subprog_end &&
17118 poke->insn_idx >= subprog_start)
17119 poke->aux = func[i]->aux;
17122 func[i]->aux->name[0] = 'F';
17123 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17124 func[i]->jit_requested = 1;
17125 func[i]->blinding_requested = prog->blinding_requested;
17126 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17127 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17128 func[i]->aux->linfo = prog->aux->linfo;
17129 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17130 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17131 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17133 insn = func[i]->insnsi;
17134 for (j = 0; j < func[i]->len; j++, insn++) {
17135 if (BPF_CLASS(insn->code) == BPF_LDX &&
17136 BPF_MODE(insn->code) == BPF_PROBE_MEM)
17139 func[i]->aux->num_exentries = num_exentries;
17140 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17141 func[i] = bpf_int_jit_compile(func[i]);
17142 if (!func[i]->jited) {
17149 /* at this point all bpf functions were successfully JITed
17150 * now populate all bpf_calls with correct addresses and
17151 * run last pass of JIT
17153 for (i = 0; i < env->subprog_cnt; i++) {
17154 insn = func[i]->insnsi;
17155 for (j = 0; j < func[i]->len; j++, insn++) {
17156 if (bpf_pseudo_func(insn)) {
17157 subprog = insn->off;
17158 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17159 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17162 if (!bpf_pseudo_call(insn))
17164 subprog = insn->off;
17165 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
17168 /* we use the aux data to keep a list of the start addresses
17169 * of the JITed images for each function in the program
17171 * for some architectures, such as powerpc64, the imm field
17172 * might not be large enough to hold the offset of the start
17173 * address of the callee's JITed image from __bpf_call_base
17175 * in such cases, we can lookup the start address of a callee
17176 * by using its subprog id, available from the off field of
17177 * the call instruction, as an index for this list
17179 func[i]->aux->func = func;
17180 func[i]->aux->func_cnt = env->subprog_cnt;
17182 for (i = 0; i < env->subprog_cnt; i++) {
17183 old_bpf_func = func[i]->bpf_func;
17184 tmp = bpf_int_jit_compile(func[i]);
17185 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17186 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
17193 /* finally lock prog and jit images for all functions and
17194 * populate kallsysm
17196 for (i = 0; i < env->subprog_cnt; i++) {
17197 bpf_prog_lock_ro(func[i]);
17198 bpf_prog_kallsyms_add(func[i]);
17201 /* Last step: make now unused interpreter insns from main
17202 * prog consistent for later dump requests, so they can
17203 * later look the same as if they were interpreted only.
17205 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17206 if (bpf_pseudo_func(insn)) {
17207 insn[0].imm = env->insn_aux_data[i].call_imm;
17208 insn[1].imm = insn->off;
17212 if (!bpf_pseudo_call(insn))
17214 insn->off = env->insn_aux_data[i].call_imm;
17215 subprog = find_subprog(env, i + insn->off + 1);
17216 insn->imm = subprog;
17220 prog->bpf_func = func[0]->bpf_func;
17221 prog->jited_len = func[0]->jited_len;
17222 prog->aux->func = func;
17223 prog->aux->func_cnt = env->subprog_cnt;
17224 bpf_prog_jit_attempt_done(prog);
17227 /* We failed JIT'ing, so at this point we need to unregister poke
17228 * descriptors from subprogs, so that kernel is not attempting to
17229 * patch it anymore as we're freeing the subprog JIT memory.
17231 for (i = 0; i < prog->aux->size_poke_tab; i++) {
17232 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17233 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17235 /* At this point we're guaranteed that poke descriptors are not
17236 * live anymore. We can just unlink its descriptor table as it's
17237 * released with the main prog.
17239 for (i = 0; i < env->subprog_cnt; i++) {
17242 func[i]->aux->poke_tab = NULL;
17243 bpf_jit_free(func[i]);
17247 /* cleanup main prog to be interpreted */
17248 prog->jit_requested = 0;
17249 prog->blinding_requested = 0;
17250 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17251 if (!bpf_pseudo_call(insn))
17254 insn->imm = env->insn_aux_data[i].call_imm;
17256 bpf_prog_jit_attempt_done(prog);
17260 static int fixup_call_args(struct bpf_verifier_env *env)
17262 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17263 struct bpf_prog *prog = env->prog;
17264 struct bpf_insn *insn = prog->insnsi;
17265 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
17270 if (env->prog->jit_requested &&
17271 !bpf_prog_is_offloaded(env->prog->aux)) {
17272 err = jit_subprogs(env);
17275 if (err == -EFAULT)
17278 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17279 if (has_kfunc_call) {
17280 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
17283 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
17284 /* When JIT fails the progs with bpf2bpf calls and tail_calls
17285 * have to be rejected, since interpreter doesn't support them yet.
17287 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
17290 for (i = 0; i < prog->len; i++, insn++) {
17291 if (bpf_pseudo_func(insn)) {
17292 /* When JIT fails the progs with callback calls
17293 * have to be rejected, since interpreter doesn't support them yet.
17295 verbose(env, "callbacks are not allowed in non-JITed programs\n");
17299 if (!bpf_pseudo_call(insn))
17301 depth = get_callee_stack_depth(env, insn, i);
17304 bpf_patch_call_args(insn, depth);
17311 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
17312 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
17314 const struct bpf_kfunc_desc *desc;
17318 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
17324 if (bpf_dev_bound_kfunc_id(insn->imm)) {
17325 xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm);
17327 insn->imm = BPF_CALL_IMM(xdp_kfunc);
17331 /* fallback to default kfunc when not supported by netdev */
17334 /* insn->imm has the btf func_id. Replace it with
17335 * an address (relative to __bpf_call_base).
17337 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
17339 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
17344 insn->imm = desc->imm;
17347 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
17348 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17349 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17350 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
17352 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
17353 insn_buf[1] = addr[0];
17354 insn_buf[2] = addr[1];
17355 insn_buf[3] = *insn;
17357 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
17358 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17359 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17361 insn_buf[0] = addr[0];
17362 insn_buf[1] = addr[1];
17363 insn_buf[2] = *insn;
17365 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
17366 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
17367 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
17369 } else if (desc->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
17370 bool seen_direct_write = env->seen_direct_write;
17371 bool is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
17374 insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly);
17376 /* restore env->seen_direct_write to its original value, since
17377 * may_access_direct_pkt_data mutates it
17379 env->seen_direct_write = seen_direct_write;
17384 /* Do various post-verification rewrites in a single program pass.
17385 * These rewrites simplify JIT and interpreter implementations.
17387 static int do_misc_fixups(struct bpf_verifier_env *env)
17389 struct bpf_prog *prog = env->prog;
17390 enum bpf_attach_type eatype = prog->expected_attach_type;
17391 enum bpf_prog_type prog_type = resolve_prog_type(prog);
17392 struct bpf_insn *insn = prog->insnsi;
17393 const struct bpf_func_proto *fn;
17394 const int insn_cnt = prog->len;
17395 const struct bpf_map_ops *ops;
17396 struct bpf_insn_aux_data *aux;
17397 struct bpf_insn insn_buf[16];
17398 struct bpf_prog *new_prog;
17399 struct bpf_map *map_ptr;
17400 int i, ret, cnt, delta = 0;
17402 for (i = 0; i < insn_cnt; i++, insn++) {
17403 /* Make divide-by-zero exceptions impossible. */
17404 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
17405 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
17406 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
17407 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
17408 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
17409 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
17410 struct bpf_insn *patchlet;
17411 struct bpf_insn chk_and_div[] = {
17412 /* [R,W]x div 0 -> 0 */
17413 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17414 BPF_JNE | BPF_K, insn->src_reg,
17416 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
17417 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17420 struct bpf_insn chk_and_mod[] = {
17421 /* [R,W]x mod 0 -> [R,W]x */
17422 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17423 BPF_JEQ | BPF_K, insn->src_reg,
17424 0, 1 + (is64 ? 0 : 1), 0),
17426 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17427 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
17430 patchlet = isdiv ? chk_and_div : chk_and_mod;
17431 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
17432 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
17434 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
17439 env->prog = prog = new_prog;
17440 insn = new_prog->insnsi + i + delta;
17444 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
17445 if (BPF_CLASS(insn->code) == BPF_LD &&
17446 (BPF_MODE(insn->code) == BPF_ABS ||
17447 BPF_MODE(insn->code) == BPF_IND)) {
17448 cnt = env->ops->gen_ld_abs(insn, insn_buf);
17449 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
17450 verbose(env, "bpf verifier is misconfigured\n");
17454 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17459 env->prog = prog = new_prog;
17460 insn = new_prog->insnsi + i + delta;
17464 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
17465 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
17466 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
17467 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
17468 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
17469 struct bpf_insn *patch = &insn_buf[0];
17470 bool issrc, isneg, isimm;
17473 aux = &env->insn_aux_data[i + delta];
17474 if (!aux->alu_state ||
17475 aux->alu_state == BPF_ALU_NON_POINTER)
17478 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
17479 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
17480 BPF_ALU_SANITIZE_SRC;
17481 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
17483 off_reg = issrc ? insn->src_reg : insn->dst_reg;
17485 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17488 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17489 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17490 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
17491 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
17492 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
17493 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
17494 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
17497 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
17498 insn->src_reg = BPF_REG_AX;
17500 insn->code = insn->code == code_add ?
17501 code_sub : code_add;
17503 if (issrc && isneg && !isimm)
17504 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17505 cnt = patch - insn_buf;
17507 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17512 env->prog = prog = new_prog;
17513 insn = new_prog->insnsi + i + delta;
17517 if (insn->code != (BPF_JMP | BPF_CALL))
17519 if (insn->src_reg == BPF_PSEUDO_CALL)
17521 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17522 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
17528 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17533 env->prog = prog = new_prog;
17534 insn = new_prog->insnsi + i + delta;
17538 if (insn->imm == BPF_FUNC_get_route_realm)
17539 prog->dst_needed = 1;
17540 if (insn->imm == BPF_FUNC_get_prandom_u32)
17541 bpf_user_rnd_init_once();
17542 if (insn->imm == BPF_FUNC_override_return)
17543 prog->kprobe_override = 1;
17544 if (insn->imm == BPF_FUNC_tail_call) {
17545 /* If we tail call into other programs, we
17546 * cannot make any assumptions since they can
17547 * be replaced dynamically during runtime in
17548 * the program array.
17550 prog->cb_access = 1;
17551 if (!allow_tail_call_in_subprogs(env))
17552 prog->aux->stack_depth = MAX_BPF_STACK;
17553 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
17555 /* mark bpf_tail_call as different opcode to avoid
17556 * conditional branch in the interpreter for every normal
17557 * call and to prevent accidental JITing by JIT compiler
17558 * that doesn't support bpf_tail_call yet
17561 insn->code = BPF_JMP | BPF_TAIL_CALL;
17563 aux = &env->insn_aux_data[i + delta];
17564 if (env->bpf_capable && !prog->blinding_requested &&
17565 prog->jit_requested &&
17566 !bpf_map_key_poisoned(aux) &&
17567 !bpf_map_ptr_poisoned(aux) &&
17568 !bpf_map_ptr_unpriv(aux)) {
17569 struct bpf_jit_poke_descriptor desc = {
17570 .reason = BPF_POKE_REASON_TAIL_CALL,
17571 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
17572 .tail_call.key = bpf_map_key_immediate(aux),
17573 .insn_idx = i + delta,
17576 ret = bpf_jit_add_poke_descriptor(prog, &desc);
17578 verbose(env, "adding tail call poke descriptor failed\n");
17582 insn->imm = ret + 1;
17586 if (!bpf_map_ptr_unpriv(aux))
17589 /* instead of changing every JIT dealing with tail_call
17590 * emit two extra insns:
17591 * if (index >= max_entries) goto out;
17592 * index &= array->index_mask;
17593 * to avoid out-of-bounds cpu speculation
17595 if (bpf_map_ptr_poisoned(aux)) {
17596 verbose(env, "tail_call abusing map_ptr\n");
17600 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
17601 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
17602 map_ptr->max_entries, 2);
17603 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
17604 container_of(map_ptr,
17607 insn_buf[2] = *insn;
17609 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17614 env->prog = prog = new_prog;
17615 insn = new_prog->insnsi + i + delta;
17619 if (insn->imm == BPF_FUNC_timer_set_callback) {
17620 /* The verifier will process callback_fn as many times as necessary
17621 * with different maps and the register states prepared by
17622 * set_timer_callback_state will be accurate.
17624 * The following use case is valid:
17625 * map1 is shared by prog1, prog2, prog3.
17626 * prog1 calls bpf_timer_init for some map1 elements
17627 * prog2 calls bpf_timer_set_callback for some map1 elements.
17628 * Those that were not bpf_timer_init-ed will return -EINVAL.
17629 * prog3 calls bpf_timer_start for some map1 elements.
17630 * Those that were not both bpf_timer_init-ed and
17631 * bpf_timer_set_callback-ed will return -EINVAL.
17633 struct bpf_insn ld_addrs[2] = {
17634 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
17637 insn_buf[0] = ld_addrs[0];
17638 insn_buf[1] = ld_addrs[1];
17639 insn_buf[2] = *insn;
17642 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17647 env->prog = prog = new_prog;
17648 insn = new_prog->insnsi + i + delta;
17649 goto patch_call_imm;
17652 if (is_storage_get_function(insn->imm)) {
17653 if (!env->prog->aux->sleepable ||
17654 env->insn_aux_data[i + delta].storage_get_func_atomic)
17655 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
17657 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
17658 insn_buf[1] = *insn;
17661 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17666 env->prog = prog = new_prog;
17667 insn = new_prog->insnsi + i + delta;
17668 goto patch_call_imm;
17671 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
17672 * and other inlining handlers are currently limited to 64 bit
17675 if (prog->jit_requested && BITS_PER_LONG == 64 &&
17676 (insn->imm == BPF_FUNC_map_lookup_elem ||
17677 insn->imm == BPF_FUNC_map_update_elem ||
17678 insn->imm == BPF_FUNC_map_delete_elem ||
17679 insn->imm == BPF_FUNC_map_push_elem ||
17680 insn->imm == BPF_FUNC_map_pop_elem ||
17681 insn->imm == BPF_FUNC_map_peek_elem ||
17682 insn->imm == BPF_FUNC_redirect_map ||
17683 insn->imm == BPF_FUNC_for_each_map_elem ||
17684 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
17685 aux = &env->insn_aux_data[i + delta];
17686 if (bpf_map_ptr_poisoned(aux))
17687 goto patch_call_imm;
17689 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
17690 ops = map_ptr->ops;
17691 if (insn->imm == BPF_FUNC_map_lookup_elem &&
17692 ops->map_gen_lookup) {
17693 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
17694 if (cnt == -EOPNOTSUPP)
17695 goto patch_map_ops_generic;
17696 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
17697 verbose(env, "bpf verifier is misconfigured\n");
17701 new_prog = bpf_patch_insn_data(env, i + delta,
17707 env->prog = prog = new_prog;
17708 insn = new_prog->insnsi + i + delta;
17712 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
17713 (void *(*)(struct bpf_map *map, void *key))NULL));
17714 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
17715 (long (*)(struct bpf_map *map, void *key))NULL));
17716 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
17717 (long (*)(struct bpf_map *map, void *key, void *value,
17719 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
17720 (long (*)(struct bpf_map *map, void *value,
17722 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
17723 (long (*)(struct bpf_map *map, void *value))NULL));
17724 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
17725 (long (*)(struct bpf_map *map, void *value))NULL));
17726 BUILD_BUG_ON(!__same_type(ops->map_redirect,
17727 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
17728 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
17729 (long (*)(struct bpf_map *map,
17730 bpf_callback_t callback_fn,
17731 void *callback_ctx,
17733 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
17734 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
17736 patch_map_ops_generic:
17737 switch (insn->imm) {
17738 case BPF_FUNC_map_lookup_elem:
17739 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
17741 case BPF_FUNC_map_update_elem:
17742 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
17744 case BPF_FUNC_map_delete_elem:
17745 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
17747 case BPF_FUNC_map_push_elem:
17748 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
17750 case BPF_FUNC_map_pop_elem:
17751 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
17753 case BPF_FUNC_map_peek_elem:
17754 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
17756 case BPF_FUNC_redirect_map:
17757 insn->imm = BPF_CALL_IMM(ops->map_redirect);
17759 case BPF_FUNC_for_each_map_elem:
17760 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
17762 case BPF_FUNC_map_lookup_percpu_elem:
17763 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
17767 goto patch_call_imm;
17770 /* Implement bpf_jiffies64 inline. */
17771 if (prog->jit_requested && BITS_PER_LONG == 64 &&
17772 insn->imm == BPF_FUNC_jiffies64) {
17773 struct bpf_insn ld_jiffies_addr[2] = {
17774 BPF_LD_IMM64(BPF_REG_0,
17775 (unsigned long)&jiffies),
17778 insn_buf[0] = ld_jiffies_addr[0];
17779 insn_buf[1] = ld_jiffies_addr[1];
17780 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
17784 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
17790 env->prog = prog = new_prog;
17791 insn = new_prog->insnsi + i + delta;
17795 /* Implement bpf_get_func_arg inline. */
17796 if (prog_type == BPF_PROG_TYPE_TRACING &&
17797 insn->imm == BPF_FUNC_get_func_arg) {
17798 /* Load nr_args from ctx - 8 */
17799 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17800 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
17801 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
17802 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
17803 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
17804 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17805 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
17806 insn_buf[7] = BPF_JMP_A(1);
17807 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
17810 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17815 env->prog = prog = new_prog;
17816 insn = new_prog->insnsi + i + delta;
17820 /* Implement bpf_get_func_ret inline. */
17821 if (prog_type == BPF_PROG_TYPE_TRACING &&
17822 insn->imm == BPF_FUNC_get_func_ret) {
17823 if (eatype == BPF_TRACE_FEXIT ||
17824 eatype == BPF_MODIFY_RETURN) {
17825 /* Load nr_args from ctx - 8 */
17826 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17827 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
17828 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
17829 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17830 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
17831 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
17834 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
17838 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17843 env->prog = prog = new_prog;
17844 insn = new_prog->insnsi + i + delta;
17848 /* Implement get_func_arg_cnt inline. */
17849 if (prog_type == BPF_PROG_TYPE_TRACING &&
17850 insn->imm == BPF_FUNC_get_func_arg_cnt) {
17851 /* Load nr_args from ctx - 8 */
17852 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17854 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17858 env->prog = prog = new_prog;
17859 insn = new_prog->insnsi + i + delta;
17863 /* Implement bpf_get_func_ip inline. */
17864 if (prog_type == BPF_PROG_TYPE_TRACING &&
17865 insn->imm == BPF_FUNC_get_func_ip) {
17866 /* Load IP address from ctx - 16 */
17867 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
17869 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17873 env->prog = prog = new_prog;
17874 insn = new_prog->insnsi + i + delta;
17879 fn = env->ops->get_func_proto(insn->imm, env->prog);
17880 /* all functions that have prototype and verifier allowed
17881 * programs to call them, must be real in-kernel functions
17885 "kernel subsystem misconfigured func %s#%d\n",
17886 func_id_name(insn->imm), insn->imm);
17889 insn->imm = fn->func - __bpf_call_base;
17892 /* Since poke tab is now finalized, publish aux to tracker. */
17893 for (i = 0; i < prog->aux->size_poke_tab; i++) {
17894 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17895 if (!map_ptr->ops->map_poke_track ||
17896 !map_ptr->ops->map_poke_untrack ||
17897 !map_ptr->ops->map_poke_run) {
17898 verbose(env, "bpf verifier is misconfigured\n");
17902 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
17904 verbose(env, "tracking tail call prog failed\n");
17909 sort_kfunc_descs_by_imm(env->prog);
17914 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
17917 u32 callback_subprogno,
17920 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
17921 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
17922 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
17923 int reg_loop_max = BPF_REG_6;
17924 int reg_loop_cnt = BPF_REG_7;
17925 int reg_loop_ctx = BPF_REG_8;
17927 struct bpf_prog *new_prog;
17928 u32 callback_start;
17929 u32 call_insn_offset;
17930 s32 callback_offset;
17932 /* This represents an inlined version of bpf_iter.c:bpf_loop,
17933 * be careful to modify this code in sync.
17935 struct bpf_insn insn_buf[] = {
17936 /* Return error and jump to the end of the patch if
17937 * expected number of iterations is too big.
17939 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
17940 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
17941 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
17942 /* spill R6, R7, R8 to use these as loop vars */
17943 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
17944 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
17945 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
17946 /* initialize loop vars */
17947 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
17948 BPF_MOV32_IMM(reg_loop_cnt, 0),
17949 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
17951 * if reg_loop_cnt >= reg_loop_max skip the loop body
17953 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
17955 * correct callback offset would be set after patching
17957 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
17958 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
17960 /* increment loop counter */
17961 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
17962 /* jump to loop header if callback returned 0 */
17963 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
17964 /* return value of bpf_loop,
17965 * set R0 to the number of iterations
17967 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
17968 /* restore original values of R6, R7, R8 */
17969 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
17970 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
17971 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
17974 *cnt = ARRAY_SIZE(insn_buf);
17975 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
17979 /* callback start is known only after patching */
17980 callback_start = env->subprog_info[callback_subprogno].start;
17981 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
17982 call_insn_offset = position + 12;
17983 callback_offset = callback_start - call_insn_offset - 1;
17984 new_prog->insnsi[call_insn_offset].imm = callback_offset;
17989 static bool is_bpf_loop_call(struct bpf_insn *insn)
17991 return insn->code == (BPF_JMP | BPF_CALL) &&
17992 insn->src_reg == 0 &&
17993 insn->imm == BPF_FUNC_loop;
17996 /* For all sub-programs in the program (including main) check
17997 * insn_aux_data to see if there are bpf_loop calls that require
17998 * inlining. If such calls are found the calls are replaced with a
17999 * sequence of instructions produced by `inline_bpf_loop` function and
18000 * subprog stack_depth is increased by the size of 3 registers.
18001 * This stack space is used to spill values of the R6, R7, R8. These
18002 * registers are used to store the loop bound, counter and context
18005 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18007 struct bpf_subprog_info *subprogs = env->subprog_info;
18008 int i, cur_subprog = 0, cnt, delta = 0;
18009 struct bpf_insn *insn = env->prog->insnsi;
18010 int insn_cnt = env->prog->len;
18011 u16 stack_depth = subprogs[cur_subprog].stack_depth;
18012 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18013 u16 stack_depth_extra = 0;
18015 for (i = 0; i < insn_cnt; i++, insn++) {
18016 struct bpf_loop_inline_state *inline_state =
18017 &env->insn_aux_data[i + delta].loop_inline_state;
18019 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18020 struct bpf_prog *new_prog;
18022 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18023 new_prog = inline_bpf_loop(env,
18025 -(stack_depth + stack_depth_extra),
18026 inline_state->callback_subprogno,
18032 env->prog = new_prog;
18033 insn = new_prog->insnsi + i + delta;
18036 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18037 subprogs[cur_subprog].stack_depth += stack_depth_extra;
18039 stack_depth = subprogs[cur_subprog].stack_depth;
18040 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18041 stack_depth_extra = 0;
18045 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18050 static void free_states(struct bpf_verifier_env *env)
18052 struct bpf_verifier_state_list *sl, *sln;
18055 sl = env->free_list;
18058 free_verifier_state(&sl->state, false);
18062 env->free_list = NULL;
18064 if (!env->explored_states)
18067 for (i = 0; i < state_htab_size(env); i++) {
18068 sl = env->explored_states[i];
18072 free_verifier_state(&sl->state, false);
18076 env->explored_states[i] = NULL;
18080 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18082 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18083 struct bpf_verifier_state *state;
18084 struct bpf_reg_state *regs;
18087 env->prev_linfo = NULL;
18090 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18093 state->curframe = 0;
18094 state->speculative = false;
18095 state->branches = 1;
18096 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18097 if (!state->frame[0]) {
18101 env->cur_state = state;
18102 init_func_state(env, state->frame[0],
18103 BPF_MAIN_FUNC /* callsite */,
18106 state->first_insn_idx = env->subprog_info[subprog].start;
18107 state->last_insn_idx = -1;
18109 regs = state->frame[state->curframe]->regs;
18110 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18111 ret = btf_prepare_func_args(env, subprog, regs);
18114 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18115 if (regs[i].type == PTR_TO_CTX)
18116 mark_reg_known_zero(env, regs, i);
18117 else if (regs[i].type == SCALAR_VALUE)
18118 mark_reg_unknown(env, regs, i);
18119 else if (base_type(regs[i].type) == PTR_TO_MEM) {
18120 const u32 mem_size = regs[i].mem_size;
18122 mark_reg_known_zero(env, regs, i);
18123 regs[i].mem_size = mem_size;
18124 regs[i].id = ++env->id_gen;
18128 /* 1st arg to a function */
18129 regs[BPF_REG_1].type = PTR_TO_CTX;
18130 mark_reg_known_zero(env, regs, BPF_REG_1);
18131 ret = btf_check_subprog_arg_match(env, subprog, regs);
18132 if (ret == -EFAULT)
18133 /* unlikely verifier bug. abort.
18134 * ret == 0 and ret < 0 are sadly acceptable for
18135 * main() function due to backward compatibility.
18136 * Like socket filter program may be written as:
18137 * int bpf_prog(struct pt_regs *ctx)
18138 * and never dereference that ctx in the program.
18139 * 'struct pt_regs' is a type mismatch for socket
18140 * filter that should be using 'struct __sk_buff'.
18145 ret = do_check(env);
18147 /* check for NULL is necessary, since cur_state can be freed inside
18148 * do_check() under memory pressure.
18150 if (env->cur_state) {
18151 free_verifier_state(env->cur_state, true);
18152 env->cur_state = NULL;
18154 while (!pop_stack(env, NULL, NULL, false));
18155 if (!ret && pop_log)
18156 bpf_vlog_reset(&env->log, 0);
18161 /* Verify all global functions in a BPF program one by one based on their BTF.
18162 * All global functions must pass verification. Otherwise the whole program is rejected.
18173 * foo() will be verified first for R1=any_scalar_value. During verification it
18174 * will be assumed that bar() already verified successfully and call to bar()
18175 * from foo() will be checked for type match only. Later bar() will be verified
18176 * independently to check that it's safe for R1=any_scalar_value.
18178 static int do_check_subprogs(struct bpf_verifier_env *env)
18180 struct bpf_prog_aux *aux = env->prog->aux;
18183 if (!aux->func_info)
18186 for (i = 1; i < env->subprog_cnt; i++) {
18187 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18189 env->insn_idx = env->subprog_info[i].start;
18190 WARN_ON_ONCE(env->insn_idx == 0);
18191 ret = do_check_common(env, i);
18194 } else if (env->log.level & BPF_LOG_LEVEL) {
18196 "Func#%d is safe for any args that match its prototype\n",
18203 static int do_check_main(struct bpf_verifier_env *env)
18208 ret = do_check_common(env, 0);
18210 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18215 static void print_verification_stats(struct bpf_verifier_env *env)
18219 if (env->log.level & BPF_LOG_STATS) {
18220 verbose(env, "verification time %lld usec\n",
18221 div_u64(env->verification_time, 1000));
18222 verbose(env, "stack depth ");
18223 for (i = 0; i < env->subprog_cnt; i++) {
18224 u32 depth = env->subprog_info[i].stack_depth;
18226 verbose(env, "%d", depth);
18227 if (i + 1 < env->subprog_cnt)
18230 verbose(env, "\n");
18232 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18233 "total_states %d peak_states %d mark_read %d\n",
18234 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18235 env->max_states_per_insn, env->total_states,
18236 env->peak_states, env->longest_mark_read_walk);
18239 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18241 const struct btf_type *t, *func_proto;
18242 const struct bpf_struct_ops *st_ops;
18243 const struct btf_member *member;
18244 struct bpf_prog *prog = env->prog;
18245 u32 btf_id, member_idx;
18248 if (!prog->gpl_compatible) {
18249 verbose(env, "struct ops programs must have a GPL compatible license\n");
18253 btf_id = prog->aux->attach_btf_id;
18254 st_ops = bpf_struct_ops_find(btf_id);
18256 verbose(env, "attach_btf_id %u is not a supported struct\n",
18262 member_idx = prog->expected_attach_type;
18263 if (member_idx >= btf_type_vlen(t)) {
18264 verbose(env, "attach to invalid member idx %u of struct %s\n",
18265 member_idx, st_ops->name);
18269 member = &btf_type_member(t)[member_idx];
18270 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
18271 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
18274 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18275 mname, member_idx, st_ops->name);
18279 if (st_ops->check_member) {
18280 int err = st_ops->check_member(t, member, prog);
18283 verbose(env, "attach to unsupported member %s of struct %s\n",
18284 mname, st_ops->name);
18289 prog->aux->attach_func_proto = func_proto;
18290 prog->aux->attach_func_name = mname;
18291 env->ops = st_ops->verifier_ops;
18295 #define SECURITY_PREFIX "security_"
18297 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18299 if (within_error_injection_list(addr) ||
18300 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18306 /* list of non-sleepable functions that are otherwise on
18307 * ALLOW_ERROR_INJECTION list
18309 BTF_SET_START(btf_non_sleepable_error_inject)
18310 /* Three functions below can be called from sleepable and non-sleepable context.
18311 * Assume non-sleepable from bpf safety point of view.
18313 BTF_ID(func, __filemap_add_folio)
18314 BTF_ID(func, should_fail_alloc_page)
18315 BTF_ID(func, should_failslab)
18316 BTF_SET_END(btf_non_sleepable_error_inject)
18318 static int check_non_sleepable_error_inject(u32 btf_id)
18320 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18323 int bpf_check_attach_target(struct bpf_verifier_log *log,
18324 const struct bpf_prog *prog,
18325 const struct bpf_prog *tgt_prog,
18327 struct bpf_attach_target_info *tgt_info)
18329 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
18330 const char prefix[] = "btf_trace_";
18331 int ret = 0, subprog = -1, i;
18332 const struct btf_type *t;
18333 bool conservative = true;
18337 struct module *mod = NULL;
18340 bpf_log(log, "Tracing programs must provide btf_id\n");
18343 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
18346 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
18349 t = btf_type_by_id(btf, btf_id);
18351 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
18354 tname = btf_name_by_offset(btf, t->name_off);
18356 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
18360 struct bpf_prog_aux *aux = tgt_prog->aux;
18362 if (bpf_prog_is_dev_bound(prog->aux) &&
18363 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
18364 bpf_log(log, "Target program bound device mismatch");
18368 for (i = 0; i < aux->func_info_cnt; i++)
18369 if (aux->func_info[i].type_id == btf_id) {
18373 if (subprog == -1) {
18374 bpf_log(log, "Subprog %s doesn't exist\n", tname);
18377 conservative = aux->func_info_aux[subprog].unreliable;
18378 if (prog_extension) {
18379 if (conservative) {
18381 "Cannot replace static functions\n");
18384 if (!prog->jit_requested) {
18386 "Extension programs should be JITed\n");
18390 if (!tgt_prog->jited) {
18391 bpf_log(log, "Can attach to only JITed progs\n");
18394 if (tgt_prog->type == prog->type) {
18395 /* Cannot fentry/fexit another fentry/fexit program.
18396 * Cannot attach program extension to another extension.
18397 * It's ok to attach fentry/fexit to extension program.
18399 bpf_log(log, "Cannot recursively attach\n");
18402 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
18404 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
18405 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
18406 /* Program extensions can extend all program types
18407 * except fentry/fexit. The reason is the following.
18408 * The fentry/fexit programs are used for performance
18409 * analysis, stats and can be attached to any program
18410 * type except themselves. When extension program is
18411 * replacing XDP function it is necessary to allow
18412 * performance analysis of all functions. Both original
18413 * XDP program and its program extension. Hence
18414 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
18415 * allowed. If extending of fentry/fexit was allowed it
18416 * would be possible to create long call chain
18417 * fentry->extension->fentry->extension beyond
18418 * reasonable stack size. Hence extending fentry is not
18421 bpf_log(log, "Cannot extend fentry/fexit\n");
18425 if (prog_extension) {
18426 bpf_log(log, "Cannot replace kernel functions\n");
18431 switch (prog->expected_attach_type) {
18432 case BPF_TRACE_RAW_TP:
18435 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
18438 if (!btf_type_is_typedef(t)) {
18439 bpf_log(log, "attach_btf_id %u is not a typedef\n",
18443 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
18444 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
18448 tname += sizeof(prefix) - 1;
18449 t = btf_type_by_id(btf, t->type);
18450 if (!btf_type_is_ptr(t))
18451 /* should never happen in valid vmlinux build */
18453 t = btf_type_by_id(btf, t->type);
18454 if (!btf_type_is_func_proto(t))
18455 /* should never happen in valid vmlinux build */
18459 case BPF_TRACE_ITER:
18460 if (!btf_type_is_func(t)) {
18461 bpf_log(log, "attach_btf_id %u is not a function\n",
18465 t = btf_type_by_id(btf, t->type);
18466 if (!btf_type_is_func_proto(t))
18468 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
18473 if (!prog_extension)
18476 case BPF_MODIFY_RETURN:
18478 case BPF_LSM_CGROUP:
18479 case BPF_TRACE_FENTRY:
18480 case BPF_TRACE_FEXIT:
18481 if (!btf_type_is_func(t)) {
18482 bpf_log(log, "attach_btf_id %u is not a function\n",
18486 if (prog_extension &&
18487 btf_check_type_match(log, prog, btf, t))
18489 t = btf_type_by_id(btf, t->type);
18490 if (!btf_type_is_func_proto(t))
18493 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
18494 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
18495 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
18498 if (tgt_prog && conservative)
18501 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
18507 addr = (long) tgt_prog->bpf_func;
18509 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
18511 if (btf_is_module(btf)) {
18512 mod = btf_try_get_module(btf);
18514 addr = find_kallsyms_symbol_value(mod, tname);
18518 addr = kallsyms_lookup_name(tname);
18523 "The address of function %s cannot be found\n",
18529 if (prog->aux->sleepable) {
18531 switch (prog->type) {
18532 case BPF_PROG_TYPE_TRACING:
18534 /* fentry/fexit/fmod_ret progs can be sleepable if they are
18535 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
18537 if (!check_non_sleepable_error_inject(btf_id) &&
18538 within_error_injection_list(addr))
18540 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
18541 * in the fmodret id set with the KF_SLEEPABLE flag.
18544 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
18546 if (flags && (*flags & KF_SLEEPABLE))
18550 case BPF_PROG_TYPE_LSM:
18551 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
18552 * Only some of them are sleepable.
18554 if (bpf_lsm_is_sleepable_hook(btf_id))
18562 bpf_log(log, "%s is not sleepable\n", tname);
18565 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
18568 bpf_log(log, "can't modify return codes of BPF programs\n");
18572 if (btf_kfunc_is_modify_return(btf, btf_id) ||
18573 !check_attach_modify_return(addr, tname))
18577 bpf_log(log, "%s() is not modifiable\n", tname);
18584 tgt_info->tgt_addr = addr;
18585 tgt_info->tgt_name = tname;
18586 tgt_info->tgt_type = t;
18587 tgt_info->tgt_mod = mod;
18591 BTF_SET_START(btf_id_deny)
18594 BTF_ID(func, migrate_disable)
18595 BTF_ID(func, migrate_enable)
18597 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
18598 BTF_ID(func, rcu_read_unlock_strict)
18600 BTF_SET_END(btf_id_deny)
18602 static bool can_be_sleepable(struct bpf_prog *prog)
18604 if (prog->type == BPF_PROG_TYPE_TRACING) {
18605 switch (prog->expected_attach_type) {
18606 case BPF_TRACE_FENTRY:
18607 case BPF_TRACE_FEXIT:
18608 case BPF_MODIFY_RETURN:
18609 case BPF_TRACE_ITER:
18615 return prog->type == BPF_PROG_TYPE_LSM ||
18616 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
18617 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
18620 static int check_attach_btf_id(struct bpf_verifier_env *env)
18622 struct bpf_prog *prog = env->prog;
18623 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
18624 struct bpf_attach_target_info tgt_info = {};
18625 u32 btf_id = prog->aux->attach_btf_id;
18626 struct bpf_trampoline *tr;
18630 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
18631 if (prog->aux->sleepable)
18632 /* attach_btf_id checked to be zero already */
18634 verbose(env, "Syscall programs can only be sleepable\n");
18638 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
18639 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
18643 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
18644 return check_struct_ops_btf_id(env);
18646 if (prog->type != BPF_PROG_TYPE_TRACING &&
18647 prog->type != BPF_PROG_TYPE_LSM &&
18648 prog->type != BPF_PROG_TYPE_EXT)
18651 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
18655 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
18656 /* to make freplace equivalent to their targets, they need to
18657 * inherit env->ops and expected_attach_type for the rest of the
18660 env->ops = bpf_verifier_ops[tgt_prog->type];
18661 prog->expected_attach_type = tgt_prog->expected_attach_type;
18664 /* store info about the attachment target that will be used later */
18665 prog->aux->attach_func_proto = tgt_info.tgt_type;
18666 prog->aux->attach_func_name = tgt_info.tgt_name;
18667 prog->aux->mod = tgt_info.tgt_mod;
18670 prog->aux->saved_dst_prog_type = tgt_prog->type;
18671 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
18674 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
18675 prog->aux->attach_btf_trace = true;
18677 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
18678 if (!bpf_iter_prog_supported(prog))
18683 if (prog->type == BPF_PROG_TYPE_LSM) {
18684 ret = bpf_lsm_verify_prog(&env->log, prog);
18687 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
18688 btf_id_set_contains(&btf_id_deny, btf_id)) {
18692 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
18693 tr = bpf_trampoline_get(key, &tgt_info);
18697 prog->aux->dst_trampoline = tr;
18701 struct btf *bpf_get_btf_vmlinux(void)
18703 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
18704 mutex_lock(&bpf_verifier_lock);
18706 btf_vmlinux = btf_parse_vmlinux();
18707 mutex_unlock(&bpf_verifier_lock);
18709 return btf_vmlinux;
18712 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
18714 u64 start_time = ktime_get_ns();
18715 struct bpf_verifier_env *env;
18716 int i, len, ret = -EINVAL, err;
18720 /* no program is valid */
18721 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
18724 /* 'struct bpf_verifier_env' can be global, but since it's not small,
18725 * allocate/free it every time bpf_check() is called
18727 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
18731 len = (*prog)->len;
18732 env->insn_aux_data =
18733 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
18735 if (!env->insn_aux_data)
18737 for (i = 0; i < len; i++)
18738 env->insn_aux_data[i].orig_idx = i;
18740 env->ops = bpf_verifier_ops[env->prog->type];
18741 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
18742 is_priv = bpf_capable();
18744 bpf_get_btf_vmlinux();
18746 /* grab the mutex to protect few globals used by verifier */
18748 mutex_lock(&bpf_verifier_lock);
18750 /* user could have requested verbose verifier output
18751 * and supplied buffer to store the verification trace
18753 ret = bpf_vlog_init(&env->log, attr->log_level,
18754 (char __user *) (unsigned long) attr->log_buf,
18759 mark_verifier_state_clean(env);
18761 if (IS_ERR(btf_vmlinux)) {
18762 /* Either gcc or pahole or kernel are broken. */
18763 verbose(env, "in-kernel BTF is malformed\n");
18764 ret = PTR_ERR(btf_vmlinux);
18765 goto skip_full_check;
18768 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
18769 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
18770 env->strict_alignment = true;
18771 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
18772 env->strict_alignment = false;
18774 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
18775 env->allow_uninit_stack = bpf_allow_uninit_stack();
18776 env->bypass_spec_v1 = bpf_bypass_spec_v1();
18777 env->bypass_spec_v4 = bpf_bypass_spec_v4();
18778 env->bpf_capable = bpf_capable();
18781 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
18783 env->explored_states = kvcalloc(state_htab_size(env),
18784 sizeof(struct bpf_verifier_state_list *),
18787 if (!env->explored_states)
18788 goto skip_full_check;
18790 ret = add_subprog_and_kfunc(env);
18792 goto skip_full_check;
18794 ret = check_subprogs(env);
18796 goto skip_full_check;
18798 ret = check_btf_info(env, attr, uattr);
18800 goto skip_full_check;
18802 ret = check_attach_btf_id(env);
18804 goto skip_full_check;
18806 ret = resolve_pseudo_ldimm64(env);
18808 goto skip_full_check;
18810 if (bpf_prog_is_offloaded(env->prog->aux)) {
18811 ret = bpf_prog_offload_verifier_prep(env->prog);
18813 goto skip_full_check;
18816 ret = check_cfg(env);
18818 goto skip_full_check;
18820 ret = do_check_subprogs(env);
18821 ret = ret ?: do_check_main(env);
18823 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
18824 ret = bpf_prog_offload_finalize(env);
18827 kvfree(env->explored_states);
18830 ret = check_max_stack_depth(env);
18832 /* instruction rewrites happen after this point */
18834 ret = optimize_bpf_loop(env);
18838 opt_hard_wire_dead_code_branches(env);
18840 ret = opt_remove_dead_code(env);
18842 ret = opt_remove_nops(env);
18845 sanitize_dead_code(env);
18849 /* program is valid, convert *(u32*)(ctx + off) accesses */
18850 ret = convert_ctx_accesses(env);
18853 ret = do_misc_fixups(env);
18855 /* do 32-bit optimization after insn patching has done so those patched
18856 * insns could be handled correctly.
18858 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
18859 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
18860 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
18865 ret = fixup_call_args(env);
18867 env->verification_time = ktime_get_ns() - start_time;
18868 print_verification_stats(env);
18869 env->prog->aux->verified_insns = env->insn_processed;
18871 /* preserve original error even if log finalization is successful */
18872 err = bpf_vlog_finalize(&env->log, &log_true_size);
18876 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
18877 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
18878 &log_true_size, sizeof(log_true_size))) {
18880 goto err_release_maps;
18884 goto err_release_maps;
18886 if (env->used_map_cnt) {
18887 /* if program passed verifier, update used_maps in bpf_prog_info */
18888 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
18889 sizeof(env->used_maps[0]),
18892 if (!env->prog->aux->used_maps) {
18894 goto err_release_maps;
18897 memcpy(env->prog->aux->used_maps, env->used_maps,
18898 sizeof(env->used_maps[0]) * env->used_map_cnt);
18899 env->prog->aux->used_map_cnt = env->used_map_cnt;
18901 if (env->used_btf_cnt) {
18902 /* if program passed verifier, update used_btfs in bpf_prog_aux */
18903 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
18904 sizeof(env->used_btfs[0]),
18906 if (!env->prog->aux->used_btfs) {
18908 goto err_release_maps;
18911 memcpy(env->prog->aux->used_btfs, env->used_btfs,
18912 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
18913 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
18915 if (env->used_map_cnt || env->used_btf_cnt) {
18916 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
18917 * bpf_ld_imm64 instructions
18919 convert_pseudo_ld_imm64(env);
18922 adjust_btf_func(env);
18925 if (!env->prog->aux->used_maps)
18926 /* if we didn't copy map pointers into bpf_prog_info, release
18927 * them now. Otherwise free_used_maps() will release them.
18930 if (!env->prog->aux->used_btfs)
18933 /* extension progs temporarily inherit the attach_type of their targets
18934 for verification purposes, so set it back to zero before returning
18936 if (env->prog->type == BPF_PROG_TYPE_EXT)
18937 env->prog->expected_attach_type = 0;
18942 mutex_unlock(&bpf_verifier_lock);
18943 vfree(env->insn_aux_data);