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 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
343 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
345 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
346 "verifier log line truncated - local buffer too short\n");
348 if (log->level == BPF_LOG_KERNEL) {
349 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
351 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
355 n = min(log->len_total - log->len_used - 1, n);
357 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
363 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
367 if (!bpf_verifier_log_needed(log))
370 log->len_used = new_pos;
371 if (put_user(zero, log->ubuf + new_pos))
375 /* log_level controls verbosity level of eBPF verifier.
376 * bpf_verifier_log_write() is used to dump the verification trace to the log,
377 * so the user can figure out what's wrong with the program
379 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
380 const char *fmt, ...)
384 if (!bpf_verifier_log_needed(&env->log))
388 bpf_verifier_vlog(&env->log, fmt, args);
391 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
393 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
395 struct bpf_verifier_env *env = private_data;
398 if (!bpf_verifier_log_needed(&env->log))
402 bpf_verifier_vlog(&env->log, fmt, args);
406 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
407 const char *fmt, ...)
411 if (!bpf_verifier_log_needed(log))
415 bpf_verifier_vlog(log, fmt, args);
418 EXPORT_SYMBOL_GPL(bpf_log);
420 static const char *ltrim(const char *s)
428 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
430 const char *prefix_fmt, ...)
432 const struct bpf_line_info *linfo;
434 if (!bpf_verifier_log_needed(&env->log))
437 linfo = find_linfo(env, insn_off);
438 if (!linfo || linfo == env->prev_linfo)
444 va_start(args, prefix_fmt);
445 bpf_verifier_vlog(&env->log, prefix_fmt, args);
450 ltrim(btf_name_by_offset(env->prog->aux->btf,
453 env->prev_linfo = linfo;
456 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
457 struct bpf_reg_state *reg,
458 struct tnum *range, const char *ctx,
459 const char *reg_name)
463 verbose(env, "At %s the register %s ", ctx, reg_name);
464 if (!tnum_is_unknown(reg->var_off)) {
465 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
466 verbose(env, "has value %s", tn_buf);
468 verbose(env, "has unknown scalar value");
470 tnum_strn(tn_buf, sizeof(tn_buf), *range);
471 verbose(env, " should have been in %s\n", tn_buf);
474 static bool type_is_pkt_pointer(enum bpf_reg_type type)
476 type = base_type(type);
477 return type == PTR_TO_PACKET ||
478 type == PTR_TO_PACKET_META;
481 static bool type_is_sk_pointer(enum bpf_reg_type type)
483 return type == PTR_TO_SOCKET ||
484 type == PTR_TO_SOCK_COMMON ||
485 type == PTR_TO_TCP_SOCK ||
486 type == PTR_TO_XDP_SOCK;
489 static bool type_may_be_null(u32 type)
491 return type & PTR_MAYBE_NULL;
494 static bool reg_type_not_null(enum bpf_reg_type type)
496 if (type_may_be_null(type))
499 type = base_type(type);
500 return type == PTR_TO_SOCKET ||
501 type == PTR_TO_TCP_SOCK ||
502 type == PTR_TO_MAP_VALUE ||
503 type == PTR_TO_MAP_KEY ||
504 type == PTR_TO_SOCK_COMMON ||
508 static bool type_is_ptr_alloc_obj(u32 type)
510 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
513 static bool type_is_non_owning_ref(u32 type)
515 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
518 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
520 struct btf_record *rec = NULL;
521 struct btf_struct_meta *meta;
523 if (reg->type == PTR_TO_MAP_VALUE) {
524 rec = reg->map_ptr->record;
525 } else if (type_is_ptr_alloc_obj(reg->type)) {
526 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
533 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
535 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
538 static bool type_is_rdonly_mem(u32 type)
540 return type & MEM_RDONLY;
543 static bool is_acquire_function(enum bpf_func_id func_id,
544 const struct bpf_map *map)
546 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
548 if (func_id == BPF_FUNC_sk_lookup_tcp ||
549 func_id == BPF_FUNC_sk_lookup_udp ||
550 func_id == BPF_FUNC_skc_lookup_tcp ||
551 func_id == BPF_FUNC_ringbuf_reserve ||
552 func_id == BPF_FUNC_kptr_xchg)
555 if (func_id == BPF_FUNC_map_lookup_elem &&
556 (map_type == BPF_MAP_TYPE_SOCKMAP ||
557 map_type == BPF_MAP_TYPE_SOCKHASH))
563 static bool is_ptr_cast_function(enum bpf_func_id func_id)
565 return func_id == BPF_FUNC_tcp_sock ||
566 func_id == BPF_FUNC_sk_fullsock ||
567 func_id == BPF_FUNC_skc_to_tcp_sock ||
568 func_id == BPF_FUNC_skc_to_tcp6_sock ||
569 func_id == BPF_FUNC_skc_to_udp6_sock ||
570 func_id == BPF_FUNC_skc_to_mptcp_sock ||
571 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
572 func_id == BPF_FUNC_skc_to_tcp_request_sock;
575 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
577 return func_id == BPF_FUNC_dynptr_data;
580 static bool is_callback_calling_function(enum bpf_func_id func_id)
582 return func_id == BPF_FUNC_for_each_map_elem ||
583 func_id == BPF_FUNC_timer_set_callback ||
584 func_id == BPF_FUNC_find_vma ||
585 func_id == BPF_FUNC_loop ||
586 func_id == BPF_FUNC_user_ringbuf_drain;
589 static bool is_storage_get_function(enum bpf_func_id func_id)
591 return func_id == BPF_FUNC_sk_storage_get ||
592 func_id == BPF_FUNC_inode_storage_get ||
593 func_id == BPF_FUNC_task_storage_get ||
594 func_id == BPF_FUNC_cgrp_storage_get;
597 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
598 const struct bpf_map *map)
600 int ref_obj_uses = 0;
602 if (is_ptr_cast_function(func_id))
604 if (is_acquire_function(func_id, map))
606 if (is_dynptr_ref_function(func_id))
609 return ref_obj_uses > 1;
612 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
614 return BPF_CLASS(insn->code) == BPF_STX &&
615 BPF_MODE(insn->code) == BPF_ATOMIC &&
616 insn->imm == BPF_CMPXCHG;
619 /* string representation of 'enum bpf_reg_type'
621 * Note that reg_type_str() can not appear more than once in a single verbose()
624 static const char *reg_type_str(struct bpf_verifier_env *env,
625 enum bpf_reg_type type)
627 char postfix[16] = {0}, prefix[64] = {0};
628 static const char * const str[] = {
630 [SCALAR_VALUE] = "scalar",
631 [PTR_TO_CTX] = "ctx",
632 [CONST_PTR_TO_MAP] = "map_ptr",
633 [PTR_TO_MAP_VALUE] = "map_value",
634 [PTR_TO_STACK] = "fp",
635 [PTR_TO_PACKET] = "pkt",
636 [PTR_TO_PACKET_META] = "pkt_meta",
637 [PTR_TO_PACKET_END] = "pkt_end",
638 [PTR_TO_FLOW_KEYS] = "flow_keys",
639 [PTR_TO_SOCKET] = "sock",
640 [PTR_TO_SOCK_COMMON] = "sock_common",
641 [PTR_TO_TCP_SOCK] = "tcp_sock",
642 [PTR_TO_TP_BUFFER] = "tp_buffer",
643 [PTR_TO_XDP_SOCK] = "xdp_sock",
644 [PTR_TO_BTF_ID] = "ptr_",
645 [PTR_TO_MEM] = "mem",
646 [PTR_TO_BUF] = "buf",
647 [PTR_TO_FUNC] = "func",
648 [PTR_TO_MAP_KEY] = "map_key",
649 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr",
652 if (type & PTR_MAYBE_NULL) {
653 if (base_type(type) == PTR_TO_BTF_ID)
654 strncpy(postfix, "or_null_", 16);
656 strncpy(postfix, "_or_null", 16);
659 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
660 type & MEM_RDONLY ? "rdonly_" : "",
661 type & MEM_RINGBUF ? "ringbuf_" : "",
662 type & MEM_USER ? "user_" : "",
663 type & MEM_PERCPU ? "percpu_" : "",
664 type & MEM_RCU ? "rcu_" : "",
665 type & PTR_UNTRUSTED ? "untrusted_" : "",
666 type & PTR_TRUSTED ? "trusted_" : ""
669 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
670 prefix, str[base_type(type)], postfix);
671 return env->type_str_buf;
674 static char slot_type_char[] = {
675 [STACK_INVALID] = '?',
679 [STACK_DYNPTR] = 'd',
683 static void print_liveness(struct bpf_verifier_env *env,
684 enum bpf_reg_liveness live)
686 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
688 if (live & REG_LIVE_READ)
690 if (live & REG_LIVE_WRITTEN)
692 if (live & REG_LIVE_DONE)
696 static int __get_spi(s32 off)
698 return (-off - 1) / BPF_REG_SIZE;
701 static struct bpf_func_state *func(struct bpf_verifier_env *env,
702 const struct bpf_reg_state *reg)
704 struct bpf_verifier_state *cur = env->cur_state;
706 return cur->frame[reg->frameno];
709 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
711 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
713 /* We need to check that slots between [spi - nr_slots + 1, spi] are
714 * within [0, allocated_stack).
716 * Please note that the spi grows downwards. For example, a dynptr
717 * takes the size of two stack slots; the first slot will be at
718 * spi and the second slot will be at spi - 1.
720 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
723 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
724 const char *obj_kind, int nr_slots)
728 if (!tnum_is_const(reg->var_off)) {
729 verbose(env, "%s has to be at a constant offset\n", obj_kind);
733 off = reg->off + reg->var_off.value;
734 if (off % BPF_REG_SIZE) {
735 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
739 spi = __get_spi(off);
740 if (spi + 1 < nr_slots) {
741 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
745 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
750 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
752 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
755 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
757 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
760 static const char *btf_type_name(const struct btf *btf, u32 id)
762 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
765 static const char *dynptr_type_str(enum bpf_dynptr_type type)
768 case BPF_DYNPTR_TYPE_LOCAL:
770 case BPF_DYNPTR_TYPE_RINGBUF:
772 case BPF_DYNPTR_TYPE_SKB:
774 case BPF_DYNPTR_TYPE_XDP:
776 case BPF_DYNPTR_TYPE_INVALID:
779 WARN_ONCE(1, "unknown dynptr type %d\n", type);
784 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
786 if (!btf || btf_id == 0)
789 /* we already validated that type is valid and has conforming name */
790 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
793 static const char *iter_state_str(enum bpf_iter_state state)
796 case BPF_ITER_STATE_ACTIVE:
798 case BPF_ITER_STATE_DRAINED:
800 case BPF_ITER_STATE_INVALID:
803 WARN_ONCE(1, "unknown iter state %d\n", state);
808 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
810 env->scratched_regs |= 1U << regno;
813 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
815 env->scratched_stack_slots |= 1ULL << spi;
818 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
820 return (env->scratched_regs >> regno) & 1;
823 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
825 return (env->scratched_stack_slots >> regno) & 1;
828 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
830 return env->scratched_regs || env->scratched_stack_slots;
833 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
835 env->scratched_regs = 0U;
836 env->scratched_stack_slots = 0ULL;
839 /* Used for printing the entire verifier state. */
840 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
842 env->scratched_regs = ~0U;
843 env->scratched_stack_slots = ~0ULL;
846 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
848 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
849 case DYNPTR_TYPE_LOCAL:
850 return BPF_DYNPTR_TYPE_LOCAL;
851 case DYNPTR_TYPE_RINGBUF:
852 return BPF_DYNPTR_TYPE_RINGBUF;
853 case DYNPTR_TYPE_SKB:
854 return BPF_DYNPTR_TYPE_SKB;
855 case DYNPTR_TYPE_XDP:
856 return BPF_DYNPTR_TYPE_XDP;
858 return BPF_DYNPTR_TYPE_INVALID;
862 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
865 case BPF_DYNPTR_TYPE_LOCAL:
866 return DYNPTR_TYPE_LOCAL;
867 case BPF_DYNPTR_TYPE_RINGBUF:
868 return DYNPTR_TYPE_RINGBUF;
869 case BPF_DYNPTR_TYPE_SKB:
870 return DYNPTR_TYPE_SKB;
871 case BPF_DYNPTR_TYPE_XDP:
872 return DYNPTR_TYPE_XDP;
878 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
880 return type == BPF_DYNPTR_TYPE_RINGBUF;
883 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
884 enum bpf_dynptr_type type,
885 bool first_slot, int dynptr_id);
887 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
888 struct bpf_reg_state *reg);
890 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
891 struct bpf_reg_state *sreg1,
892 struct bpf_reg_state *sreg2,
893 enum bpf_dynptr_type type)
895 int id = ++env->id_gen;
897 __mark_dynptr_reg(sreg1, type, true, id);
898 __mark_dynptr_reg(sreg2, type, false, id);
901 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
902 struct bpf_reg_state *reg,
903 enum bpf_dynptr_type type)
905 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
908 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
909 struct bpf_func_state *state, int spi);
911 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
912 enum bpf_arg_type arg_type, int insn_idx)
914 struct bpf_func_state *state = func(env, reg);
915 enum bpf_dynptr_type type;
918 spi = dynptr_get_spi(env, reg);
922 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
923 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
924 * to ensure that for the following example:
927 * So marking spi = 2 should lead to destruction of both d1 and d2. In
928 * case they do belong to same dynptr, second call won't see slot_type
929 * as STACK_DYNPTR and will simply skip destruction.
931 err = destroy_if_dynptr_stack_slot(env, state, spi);
934 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
938 for (i = 0; i < BPF_REG_SIZE; i++) {
939 state->stack[spi].slot_type[i] = STACK_DYNPTR;
940 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
943 type = arg_to_dynptr_type(arg_type);
944 if (type == BPF_DYNPTR_TYPE_INVALID)
947 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
948 &state->stack[spi - 1].spilled_ptr, type);
950 if (dynptr_type_refcounted(type)) {
951 /* The id is used to track proper releasing */
952 id = acquire_reference_state(env, insn_idx);
956 state->stack[spi].spilled_ptr.ref_obj_id = id;
957 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
960 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
961 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
966 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
968 struct bpf_func_state *state = func(env, reg);
971 spi = dynptr_get_spi(env, reg);
975 for (i = 0; i < BPF_REG_SIZE; i++) {
976 state->stack[spi].slot_type[i] = STACK_INVALID;
977 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
980 /* Invalidate any slices associated with this dynptr */
981 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
982 WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
984 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
985 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
987 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
989 * While we don't allow reading STACK_INVALID, it is still possible to
990 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
991 * helpers or insns can do partial read of that part without failing,
992 * but check_stack_range_initialized, check_stack_read_var_off, and
993 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
994 * the slot conservatively. Hence we need to prevent those liveness
997 * This was not a problem before because STACK_INVALID is only set by
998 * default (where the default reg state has its reg->parent as NULL), or
999 * in clean_live_states after REG_LIVE_DONE (at which point
1000 * mark_reg_read won't walk reg->parent chain), but not randomly during
1001 * verifier state exploration (like we did above). Hence, for our case
1002 * parentage chain will still be live (i.e. reg->parent may be
1003 * non-NULL), while earlier reg->parent was NULL, so we need
1004 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
1005 * done later on reads or by mark_dynptr_read as well to unnecessary
1006 * mark registers in verifier state.
1008 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1009 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1014 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1015 struct bpf_reg_state *reg);
1017 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1019 if (!env->allow_ptr_leaks)
1020 __mark_reg_not_init(env, reg);
1022 __mark_reg_unknown(env, reg);
1025 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1026 struct bpf_func_state *state, int spi)
1028 struct bpf_func_state *fstate;
1029 struct bpf_reg_state *dreg;
1032 /* We always ensure that STACK_DYNPTR is never set partially,
1033 * hence just checking for slot_type[0] is enough. This is
1034 * different for STACK_SPILL, where it may be only set for
1035 * 1 byte, so code has to use is_spilled_reg.
1037 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1040 /* Reposition spi to first slot */
1041 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1044 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1045 verbose(env, "cannot overwrite referenced dynptr\n");
1049 mark_stack_slot_scratched(env, spi);
1050 mark_stack_slot_scratched(env, spi - 1);
1052 /* Writing partially to one dynptr stack slot destroys both. */
1053 for (i = 0; i < BPF_REG_SIZE; i++) {
1054 state->stack[spi].slot_type[i] = STACK_INVALID;
1055 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1058 dynptr_id = state->stack[spi].spilled_ptr.id;
1059 /* Invalidate any slices associated with this dynptr */
1060 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1061 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1062 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1064 if (dreg->dynptr_id == dynptr_id)
1065 mark_reg_invalid(env, dreg);
1068 /* Do not release reference state, we are destroying dynptr on stack,
1069 * not using some helper to release it. Just reset register.
1071 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1072 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1074 /* Same reason as unmark_stack_slots_dynptr above */
1075 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1076 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1081 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1085 if (reg->type == CONST_PTR_TO_DYNPTR)
1088 spi = dynptr_get_spi(env, reg);
1090 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1091 * error because this just means the stack state hasn't been updated yet.
1092 * We will do check_mem_access to check and update stack bounds later.
1094 if (spi < 0 && spi != -ERANGE)
1097 /* We don't need to check if the stack slots are marked by previous
1098 * dynptr initializations because we allow overwriting existing unreferenced
1099 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1100 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1101 * touching are completely destructed before we reinitialize them for a new
1102 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1103 * instead of delaying it until the end where the user will get "Unreleased
1109 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1111 struct bpf_func_state *state = func(env, reg);
1114 /* This already represents first slot of initialized bpf_dynptr.
1116 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1117 * check_func_arg_reg_off's logic, so we don't need to check its
1118 * offset and alignment.
1120 if (reg->type == CONST_PTR_TO_DYNPTR)
1123 spi = dynptr_get_spi(env, reg);
1126 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1129 for (i = 0; i < BPF_REG_SIZE; i++) {
1130 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1131 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1138 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1139 enum bpf_arg_type arg_type)
1141 struct bpf_func_state *state = func(env, reg);
1142 enum bpf_dynptr_type dynptr_type;
1145 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1146 if (arg_type == ARG_PTR_TO_DYNPTR)
1149 dynptr_type = arg_to_dynptr_type(arg_type);
1150 if (reg->type == CONST_PTR_TO_DYNPTR) {
1151 return reg->dynptr.type == dynptr_type;
1153 spi = dynptr_get_spi(env, reg);
1156 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1160 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1162 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1163 struct bpf_reg_state *reg, int insn_idx,
1164 struct btf *btf, u32 btf_id, int nr_slots)
1166 struct bpf_func_state *state = func(env, reg);
1169 spi = iter_get_spi(env, reg, nr_slots);
1173 id = acquire_reference_state(env, insn_idx);
1177 for (i = 0; i < nr_slots; i++) {
1178 struct bpf_stack_state *slot = &state->stack[spi - i];
1179 struct bpf_reg_state *st = &slot->spilled_ptr;
1181 __mark_reg_known_zero(st);
1182 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1183 st->live |= REG_LIVE_WRITTEN;
1184 st->ref_obj_id = i == 0 ? id : 0;
1186 st->iter.btf_id = btf_id;
1187 st->iter.state = BPF_ITER_STATE_ACTIVE;
1190 for (j = 0; j < BPF_REG_SIZE; j++)
1191 slot->slot_type[j] = STACK_ITER;
1193 mark_stack_slot_scratched(env, spi - i);
1199 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1200 struct bpf_reg_state *reg, int nr_slots)
1202 struct bpf_func_state *state = func(env, reg);
1205 spi = iter_get_spi(env, reg, nr_slots);
1209 for (i = 0; i < nr_slots; i++) {
1210 struct bpf_stack_state *slot = &state->stack[spi - i];
1211 struct bpf_reg_state *st = &slot->spilled_ptr;
1214 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1216 __mark_reg_not_init(env, st);
1218 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1219 st->live |= REG_LIVE_WRITTEN;
1221 for (j = 0; j < BPF_REG_SIZE; j++)
1222 slot->slot_type[j] = STACK_INVALID;
1224 mark_stack_slot_scratched(env, spi - i);
1230 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1231 struct bpf_reg_state *reg, int nr_slots)
1233 struct bpf_func_state *state = func(env, reg);
1236 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1237 * will do check_mem_access to check and update stack bounds later, so
1238 * return true for that case.
1240 spi = iter_get_spi(env, reg, nr_slots);
1246 for (i = 0; i < nr_slots; i++) {
1247 struct bpf_stack_state *slot = &state->stack[spi - i];
1249 for (j = 0; j < BPF_REG_SIZE; j++)
1250 if (slot->slot_type[j] == STACK_ITER)
1257 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1258 struct btf *btf, u32 btf_id, int nr_slots)
1260 struct bpf_func_state *state = func(env, reg);
1263 spi = iter_get_spi(env, reg, nr_slots);
1267 for (i = 0; i < nr_slots; i++) {
1268 struct bpf_stack_state *slot = &state->stack[spi - i];
1269 struct bpf_reg_state *st = &slot->spilled_ptr;
1271 /* only main (first) slot has ref_obj_id set */
1272 if (i == 0 && !st->ref_obj_id)
1274 if (i != 0 && st->ref_obj_id)
1276 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1279 for (j = 0; j < BPF_REG_SIZE; j++)
1280 if (slot->slot_type[j] != STACK_ITER)
1287 /* Check if given stack slot is "special":
1288 * - spilled register state (STACK_SPILL);
1289 * - dynptr state (STACK_DYNPTR);
1290 * - iter state (STACK_ITER).
1292 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1294 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1306 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1311 /* The reg state of a pointer or a bounded scalar was saved when
1312 * it was spilled to the stack.
1314 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1316 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1319 static void scrub_spilled_slot(u8 *stype)
1321 if (*stype != STACK_INVALID)
1322 *stype = STACK_MISC;
1325 static void print_verifier_state(struct bpf_verifier_env *env,
1326 const struct bpf_func_state *state,
1329 const struct bpf_reg_state *reg;
1330 enum bpf_reg_type t;
1334 verbose(env, " frame%d:", state->frameno);
1335 for (i = 0; i < MAX_BPF_REG; i++) {
1336 reg = &state->regs[i];
1340 if (!print_all && !reg_scratched(env, i))
1342 verbose(env, " R%d", i);
1343 print_liveness(env, reg->live);
1345 if (t == SCALAR_VALUE && reg->precise)
1347 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1348 tnum_is_const(reg->var_off)) {
1349 /* reg->off should be 0 for SCALAR_VALUE */
1350 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1351 verbose(env, "%lld", reg->var_off.value + reg->off);
1353 const char *sep = "";
1355 verbose(env, "%s", reg_type_str(env, t));
1356 if (base_type(t) == PTR_TO_BTF_ID)
1357 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1360 * _a stands for append, was shortened to avoid multiline statements below.
1361 * This macro is used to output a comma separated list of attributes.
1363 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1366 verbose_a("id=%d", reg->id);
1367 if (reg->ref_obj_id)
1368 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1369 if (type_is_non_owning_ref(reg->type))
1370 verbose_a("%s", "non_own_ref");
1371 if (t != SCALAR_VALUE)
1372 verbose_a("off=%d", reg->off);
1373 if (type_is_pkt_pointer(t))
1374 verbose_a("r=%d", reg->range);
1375 else if (base_type(t) == CONST_PTR_TO_MAP ||
1376 base_type(t) == PTR_TO_MAP_KEY ||
1377 base_type(t) == PTR_TO_MAP_VALUE)
1378 verbose_a("ks=%d,vs=%d",
1379 reg->map_ptr->key_size,
1380 reg->map_ptr->value_size);
1381 if (tnum_is_const(reg->var_off)) {
1382 /* Typically an immediate SCALAR_VALUE, but
1383 * could be a pointer whose offset is too big
1386 verbose_a("imm=%llx", reg->var_off.value);
1388 if (reg->smin_value != reg->umin_value &&
1389 reg->smin_value != S64_MIN)
1390 verbose_a("smin=%lld", (long long)reg->smin_value);
1391 if (reg->smax_value != reg->umax_value &&
1392 reg->smax_value != S64_MAX)
1393 verbose_a("smax=%lld", (long long)reg->smax_value);
1394 if (reg->umin_value != 0)
1395 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1396 if (reg->umax_value != U64_MAX)
1397 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1398 if (!tnum_is_unknown(reg->var_off)) {
1401 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1402 verbose_a("var_off=%s", tn_buf);
1404 if (reg->s32_min_value != reg->smin_value &&
1405 reg->s32_min_value != S32_MIN)
1406 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1407 if (reg->s32_max_value != reg->smax_value &&
1408 reg->s32_max_value != S32_MAX)
1409 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1410 if (reg->u32_min_value != reg->umin_value &&
1411 reg->u32_min_value != U32_MIN)
1412 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1413 if (reg->u32_max_value != reg->umax_value &&
1414 reg->u32_max_value != U32_MAX)
1415 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1422 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1423 char types_buf[BPF_REG_SIZE + 1];
1427 for (j = 0; j < BPF_REG_SIZE; j++) {
1428 if (state->stack[i].slot_type[j] != STACK_INVALID)
1430 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1432 types_buf[BPF_REG_SIZE] = 0;
1435 if (!print_all && !stack_slot_scratched(env, i))
1437 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1439 reg = &state->stack[i].spilled_ptr;
1442 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1443 print_liveness(env, reg->live);
1444 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1445 if (t == SCALAR_VALUE && reg->precise)
1447 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1448 verbose(env, "%lld", reg->var_off.value + reg->off);
1451 i += BPF_DYNPTR_NR_SLOTS - 1;
1452 reg = &state->stack[i].spilled_ptr;
1454 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1455 print_liveness(env, reg->live);
1456 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1457 if (reg->ref_obj_id)
1458 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1461 /* only main slot has ref_obj_id set; skip others */
1462 reg = &state->stack[i].spilled_ptr;
1463 if (!reg->ref_obj_id)
1466 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1467 print_liveness(env, reg->live);
1468 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1469 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1470 reg->ref_obj_id, iter_state_str(reg->iter.state),
1476 reg = &state->stack[i].spilled_ptr;
1478 for (j = 0; j < BPF_REG_SIZE; j++)
1479 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1480 types_buf[BPF_REG_SIZE] = 0;
1482 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1483 print_liveness(env, reg->live);
1484 verbose(env, "=%s", types_buf);
1488 if (state->acquired_refs && state->refs[0].id) {
1489 verbose(env, " refs=%d", state->refs[0].id);
1490 for (i = 1; i < state->acquired_refs; i++)
1491 if (state->refs[i].id)
1492 verbose(env, ",%d", state->refs[i].id);
1494 if (state->in_callback_fn)
1495 verbose(env, " cb");
1496 if (state->in_async_callback_fn)
1497 verbose(env, " async_cb");
1499 mark_verifier_state_clean(env);
1502 static inline u32 vlog_alignment(u32 pos)
1504 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1505 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1508 static void print_insn_state(struct bpf_verifier_env *env,
1509 const struct bpf_func_state *state)
1511 if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
1512 /* remove new line character */
1513 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1514 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1516 verbose(env, "%d:", env->insn_idx);
1518 print_verifier_state(env, state, false);
1521 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1522 * small to hold src. This is different from krealloc since we don't want to preserve
1523 * the contents of dst.
1525 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1528 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1534 if (ZERO_OR_NULL_PTR(src))
1537 if (unlikely(check_mul_overflow(n, size, &bytes)))
1540 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1541 dst = krealloc(orig, alloc_bytes, flags);
1547 memcpy(dst, src, bytes);
1549 return dst ? dst : ZERO_SIZE_PTR;
1552 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1553 * small to hold new_n items. new items are zeroed out if the array grows.
1555 * Contrary to krealloc_array, does not free arr if new_n is zero.
1557 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1562 if (!new_n || old_n == new_n)
1565 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1566 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1574 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1577 return arr ? arr : ZERO_SIZE_PTR;
1580 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1582 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1583 sizeof(struct bpf_reference_state), GFP_KERNEL);
1587 dst->acquired_refs = src->acquired_refs;
1591 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1593 size_t n = src->allocated_stack / BPF_REG_SIZE;
1595 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1600 dst->allocated_stack = src->allocated_stack;
1604 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1606 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1607 sizeof(struct bpf_reference_state));
1611 state->acquired_refs = n;
1615 static int grow_stack_state(struct bpf_func_state *state, int size)
1617 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1622 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1626 state->allocated_stack = size;
1630 /* Acquire a pointer id from the env and update the state->refs to include
1631 * this new pointer reference.
1632 * On success, returns a valid pointer id to associate with the register
1633 * On failure, returns a negative errno.
1635 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1637 struct bpf_func_state *state = cur_func(env);
1638 int new_ofs = state->acquired_refs;
1641 err = resize_reference_state(state, state->acquired_refs + 1);
1645 state->refs[new_ofs].id = id;
1646 state->refs[new_ofs].insn_idx = insn_idx;
1647 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1652 /* release function corresponding to acquire_reference_state(). Idempotent. */
1653 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1657 last_idx = state->acquired_refs - 1;
1658 for (i = 0; i < state->acquired_refs; i++) {
1659 if (state->refs[i].id == ptr_id) {
1660 /* Cannot release caller references in callbacks */
1661 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1663 if (last_idx && i != last_idx)
1664 memcpy(&state->refs[i], &state->refs[last_idx],
1665 sizeof(*state->refs));
1666 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1667 state->acquired_refs--;
1674 static void free_func_state(struct bpf_func_state *state)
1679 kfree(state->stack);
1683 static void clear_jmp_history(struct bpf_verifier_state *state)
1685 kfree(state->jmp_history);
1686 state->jmp_history = NULL;
1687 state->jmp_history_cnt = 0;
1690 static void free_verifier_state(struct bpf_verifier_state *state,
1695 for (i = 0; i <= state->curframe; i++) {
1696 free_func_state(state->frame[i]);
1697 state->frame[i] = NULL;
1699 clear_jmp_history(state);
1704 /* copy verifier state from src to dst growing dst stack space
1705 * when necessary to accommodate larger src stack
1707 static int copy_func_state(struct bpf_func_state *dst,
1708 const struct bpf_func_state *src)
1712 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1713 err = copy_reference_state(dst, src);
1716 return copy_stack_state(dst, src);
1719 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1720 const struct bpf_verifier_state *src)
1722 struct bpf_func_state *dst;
1725 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1726 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1728 if (!dst_state->jmp_history)
1730 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1732 /* if dst has more stack frames then src frame, free them */
1733 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1734 free_func_state(dst_state->frame[i]);
1735 dst_state->frame[i] = NULL;
1737 dst_state->speculative = src->speculative;
1738 dst_state->active_rcu_lock = src->active_rcu_lock;
1739 dst_state->curframe = src->curframe;
1740 dst_state->active_lock.ptr = src->active_lock.ptr;
1741 dst_state->active_lock.id = src->active_lock.id;
1742 dst_state->branches = src->branches;
1743 dst_state->parent = src->parent;
1744 dst_state->first_insn_idx = src->first_insn_idx;
1745 dst_state->last_insn_idx = src->last_insn_idx;
1746 for (i = 0; i <= src->curframe; i++) {
1747 dst = dst_state->frame[i];
1749 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1752 dst_state->frame[i] = dst;
1754 err = copy_func_state(dst, src->frame[i]);
1761 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1764 u32 br = --st->branches;
1766 /* WARN_ON(br > 1) technically makes sense here,
1767 * but see comment in push_stack(), hence:
1769 WARN_ONCE((int)br < 0,
1770 "BUG update_branch_counts:branches_to_explore=%d\n",
1778 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1779 int *insn_idx, bool pop_log)
1781 struct bpf_verifier_state *cur = env->cur_state;
1782 struct bpf_verifier_stack_elem *elem, *head = env->head;
1785 if (env->head == NULL)
1789 err = copy_verifier_state(cur, &head->st);
1794 bpf_vlog_reset(&env->log, head->log_pos);
1796 *insn_idx = head->insn_idx;
1798 *prev_insn_idx = head->prev_insn_idx;
1800 free_verifier_state(&head->st, false);
1807 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1808 int insn_idx, int prev_insn_idx,
1811 struct bpf_verifier_state *cur = env->cur_state;
1812 struct bpf_verifier_stack_elem *elem;
1815 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1819 elem->insn_idx = insn_idx;
1820 elem->prev_insn_idx = prev_insn_idx;
1821 elem->next = env->head;
1822 elem->log_pos = env->log.len_used;
1825 err = copy_verifier_state(&elem->st, cur);
1828 elem->st.speculative |= speculative;
1829 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1830 verbose(env, "The sequence of %d jumps is too complex.\n",
1834 if (elem->st.parent) {
1835 ++elem->st.parent->branches;
1836 /* WARN_ON(branches > 2) technically makes sense here,
1838 * 1. speculative states will bump 'branches' for non-branch
1840 * 2. is_state_visited() heuristics may decide not to create
1841 * a new state for a sequence of branches and all such current
1842 * and cloned states will be pointing to a single parent state
1843 * which might have large 'branches' count.
1848 free_verifier_state(env->cur_state, true);
1849 env->cur_state = NULL;
1850 /* pop all elements and return */
1851 while (!pop_stack(env, NULL, NULL, false));
1855 #define CALLER_SAVED_REGS 6
1856 static const int caller_saved[CALLER_SAVED_REGS] = {
1857 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1860 /* This helper doesn't clear reg->id */
1861 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1863 reg->var_off = tnum_const(imm);
1864 reg->smin_value = (s64)imm;
1865 reg->smax_value = (s64)imm;
1866 reg->umin_value = imm;
1867 reg->umax_value = imm;
1869 reg->s32_min_value = (s32)imm;
1870 reg->s32_max_value = (s32)imm;
1871 reg->u32_min_value = (u32)imm;
1872 reg->u32_max_value = (u32)imm;
1875 /* Mark the unknown part of a register (variable offset or scalar value) as
1876 * known to have the value @imm.
1878 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1880 /* Clear off and union(map_ptr, range) */
1881 memset(((u8 *)reg) + sizeof(reg->type), 0,
1882 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1884 reg->ref_obj_id = 0;
1885 ___mark_reg_known(reg, imm);
1888 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1890 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1891 reg->s32_min_value = (s32)imm;
1892 reg->s32_max_value = (s32)imm;
1893 reg->u32_min_value = (u32)imm;
1894 reg->u32_max_value = (u32)imm;
1897 /* Mark the 'variable offset' part of a register as zero. This should be
1898 * used only on registers holding a pointer type.
1900 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1902 __mark_reg_known(reg, 0);
1905 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1907 __mark_reg_known(reg, 0);
1908 reg->type = SCALAR_VALUE;
1911 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1912 struct bpf_reg_state *regs, u32 regno)
1914 if (WARN_ON(regno >= MAX_BPF_REG)) {
1915 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1916 /* Something bad happened, let's kill all regs */
1917 for (regno = 0; regno < MAX_BPF_REG; regno++)
1918 __mark_reg_not_init(env, regs + regno);
1921 __mark_reg_known_zero(regs + regno);
1924 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1925 bool first_slot, int dynptr_id)
1927 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1928 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1929 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1931 __mark_reg_known_zero(reg);
1932 reg->type = CONST_PTR_TO_DYNPTR;
1933 /* Give each dynptr a unique id to uniquely associate slices to it. */
1934 reg->id = dynptr_id;
1935 reg->dynptr.type = type;
1936 reg->dynptr.first_slot = first_slot;
1939 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1941 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1942 const struct bpf_map *map = reg->map_ptr;
1944 if (map->inner_map_meta) {
1945 reg->type = CONST_PTR_TO_MAP;
1946 reg->map_ptr = map->inner_map_meta;
1947 /* transfer reg's id which is unique for every map_lookup_elem
1948 * as UID of the inner map.
1950 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1951 reg->map_uid = reg->id;
1952 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1953 reg->type = PTR_TO_XDP_SOCK;
1954 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1955 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1956 reg->type = PTR_TO_SOCKET;
1958 reg->type = PTR_TO_MAP_VALUE;
1963 reg->type &= ~PTR_MAYBE_NULL;
1966 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1967 struct btf_field_graph_root *ds_head)
1969 __mark_reg_known_zero(®s[regno]);
1970 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1971 regs[regno].btf = ds_head->btf;
1972 regs[regno].btf_id = ds_head->value_btf_id;
1973 regs[regno].off = ds_head->node_offset;
1976 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1978 return type_is_pkt_pointer(reg->type);
1981 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1983 return reg_is_pkt_pointer(reg) ||
1984 reg->type == PTR_TO_PACKET_END;
1987 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1989 return base_type(reg->type) == PTR_TO_MEM &&
1990 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1993 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1994 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1995 enum bpf_reg_type which)
1997 /* The register can already have a range from prior markings.
1998 * This is fine as long as it hasn't been advanced from its
2001 return reg->type == which &&
2004 tnum_equals_const(reg->var_off, 0);
2007 /* Reset the min/max bounds of a register */
2008 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2010 reg->smin_value = S64_MIN;
2011 reg->smax_value = S64_MAX;
2012 reg->umin_value = 0;
2013 reg->umax_value = U64_MAX;
2015 reg->s32_min_value = S32_MIN;
2016 reg->s32_max_value = S32_MAX;
2017 reg->u32_min_value = 0;
2018 reg->u32_max_value = U32_MAX;
2021 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2023 reg->smin_value = S64_MIN;
2024 reg->smax_value = S64_MAX;
2025 reg->umin_value = 0;
2026 reg->umax_value = U64_MAX;
2029 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2031 reg->s32_min_value = S32_MIN;
2032 reg->s32_max_value = S32_MAX;
2033 reg->u32_min_value = 0;
2034 reg->u32_max_value = U32_MAX;
2037 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2039 struct tnum var32_off = tnum_subreg(reg->var_off);
2041 /* min signed is max(sign bit) | min(other bits) */
2042 reg->s32_min_value = max_t(s32, reg->s32_min_value,
2043 var32_off.value | (var32_off.mask & S32_MIN));
2044 /* max signed is min(sign bit) | max(other bits) */
2045 reg->s32_max_value = min_t(s32, reg->s32_max_value,
2046 var32_off.value | (var32_off.mask & S32_MAX));
2047 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2048 reg->u32_max_value = min(reg->u32_max_value,
2049 (u32)(var32_off.value | var32_off.mask));
2052 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2054 /* min signed is max(sign bit) | min(other bits) */
2055 reg->smin_value = max_t(s64, reg->smin_value,
2056 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2057 /* max signed is min(sign bit) | max(other bits) */
2058 reg->smax_value = min_t(s64, reg->smax_value,
2059 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2060 reg->umin_value = max(reg->umin_value, reg->var_off.value);
2061 reg->umax_value = min(reg->umax_value,
2062 reg->var_off.value | reg->var_off.mask);
2065 static void __update_reg_bounds(struct bpf_reg_state *reg)
2067 __update_reg32_bounds(reg);
2068 __update_reg64_bounds(reg);
2071 /* Uses signed min/max values to inform unsigned, and vice-versa */
2072 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2074 /* Learn sign from signed bounds.
2075 * If we cannot cross the sign boundary, then signed and unsigned bounds
2076 * are the same, so combine. This works even in the negative case, e.g.
2077 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2079 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2080 reg->s32_min_value = reg->u32_min_value =
2081 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2082 reg->s32_max_value = reg->u32_max_value =
2083 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2086 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2087 * boundary, so we must be careful.
2089 if ((s32)reg->u32_max_value >= 0) {
2090 /* Positive. We can't learn anything from the smin, but smax
2091 * is positive, hence safe.
2093 reg->s32_min_value = reg->u32_min_value;
2094 reg->s32_max_value = reg->u32_max_value =
2095 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2096 } else if ((s32)reg->u32_min_value < 0) {
2097 /* Negative. We can't learn anything from the smax, but smin
2098 * is negative, hence safe.
2100 reg->s32_min_value = reg->u32_min_value =
2101 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2102 reg->s32_max_value = reg->u32_max_value;
2106 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2108 /* Learn sign from signed bounds.
2109 * If we cannot cross the sign boundary, then signed and unsigned bounds
2110 * are the same, so combine. This works even in the negative case, e.g.
2111 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2113 if (reg->smin_value >= 0 || reg->smax_value < 0) {
2114 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2116 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2120 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2121 * boundary, so we must be careful.
2123 if ((s64)reg->umax_value >= 0) {
2124 /* Positive. We can't learn anything from the smin, but smax
2125 * is positive, hence safe.
2127 reg->smin_value = reg->umin_value;
2128 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2130 } else if ((s64)reg->umin_value < 0) {
2131 /* Negative. We can't learn anything from the smax, but smin
2132 * is negative, hence safe.
2134 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2136 reg->smax_value = reg->umax_value;
2140 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2142 __reg32_deduce_bounds(reg);
2143 __reg64_deduce_bounds(reg);
2146 /* Attempts to improve var_off based on unsigned min/max information */
2147 static void __reg_bound_offset(struct bpf_reg_state *reg)
2149 struct tnum var64_off = tnum_intersect(reg->var_off,
2150 tnum_range(reg->umin_value,
2152 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2153 tnum_range(reg->u32_min_value,
2154 reg->u32_max_value));
2156 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2159 static void reg_bounds_sync(struct bpf_reg_state *reg)
2161 /* We might have learned new bounds from the var_off. */
2162 __update_reg_bounds(reg);
2163 /* We might have learned something about the sign bit. */
2164 __reg_deduce_bounds(reg);
2165 /* We might have learned some bits from the bounds. */
2166 __reg_bound_offset(reg);
2167 /* Intersecting with the old var_off might have improved our bounds
2168 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2169 * then new var_off is (0; 0x7f...fc) which improves our umax.
2171 __update_reg_bounds(reg);
2174 static bool __reg32_bound_s64(s32 a)
2176 return a >= 0 && a <= S32_MAX;
2179 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2181 reg->umin_value = reg->u32_min_value;
2182 reg->umax_value = reg->u32_max_value;
2184 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2185 * be positive otherwise set to worse case bounds and refine later
2188 if (__reg32_bound_s64(reg->s32_min_value) &&
2189 __reg32_bound_s64(reg->s32_max_value)) {
2190 reg->smin_value = reg->s32_min_value;
2191 reg->smax_value = reg->s32_max_value;
2193 reg->smin_value = 0;
2194 reg->smax_value = U32_MAX;
2198 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2200 /* special case when 64-bit register has upper 32-bit register
2201 * zeroed. Typically happens after zext or <<32, >>32 sequence
2202 * allowing us to use 32-bit bounds directly,
2204 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2205 __reg_assign_32_into_64(reg);
2207 /* Otherwise the best we can do is push lower 32bit known and
2208 * unknown bits into register (var_off set from jmp logic)
2209 * then learn as much as possible from the 64-bit tnum
2210 * known and unknown bits. The previous smin/smax bounds are
2211 * invalid here because of jmp32 compare so mark them unknown
2212 * so they do not impact tnum bounds calculation.
2214 __mark_reg64_unbounded(reg);
2216 reg_bounds_sync(reg);
2219 static bool __reg64_bound_s32(s64 a)
2221 return a >= S32_MIN && a <= S32_MAX;
2224 static bool __reg64_bound_u32(u64 a)
2226 return a >= U32_MIN && a <= U32_MAX;
2229 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2231 __mark_reg32_unbounded(reg);
2232 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2233 reg->s32_min_value = (s32)reg->smin_value;
2234 reg->s32_max_value = (s32)reg->smax_value;
2236 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2237 reg->u32_min_value = (u32)reg->umin_value;
2238 reg->u32_max_value = (u32)reg->umax_value;
2240 reg_bounds_sync(reg);
2243 /* Mark a register as having a completely unknown (scalar) value. */
2244 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2245 struct bpf_reg_state *reg)
2248 * Clear type, off, and union(map_ptr, range) and
2249 * padding between 'type' and union
2251 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2252 reg->type = SCALAR_VALUE;
2254 reg->ref_obj_id = 0;
2255 reg->var_off = tnum_unknown;
2257 reg->precise = !env->bpf_capable;
2258 __mark_reg_unbounded(reg);
2261 static void mark_reg_unknown(struct bpf_verifier_env *env,
2262 struct bpf_reg_state *regs, u32 regno)
2264 if (WARN_ON(regno >= MAX_BPF_REG)) {
2265 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2266 /* Something bad happened, let's kill all regs except FP */
2267 for (regno = 0; regno < BPF_REG_FP; regno++)
2268 __mark_reg_not_init(env, regs + regno);
2271 __mark_reg_unknown(env, regs + regno);
2274 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2275 struct bpf_reg_state *reg)
2277 __mark_reg_unknown(env, reg);
2278 reg->type = NOT_INIT;
2281 static void mark_reg_not_init(struct bpf_verifier_env *env,
2282 struct bpf_reg_state *regs, u32 regno)
2284 if (WARN_ON(regno >= MAX_BPF_REG)) {
2285 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2286 /* Something bad happened, let's kill all regs except FP */
2287 for (regno = 0; regno < BPF_REG_FP; regno++)
2288 __mark_reg_not_init(env, regs + regno);
2291 __mark_reg_not_init(env, regs + regno);
2294 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2295 struct bpf_reg_state *regs, u32 regno,
2296 enum bpf_reg_type reg_type,
2297 struct btf *btf, u32 btf_id,
2298 enum bpf_type_flag flag)
2300 if (reg_type == SCALAR_VALUE) {
2301 mark_reg_unknown(env, regs, regno);
2304 mark_reg_known_zero(env, regs, regno);
2305 regs[regno].type = PTR_TO_BTF_ID | flag;
2306 regs[regno].btf = btf;
2307 regs[regno].btf_id = btf_id;
2310 #define DEF_NOT_SUBREG (0)
2311 static void init_reg_state(struct bpf_verifier_env *env,
2312 struct bpf_func_state *state)
2314 struct bpf_reg_state *regs = state->regs;
2317 for (i = 0; i < MAX_BPF_REG; i++) {
2318 mark_reg_not_init(env, regs, i);
2319 regs[i].live = REG_LIVE_NONE;
2320 regs[i].parent = NULL;
2321 regs[i].subreg_def = DEF_NOT_SUBREG;
2325 regs[BPF_REG_FP].type = PTR_TO_STACK;
2326 mark_reg_known_zero(env, regs, BPF_REG_FP);
2327 regs[BPF_REG_FP].frameno = state->frameno;
2330 #define BPF_MAIN_FUNC (-1)
2331 static void init_func_state(struct bpf_verifier_env *env,
2332 struct bpf_func_state *state,
2333 int callsite, int frameno, int subprogno)
2335 state->callsite = callsite;
2336 state->frameno = frameno;
2337 state->subprogno = subprogno;
2338 state->callback_ret_range = tnum_range(0, 0);
2339 init_reg_state(env, state);
2340 mark_verifier_state_scratched(env);
2343 /* Similar to push_stack(), but for async callbacks */
2344 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2345 int insn_idx, int prev_insn_idx,
2348 struct bpf_verifier_stack_elem *elem;
2349 struct bpf_func_state *frame;
2351 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2355 elem->insn_idx = insn_idx;
2356 elem->prev_insn_idx = prev_insn_idx;
2357 elem->next = env->head;
2358 elem->log_pos = env->log.len_used;
2361 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2363 "The sequence of %d jumps is too complex for async cb.\n",
2367 /* Unlike push_stack() do not copy_verifier_state().
2368 * The caller state doesn't matter.
2369 * This is async callback. It starts in a fresh stack.
2370 * Initialize it similar to do_check_common().
2372 elem->st.branches = 1;
2373 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2376 init_func_state(env, frame,
2377 BPF_MAIN_FUNC /* callsite */,
2378 0 /* frameno within this callchain */,
2379 subprog /* subprog number within this prog */);
2380 elem->st.frame[0] = frame;
2383 free_verifier_state(env->cur_state, true);
2384 env->cur_state = NULL;
2385 /* pop all elements and return */
2386 while (!pop_stack(env, NULL, NULL, false));
2392 SRC_OP, /* register is used as source operand */
2393 DST_OP, /* register is used as destination operand */
2394 DST_OP_NO_MARK /* same as above, check only, don't mark */
2397 static int cmp_subprogs(const void *a, const void *b)
2399 return ((struct bpf_subprog_info *)a)->start -
2400 ((struct bpf_subprog_info *)b)->start;
2403 static int find_subprog(struct bpf_verifier_env *env, int off)
2405 struct bpf_subprog_info *p;
2407 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2408 sizeof(env->subprog_info[0]), cmp_subprogs);
2411 return p - env->subprog_info;
2415 static int add_subprog(struct bpf_verifier_env *env, int off)
2417 int insn_cnt = env->prog->len;
2420 if (off >= insn_cnt || off < 0) {
2421 verbose(env, "call to invalid destination\n");
2424 ret = find_subprog(env, off);
2427 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2428 verbose(env, "too many subprograms\n");
2431 /* determine subprog starts. The end is one before the next starts */
2432 env->subprog_info[env->subprog_cnt++].start = off;
2433 sort(env->subprog_info, env->subprog_cnt,
2434 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2435 return env->subprog_cnt - 1;
2438 #define MAX_KFUNC_DESCS 256
2439 #define MAX_KFUNC_BTFS 256
2441 struct bpf_kfunc_desc {
2442 struct btf_func_model func_model;
2448 struct bpf_kfunc_btf {
2450 struct module *module;
2454 struct bpf_kfunc_desc_tab {
2455 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2459 struct bpf_kfunc_btf_tab {
2460 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2464 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2466 const struct bpf_kfunc_desc *d0 = a;
2467 const struct bpf_kfunc_desc *d1 = b;
2469 /* func_id is not greater than BTF_MAX_TYPE */
2470 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2473 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2475 const struct bpf_kfunc_btf *d0 = a;
2476 const struct bpf_kfunc_btf *d1 = b;
2478 return d0->offset - d1->offset;
2481 static const struct bpf_kfunc_desc *
2482 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2484 struct bpf_kfunc_desc desc = {
2488 struct bpf_kfunc_desc_tab *tab;
2490 tab = prog->aux->kfunc_tab;
2491 return bsearch(&desc, tab->descs, tab->nr_descs,
2492 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2495 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2498 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2499 struct bpf_kfunc_btf_tab *tab;
2500 struct bpf_kfunc_btf *b;
2505 tab = env->prog->aux->kfunc_btf_tab;
2506 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2507 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2509 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2510 verbose(env, "too many different module BTFs\n");
2511 return ERR_PTR(-E2BIG);
2514 if (bpfptr_is_null(env->fd_array)) {
2515 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2516 return ERR_PTR(-EPROTO);
2519 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2520 offset * sizeof(btf_fd),
2522 return ERR_PTR(-EFAULT);
2524 btf = btf_get_by_fd(btf_fd);
2526 verbose(env, "invalid module BTF fd specified\n");
2530 if (!btf_is_module(btf)) {
2531 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2533 return ERR_PTR(-EINVAL);
2536 mod = btf_try_get_module(btf);
2539 return ERR_PTR(-ENXIO);
2542 b = &tab->descs[tab->nr_descs++];
2547 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2548 kfunc_btf_cmp_by_off, NULL);
2553 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2558 while (tab->nr_descs--) {
2559 module_put(tab->descs[tab->nr_descs].module);
2560 btf_put(tab->descs[tab->nr_descs].btf);
2565 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2569 /* In the future, this can be allowed to increase limit
2570 * of fd index into fd_array, interpreted as u16.
2572 verbose(env, "negative offset disallowed for kernel module function call\n");
2573 return ERR_PTR(-EINVAL);
2576 return __find_kfunc_desc_btf(env, offset);
2578 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2581 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2583 const struct btf_type *func, *func_proto;
2584 struct bpf_kfunc_btf_tab *btf_tab;
2585 struct bpf_kfunc_desc_tab *tab;
2586 struct bpf_prog_aux *prog_aux;
2587 struct bpf_kfunc_desc *desc;
2588 const char *func_name;
2589 struct btf *desc_btf;
2590 unsigned long call_imm;
2594 prog_aux = env->prog->aux;
2595 tab = prog_aux->kfunc_tab;
2596 btf_tab = prog_aux->kfunc_btf_tab;
2599 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2603 if (!env->prog->jit_requested) {
2604 verbose(env, "JIT is required for calling kernel function\n");
2608 if (!bpf_jit_supports_kfunc_call()) {
2609 verbose(env, "JIT does not support calling kernel function\n");
2613 if (!env->prog->gpl_compatible) {
2614 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2618 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2621 prog_aux->kfunc_tab = tab;
2624 /* func_id == 0 is always invalid, but instead of returning an error, be
2625 * conservative and wait until the code elimination pass before returning
2626 * error, so that invalid calls that get pruned out can be in BPF programs
2627 * loaded from userspace. It is also required that offset be untouched
2630 if (!func_id && !offset)
2633 if (!btf_tab && offset) {
2634 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2637 prog_aux->kfunc_btf_tab = btf_tab;
2640 desc_btf = find_kfunc_desc_btf(env, offset);
2641 if (IS_ERR(desc_btf)) {
2642 verbose(env, "failed to find BTF for kernel function\n");
2643 return PTR_ERR(desc_btf);
2646 if (find_kfunc_desc(env->prog, func_id, offset))
2649 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2650 verbose(env, "too many different kernel function calls\n");
2654 func = btf_type_by_id(desc_btf, func_id);
2655 if (!func || !btf_type_is_func(func)) {
2656 verbose(env, "kernel btf_id %u is not a function\n",
2660 func_proto = btf_type_by_id(desc_btf, func->type);
2661 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2662 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2667 func_name = btf_name_by_offset(desc_btf, func->name_off);
2668 addr = kallsyms_lookup_name(func_name);
2670 verbose(env, "cannot find address for kernel function %s\n",
2675 call_imm = BPF_CALL_IMM(addr);
2676 /* Check whether or not the relative offset overflows desc->imm */
2677 if ((unsigned long)(s32)call_imm != call_imm) {
2678 verbose(env, "address of kernel function %s is out of range\n",
2683 if (bpf_dev_bound_kfunc_id(func_id)) {
2684 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2689 desc = &tab->descs[tab->nr_descs++];
2690 desc->func_id = func_id;
2691 desc->imm = call_imm;
2692 desc->offset = offset;
2693 err = btf_distill_func_proto(&env->log, desc_btf,
2694 func_proto, func_name,
2697 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2698 kfunc_desc_cmp_by_id_off, NULL);
2702 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2704 const struct bpf_kfunc_desc *d0 = a;
2705 const struct bpf_kfunc_desc *d1 = b;
2707 if (d0->imm > d1->imm)
2709 else if (d0->imm < d1->imm)
2714 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2716 struct bpf_kfunc_desc_tab *tab;
2718 tab = prog->aux->kfunc_tab;
2722 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2723 kfunc_desc_cmp_by_imm, NULL);
2726 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2728 return !!prog->aux->kfunc_tab;
2731 const struct btf_func_model *
2732 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2733 const struct bpf_insn *insn)
2735 const struct bpf_kfunc_desc desc = {
2738 const struct bpf_kfunc_desc *res;
2739 struct bpf_kfunc_desc_tab *tab;
2741 tab = prog->aux->kfunc_tab;
2742 res = bsearch(&desc, tab->descs, tab->nr_descs,
2743 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2745 return res ? &res->func_model : NULL;
2748 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2750 struct bpf_subprog_info *subprog = env->subprog_info;
2751 struct bpf_insn *insn = env->prog->insnsi;
2752 int i, ret, insn_cnt = env->prog->len;
2754 /* Add entry function. */
2755 ret = add_subprog(env, 0);
2759 for (i = 0; i < insn_cnt; i++, insn++) {
2760 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2761 !bpf_pseudo_kfunc_call(insn))
2764 if (!env->bpf_capable) {
2765 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2769 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2770 ret = add_subprog(env, i + insn->imm + 1);
2772 ret = add_kfunc_call(env, insn->imm, insn->off);
2778 /* Add a fake 'exit' subprog which could simplify subprog iteration
2779 * logic. 'subprog_cnt' should not be increased.
2781 subprog[env->subprog_cnt].start = insn_cnt;
2783 if (env->log.level & BPF_LOG_LEVEL2)
2784 for (i = 0; i < env->subprog_cnt; i++)
2785 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2790 static int check_subprogs(struct bpf_verifier_env *env)
2792 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2793 struct bpf_subprog_info *subprog = env->subprog_info;
2794 struct bpf_insn *insn = env->prog->insnsi;
2795 int insn_cnt = env->prog->len;
2797 /* now check that all jumps are within the same subprog */
2798 subprog_start = subprog[cur_subprog].start;
2799 subprog_end = subprog[cur_subprog + 1].start;
2800 for (i = 0; i < insn_cnt; i++) {
2801 u8 code = insn[i].code;
2803 if (code == (BPF_JMP | BPF_CALL) &&
2804 insn[i].src_reg == 0 &&
2805 insn[i].imm == BPF_FUNC_tail_call)
2806 subprog[cur_subprog].has_tail_call = true;
2807 if (BPF_CLASS(code) == BPF_LD &&
2808 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2809 subprog[cur_subprog].has_ld_abs = true;
2810 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2812 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2814 off = i + insn[i].off + 1;
2815 if (off < subprog_start || off >= subprog_end) {
2816 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2820 if (i == subprog_end - 1) {
2821 /* to avoid fall-through from one subprog into another
2822 * the last insn of the subprog should be either exit
2823 * or unconditional jump back
2825 if (code != (BPF_JMP | BPF_EXIT) &&
2826 code != (BPF_JMP | BPF_JA)) {
2827 verbose(env, "last insn is not an exit or jmp\n");
2830 subprog_start = subprog_end;
2832 if (cur_subprog < env->subprog_cnt)
2833 subprog_end = subprog[cur_subprog + 1].start;
2839 /* Parentage chain of this register (or stack slot) should take care of all
2840 * issues like callee-saved registers, stack slot allocation time, etc.
2842 static int mark_reg_read(struct bpf_verifier_env *env,
2843 const struct bpf_reg_state *state,
2844 struct bpf_reg_state *parent, u8 flag)
2846 bool writes = parent == state->parent; /* Observe write marks */
2850 /* if read wasn't screened by an earlier write ... */
2851 if (writes && state->live & REG_LIVE_WRITTEN)
2853 if (parent->live & REG_LIVE_DONE) {
2854 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2855 reg_type_str(env, parent->type),
2856 parent->var_off.value, parent->off);
2859 /* The first condition is more likely to be true than the
2860 * second, checked it first.
2862 if ((parent->live & REG_LIVE_READ) == flag ||
2863 parent->live & REG_LIVE_READ64)
2864 /* The parentage chain never changes and
2865 * this parent was already marked as LIVE_READ.
2866 * There is no need to keep walking the chain again and
2867 * keep re-marking all parents as LIVE_READ.
2868 * This case happens when the same register is read
2869 * multiple times without writes into it in-between.
2870 * Also, if parent has the stronger REG_LIVE_READ64 set,
2871 * then no need to set the weak REG_LIVE_READ32.
2874 /* ... then we depend on parent's value */
2875 parent->live |= flag;
2876 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2877 if (flag == REG_LIVE_READ64)
2878 parent->live &= ~REG_LIVE_READ32;
2880 parent = state->parent;
2885 if (env->longest_mark_read_walk < cnt)
2886 env->longest_mark_read_walk = cnt;
2890 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2892 struct bpf_func_state *state = func(env, reg);
2895 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2896 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2899 if (reg->type == CONST_PTR_TO_DYNPTR)
2901 spi = dynptr_get_spi(env, reg);
2904 /* Caller ensures dynptr is valid and initialized, which means spi is in
2905 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2908 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2909 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2912 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2913 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2916 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2917 int spi, int nr_slots)
2919 struct bpf_func_state *state = func(env, reg);
2922 for (i = 0; i < nr_slots; i++) {
2923 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2925 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2929 mark_stack_slot_scratched(env, spi - i);
2935 /* This function is supposed to be used by the following 32-bit optimization
2936 * code only. It returns TRUE if the source or destination register operates
2937 * on 64-bit, otherwise return FALSE.
2939 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2940 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2945 class = BPF_CLASS(code);
2947 if (class == BPF_JMP) {
2948 /* BPF_EXIT for "main" will reach here. Return TRUE
2953 if (op == BPF_CALL) {
2954 /* BPF to BPF call will reach here because of marking
2955 * caller saved clobber with DST_OP_NO_MARK for which we
2956 * don't care the register def because they are anyway
2957 * marked as NOT_INIT already.
2959 if (insn->src_reg == BPF_PSEUDO_CALL)
2961 /* Helper call will reach here because of arg type
2962 * check, conservatively return TRUE.
2971 if (class == BPF_ALU64 || class == BPF_JMP ||
2972 /* BPF_END always use BPF_ALU class. */
2973 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2976 if (class == BPF_ALU || class == BPF_JMP32)
2979 if (class == BPF_LDX) {
2981 return BPF_SIZE(code) == BPF_DW;
2982 /* LDX source must be ptr. */
2986 if (class == BPF_STX) {
2987 /* BPF_STX (including atomic variants) has multiple source
2988 * operands, one of which is a ptr. Check whether the caller is
2991 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2993 return BPF_SIZE(code) == BPF_DW;
2996 if (class == BPF_LD) {
2997 u8 mode = BPF_MODE(code);
3000 if (mode == BPF_IMM)
3003 /* Both LD_IND and LD_ABS return 32-bit data. */
3007 /* Implicit ctx ptr. */
3008 if (regno == BPF_REG_6)
3011 /* Explicit source could be any width. */
3015 if (class == BPF_ST)
3016 /* The only source register for BPF_ST is a ptr. */
3019 /* Conservatively return true at default. */
3023 /* Return the regno defined by the insn, or -1. */
3024 static int insn_def_regno(const struct bpf_insn *insn)
3026 switch (BPF_CLASS(insn->code)) {
3032 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3033 (insn->imm & BPF_FETCH)) {
3034 if (insn->imm == BPF_CMPXCHG)
3037 return insn->src_reg;
3042 return insn->dst_reg;
3046 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3047 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3049 int dst_reg = insn_def_regno(insn);
3054 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3057 static void mark_insn_zext(struct bpf_verifier_env *env,
3058 struct bpf_reg_state *reg)
3060 s32 def_idx = reg->subreg_def;
3062 if (def_idx == DEF_NOT_SUBREG)
3065 env->insn_aux_data[def_idx - 1].zext_dst = true;
3066 /* The dst will be zero extended, so won't be sub-register anymore. */
3067 reg->subreg_def = DEF_NOT_SUBREG;
3070 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3071 enum reg_arg_type t)
3073 struct bpf_verifier_state *vstate = env->cur_state;
3074 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3075 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3076 struct bpf_reg_state *reg, *regs = state->regs;
3079 if (regno >= MAX_BPF_REG) {
3080 verbose(env, "R%d is invalid\n", regno);
3084 mark_reg_scratched(env, regno);
3087 rw64 = is_reg64(env, insn, regno, reg, t);
3089 /* check whether register used as source operand can be read */
3090 if (reg->type == NOT_INIT) {
3091 verbose(env, "R%d !read_ok\n", regno);
3094 /* We don't need to worry about FP liveness because it's read-only */
3095 if (regno == BPF_REG_FP)
3099 mark_insn_zext(env, reg);
3101 return mark_reg_read(env, reg, reg->parent,
3102 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3104 /* check whether register used as dest operand can be written to */
3105 if (regno == BPF_REG_FP) {
3106 verbose(env, "frame pointer is read only\n");
3109 reg->live |= REG_LIVE_WRITTEN;
3110 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3112 mark_reg_unknown(env, regs, regno);
3117 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3119 env->insn_aux_data[idx].jmp_point = true;
3122 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3124 return env->insn_aux_data[insn_idx].jmp_point;
3127 /* for any branch, call, exit record the history of jmps in the given state */
3128 static int push_jmp_history(struct bpf_verifier_env *env,
3129 struct bpf_verifier_state *cur)
3131 u32 cnt = cur->jmp_history_cnt;
3132 struct bpf_idx_pair *p;
3135 if (!is_jmp_point(env, env->insn_idx))
3139 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3140 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3143 p[cnt - 1].idx = env->insn_idx;
3144 p[cnt - 1].prev_idx = env->prev_insn_idx;
3145 cur->jmp_history = p;
3146 cur->jmp_history_cnt = cnt;
3150 /* Backtrack one insn at a time. If idx is not at the top of recorded
3151 * history then previous instruction came from straight line execution.
3153 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3158 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3159 i = st->jmp_history[cnt - 1].prev_idx;
3167 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3169 const struct btf_type *func;
3170 struct btf *desc_btf;
3172 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3175 desc_btf = find_kfunc_desc_btf(data, insn->off);
3176 if (IS_ERR(desc_btf))
3179 func = btf_type_by_id(desc_btf, insn->imm);
3180 return btf_name_by_offset(desc_btf, func->name_off);
3183 /* For given verifier state backtrack_insn() is called from the last insn to
3184 * the first insn. Its purpose is to compute a bitmask of registers and
3185 * stack slots that needs precision in the parent verifier state.
3187 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
3188 u32 *reg_mask, u64 *stack_mask)
3190 const struct bpf_insn_cbs cbs = {
3191 .cb_call = disasm_kfunc_name,
3192 .cb_print = verbose,
3193 .private_data = env,
3195 struct bpf_insn *insn = env->prog->insnsi + idx;
3196 u8 class = BPF_CLASS(insn->code);
3197 u8 opcode = BPF_OP(insn->code);
3198 u8 mode = BPF_MODE(insn->code);
3199 u32 dreg = 1u << insn->dst_reg;
3200 u32 sreg = 1u << insn->src_reg;
3203 if (insn->code == 0)
3205 if (env->log.level & BPF_LOG_LEVEL2) {
3206 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
3207 verbose(env, "%d: ", idx);
3208 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3211 if (class == BPF_ALU || class == BPF_ALU64) {
3212 if (!(*reg_mask & dreg))
3214 if (opcode == BPF_MOV) {
3215 if (BPF_SRC(insn->code) == BPF_X) {
3217 * dreg needs precision after this insn
3218 * sreg needs precision before this insn
3224 * dreg needs precision after this insn.
3225 * Corresponding register is already marked
3226 * as precise=true in this verifier state.
3227 * No further markings in parent are necessary
3232 if (BPF_SRC(insn->code) == BPF_X) {
3234 * both dreg and sreg need precision
3239 * dreg still needs precision before this insn
3242 } else if (class == BPF_LDX) {
3243 if (!(*reg_mask & dreg))
3247 /* scalars can only be spilled into stack w/o losing precision.
3248 * Load from any other memory can be zero extended.
3249 * The desire to keep that precision is already indicated
3250 * by 'precise' mark in corresponding register of this state.
3251 * No further tracking necessary.
3253 if (insn->src_reg != BPF_REG_FP)
3256 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3257 * that [fp - off] slot contains scalar that needs to be
3258 * tracked with precision
3260 spi = (-insn->off - 1) / BPF_REG_SIZE;
3262 verbose(env, "BUG spi %d\n", spi);
3263 WARN_ONCE(1, "verifier backtracking bug");
3266 *stack_mask |= 1ull << spi;
3267 } else if (class == BPF_STX || class == BPF_ST) {
3268 if (*reg_mask & dreg)
3269 /* stx & st shouldn't be using _scalar_ dst_reg
3270 * to access memory. It means backtracking
3271 * encountered a case of pointer subtraction.
3274 /* scalars can only be spilled into stack */
3275 if (insn->dst_reg != BPF_REG_FP)
3277 spi = (-insn->off - 1) / BPF_REG_SIZE;
3279 verbose(env, "BUG spi %d\n", spi);
3280 WARN_ONCE(1, "verifier backtracking bug");
3283 if (!(*stack_mask & (1ull << spi)))
3285 *stack_mask &= ~(1ull << spi);
3286 if (class == BPF_STX)
3288 } else if (class == BPF_JMP || class == BPF_JMP32) {
3289 if (opcode == BPF_CALL) {
3290 if (insn->src_reg == BPF_PSEUDO_CALL)
3292 /* BPF helpers that invoke callback subprogs are
3293 * equivalent to BPF_PSEUDO_CALL above
3295 if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
3297 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3298 * catch this error later. Make backtracking conservative
3301 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3303 /* regular helper call sets R0 */
3305 if (*reg_mask & 0x3f) {
3306 /* if backtracing was looking for registers R1-R5
3307 * they should have been found already.
3309 verbose(env, "BUG regs %x\n", *reg_mask);
3310 WARN_ONCE(1, "verifier backtracking bug");
3313 } else if (opcode == BPF_EXIT) {
3316 } else if (class == BPF_LD) {
3317 if (!(*reg_mask & dreg))
3320 /* It's ld_imm64 or ld_abs or ld_ind.
3321 * For ld_imm64 no further tracking of precision
3322 * into parent is necessary
3324 if (mode == BPF_IND || mode == BPF_ABS)
3325 /* to be analyzed */
3331 /* the scalar precision tracking algorithm:
3332 * . at the start all registers have precise=false.
3333 * . scalar ranges are tracked as normal through alu and jmp insns.
3334 * . once precise value of the scalar register is used in:
3335 * . ptr + scalar alu
3336 * . if (scalar cond K|scalar)
3337 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3338 * backtrack through the verifier states and mark all registers and
3339 * stack slots with spilled constants that these scalar regisers
3340 * should be precise.
3341 * . during state pruning two registers (or spilled stack slots)
3342 * are equivalent if both are not precise.
3344 * Note the verifier cannot simply walk register parentage chain,
3345 * since many different registers and stack slots could have been
3346 * used to compute single precise scalar.
3348 * The approach of starting with precise=true for all registers and then
3349 * backtrack to mark a register as not precise when the verifier detects
3350 * that program doesn't care about specific value (e.g., when helper
3351 * takes register as ARG_ANYTHING parameter) is not safe.
3353 * It's ok to walk single parentage chain of the verifier states.
3354 * It's possible that this backtracking will go all the way till 1st insn.
3355 * All other branches will be explored for needing precision later.
3357 * The backtracking needs to deal with cases like:
3358 * 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)
3361 * if r5 > 0x79f goto pc+7
3362 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3365 * call bpf_perf_event_output#25
3366 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3370 * call foo // uses callee's r6 inside to compute r0
3374 * to track above reg_mask/stack_mask needs to be independent for each frame.
3376 * Also if parent's curframe > frame where backtracking started,
3377 * the verifier need to mark registers in both frames, otherwise callees
3378 * may incorrectly prune callers. This is similar to
3379 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3381 * For now backtracking falls back into conservative marking.
3383 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3384 struct bpf_verifier_state *st)
3386 struct bpf_func_state *func;
3387 struct bpf_reg_state *reg;
3390 /* big hammer: mark all scalars precise in this path.
3391 * pop_stack may still get !precise scalars.
3392 * We also skip current state and go straight to first parent state,
3393 * because precision markings in current non-checkpointed state are
3394 * not needed. See why in the comment in __mark_chain_precision below.
3396 for (st = st->parent; st; st = st->parent) {
3397 for (i = 0; i <= st->curframe; i++) {
3398 func = st->frame[i];
3399 for (j = 0; j < BPF_REG_FP; j++) {
3400 reg = &func->regs[j];
3401 if (reg->type != SCALAR_VALUE)
3403 reg->precise = true;
3405 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3406 if (!is_spilled_reg(&func->stack[j]))
3408 reg = &func->stack[j].spilled_ptr;
3409 if (reg->type != SCALAR_VALUE)
3411 reg->precise = true;
3417 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3419 struct bpf_func_state *func;
3420 struct bpf_reg_state *reg;
3423 for (i = 0; i <= st->curframe; i++) {
3424 func = st->frame[i];
3425 for (j = 0; j < BPF_REG_FP; j++) {
3426 reg = &func->regs[j];
3427 if (reg->type != SCALAR_VALUE)
3429 reg->precise = false;
3431 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3432 if (!is_spilled_reg(&func->stack[j]))
3434 reg = &func->stack[j].spilled_ptr;
3435 if (reg->type != SCALAR_VALUE)
3437 reg->precise = false;
3443 * __mark_chain_precision() backtracks BPF program instruction sequence and
3444 * chain of verifier states making sure that register *regno* (if regno >= 0)
3445 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3446 * SCALARS, as well as any other registers and slots that contribute to
3447 * a tracked state of given registers/stack slots, depending on specific BPF
3448 * assembly instructions (see backtrack_insns() for exact instruction handling
3449 * logic). This backtracking relies on recorded jmp_history and is able to
3450 * traverse entire chain of parent states. This process ends only when all the
3451 * necessary registers/slots and their transitive dependencies are marked as
3454 * One important and subtle aspect is that precise marks *do not matter* in
3455 * the currently verified state (current state). It is important to understand
3456 * why this is the case.
3458 * First, note that current state is the state that is not yet "checkpointed",
3459 * i.e., it is not yet put into env->explored_states, and it has no children
3460 * states as well. It's ephemeral, and can end up either a) being discarded if
3461 * compatible explored state is found at some point or BPF_EXIT instruction is
3462 * reached or b) checkpointed and put into env->explored_states, branching out
3463 * into one or more children states.
3465 * In the former case, precise markings in current state are completely
3466 * ignored by state comparison code (see regsafe() for details). Only
3467 * checkpointed ("old") state precise markings are important, and if old
3468 * state's register/slot is precise, regsafe() assumes current state's
3469 * register/slot as precise and checks value ranges exactly and precisely. If
3470 * states turn out to be compatible, current state's necessary precise
3471 * markings and any required parent states' precise markings are enforced
3472 * after the fact with propagate_precision() logic, after the fact. But it's
3473 * important to realize that in this case, even after marking current state
3474 * registers/slots as precise, we immediately discard current state. So what
3475 * actually matters is any of the precise markings propagated into current
3476 * state's parent states, which are always checkpointed (due to b) case above).
3477 * As such, for scenario a) it doesn't matter if current state has precise
3478 * markings set or not.
3480 * Now, for the scenario b), checkpointing and forking into child(ren)
3481 * state(s). Note that before current state gets to checkpointing step, any
3482 * processed instruction always assumes precise SCALAR register/slot
3483 * knowledge: if precise value or range is useful to prune jump branch, BPF
3484 * verifier takes this opportunity enthusiastically. Similarly, when
3485 * register's value is used to calculate offset or memory address, exact
3486 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3487 * what we mentioned above about state comparison ignoring precise markings
3488 * during state comparison, BPF verifier ignores and also assumes precise
3489 * markings *at will* during instruction verification process. But as verifier
3490 * assumes precision, it also propagates any precision dependencies across
3491 * parent states, which are not yet finalized, so can be further restricted
3492 * based on new knowledge gained from restrictions enforced by their children
3493 * states. This is so that once those parent states are finalized, i.e., when
3494 * they have no more active children state, state comparison logic in
3495 * is_state_visited() would enforce strict and precise SCALAR ranges, if
3496 * required for correctness.
3498 * To build a bit more intuition, note also that once a state is checkpointed,
3499 * the path we took to get to that state is not important. This is crucial
3500 * property for state pruning. When state is checkpointed and finalized at
3501 * some instruction index, it can be correctly and safely used to "short
3502 * circuit" any *compatible* state that reaches exactly the same instruction
3503 * index. I.e., if we jumped to that instruction from a completely different
3504 * code path than original finalized state was derived from, it doesn't
3505 * matter, current state can be discarded because from that instruction
3506 * forward having a compatible state will ensure we will safely reach the
3507 * exit. States describe preconditions for further exploration, but completely
3508 * forget the history of how we got here.
3510 * This also means that even if we needed precise SCALAR range to get to
3511 * finalized state, but from that point forward *that same* SCALAR register is
3512 * never used in a precise context (i.e., it's precise value is not needed for
3513 * correctness), it's correct and safe to mark such register as "imprecise"
3514 * (i.e., precise marking set to false). This is what we rely on when we do
3515 * not set precise marking in current state. If no child state requires
3516 * precision for any given SCALAR register, it's safe to dictate that it can
3517 * be imprecise. If any child state does require this register to be precise,
3518 * we'll mark it precise later retroactively during precise markings
3519 * propagation from child state to parent states.
3521 * Skipping precise marking setting in current state is a mild version of
3522 * relying on the above observation. But we can utilize this property even
3523 * more aggressively by proactively forgetting any precise marking in the
3524 * current state (which we inherited from the parent state), right before we
3525 * checkpoint it and branch off into new child state. This is done by
3526 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3527 * finalized states which help in short circuiting more future states.
3529 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
3532 struct bpf_verifier_state *st = env->cur_state;
3533 int first_idx = st->first_insn_idx;
3534 int last_idx = env->insn_idx;
3535 struct bpf_func_state *func;
3536 struct bpf_reg_state *reg;
3537 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
3538 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
3539 bool skip_first = true;
3540 bool new_marks = false;
3543 if (!env->bpf_capable)
3546 /* Do sanity checks against current state of register and/or stack
3547 * slot, but don't set precise flag in current state, as precision
3548 * tracking in the current state is unnecessary.
3550 func = st->frame[frame];
3552 reg = &func->regs[regno];
3553 if (reg->type != SCALAR_VALUE) {
3554 WARN_ONCE(1, "backtracing misuse");
3561 if (!is_spilled_reg(&func->stack[spi])) {
3565 reg = &func->stack[spi].spilled_ptr;
3566 if (reg->type != SCALAR_VALUE) {
3576 if (!reg_mask && !stack_mask)
3580 DECLARE_BITMAP(mask, 64);
3581 u32 history = st->jmp_history_cnt;
3583 if (env->log.level & BPF_LOG_LEVEL2)
3584 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3587 /* we are at the entry into subprog, which
3588 * is expected for global funcs, but only if
3589 * requested precise registers are R1-R5
3590 * (which are global func's input arguments)
3592 if (st->curframe == 0 &&
3593 st->frame[0]->subprogno > 0 &&
3594 st->frame[0]->callsite == BPF_MAIN_FUNC &&
3595 stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3596 bitmap_from_u64(mask, reg_mask);
3597 for_each_set_bit(i, mask, 32) {
3598 reg = &st->frame[0]->regs[i];
3599 if (reg->type != SCALAR_VALUE) {
3600 reg_mask &= ~(1u << i);
3603 reg->precise = true;
3608 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3609 st->frame[0]->subprogno, reg_mask, stack_mask);
3610 WARN_ONCE(1, "verifier backtracking bug");
3614 for (i = last_idx;;) {
3619 err = backtrack_insn(env, i, ®_mask, &stack_mask);
3621 if (err == -ENOTSUPP) {
3622 mark_all_scalars_precise(env, st);
3627 if (!reg_mask && !stack_mask)
3628 /* Found assignment(s) into tracked register in this state.
3629 * Since this state is already marked, just return.
3630 * Nothing to be tracked further in the parent state.
3635 i = get_prev_insn_idx(st, i, &history);
3636 if (i >= env->prog->len) {
3637 /* This can happen if backtracking reached insn 0
3638 * and there are still reg_mask or stack_mask
3640 * It means the backtracking missed the spot where
3641 * particular register was initialized with a constant.
3643 verbose(env, "BUG backtracking idx %d\n", i);
3644 WARN_ONCE(1, "verifier backtracking bug");
3653 func = st->frame[frame];
3654 bitmap_from_u64(mask, reg_mask);
3655 for_each_set_bit(i, mask, 32) {
3656 reg = &func->regs[i];
3657 if (reg->type != SCALAR_VALUE) {
3658 reg_mask &= ~(1u << i);
3663 reg->precise = true;
3666 bitmap_from_u64(mask, stack_mask);
3667 for_each_set_bit(i, mask, 64) {
3668 if (i >= func->allocated_stack / BPF_REG_SIZE) {
3669 /* the sequence of instructions:
3671 * 3: (7b) *(u64 *)(r3 -8) = r0
3672 * 4: (79) r4 = *(u64 *)(r10 -8)
3673 * doesn't contain jmps. It's backtracked
3674 * as a single block.
3675 * During backtracking insn 3 is not recognized as
3676 * stack access, so at the end of backtracking
3677 * stack slot fp-8 is still marked in stack_mask.
3678 * However the parent state may not have accessed
3679 * fp-8 and it's "unallocated" stack space.
3680 * In such case fallback to conservative.
3682 mark_all_scalars_precise(env, st);
3686 if (!is_spilled_reg(&func->stack[i])) {
3687 stack_mask &= ~(1ull << i);
3690 reg = &func->stack[i].spilled_ptr;
3691 if (reg->type != SCALAR_VALUE) {
3692 stack_mask &= ~(1ull << i);
3697 reg->precise = true;
3699 if (env->log.level & BPF_LOG_LEVEL2) {
3700 verbose(env, "parent %s regs=%x stack=%llx marks:",
3701 new_marks ? "didn't have" : "already had",
3702 reg_mask, stack_mask);
3703 print_verifier_state(env, func, true);
3706 if (!reg_mask && !stack_mask)
3711 last_idx = st->last_insn_idx;
3712 first_idx = st->first_insn_idx;
3717 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3719 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3722 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3724 return __mark_chain_precision(env, frame, regno, -1);
3727 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3729 return __mark_chain_precision(env, frame, -1, spi);
3732 static bool is_spillable_regtype(enum bpf_reg_type type)
3734 switch (base_type(type)) {
3735 case PTR_TO_MAP_VALUE:
3739 case PTR_TO_PACKET_META:
3740 case PTR_TO_PACKET_END:
3741 case PTR_TO_FLOW_KEYS:
3742 case CONST_PTR_TO_MAP:
3744 case PTR_TO_SOCK_COMMON:
3745 case PTR_TO_TCP_SOCK:
3746 case PTR_TO_XDP_SOCK:
3751 case PTR_TO_MAP_KEY:
3758 /* Does this register contain a constant zero? */
3759 static bool register_is_null(struct bpf_reg_state *reg)
3761 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3764 static bool register_is_const(struct bpf_reg_state *reg)
3766 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3769 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3771 return tnum_is_unknown(reg->var_off) &&
3772 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3773 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3774 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3775 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3778 static bool register_is_bounded(struct bpf_reg_state *reg)
3780 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3783 static bool __is_pointer_value(bool allow_ptr_leaks,
3784 const struct bpf_reg_state *reg)
3786 if (allow_ptr_leaks)
3789 return reg->type != SCALAR_VALUE;
3792 /* Copy src state preserving dst->parent and dst->live fields */
3793 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3795 struct bpf_reg_state *parent = dst->parent;
3796 enum bpf_reg_liveness live = dst->live;
3799 dst->parent = parent;
3803 static void save_register_state(struct bpf_func_state *state,
3804 int spi, struct bpf_reg_state *reg,
3809 copy_register_state(&state->stack[spi].spilled_ptr, reg);
3810 if (size == BPF_REG_SIZE)
3811 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3813 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3814 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3816 /* size < 8 bytes spill */
3818 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3821 static bool is_bpf_st_mem(struct bpf_insn *insn)
3823 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3826 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3827 * stack boundary and alignment are checked in check_mem_access()
3829 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3830 /* stack frame we're writing to */
3831 struct bpf_func_state *state,
3832 int off, int size, int value_regno,
3835 struct bpf_func_state *cur; /* state of the current function */
3836 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3837 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3838 struct bpf_reg_state *reg = NULL;
3839 u32 dst_reg = insn->dst_reg;
3841 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3844 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3845 * so it's aligned access and [off, off + size) are within stack limits
3847 if (!env->allow_ptr_leaks &&
3848 state->stack[spi].slot_type[0] == STACK_SPILL &&
3849 size != BPF_REG_SIZE) {
3850 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3854 cur = env->cur_state->frame[env->cur_state->curframe];
3855 if (value_regno >= 0)
3856 reg = &cur->regs[value_regno];
3857 if (!env->bypass_spec_v4) {
3858 bool sanitize = reg && is_spillable_regtype(reg->type);
3860 for (i = 0; i < size; i++) {
3861 u8 type = state->stack[spi].slot_type[i];
3863 if (type != STACK_MISC && type != STACK_ZERO) {
3870 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3873 err = destroy_if_dynptr_stack_slot(env, state, spi);
3877 mark_stack_slot_scratched(env, spi);
3878 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3879 !register_is_null(reg) && env->bpf_capable) {
3880 if (dst_reg != BPF_REG_FP) {
3881 /* The backtracking logic can only recognize explicit
3882 * stack slot address like [fp - 8]. Other spill of
3883 * scalar via different register has to be conservative.
3884 * Backtrack from here and mark all registers as precise
3885 * that contributed into 'reg' being a constant.
3887 err = mark_chain_precision(env, value_regno);
3891 save_register_state(state, spi, reg, size);
3892 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3893 insn->imm != 0 && env->bpf_capable) {
3894 struct bpf_reg_state fake_reg = {};
3896 __mark_reg_known(&fake_reg, (u32)insn->imm);
3897 fake_reg.type = SCALAR_VALUE;
3898 save_register_state(state, spi, &fake_reg, size);
3899 } else if (reg && is_spillable_regtype(reg->type)) {
3900 /* register containing pointer is being spilled into stack */
3901 if (size != BPF_REG_SIZE) {
3902 verbose_linfo(env, insn_idx, "; ");
3903 verbose(env, "invalid size of register spill\n");
3906 if (state != cur && reg->type == PTR_TO_STACK) {
3907 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3910 save_register_state(state, spi, reg, size);
3912 u8 type = STACK_MISC;
3914 /* regular write of data into stack destroys any spilled ptr */
3915 state->stack[spi].spilled_ptr.type = NOT_INIT;
3916 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
3917 if (is_stack_slot_special(&state->stack[spi]))
3918 for (i = 0; i < BPF_REG_SIZE; i++)
3919 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3921 /* only mark the slot as written if all 8 bytes were written
3922 * otherwise read propagation may incorrectly stop too soon
3923 * when stack slots are partially written.
3924 * This heuristic means that read propagation will be
3925 * conservative, since it will add reg_live_read marks
3926 * to stack slots all the way to first state when programs
3927 * writes+reads less than 8 bytes
3929 if (size == BPF_REG_SIZE)
3930 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3932 /* when we zero initialize stack slots mark them as such */
3933 if ((reg && register_is_null(reg)) ||
3934 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3935 /* backtracking doesn't work for STACK_ZERO yet. */
3936 err = mark_chain_precision(env, value_regno);
3942 /* Mark slots affected by this stack write. */
3943 for (i = 0; i < size; i++)
3944 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3950 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3951 * known to contain a variable offset.
3952 * This function checks whether the write is permitted and conservatively
3953 * tracks the effects of the write, considering that each stack slot in the
3954 * dynamic range is potentially written to.
3956 * 'off' includes 'regno->off'.
3957 * 'value_regno' can be -1, meaning that an unknown value is being written to
3960 * Spilled pointers in range are not marked as written because we don't know
3961 * what's going to be actually written. This means that read propagation for
3962 * future reads cannot be terminated by this write.
3964 * For privileged programs, uninitialized stack slots are considered
3965 * initialized by this write (even though we don't know exactly what offsets
3966 * are going to be written to). The idea is that we don't want the verifier to
3967 * reject future reads that access slots written to through variable offsets.
3969 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3970 /* func where register points to */
3971 struct bpf_func_state *state,
3972 int ptr_regno, int off, int size,
3973 int value_regno, int insn_idx)
3975 struct bpf_func_state *cur; /* state of the current function */
3976 int min_off, max_off;
3978 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3979 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3980 bool writing_zero = false;
3981 /* set if the fact that we're writing a zero is used to let any
3982 * stack slots remain STACK_ZERO
3984 bool zero_used = false;
3986 cur = env->cur_state->frame[env->cur_state->curframe];
3987 ptr_reg = &cur->regs[ptr_regno];
3988 min_off = ptr_reg->smin_value + off;
3989 max_off = ptr_reg->smax_value + off + size;
3990 if (value_regno >= 0)
3991 value_reg = &cur->regs[value_regno];
3992 if ((value_reg && register_is_null(value_reg)) ||
3993 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
3994 writing_zero = true;
3996 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4000 for (i = min_off; i < max_off; i++) {
4004 err = destroy_if_dynptr_stack_slot(env, state, spi);
4009 /* Variable offset writes destroy any spilled pointers in range. */
4010 for (i = min_off; i < max_off; i++) {
4011 u8 new_type, *stype;
4015 spi = slot / BPF_REG_SIZE;
4016 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4017 mark_stack_slot_scratched(env, spi);
4019 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4020 /* Reject the write if range we may write to has not
4021 * been initialized beforehand. If we didn't reject
4022 * here, the ptr status would be erased below (even
4023 * though not all slots are actually overwritten),
4024 * possibly opening the door to leaks.
4026 * We do however catch STACK_INVALID case below, and
4027 * only allow reading possibly uninitialized memory
4028 * later for CAP_PERFMON, as the write may not happen to
4031 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4036 /* Erase all spilled pointers. */
4037 state->stack[spi].spilled_ptr.type = NOT_INIT;
4039 /* Update the slot type. */
4040 new_type = STACK_MISC;
4041 if (writing_zero && *stype == STACK_ZERO) {
4042 new_type = STACK_ZERO;
4045 /* If the slot is STACK_INVALID, we check whether it's OK to
4046 * pretend that it will be initialized by this write. The slot
4047 * might not actually be written to, and so if we mark it as
4048 * initialized future reads might leak uninitialized memory.
4049 * For privileged programs, we will accept such reads to slots
4050 * that may or may not be written because, if we're reject
4051 * them, the error would be too confusing.
4053 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4054 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4061 /* backtracking doesn't work for STACK_ZERO yet. */
4062 err = mark_chain_precision(env, value_regno);
4069 /* When register 'dst_regno' is assigned some values from stack[min_off,
4070 * max_off), we set the register's type according to the types of the
4071 * respective stack slots. If all the stack values are known to be zeros, then
4072 * so is the destination reg. Otherwise, the register is considered to be
4073 * SCALAR. This function does not deal with register filling; the caller must
4074 * ensure that all spilled registers in the stack range have been marked as
4077 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4078 /* func where src register points to */
4079 struct bpf_func_state *ptr_state,
4080 int min_off, int max_off, int dst_regno)
4082 struct bpf_verifier_state *vstate = env->cur_state;
4083 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4088 for (i = min_off; i < max_off; i++) {
4090 spi = slot / BPF_REG_SIZE;
4091 stype = ptr_state->stack[spi].slot_type;
4092 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4096 if (zeros == max_off - min_off) {
4097 /* any access_size read into register is zero extended,
4098 * so the whole register == const_zero
4100 __mark_reg_const_zero(&state->regs[dst_regno]);
4101 /* backtracking doesn't support STACK_ZERO yet,
4102 * so mark it precise here, so that later
4103 * backtracking can stop here.
4104 * Backtracking may not need this if this register
4105 * doesn't participate in pointer adjustment.
4106 * Forward propagation of precise flag is not
4107 * necessary either. This mark is only to stop
4108 * backtracking. Any register that contributed
4109 * to const 0 was marked precise before spill.
4111 state->regs[dst_regno].precise = true;
4113 /* have read misc data from the stack */
4114 mark_reg_unknown(env, state->regs, dst_regno);
4116 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4119 /* Read the stack at 'off' and put the results into the register indicated by
4120 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4123 * 'dst_regno' can be -1, meaning that the read value is not going to a
4126 * The access is assumed to be within the current stack bounds.
4128 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4129 /* func where src register points to */
4130 struct bpf_func_state *reg_state,
4131 int off, int size, int dst_regno)
4133 struct bpf_verifier_state *vstate = env->cur_state;
4134 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4135 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4136 struct bpf_reg_state *reg;
4139 stype = reg_state->stack[spi].slot_type;
4140 reg = ®_state->stack[spi].spilled_ptr;
4142 if (is_spilled_reg(®_state->stack[spi])) {
4145 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4148 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4149 if (reg->type != SCALAR_VALUE) {
4150 verbose_linfo(env, env->insn_idx, "; ");
4151 verbose(env, "invalid size of register fill\n");
4155 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4159 if (!(off % BPF_REG_SIZE) && size == spill_size) {
4160 /* The earlier check_reg_arg() has decided the
4161 * subreg_def for this insn. Save it first.
4163 s32 subreg_def = state->regs[dst_regno].subreg_def;
4165 copy_register_state(&state->regs[dst_regno], reg);
4166 state->regs[dst_regno].subreg_def = subreg_def;
4168 for (i = 0; i < size; i++) {
4169 type = stype[(slot - i) % BPF_REG_SIZE];
4170 if (type == STACK_SPILL)
4172 if (type == STACK_MISC)
4174 if (type == STACK_INVALID && env->allow_uninit_stack)
4176 verbose(env, "invalid read from stack off %d+%d size %d\n",
4180 mark_reg_unknown(env, state->regs, dst_regno);
4182 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4186 if (dst_regno >= 0) {
4187 /* restore register state from stack */
4188 copy_register_state(&state->regs[dst_regno], reg);
4189 /* mark reg as written since spilled pointer state likely
4190 * has its liveness marks cleared by is_state_visited()
4191 * which resets stack/reg liveness for state transitions
4193 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4194 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4195 /* If dst_regno==-1, the caller is asking us whether
4196 * it is acceptable to use this value as a SCALAR_VALUE
4198 * We must not allow unprivileged callers to do that
4199 * with spilled pointers.
4201 verbose(env, "leaking pointer from stack off %d\n",
4205 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4207 for (i = 0; i < size; i++) {
4208 type = stype[(slot - i) % BPF_REG_SIZE];
4209 if (type == STACK_MISC)
4211 if (type == STACK_ZERO)
4213 if (type == STACK_INVALID && env->allow_uninit_stack)
4215 verbose(env, "invalid read from stack off %d+%d size %d\n",
4219 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4221 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4226 enum bpf_access_src {
4227 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4228 ACCESS_HELPER = 2, /* the access is performed by a helper */
4231 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4232 int regno, int off, int access_size,
4233 bool zero_size_allowed,
4234 enum bpf_access_src type,
4235 struct bpf_call_arg_meta *meta);
4237 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4239 return cur_regs(env) + regno;
4242 /* Read the stack at 'ptr_regno + off' and put the result into the register
4244 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4245 * but not its variable offset.
4246 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4248 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4249 * filling registers (i.e. reads of spilled register cannot be detected when
4250 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4251 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4252 * offset; for a fixed offset check_stack_read_fixed_off should be used
4255 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4256 int ptr_regno, int off, int size, int dst_regno)
4258 /* The state of the source register. */
4259 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4260 struct bpf_func_state *ptr_state = func(env, reg);
4262 int min_off, max_off;
4264 /* Note that we pass a NULL meta, so raw access will not be permitted.
4266 err = check_stack_range_initialized(env, ptr_regno, off, size,
4267 false, ACCESS_DIRECT, NULL);
4271 min_off = reg->smin_value + off;
4272 max_off = reg->smax_value + off;
4273 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4277 /* check_stack_read dispatches to check_stack_read_fixed_off or
4278 * check_stack_read_var_off.
4280 * The caller must ensure that the offset falls within the allocated stack
4283 * 'dst_regno' is a register which will receive the value from the stack. It
4284 * can be -1, meaning that the read value is not going to a register.
4286 static int check_stack_read(struct bpf_verifier_env *env,
4287 int ptr_regno, int off, int size,
4290 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4291 struct bpf_func_state *state = func(env, reg);
4293 /* Some accesses are only permitted with a static offset. */
4294 bool var_off = !tnum_is_const(reg->var_off);
4296 /* The offset is required to be static when reads don't go to a
4297 * register, in order to not leak pointers (see
4298 * check_stack_read_fixed_off).
4300 if (dst_regno < 0 && var_off) {
4303 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4304 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4308 /* Variable offset is prohibited for unprivileged mode for simplicity
4309 * since it requires corresponding support in Spectre masking for stack
4310 * ALU. See also retrieve_ptr_limit(). The check in
4311 * check_stack_access_for_ptr_arithmetic() called by
4312 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4313 * with variable offsets, therefore no check is required here. Further,
4314 * just checking it here would be insufficient as speculative stack
4315 * writes could still lead to unsafe speculative behaviour.
4318 off += reg->var_off.value;
4319 err = check_stack_read_fixed_off(env, state, off, size,
4322 /* Variable offset stack reads need more conservative handling
4323 * than fixed offset ones. Note that dst_regno >= 0 on this
4326 err = check_stack_read_var_off(env, ptr_regno, off, size,
4333 /* check_stack_write dispatches to check_stack_write_fixed_off or
4334 * check_stack_write_var_off.
4336 * 'ptr_regno' is the register used as a pointer into the stack.
4337 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4338 * 'value_regno' is the register whose value we're writing to the stack. It can
4339 * be -1, meaning that we're not writing from a register.
4341 * The caller must ensure that the offset falls within the maximum stack size.
4343 static int check_stack_write(struct bpf_verifier_env *env,
4344 int ptr_regno, int off, int size,
4345 int value_regno, int insn_idx)
4347 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4348 struct bpf_func_state *state = func(env, reg);
4351 if (tnum_is_const(reg->var_off)) {
4352 off += reg->var_off.value;
4353 err = check_stack_write_fixed_off(env, state, off, size,
4354 value_regno, insn_idx);
4356 /* Variable offset stack reads need more conservative handling
4357 * than fixed offset ones.
4359 err = check_stack_write_var_off(env, state,
4360 ptr_regno, off, size,
4361 value_regno, insn_idx);
4366 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4367 int off, int size, enum bpf_access_type type)
4369 struct bpf_reg_state *regs = cur_regs(env);
4370 struct bpf_map *map = regs[regno].map_ptr;
4371 u32 cap = bpf_map_flags_to_cap(map);
4373 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4374 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4375 map->value_size, off, size);
4379 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4380 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4381 map->value_size, off, size);
4388 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4389 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4390 int off, int size, u32 mem_size,
4391 bool zero_size_allowed)
4393 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4394 struct bpf_reg_state *reg;
4396 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4399 reg = &cur_regs(env)[regno];
4400 switch (reg->type) {
4401 case PTR_TO_MAP_KEY:
4402 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4403 mem_size, off, size);
4405 case PTR_TO_MAP_VALUE:
4406 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4407 mem_size, off, size);
4410 case PTR_TO_PACKET_META:
4411 case PTR_TO_PACKET_END:
4412 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4413 off, size, regno, reg->id, off, mem_size);
4417 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4418 mem_size, off, size);
4424 /* check read/write into a memory region with possible variable offset */
4425 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4426 int off, int size, u32 mem_size,
4427 bool zero_size_allowed)
4429 struct bpf_verifier_state *vstate = env->cur_state;
4430 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4431 struct bpf_reg_state *reg = &state->regs[regno];
4434 /* We may have adjusted the register pointing to memory region, so we
4435 * need to try adding each of min_value and max_value to off
4436 * to make sure our theoretical access will be safe.
4438 * The minimum value is only important with signed
4439 * comparisons where we can't assume the floor of a
4440 * value is 0. If we are using signed variables for our
4441 * index'es we need to make sure that whatever we use
4442 * will have a set floor within our range.
4444 if (reg->smin_value < 0 &&
4445 (reg->smin_value == S64_MIN ||
4446 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4447 reg->smin_value + off < 0)) {
4448 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4452 err = __check_mem_access(env, regno, reg->smin_value + off, size,
4453 mem_size, zero_size_allowed);
4455 verbose(env, "R%d min value is outside of the allowed memory range\n",
4460 /* If we haven't set a max value then we need to bail since we can't be
4461 * sure we won't do bad things.
4462 * If reg->umax_value + off could overflow, treat that as unbounded too.
4464 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4465 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4469 err = __check_mem_access(env, regno, reg->umax_value + off, size,
4470 mem_size, zero_size_allowed);
4472 verbose(env, "R%d max value is outside of the allowed memory range\n",
4480 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4481 const struct bpf_reg_state *reg, int regno,
4484 /* Access to this pointer-typed register or passing it to a helper
4485 * is only allowed in its original, unmodified form.
4489 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4490 reg_type_str(env, reg->type), regno, reg->off);
4494 if (!fixed_off_ok && reg->off) {
4495 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4496 reg_type_str(env, reg->type), regno, reg->off);
4500 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4503 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4504 verbose(env, "variable %s access var_off=%s disallowed\n",
4505 reg_type_str(env, reg->type), tn_buf);
4512 int check_ptr_off_reg(struct bpf_verifier_env *env,
4513 const struct bpf_reg_state *reg, int regno)
4515 return __check_ptr_off_reg(env, reg, regno, false);
4518 static int map_kptr_match_type(struct bpf_verifier_env *env,
4519 struct btf_field *kptr_field,
4520 struct bpf_reg_state *reg, u32 regno)
4522 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4523 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4524 const char *reg_name = "";
4526 /* Only unreferenced case accepts untrusted pointers */
4527 if (kptr_field->type == BPF_KPTR_UNREF)
4528 perm_flags |= PTR_UNTRUSTED;
4530 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4533 if (!btf_is_kernel(reg->btf)) {
4534 verbose(env, "R%d must point to kernel BTF\n", regno);
4537 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
4538 reg_name = btf_type_name(reg->btf, reg->btf_id);
4540 /* For ref_ptr case, release function check should ensure we get one
4541 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4542 * normal store of unreferenced kptr, we must ensure var_off is zero.
4543 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4544 * reg->off and reg->ref_obj_id are not needed here.
4546 if (__check_ptr_off_reg(env, reg, regno, true))
4549 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
4550 * we also need to take into account the reg->off.
4552 * We want to support cases like:
4560 * v = func(); // PTR_TO_BTF_ID
4561 * val->foo = v; // reg->off is zero, btf and btf_id match type
4562 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4563 * // first member type of struct after comparison fails
4564 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4567 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
4568 * is zero. We must also ensure that btf_struct_ids_match does not walk
4569 * the struct to match type against first member of struct, i.e. reject
4570 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4571 * strict mode to true for type match.
4573 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4574 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4575 kptr_field->type == BPF_KPTR_REF))
4579 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4580 reg_type_str(env, reg->type), reg_name);
4581 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4582 if (kptr_field->type == BPF_KPTR_UNREF)
4583 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4590 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4591 * can dereference RCU protected pointers and result is PTR_TRUSTED.
4593 static bool in_rcu_cs(struct bpf_verifier_env *env)
4595 return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
4598 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4599 BTF_SET_START(rcu_protected_types)
4600 BTF_ID(struct, prog_test_ref_kfunc)
4601 BTF_ID(struct, cgroup)
4602 BTF_ID(struct, bpf_cpumask)
4603 BTF_ID(struct, task_struct)
4604 BTF_SET_END(rcu_protected_types)
4606 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4608 if (!btf_is_kernel(btf))
4610 return btf_id_set_contains(&rcu_protected_types, btf_id);
4613 static bool rcu_safe_kptr(const struct btf_field *field)
4615 const struct btf_field_kptr *kptr = &field->kptr;
4617 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
4620 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4621 int value_regno, int insn_idx,
4622 struct btf_field *kptr_field)
4624 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4625 int class = BPF_CLASS(insn->code);
4626 struct bpf_reg_state *val_reg;
4628 /* Things we already checked for in check_map_access and caller:
4629 * - Reject cases where variable offset may touch kptr
4630 * - size of access (must be BPF_DW)
4631 * - tnum_is_const(reg->var_off)
4632 * - kptr_field->offset == off + reg->var_off.value
4634 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4635 if (BPF_MODE(insn->code) != BPF_MEM) {
4636 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4640 /* We only allow loading referenced kptr, since it will be marked as
4641 * untrusted, similar to unreferenced kptr.
4643 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4644 verbose(env, "store to referenced kptr disallowed\n");
4648 if (class == BPF_LDX) {
4649 val_reg = reg_state(env, value_regno);
4650 /* We can simply mark the value_regno receiving the pointer
4651 * value from map as PTR_TO_BTF_ID, with the correct type.
4653 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4654 kptr_field->kptr.btf_id,
4655 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
4656 PTR_MAYBE_NULL | MEM_RCU :
4657 PTR_MAYBE_NULL | PTR_UNTRUSTED);
4658 /* For mark_ptr_or_null_reg */
4659 val_reg->id = ++env->id_gen;
4660 } else if (class == BPF_STX) {
4661 val_reg = reg_state(env, value_regno);
4662 if (!register_is_null(val_reg) &&
4663 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4665 } else if (class == BPF_ST) {
4667 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4668 kptr_field->offset);
4672 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4678 /* check read/write into a map element with possible variable offset */
4679 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4680 int off, int size, bool zero_size_allowed,
4681 enum bpf_access_src src)
4683 struct bpf_verifier_state *vstate = env->cur_state;
4684 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4685 struct bpf_reg_state *reg = &state->regs[regno];
4686 struct bpf_map *map = reg->map_ptr;
4687 struct btf_record *rec;
4690 err = check_mem_region_access(env, regno, off, size, map->value_size,
4695 if (IS_ERR_OR_NULL(map->record))
4698 for (i = 0; i < rec->cnt; i++) {
4699 struct btf_field *field = &rec->fields[i];
4700 u32 p = field->offset;
4702 /* If any part of a field can be touched by load/store, reject
4703 * this program. To check that [x1, x2) overlaps with [y1, y2),
4704 * it is sufficient to check x1 < y2 && y1 < x2.
4706 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4707 p < reg->umax_value + off + size) {
4708 switch (field->type) {
4709 case BPF_KPTR_UNREF:
4711 if (src != ACCESS_DIRECT) {
4712 verbose(env, "kptr cannot be accessed indirectly by helper\n");
4715 if (!tnum_is_const(reg->var_off)) {
4716 verbose(env, "kptr access cannot have variable offset\n");
4719 if (p != off + reg->var_off.value) {
4720 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4721 p, off + reg->var_off.value);
4724 if (size != bpf_size_to_bytes(BPF_DW)) {
4725 verbose(env, "kptr access size must be BPF_DW\n");
4730 verbose(env, "%s cannot be accessed directly by load/store\n",
4731 btf_field_type_name(field->type));
4739 #define MAX_PACKET_OFF 0xffff
4741 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4742 const struct bpf_call_arg_meta *meta,
4743 enum bpf_access_type t)
4745 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4747 switch (prog_type) {
4748 /* Program types only with direct read access go here! */
4749 case BPF_PROG_TYPE_LWT_IN:
4750 case BPF_PROG_TYPE_LWT_OUT:
4751 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4752 case BPF_PROG_TYPE_SK_REUSEPORT:
4753 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4754 case BPF_PROG_TYPE_CGROUP_SKB:
4759 /* Program types with direct read + write access go here! */
4760 case BPF_PROG_TYPE_SCHED_CLS:
4761 case BPF_PROG_TYPE_SCHED_ACT:
4762 case BPF_PROG_TYPE_XDP:
4763 case BPF_PROG_TYPE_LWT_XMIT:
4764 case BPF_PROG_TYPE_SK_SKB:
4765 case BPF_PROG_TYPE_SK_MSG:
4767 return meta->pkt_access;
4769 env->seen_direct_write = true;
4772 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4774 env->seen_direct_write = true;
4783 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4784 int size, bool zero_size_allowed)
4786 struct bpf_reg_state *regs = cur_regs(env);
4787 struct bpf_reg_state *reg = ®s[regno];
4790 /* We may have added a variable offset to the packet pointer; but any
4791 * reg->range we have comes after that. We are only checking the fixed
4795 /* We don't allow negative numbers, because we aren't tracking enough
4796 * detail to prove they're safe.
4798 if (reg->smin_value < 0) {
4799 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4804 err = reg->range < 0 ? -EINVAL :
4805 __check_mem_access(env, regno, off, size, reg->range,
4808 verbose(env, "R%d offset is outside of the packet\n", regno);
4812 /* __check_mem_access has made sure "off + size - 1" is within u16.
4813 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4814 * otherwise find_good_pkt_pointers would have refused to set range info
4815 * that __check_mem_access would have rejected this pkt access.
4816 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4818 env->prog->aux->max_pkt_offset =
4819 max_t(u32, env->prog->aux->max_pkt_offset,
4820 off + reg->umax_value + size - 1);
4825 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
4826 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4827 enum bpf_access_type t, enum bpf_reg_type *reg_type,
4828 struct btf **btf, u32 *btf_id)
4830 struct bpf_insn_access_aux info = {
4831 .reg_type = *reg_type,
4835 if (env->ops->is_valid_access &&
4836 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4837 /* A non zero info.ctx_field_size indicates that this field is a
4838 * candidate for later verifier transformation to load the whole
4839 * field and then apply a mask when accessed with a narrower
4840 * access than actual ctx access size. A zero info.ctx_field_size
4841 * will only allow for whole field access and rejects any other
4842 * type of narrower access.
4844 *reg_type = info.reg_type;
4846 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4848 *btf_id = info.btf_id;
4850 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4852 /* remember the offset of last byte accessed in ctx */
4853 if (env->prog->aux->max_ctx_offset < off + size)
4854 env->prog->aux->max_ctx_offset = off + size;
4858 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4862 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4865 if (size < 0 || off < 0 ||
4866 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4867 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4874 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4875 u32 regno, int off, int size,
4876 enum bpf_access_type t)
4878 struct bpf_reg_state *regs = cur_regs(env);
4879 struct bpf_reg_state *reg = ®s[regno];
4880 struct bpf_insn_access_aux info = {};
4883 if (reg->smin_value < 0) {
4884 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4889 switch (reg->type) {
4890 case PTR_TO_SOCK_COMMON:
4891 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4894 valid = bpf_sock_is_valid_access(off, size, t, &info);
4896 case PTR_TO_TCP_SOCK:
4897 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4899 case PTR_TO_XDP_SOCK:
4900 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4908 env->insn_aux_data[insn_idx].ctx_field_size =
4909 info.ctx_field_size;
4913 verbose(env, "R%d invalid %s access off=%d size=%d\n",
4914 regno, reg_type_str(env, reg->type), off, size);
4919 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4921 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4924 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4926 const struct bpf_reg_state *reg = reg_state(env, regno);
4928 return reg->type == PTR_TO_CTX;
4931 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4933 const struct bpf_reg_state *reg = reg_state(env, regno);
4935 return type_is_sk_pointer(reg->type);
4938 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4940 const struct bpf_reg_state *reg = reg_state(env, regno);
4942 return type_is_pkt_pointer(reg->type);
4945 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4947 const struct bpf_reg_state *reg = reg_state(env, regno);
4949 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4950 return reg->type == PTR_TO_FLOW_KEYS;
4953 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4955 /* A referenced register is always trusted. */
4956 if (reg->ref_obj_id)
4959 /* If a register is not referenced, it is trusted if it has the
4960 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4961 * other type modifiers may be safe, but we elect to take an opt-in
4962 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4965 * Eventually, we should make PTR_TRUSTED the single source of truth
4966 * for whether a register is trusted.
4968 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4969 !bpf_type_has_unsafe_modifiers(reg->type);
4972 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4974 return reg->type & MEM_RCU;
4977 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4978 const struct bpf_reg_state *reg,
4979 int off, int size, bool strict)
4981 struct tnum reg_off;
4984 /* Byte size accesses are always allowed. */
4985 if (!strict || size == 1)
4988 /* For platforms that do not have a Kconfig enabling
4989 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4990 * NET_IP_ALIGN is universally set to '2'. And on platforms
4991 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4992 * to this code only in strict mode where we want to emulate
4993 * the NET_IP_ALIGN==2 checking. Therefore use an
4994 * unconditional IP align value of '2'.
4998 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4999 if (!tnum_is_aligned(reg_off, size)) {
5002 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5004 "misaligned packet access off %d+%s+%d+%d size %d\n",
5005 ip_align, tn_buf, reg->off, off, size);
5012 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5013 const struct bpf_reg_state *reg,
5014 const char *pointer_desc,
5015 int off, int size, bool strict)
5017 struct tnum reg_off;
5019 /* Byte size accesses are always allowed. */
5020 if (!strict || size == 1)
5023 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5024 if (!tnum_is_aligned(reg_off, size)) {
5027 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5028 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5029 pointer_desc, tn_buf, reg->off, off, size);
5036 static int check_ptr_alignment(struct bpf_verifier_env *env,
5037 const struct bpf_reg_state *reg, int off,
5038 int size, bool strict_alignment_once)
5040 bool strict = env->strict_alignment || strict_alignment_once;
5041 const char *pointer_desc = "";
5043 switch (reg->type) {
5045 case PTR_TO_PACKET_META:
5046 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5047 * right in front, treat it the very same way.
5049 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5050 case PTR_TO_FLOW_KEYS:
5051 pointer_desc = "flow keys ";
5053 case PTR_TO_MAP_KEY:
5054 pointer_desc = "key ";
5056 case PTR_TO_MAP_VALUE:
5057 pointer_desc = "value ";
5060 pointer_desc = "context ";
5063 pointer_desc = "stack ";
5064 /* The stack spill tracking logic in check_stack_write_fixed_off()
5065 * and check_stack_read_fixed_off() relies on stack accesses being
5071 pointer_desc = "sock ";
5073 case PTR_TO_SOCK_COMMON:
5074 pointer_desc = "sock_common ";
5076 case PTR_TO_TCP_SOCK:
5077 pointer_desc = "tcp_sock ";
5079 case PTR_TO_XDP_SOCK:
5080 pointer_desc = "xdp_sock ";
5085 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5089 static int update_stack_depth(struct bpf_verifier_env *env,
5090 const struct bpf_func_state *func,
5093 u16 stack = env->subprog_info[func->subprogno].stack_depth;
5098 /* update known max for given subprogram */
5099 env->subprog_info[func->subprogno].stack_depth = -off;
5103 /* starting from main bpf function walk all instructions of the function
5104 * and recursively walk all callees that given function can call.
5105 * Ignore jump and exit insns.
5106 * Since recursion is prevented by check_cfg() this algorithm
5107 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5109 static int check_max_stack_depth(struct bpf_verifier_env *env)
5111 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
5112 struct bpf_subprog_info *subprog = env->subprog_info;
5113 struct bpf_insn *insn = env->prog->insnsi;
5114 bool tail_call_reachable = false;
5115 int ret_insn[MAX_CALL_FRAMES];
5116 int ret_prog[MAX_CALL_FRAMES];
5120 /* protect against potential stack overflow that might happen when
5121 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5122 * depth for such case down to 256 so that the worst case scenario
5123 * would result in 8k stack size (32 which is tailcall limit * 256 =
5126 * To get the idea what might happen, see an example:
5127 * func1 -> sub rsp, 128
5128 * subfunc1 -> sub rsp, 256
5129 * tailcall1 -> add rsp, 256
5130 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5131 * subfunc2 -> sub rsp, 64
5132 * subfunc22 -> sub rsp, 128
5133 * tailcall2 -> add rsp, 128
5134 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5136 * tailcall will unwind the current stack frame but it will not get rid
5137 * of caller's stack as shown on the example above.
5139 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5141 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5145 /* round up to 32-bytes, since this is granularity
5146 * of interpreter stack size
5148 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5149 if (depth > MAX_BPF_STACK) {
5150 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5155 subprog_end = subprog[idx + 1].start;
5156 for (; i < subprog_end; i++) {
5159 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5161 /* remember insn and function to return to */
5162 ret_insn[frame] = i + 1;
5163 ret_prog[frame] = idx;
5165 /* find the callee */
5166 next_insn = i + insn[i].imm + 1;
5167 idx = find_subprog(env, next_insn);
5169 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5173 if (subprog[idx].is_async_cb) {
5174 if (subprog[idx].has_tail_call) {
5175 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5178 /* async callbacks don't increase bpf prog stack size */
5183 if (subprog[idx].has_tail_call)
5184 tail_call_reachable = true;
5187 if (frame >= MAX_CALL_FRAMES) {
5188 verbose(env, "the call stack of %d frames is too deep !\n",
5194 /* if tail call got detected across bpf2bpf calls then mark each of the
5195 * currently present subprog frames as tail call reachable subprogs;
5196 * this info will be utilized by JIT so that we will be preserving the
5197 * tail call counter throughout bpf2bpf calls combined with tailcalls
5199 if (tail_call_reachable)
5200 for (j = 0; j < frame; j++)
5201 subprog[ret_prog[j]].tail_call_reachable = true;
5202 if (subprog[0].tail_call_reachable)
5203 env->prog->aux->tail_call_reachable = true;
5205 /* end of for() loop means the last insn of the 'subprog'
5206 * was reached. Doesn't matter whether it was JA or EXIT
5210 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5212 i = ret_insn[frame];
5213 idx = ret_prog[frame];
5217 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5218 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5219 const struct bpf_insn *insn, int idx)
5221 int start = idx + insn->imm + 1, subprog;
5223 subprog = find_subprog(env, start);
5225 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5229 return env->subprog_info[subprog].stack_depth;
5233 static int __check_buffer_access(struct bpf_verifier_env *env,
5234 const char *buf_info,
5235 const struct bpf_reg_state *reg,
5236 int regno, int off, int size)
5240 "R%d invalid %s buffer access: off=%d, size=%d\n",
5241 regno, buf_info, off, size);
5244 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5247 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5249 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5250 regno, off, tn_buf);
5257 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5258 const struct bpf_reg_state *reg,
5259 int regno, int off, int size)
5263 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5267 if (off + size > env->prog->aux->max_tp_access)
5268 env->prog->aux->max_tp_access = off + size;
5273 static int check_buffer_access(struct bpf_verifier_env *env,
5274 const struct bpf_reg_state *reg,
5275 int regno, int off, int size,
5276 bool zero_size_allowed,
5279 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5282 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5286 if (off + size > *max_access)
5287 *max_access = off + size;
5292 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5293 static void zext_32_to_64(struct bpf_reg_state *reg)
5295 reg->var_off = tnum_subreg(reg->var_off);
5296 __reg_assign_32_into_64(reg);
5299 /* truncate register to smaller size (in bytes)
5300 * must be called with size < BPF_REG_SIZE
5302 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5306 /* clear high bits in bit representation */
5307 reg->var_off = tnum_cast(reg->var_off, size);
5309 /* fix arithmetic bounds */
5310 mask = ((u64)1 << (size * 8)) - 1;
5311 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5312 reg->umin_value &= mask;
5313 reg->umax_value &= mask;
5315 reg->umin_value = 0;
5316 reg->umax_value = mask;
5318 reg->smin_value = reg->umin_value;
5319 reg->smax_value = reg->umax_value;
5321 /* If size is smaller than 32bit register the 32bit register
5322 * values are also truncated so we push 64-bit bounds into
5323 * 32-bit bounds. Above were truncated < 32-bits already.
5327 __reg_combine_64_into_32(reg);
5330 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5332 /* A map is considered read-only if the following condition are true:
5334 * 1) BPF program side cannot change any of the map content. The
5335 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5336 * and was set at map creation time.
5337 * 2) The map value(s) have been initialized from user space by a
5338 * loader and then "frozen", such that no new map update/delete
5339 * operations from syscall side are possible for the rest of
5340 * the map's lifetime from that point onwards.
5341 * 3) Any parallel/pending map update/delete operations from syscall
5342 * side have been completed. Only after that point, it's safe to
5343 * assume that map value(s) are immutable.
5345 return (map->map_flags & BPF_F_RDONLY_PROG) &&
5346 READ_ONCE(map->frozen) &&
5347 !bpf_map_write_active(map);
5350 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5356 err = map->ops->map_direct_value_addr(map, &addr, off);
5359 ptr = (void *)(long)addr + off;
5363 *val = (u64)*(u8 *)ptr;
5366 *val = (u64)*(u16 *)ptr;
5369 *val = (u64)*(u32 *)ptr;
5380 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
5381 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
5384 * Allow list few fields as RCU trusted or full trusted.
5385 * This logic doesn't allow mix tagging and will be removed once GCC supports
5389 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5390 BTF_TYPE_SAFE_RCU(struct task_struct) {
5391 const cpumask_t *cpus_ptr;
5392 struct css_set __rcu *cgroups;
5393 struct task_struct __rcu *real_parent;
5394 struct task_struct *group_leader;
5397 BTF_TYPE_SAFE_RCU(struct css_set) {
5398 struct cgroup *dfl_cgrp;
5401 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5402 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5403 struct seq_file *seq;
5406 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5407 struct bpf_iter_meta *meta;
5408 struct task_struct *task;
5411 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5415 BTF_TYPE_SAFE_TRUSTED(struct file) {
5416 struct inode *f_inode;
5419 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5420 /* no negative dentry-s in places where bpf can see it */
5421 struct inode *d_inode;
5424 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5428 static bool type_is_rcu(struct bpf_verifier_env *env,
5429 struct bpf_reg_state *reg,
5430 const char *field_name, u32 btf_id)
5432 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5433 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5435 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5438 static bool type_is_trusted(struct bpf_verifier_env *env,
5439 struct bpf_reg_state *reg,
5440 const char *field_name, u32 btf_id)
5442 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5443 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5444 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5445 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5446 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5447 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5449 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5452 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5453 struct bpf_reg_state *regs,
5454 int regno, int off, int size,
5455 enum bpf_access_type atype,
5458 struct bpf_reg_state *reg = regs + regno;
5459 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5460 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5461 const char *field_name = NULL;
5462 enum bpf_type_flag flag = 0;
5466 if (!env->allow_ptr_leaks) {
5468 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5472 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5474 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5480 "R%d is ptr_%s invalid negative access: off=%d\n",
5484 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5487 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5489 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5490 regno, tname, off, tn_buf);
5494 if (reg->type & MEM_USER) {
5496 "R%d is ptr_%s access user memory: off=%d\n",
5501 if (reg->type & MEM_PERCPU) {
5503 "R%d is ptr_%s access percpu memory: off=%d\n",
5508 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
5509 if (!btf_is_kernel(reg->btf)) {
5510 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5513 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
5515 /* Writes are permitted with default btf_struct_access for
5516 * program allocated objects (which always have ref_obj_id > 0),
5517 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5519 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
5520 verbose(env, "only read is supported\n");
5524 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5526 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5530 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
5536 if (ret != PTR_TO_BTF_ID) {
5539 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
5540 /* If this is an untrusted pointer, all pointers formed by walking it
5541 * also inherit the untrusted flag.
5543 flag = PTR_UNTRUSTED;
5545 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
5546 /* By default any pointer obtained from walking a trusted pointer is no
5547 * longer trusted, unless the field being accessed has explicitly been
5548 * marked as inheriting its parent's state of trust (either full or RCU).
5550 * 'cgroups' pointer is untrusted if task->cgroups dereference
5551 * happened in a sleepable program outside of bpf_rcu_read_lock()
5552 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
5553 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
5555 * A regular RCU-protected pointer with __rcu tag can also be deemed
5556 * trusted if we are in an RCU CS. Such pointer can be NULL.
5558 if (type_is_trusted(env, reg, field_name, btf_id)) {
5559 flag |= PTR_TRUSTED;
5560 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
5561 if (type_is_rcu(env, reg, field_name, btf_id)) {
5562 /* ignore __rcu tag and mark it MEM_RCU */
5564 } else if (flag & MEM_RCU) {
5565 /* __rcu tagged pointers can be NULL */
5566 flag |= PTR_MAYBE_NULL;
5567 } else if (flag & (MEM_PERCPU | MEM_USER)) {
5570 /* walking unknown pointers yields untrusted pointer */
5571 flag = PTR_UNTRUSTED;
5575 * If not in RCU CS or MEM_RCU pointer can be NULL then
5576 * aggressively mark as untrusted otherwise such
5577 * pointers will be plain PTR_TO_BTF_ID without flags
5578 * and will be allowed to be passed into helpers for
5581 flag = PTR_UNTRUSTED;
5584 /* Old compat. Deprecated */
5585 flag &= ~PTR_TRUSTED;
5588 if (atype == BPF_READ && value_regno >= 0)
5589 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5594 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5595 struct bpf_reg_state *regs,
5596 int regno, int off, int size,
5597 enum bpf_access_type atype,
5600 struct bpf_reg_state *reg = regs + regno;
5601 struct bpf_map *map = reg->map_ptr;
5602 struct bpf_reg_state map_reg;
5603 enum bpf_type_flag flag = 0;
5604 const struct btf_type *t;
5610 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5614 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5615 verbose(env, "map_ptr access not supported for map type %d\n",
5620 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5621 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5623 if (!env->allow_ptr_leaks) {
5625 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5631 verbose(env, "R%d is %s invalid negative access: off=%d\n",
5636 if (atype != BPF_READ) {
5637 verbose(env, "only read from %s is supported\n", tname);
5641 /* Simulate access to a PTR_TO_BTF_ID */
5642 memset(&map_reg, 0, sizeof(map_reg));
5643 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
5644 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
5648 if (value_regno >= 0)
5649 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
5654 /* Check that the stack access at the given offset is within bounds. The
5655 * maximum valid offset is -1.
5657 * The minimum valid offset is -MAX_BPF_STACK for writes, and
5658 * -state->allocated_stack for reads.
5660 static int check_stack_slot_within_bounds(int off,
5661 struct bpf_func_state *state,
5662 enum bpf_access_type t)
5667 min_valid_off = -MAX_BPF_STACK;
5669 min_valid_off = -state->allocated_stack;
5671 if (off < min_valid_off || off > -1)
5676 /* Check that the stack access at 'regno + off' falls within the maximum stack
5679 * 'off' includes `regno->offset`, but not its dynamic part (if any).
5681 static int check_stack_access_within_bounds(
5682 struct bpf_verifier_env *env,
5683 int regno, int off, int access_size,
5684 enum bpf_access_src src, enum bpf_access_type type)
5686 struct bpf_reg_state *regs = cur_regs(env);
5687 struct bpf_reg_state *reg = regs + regno;
5688 struct bpf_func_state *state = func(env, reg);
5689 int min_off, max_off;
5693 if (src == ACCESS_HELPER)
5694 /* We don't know if helpers are reading or writing (or both). */
5695 err_extra = " indirect access to";
5696 else if (type == BPF_READ)
5697 err_extra = " read from";
5699 err_extra = " write to";
5701 if (tnum_is_const(reg->var_off)) {
5702 min_off = reg->var_off.value + off;
5703 if (access_size > 0)
5704 max_off = min_off + access_size - 1;
5708 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
5709 reg->smin_value <= -BPF_MAX_VAR_OFF) {
5710 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
5714 min_off = reg->smin_value + off;
5715 if (access_size > 0)
5716 max_off = reg->smax_value + off + access_size - 1;
5721 err = check_stack_slot_within_bounds(min_off, state, type);
5723 err = check_stack_slot_within_bounds(max_off, state, type);
5726 if (tnum_is_const(reg->var_off)) {
5727 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5728 err_extra, regno, off, access_size);
5732 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5733 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5734 err_extra, regno, tn_buf, access_size);
5740 /* check whether memory at (regno + off) is accessible for t = (read | write)
5741 * if t==write, value_regno is a register which value is stored into memory
5742 * if t==read, value_regno is a register which will receive the value from memory
5743 * if t==write && value_regno==-1, some unknown value is stored into memory
5744 * if t==read && value_regno==-1, don't care what we read from memory
5746 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5747 int off, int bpf_size, enum bpf_access_type t,
5748 int value_regno, bool strict_alignment_once)
5750 struct bpf_reg_state *regs = cur_regs(env);
5751 struct bpf_reg_state *reg = regs + regno;
5752 struct bpf_func_state *state;
5755 size = bpf_size_to_bytes(bpf_size);
5759 /* alignment checks will add in reg->off themselves */
5760 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5764 /* for access checks, reg->off is just part of off */
5767 if (reg->type == PTR_TO_MAP_KEY) {
5768 if (t == BPF_WRITE) {
5769 verbose(env, "write to change key R%d not allowed\n", regno);
5773 err = check_mem_region_access(env, regno, off, size,
5774 reg->map_ptr->key_size, false);
5777 if (value_regno >= 0)
5778 mark_reg_unknown(env, regs, value_regno);
5779 } else if (reg->type == PTR_TO_MAP_VALUE) {
5780 struct btf_field *kptr_field = NULL;
5782 if (t == BPF_WRITE && value_regno >= 0 &&
5783 is_pointer_value(env, value_regno)) {
5784 verbose(env, "R%d leaks addr into map\n", value_regno);
5787 err = check_map_access_type(env, regno, off, size, t);
5790 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5793 if (tnum_is_const(reg->var_off))
5794 kptr_field = btf_record_find(reg->map_ptr->record,
5795 off + reg->var_off.value, BPF_KPTR);
5797 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5798 } else if (t == BPF_READ && value_regno >= 0) {
5799 struct bpf_map *map = reg->map_ptr;
5801 /* if map is read-only, track its contents as scalars */
5802 if (tnum_is_const(reg->var_off) &&
5803 bpf_map_is_rdonly(map) &&
5804 map->ops->map_direct_value_addr) {
5805 int map_off = off + reg->var_off.value;
5808 err = bpf_map_direct_read(map, map_off, size,
5813 regs[value_regno].type = SCALAR_VALUE;
5814 __mark_reg_known(®s[value_regno], val);
5816 mark_reg_unknown(env, regs, value_regno);
5819 } else if (base_type(reg->type) == PTR_TO_MEM) {
5820 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5822 if (type_may_be_null(reg->type)) {
5823 verbose(env, "R%d invalid mem access '%s'\n", regno,
5824 reg_type_str(env, reg->type));
5828 if (t == BPF_WRITE && rdonly_mem) {
5829 verbose(env, "R%d cannot write into %s\n",
5830 regno, reg_type_str(env, reg->type));
5834 if (t == BPF_WRITE && value_regno >= 0 &&
5835 is_pointer_value(env, value_regno)) {
5836 verbose(env, "R%d leaks addr into mem\n", value_regno);
5840 err = check_mem_region_access(env, regno, off, size,
5841 reg->mem_size, false);
5842 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5843 mark_reg_unknown(env, regs, value_regno);
5844 } else if (reg->type == PTR_TO_CTX) {
5845 enum bpf_reg_type reg_type = SCALAR_VALUE;
5846 struct btf *btf = NULL;
5849 if (t == BPF_WRITE && value_regno >= 0 &&
5850 is_pointer_value(env, value_regno)) {
5851 verbose(env, "R%d leaks addr into ctx\n", value_regno);
5855 err = check_ptr_off_reg(env, reg, regno);
5859 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
5862 verbose_linfo(env, insn_idx, "; ");
5863 if (!err && t == BPF_READ && value_regno >= 0) {
5864 /* ctx access returns either a scalar, or a
5865 * PTR_TO_PACKET[_META,_END]. In the latter
5866 * case, we know the offset is zero.
5868 if (reg_type == SCALAR_VALUE) {
5869 mark_reg_unknown(env, regs, value_regno);
5871 mark_reg_known_zero(env, regs,
5873 if (type_may_be_null(reg_type))
5874 regs[value_regno].id = ++env->id_gen;
5875 /* A load of ctx field could have different
5876 * actual load size with the one encoded in the
5877 * insn. When the dst is PTR, it is for sure not
5880 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5881 if (base_type(reg_type) == PTR_TO_BTF_ID) {
5882 regs[value_regno].btf = btf;
5883 regs[value_regno].btf_id = btf_id;
5886 regs[value_regno].type = reg_type;
5889 } else if (reg->type == PTR_TO_STACK) {
5890 /* Basic bounds checks. */
5891 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5895 state = func(env, reg);
5896 err = update_stack_depth(env, state, off);
5901 err = check_stack_read(env, regno, off, size,
5904 err = check_stack_write(env, regno, off, size,
5905 value_regno, insn_idx);
5906 } else if (reg_is_pkt_pointer(reg)) {
5907 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5908 verbose(env, "cannot write into packet\n");
5911 if (t == BPF_WRITE && value_regno >= 0 &&
5912 is_pointer_value(env, value_regno)) {
5913 verbose(env, "R%d leaks addr into packet\n",
5917 err = check_packet_access(env, regno, off, size, false);
5918 if (!err && t == BPF_READ && value_regno >= 0)
5919 mark_reg_unknown(env, regs, value_regno);
5920 } else if (reg->type == PTR_TO_FLOW_KEYS) {
5921 if (t == BPF_WRITE && value_regno >= 0 &&
5922 is_pointer_value(env, value_regno)) {
5923 verbose(env, "R%d leaks addr into flow keys\n",
5928 err = check_flow_keys_access(env, off, size);
5929 if (!err && t == BPF_READ && value_regno >= 0)
5930 mark_reg_unknown(env, regs, value_regno);
5931 } else if (type_is_sk_pointer(reg->type)) {
5932 if (t == BPF_WRITE) {
5933 verbose(env, "R%d cannot write into %s\n",
5934 regno, reg_type_str(env, reg->type));
5937 err = check_sock_access(env, insn_idx, regno, off, size, t);
5938 if (!err && value_regno >= 0)
5939 mark_reg_unknown(env, regs, value_regno);
5940 } else if (reg->type == PTR_TO_TP_BUFFER) {
5941 err = check_tp_buffer_access(env, reg, regno, off, size);
5942 if (!err && t == BPF_READ && value_regno >= 0)
5943 mark_reg_unknown(env, regs, value_regno);
5944 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5945 !type_may_be_null(reg->type)) {
5946 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5948 } else if (reg->type == CONST_PTR_TO_MAP) {
5949 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5951 } else if (base_type(reg->type) == PTR_TO_BUF) {
5952 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5956 if (t == BPF_WRITE) {
5957 verbose(env, "R%d cannot write into %s\n",
5958 regno, reg_type_str(env, reg->type));
5961 max_access = &env->prog->aux->max_rdonly_access;
5963 max_access = &env->prog->aux->max_rdwr_access;
5966 err = check_buffer_access(env, reg, regno, off, size, false,
5969 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5970 mark_reg_unknown(env, regs, value_regno);
5972 verbose(env, "R%d invalid mem access '%s'\n", regno,
5973 reg_type_str(env, reg->type));
5977 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5978 regs[value_regno].type == SCALAR_VALUE) {
5979 /* b/h/w load zero-extends, mark upper bits as known 0 */
5980 coerce_reg_to_size(®s[value_regno], size);
5985 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5990 switch (insn->imm) {
5992 case BPF_ADD | BPF_FETCH:
5994 case BPF_AND | BPF_FETCH:
5996 case BPF_OR | BPF_FETCH:
5998 case BPF_XOR | BPF_FETCH:
6003 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6007 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6008 verbose(env, "invalid atomic operand size\n");
6012 /* check src1 operand */
6013 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6017 /* check src2 operand */
6018 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6022 if (insn->imm == BPF_CMPXCHG) {
6023 /* Check comparison of R0 with memory location */
6024 const u32 aux_reg = BPF_REG_0;
6026 err = check_reg_arg(env, aux_reg, SRC_OP);
6030 if (is_pointer_value(env, aux_reg)) {
6031 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6036 if (is_pointer_value(env, insn->src_reg)) {
6037 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6041 if (is_ctx_reg(env, insn->dst_reg) ||
6042 is_pkt_reg(env, insn->dst_reg) ||
6043 is_flow_key_reg(env, insn->dst_reg) ||
6044 is_sk_reg(env, insn->dst_reg)) {
6045 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6047 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6051 if (insn->imm & BPF_FETCH) {
6052 if (insn->imm == BPF_CMPXCHG)
6053 load_reg = BPF_REG_0;
6055 load_reg = insn->src_reg;
6057 /* check and record load of old value */
6058 err = check_reg_arg(env, load_reg, DST_OP);
6062 /* This instruction accesses a memory location but doesn't
6063 * actually load it into a register.
6068 /* Check whether we can read the memory, with second call for fetch
6069 * case to simulate the register fill.
6071 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6072 BPF_SIZE(insn->code), BPF_READ, -1, true);
6073 if (!err && load_reg >= 0)
6074 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6075 BPF_SIZE(insn->code), BPF_READ, load_reg,
6080 /* Check whether we can write into the same memory. */
6081 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6082 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
6089 /* When register 'regno' is used to read the stack (either directly or through
6090 * a helper function) make sure that it's within stack boundary and, depending
6091 * on the access type, that all elements of the stack are initialized.
6093 * 'off' includes 'regno->off', but not its dynamic part (if any).
6095 * All registers that have been spilled on the stack in the slots within the
6096 * read offsets are marked as read.
6098 static int check_stack_range_initialized(
6099 struct bpf_verifier_env *env, int regno, int off,
6100 int access_size, bool zero_size_allowed,
6101 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6103 struct bpf_reg_state *reg = reg_state(env, regno);
6104 struct bpf_func_state *state = func(env, reg);
6105 int err, min_off, max_off, i, j, slot, spi;
6106 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6107 enum bpf_access_type bounds_check_type;
6108 /* Some accesses can write anything into the stack, others are
6111 bool clobber = false;
6113 if (access_size == 0 && !zero_size_allowed) {
6114 verbose(env, "invalid zero-sized read\n");
6118 if (type == ACCESS_HELPER) {
6119 /* The bounds checks for writes are more permissive than for
6120 * reads. However, if raw_mode is not set, we'll do extra
6123 bounds_check_type = BPF_WRITE;
6126 bounds_check_type = BPF_READ;
6128 err = check_stack_access_within_bounds(env, regno, off, access_size,
6129 type, bounds_check_type);
6134 if (tnum_is_const(reg->var_off)) {
6135 min_off = max_off = reg->var_off.value + off;
6137 /* Variable offset is prohibited for unprivileged mode for
6138 * simplicity since it requires corresponding support in
6139 * Spectre masking for stack ALU.
6140 * See also retrieve_ptr_limit().
6142 if (!env->bypass_spec_v1) {
6145 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6146 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6147 regno, err_extra, tn_buf);
6150 /* Only initialized buffer on stack is allowed to be accessed
6151 * with variable offset. With uninitialized buffer it's hard to
6152 * guarantee that whole memory is marked as initialized on
6153 * helper return since specific bounds are unknown what may
6154 * cause uninitialized stack leaking.
6156 if (meta && meta->raw_mode)
6159 min_off = reg->smin_value + off;
6160 max_off = reg->smax_value + off;
6163 if (meta && meta->raw_mode) {
6164 /* Ensure we won't be overwriting dynptrs when simulating byte
6165 * by byte access in check_helper_call using meta.access_size.
6166 * This would be a problem if we have a helper in the future
6169 * helper(uninit_mem, len, dynptr)
6171 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6172 * may end up writing to dynptr itself when touching memory from
6173 * arg 1. This can be relaxed on a case by case basis for known
6174 * safe cases, but reject due to the possibilitiy of aliasing by
6177 for (i = min_off; i < max_off + access_size; i++) {
6178 int stack_off = -i - 1;
6181 /* raw_mode may write past allocated_stack */
6182 if (state->allocated_stack <= stack_off)
6184 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6185 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6189 meta->access_size = access_size;
6190 meta->regno = regno;
6194 for (i = min_off; i < max_off + access_size; i++) {
6198 spi = slot / BPF_REG_SIZE;
6199 if (state->allocated_stack <= slot)
6201 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6202 if (*stype == STACK_MISC)
6204 if ((*stype == STACK_ZERO) ||
6205 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6207 /* helper can write anything into the stack */
6208 *stype = STACK_MISC;
6213 if (is_spilled_reg(&state->stack[spi]) &&
6214 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6215 env->allow_ptr_leaks)) {
6217 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6218 for (j = 0; j < BPF_REG_SIZE; j++)
6219 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6225 if (tnum_is_const(reg->var_off)) {
6226 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6227 err_extra, regno, min_off, i - min_off, access_size);
6231 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6232 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6233 err_extra, regno, tn_buf, i - min_off, access_size);
6237 /* reading any byte out of 8-byte 'spill_slot' will cause
6238 * the whole slot to be marked as 'read'
6240 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6241 state->stack[spi].spilled_ptr.parent,
6243 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6244 * be sure that whether stack slot is written to or not. Hence,
6245 * we must still conservatively propagate reads upwards even if
6246 * helper may write to the entire memory range.
6249 return update_stack_depth(env, state, min_off);
6252 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6253 int access_size, bool zero_size_allowed,
6254 struct bpf_call_arg_meta *meta)
6256 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6259 switch (base_type(reg->type)) {
6261 case PTR_TO_PACKET_META:
6262 return check_packet_access(env, regno, reg->off, access_size,
6264 case PTR_TO_MAP_KEY:
6265 if (meta && meta->raw_mode) {
6266 verbose(env, "R%d cannot write into %s\n", regno,
6267 reg_type_str(env, reg->type));
6270 return check_mem_region_access(env, regno, reg->off, access_size,
6271 reg->map_ptr->key_size, false);
6272 case PTR_TO_MAP_VALUE:
6273 if (check_map_access_type(env, regno, reg->off, access_size,
6274 meta && meta->raw_mode ? BPF_WRITE :
6277 return check_map_access(env, regno, reg->off, access_size,
6278 zero_size_allowed, ACCESS_HELPER);
6280 if (type_is_rdonly_mem(reg->type)) {
6281 if (meta && meta->raw_mode) {
6282 verbose(env, "R%d cannot write into %s\n", regno,
6283 reg_type_str(env, reg->type));
6287 return check_mem_region_access(env, regno, reg->off,
6288 access_size, reg->mem_size,
6291 if (type_is_rdonly_mem(reg->type)) {
6292 if (meta && meta->raw_mode) {
6293 verbose(env, "R%d cannot write into %s\n", regno,
6294 reg_type_str(env, reg->type));
6298 max_access = &env->prog->aux->max_rdonly_access;
6300 max_access = &env->prog->aux->max_rdwr_access;
6302 return check_buffer_access(env, reg, regno, reg->off,
6303 access_size, zero_size_allowed,
6306 return check_stack_range_initialized(
6308 regno, reg->off, access_size,
6309 zero_size_allowed, ACCESS_HELPER, meta);
6311 return check_ptr_to_btf_access(env, regs, regno, reg->off,
6312 access_size, BPF_READ, -1);
6314 /* in case the function doesn't know how to access the context,
6315 * (because we are in a program of type SYSCALL for example), we
6316 * can not statically check its size.
6317 * Dynamically check it now.
6319 if (!env->ops->convert_ctx_access) {
6320 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6321 int offset = access_size - 1;
6323 /* Allow zero-byte read from PTR_TO_CTX */
6324 if (access_size == 0)
6325 return zero_size_allowed ? 0 : -EACCES;
6327 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6332 default: /* scalar_value or invalid ptr */
6333 /* Allow zero-byte read from NULL, regardless of pointer type */
6334 if (zero_size_allowed && access_size == 0 &&
6335 register_is_null(reg))
6338 verbose(env, "R%d type=%s ", regno,
6339 reg_type_str(env, reg->type));
6340 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6345 static int check_mem_size_reg(struct bpf_verifier_env *env,
6346 struct bpf_reg_state *reg, u32 regno,
6347 bool zero_size_allowed,
6348 struct bpf_call_arg_meta *meta)
6352 /* This is used to refine r0 return value bounds for helpers
6353 * that enforce this value as an upper bound on return values.
6354 * See do_refine_retval_range() for helpers that can refine
6355 * the return value. C type of helper is u32 so we pull register
6356 * bound from umax_value however, if negative verifier errors
6357 * out. Only upper bounds can be learned because retval is an
6358 * int type and negative retvals are allowed.
6360 meta->msize_max_value = reg->umax_value;
6362 /* The register is SCALAR_VALUE; the access check
6363 * happens using its boundaries.
6365 if (!tnum_is_const(reg->var_off))
6366 /* For unprivileged variable accesses, disable raw
6367 * mode so that the program is required to
6368 * initialize all the memory that the helper could
6369 * just partially fill up.
6373 if (reg->smin_value < 0) {
6374 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6379 if (reg->umin_value == 0) {
6380 err = check_helper_mem_access(env, regno - 1, 0,
6387 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6388 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6392 err = check_helper_mem_access(env, regno - 1,
6394 zero_size_allowed, meta);
6396 err = mark_chain_precision(env, regno);
6400 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6401 u32 regno, u32 mem_size)
6403 bool may_be_null = type_may_be_null(reg->type);
6404 struct bpf_reg_state saved_reg;
6405 struct bpf_call_arg_meta meta;
6408 if (register_is_null(reg))
6411 memset(&meta, 0, sizeof(meta));
6412 /* Assuming that the register contains a value check if the memory
6413 * access is safe. Temporarily save and restore the register's state as
6414 * the conversion shouldn't be visible to a caller.
6418 mark_ptr_not_null_reg(reg);
6421 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6422 /* Check access for BPF_WRITE */
6423 meta.raw_mode = true;
6424 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6432 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6435 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6436 bool may_be_null = type_may_be_null(mem_reg->type);
6437 struct bpf_reg_state saved_reg;
6438 struct bpf_call_arg_meta meta;
6441 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6443 memset(&meta, 0, sizeof(meta));
6446 saved_reg = *mem_reg;
6447 mark_ptr_not_null_reg(mem_reg);
6450 err = check_mem_size_reg(env, reg, regno, true, &meta);
6451 /* Check access for BPF_WRITE */
6452 meta.raw_mode = true;
6453 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6456 *mem_reg = saved_reg;
6460 /* Implementation details:
6461 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6462 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6463 * Two bpf_map_lookups (even with the same key) will have different reg->id.
6464 * Two separate bpf_obj_new will also have different reg->id.
6465 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6466 * clears reg->id after value_or_null->value transition, since the verifier only
6467 * cares about the range of access to valid map value pointer and doesn't care
6468 * about actual address of the map element.
6469 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6470 * reg->id > 0 after value_or_null->value transition. By doing so
6471 * two bpf_map_lookups will be considered two different pointers that
6472 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6473 * returned from bpf_obj_new.
6474 * The verifier allows taking only one bpf_spin_lock at a time to avoid
6476 * Since only one bpf_spin_lock is allowed the checks are simpler than
6477 * reg_is_refcounted() logic. The verifier needs to remember only
6478 * one spin_lock instead of array of acquired_refs.
6479 * cur_state->active_lock remembers which map value element or allocated
6480 * object got locked and clears it after bpf_spin_unlock.
6482 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6485 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6486 struct bpf_verifier_state *cur = env->cur_state;
6487 bool is_const = tnum_is_const(reg->var_off);
6488 u64 val = reg->var_off.value;
6489 struct bpf_map *map = NULL;
6490 struct btf *btf = NULL;
6491 struct btf_record *rec;
6495 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6499 if (reg->type == PTR_TO_MAP_VALUE) {
6503 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
6511 rec = reg_btf_record(reg);
6512 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6513 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6514 map ? map->name : "kptr");
6517 if (rec->spin_lock_off != val + reg->off) {
6518 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
6519 val + reg->off, rec->spin_lock_off);
6523 if (cur->active_lock.ptr) {
6525 "Locking two bpf_spin_locks are not allowed\n");
6529 cur->active_lock.ptr = map;
6531 cur->active_lock.ptr = btf;
6532 cur->active_lock.id = reg->id;
6541 if (!cur->active_lock.ptr) {
6542 verbose(env, "bpf_spin_unlock without taking a lock\n");
6545 if (cur->active_lock.ptr != ptr ||
6546 cur->active_lock.id != reg->id) {
6547 verbose(env, "bpf_spin_unlock of different lock\n");
6551 invalidate_non_owning_refs(env);
6553 cur->active_lock.ptr = NULL;
6554 cur->active_lock.id = 0;
6559 static int process_timer_func(struct bpf_verifier_env *env, int regno,
6560 struct bpf_call_arg_meta *meta)
6562 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6563 bool is_const = tnum_is_const(reg->var_off);
6564 struct bpf_map *map = reg->map_ptr;
6565 u64 val = reg->var_off.value;
6569 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6574 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6578 if (!btf_record_has_field(map->record, BPF_TIMER)) {
6579 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
6582 if (map->record->timer_off != val + reg->off) {
6583 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
6584 val + reg->off, map->record->timer_off);
6587 if (meta->map_ptr) {
6588 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6591 meta->map_uid = reg->map_uid;
6592 meta->map_ptr = map;
6596 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6597 struct bpf_call_arg_meta *meta)
6599 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6600 struct bpf_map *map_ptr = reg->map_ptr;
6601 struct btf_field *kptr_field;
6604 if (!tnum_is_const(reg->var_off)) {
6606 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6610 if (!map_ptr->btf) {
6611 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6615 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6616 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
6620 meta->map_ptr = map_ptr;
6621 kptr_off = reg->off + reg->var_off.value;
6622 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
6624 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
6627 if (kptr_field->type != BPF_KPTR_REF) {
6628 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
6631 meta->kptr_field = kptr_field;
6635 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6636 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6638 * In both cases we deal with the first 8 bytes, but need to mark the next 8
6639 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6640 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6642 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6643 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6644 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6645 * mutate the view of the dynptr and also possibly destroy it. In the latter
6646 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6647 * memory that dynptr points to.
6649 * The verifier will keep track both levels of mutation (bpf_dynptr's in
6650 * reg->type and the memory's in reg->dynptr.type), but there is no support for
6651 * readonly dynptr view yet, hence only the first case is tracked and checked.
6653 * This is consistent with how C applies the const modifier to a struct object,
6654 * where the pointer itself inside bpf_dynptr becomes const but not what it
6657 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6658 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6660 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
6661 enum bpf_arg_type arg_type)
6663 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6666 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6667 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6669 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6670 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6674 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
6675 * constructing a mutable bpf_dynptr object.
6677 * Currently, this is only possible with PTR_TO_STACK
6678 * pointing to a region of at least 16 bytes which doesn't
6679 * contain an existing bpf_dynptr.
6681 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6682 * mutated or destroyed. However, the memory it points to
6685 * None - Points to a initialized dynptr that can be mutated and
6686 * destroyed, including mutation of the memory it points
6689 if (arg_type & MEM_UNINIT) {
6692 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6693 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6697 /* we write BPF_DW bits (8 bytes) at a time */
6698 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
6699 err = check_mem_access(env, insn_idx, regno,
6700 i, BPF_DW, BPF_WRITE, -1, false);
6705 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx);
6706 } else /* MEM_RDONLY and None case from above */ {
6707 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6708 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6709 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6713 if (!is_dynptr_reg_valid_init(env, reg)) {
6715 "Expected an initialized dynptr as arg #%d\n",
6720 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6721 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6723 "Expected a dynptr of type %s as arg #%d\n",
6724 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
6728 err = mark_dynptr_read(env, reg);
6733 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
6735 struct bpf_func_state *state = func(env, reg);
6737 return state->stack[spi].spilled_ptr.ref_obj_id;
6740 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6742 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
6745 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6747 return meta->kfunc_flags & KF_ITER_NEW;
6750 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6752 return meta->kfunc_flags & KF_ITER_NEXT;
6755 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6757 return meta->kfunc_flags & KF_ITER_DESTROY;
6760 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
6762 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
6763 * kfunc is iter state pointer
6765 return arg == 0 && is_iter_kfunc(meta);
6768 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
6769 struct bpf_kfunc_call_arg_meta *meta)
6771 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6772 const struct btf_type *t;
6773 const struct btf_param *arg;
6774 int spi, err, i, nr_slots;
6777 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
6778 arg = &btf_params(meta->func_proto)[0];
6779 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
6780 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
6781 nr_slots = t->size / BPF_REG_SIZE;
6783 if (is_iter_new_kfunc(meta)) {
6784 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
6785 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
6786 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
6787 iter_type_str(meta->btf, btf_id), regno);
6791 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
6792 err = check_mem_access(env, insn_idx, regno,
6793 i, BPF_DW, BPF_WRITE, -1, false);
6798 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
6802 /* iter_next() or iter_destroy() expect initialized iter state*/
6803 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
6804 verbose(env, "expected an initialized iter_%s as arg #%d\n",
6805 iter_type_str(meta->btf, btf_id), regno);
6809 spi = iter_get_spi(env, reg, nr_slots);
6813 err = mark_iter_read(env, reg, spi, nr_slots);
6817 /* remember meta->iter info for process_iter_next_call() */
6818 meta->iter.spi = spi;
6819 meta->iter.frameno = reg->frameno;
6820 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
6822 if (is_iter_destroy_kfunc(meta)) {
6823 err = unmark_stack_slots_iter(env, reg, nr_slots);
6832 /* process_iter_next_call() is called when verifier gets to iterator's next
6833 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
6834 * to it as just "iter_next()" in comments below.
6836 * BPF verifier relies on a crucial contract for any iter_next()
6837 * implementation: it should *eventually* return NULL, and once that happens
6838 * it should keep returning NULL. That is, once iterator exhausts elements to
6839 * iterate, it should never reset or spuriously return new elements.
6841 * With the assumption of such contract, process_iter_next_call() simulates
6842 * a fork in the verifier state to validate loop logic correctness and safety
6843 * without having to simulate infinite amount of iterations.
6845 * In current state, we first assume that iter_next() returned NULL and
6846 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
6847 * conditions we should not form an infinite loop and should eventually reach
6850 * Besides that, we also fork current state and enqueue it for later
6851 * verification. In a forked state we keep iterator state as ACTIVE
6852 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
6853 * also bump iteration depth to prevent erroneous infinite loop detection
6854 * later on (see iter_active_depths_differ() comment for details). In this
6855 * state we assume that we'll eventually loop back to another iter_next()
6856 * calls (it could be in exactly same location or in some other instruction,
6857 * it doesn't matter, we don't make any unnecessary assumptions about this,
6858 * everything revolves around iterator state in a stack slot, not which
6859 * instruction is calling iter_next()). When that happens, we either will come
6860 * to iter_next() with equivalent state and can conclude that next iteration
6861 * will proceed in exactly the same way as we just verified, so it's safe to
6862 * assume that loop converges. If not, we'll go on another iteration
6863 * simulation with a different input state, until all possible starting states
6864 * are validated or we reach maximum number of instructions limit.
6866 * This way, we will either exhaustively discover all possible input states
6867 * that iterator loop can start with and eventually will converge, or we'll
6868 * effectively regress into bounded loop simulation logic and either reach
6869 * maximum number of instructions if loop is not provably convergent, or there
6870 * is some statically known limit on number of iterations (e.g., if there is
6871 * an explicit `if n > 100 then break;` statement somewhere in the loop).
6873 * One very subtle but very important aspect is that we *always* simulate NULL
6874 * condition first (as the current state) before we simulate non-NULL case.
6875 * This has to do with intricacies of scalar precision tracking. By simulating
6876 * "exit condition" of iter_next() returning NULL first, we make sure all the
6877 * relevant precision marks *that will be set **after** we exit iterator loop*
6878 * are propagated backwards to common parent state of NULL and non-NULL
6879 * branches. Thanks to that, state equivalence checks done later in forked
6880 * state, when reaching iter_next() for ACTIVE iterator, can assume that
6881 * precision marks are finalized and won't change. Because simulating another
6882 * ACTIVE iterator iteration won't change them (because given same input
6883 * states we'll end up with exactly same output states which we are currently
6884 * comparing; and verification after the loop already propagated back what
6885 * needs to be **additionally** tracked as precise). It's subtle, grok
6886 * precision tracking for more intuitive understanding.
6888 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
6889 struct bpf_kfunc_call_arg_meta *meta)
6891 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
6892 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
6893 struct bpf_reg_state *cur_iter, *queued_iter;
6894 int iter_frameno = meta->iter.frameno;
6895 int iter_spi = meta->iter.spi;
6897 BTF_TYPE_EMIT(struct bpf_iter);
6899 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
6901 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
6902 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
6903 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
6904 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
6908 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
6909 /* branch out active iter state */
6910 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
6914 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
6915 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
6916 queued_iter->iter.depth++;
6918 queued_fr = queued_st->frame[queued_st->curframe];
6919 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
6922 /* switch to DRAINED state, but keep the depth unchanged */
6923 /* mark current iter state as drained and assume returned NULL */
6924 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
6925 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
6930 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6932 return type == ARG_CONST_SIZE ||
6933 type == ARG_CONST_SIZE_OR_ZERO;
6936 static bool arg_type_is_release(enum bpf_arg_type type)
6938 return type & OBJ_RELEASE;
6941 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6943 return base_type(type) == ARG_PTR_TO_DYNPTR;
6946 static int int_ptr_type_to_size(enum bpf_arg_type type)
6948 if (type == ARG_PTR_TO_INT)
6950 else if (type == ARG_PTR_TO_LONG)
6956 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6957 const struct bpf_call_arg_meta *meta,
6958 enum bpf_arg_type *arg_type)
6960 if (!meta->map_ptr) {
6961 /* kernel subsystem misconfigured verifier */
6962 verbose(env, "invalid map_ptr to access map->type\n");
6966 switch (meta->map_ptr->map_type) {
6967 case BPF_MAP_TYPE_SOCKMAP:
6968 case BPF_MAP_TYPE_SOCKHASH:
6969 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6970 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6972 verbose(env, "invalid arg_type for sockmap/sockhash\n");
6976 case BPF_MAP_TYPE_BLOOM_FILTER:
6977 if (meta->func_id == BPF_FUNC_map_peek_elem)
6978 *arg_type = ARG_PTR_TO_MAP_VALUE;
6986 struct bpf_reg_types {
6987 const enum bpf_reg_type types[10];
6991 static const struct bpf_reg_types sock_types = {
7001 static const struct bpf_reg_types btf_id_sock_common_types = {
7008 PTR_TO_BTF_ID | PTR_TRUSTED,
7010 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7014 static const struct bpf_reg_types mem_types = {
7022 PTR_TO_MEM | MEM_RINGBUF,
7024 PTR_TO_BTF_ID | PTR_TRUSTED,
7028 static const struct bpf_reg_types int_ptr_types = {
7038 static const struct bpf_reg_types spin_lock_types = {
7041 PTR_TO_BTF_ID | MEM_ALLOC,
7045 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7046 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7047 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7048 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7049 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7050 static const struct bpf_reg_types btf_ptr_types = {
7053 PTR_TO_BTF_ID | PTR_TRUSTED,
7054 PTR_TO_BTF_ID | MEM_RCU,
7057 static const struct bpf_reg_types percpu_btf_ptr_types = {
7059 PTR_TO_BTF_ID | MEM_PERCPU,
7060 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7063 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7064 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7065 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7066 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7067 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7068 static const struct bpf_reg_types dynptr_types = {
7071 CONST_PTR_TO_DYNPTR,
7075 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7076 [ARG_PTR_TO_MAP_KEY] = &mem_types,
7077 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
7078 [ARG_CONST_SIZE] = &scalar_types,
7079 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
7080 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
7081 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
7082 [ARG_PTR_TO_CTX] = &context_types,
7083 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
7085 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7087 [ARG_PTR_TO_SOCKET] = &fullsock_types,
7088 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
7089 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
7090 [ARG_PTR_TO_MEM] = &mem_types,
7091 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
7092 [ARG_PTR_TO_INT] = &int_ptr_types,
7093 [ARG_PTR_TO_LONG] = &int_ptr_types,
7094 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
7095 [ARG_PTR_TO_FUNC] = &func_ptr_types,
7096 [ARG_PTR_TO_STACK] = &stack_ptr_types,
7097 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
7098 [ARG_PTR_TO_TIMER] = &timer_types,
7099 [ARG_PTR_TO_KPTR] = &kptr_types,
7100 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
7103 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7104 enum bpf_arg_type arg_type,
7105 const u32 *arg_btf_id,
7106 struct bpf_call_arg_meta *meta)
7108 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7109 enum bpf_reg_type expected, type = reg->type;
7110 const struct bpf_reg_types *compatible;
7113 compatible = compatible_reg_types[base_type(arg_type)];
7115 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7119 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7120 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7122 * Same for MAYBE_NULL:
7124 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7125 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7127 * Therefore we fold these flags depending on the arg_type before comparison.
7129 if (arg_type & MEM_RDONLY)
7130 type &= ~MEM_RDONLY;
7131 if (arg_type & PTR_MAYBE_NULL)
7132 type &= ~PTR_MAYBE_NULL;
7134 if (meta->func_id == BPF_FUNC_kptr_xchg && type & MEM_ALLOC)
7137 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7138 expected = compatible->types[i];
7139 if (expected == NOT_INIT)
7142 if (type == expected)
7146 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7147 for (j = 0; j + 1 < i; j++)
7148 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7149 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7153 if (base_type(reg->type) != PTR_TO_BTF_ID)
7156 if (compatible == &mem_types) {
7157 if (!(arg_type & MEM_RDONLY)) {
7159 "%s() may write into memory pointed by R%d type=%s\n",
7160 func_id_name(meta->func_id),
7161 regno, reg_type_str(env, reg->type));
7167 switch ((int)reg->type) {
7169 case PTR_TO_BTF_ID | PTR_TRUSTED:
7170 case PTR_TO_BTF_ID | MEM_RCU:
7171 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7172 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7174 /* For bpf_sk_release, it needs to match against first member
7175 * 'struct sock_common', hence make an exception for it. This
7176 * allows bpf_sk_release to work for multiple socket types.
7178 bool strict_type_match = arg_type_is_release(arg_type) &&
7179 meta->func_id != BPF_FUNC_sk_release;
7181 if (type_may_be_null(reg->type) &&
7182 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7183 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7188 if (!compatible->btf_id) {
7189 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7192 arg_btf_id = compatible->btf_id;
7195 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7196 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7199 if (arg_btf_id == BPF_PTR_POISON) {
7200 verbose(env, "verifier internal error:");
7201 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7206 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7207 btf_vmlinux, *arg_btf_id,
7208 strict_type_match)) {
7209 verbose(env, "R%d is of type %s but %s is expected\n",
7210 regno, btf_type_name(reg->btf, reg->btf_id),
7211 btf_type_name(btf_vmlinux, *arg_btf_id));
7217 case PTR_TO_BTF_ID | MEM_ALLOC:
7218 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7219 meta->func_id != BPF_FUNC_kptr_xchg) {
7220 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7223 /* Handled by helper specific checks */
7225 case PTR_TO_BTF_ID | MEM_PERCPU:
7226 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7227 /* Handled by helper specific checks */
7230 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7236 static struct btf_field *
7237 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7239 struct btf_field *field;
7240 struct btf_record *rec;
7242 rec = reg_btf_record(reg);
7246 field = btf_record_find(rec, off, fields);
7253 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7254 const struct bpf_reg_state *reg, int regno,
7255 enum bpf_arg_type arg_type)
7257 u32 type = reg->type;
7259 /* When referenced register is passed to release function, its fixed
7262 * We will check arg_type_is_release reg has ref_obj_id when storing
7263 * meta->release_regno.
7265 if (arg_type_is_release(arg_type)) {
7266 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7267 * may not directly point to the object being released, but to
7268 * dynptr pointing to such object, which might be at some offset
7269 * on the stack. In that case, we simply to fallback to the
7272 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7275 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7276 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7277 return __check_ptr_off_reg(env, reg, regno, true);
7279 verbose(env, "R%d must have zero offset when passed to release func\n",
7281 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7282 btf_type_name(reg->btf, reg->btf_id), reg->off);
7286 /* Doing check_ptr_off_reg check for the offset will catch this
7287 * because fixed_off_ok is false, but checking here allows us
7288 * to give the user a better error message.
7291 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7295 return __check_ptr_off_reg(env, reg, regno, false);
7299 /* Pointer types where both fixed and variable offset is explicitly allowed: */
7302 case PTR_TO_PACKET_META:
7303 case PTR_TO_MAP_KEY:
7304 case PTR_TO_MAP_VALUE:
7306 case PTR_TO_MEM | MEM_RDONLY:
7307 case PTR_TO_MEM | MEM_RINGBUF:
7309 case PTR_TO_BUF | MEM_RDONLY:
7312 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7316 case PTR_TO_BTF_ID | MEM_ALLOC:
7317 case PTR_TO_BTF_ID | PTR_TRUSTED:
7318 case PTR_TO_BTF_ID | MEM_RCU:
7319 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7320 /* When referenced PTR_TO_BTF_ID is passed to release function,
7321 * its fixed offset must be 0. In the other cases, fixed offset
7322 * can be non-zero. This was already checked above. So pass
7323 * fixed_off_ok as true to allow fixed offset for all other
7324 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7325 * still need to do checks instead of returning.
7327 return __check_ptr_off_reg(env, reg, regno, true);
7329 return __check_ptr_off_reg(env, reg, regno, false);
7333 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7334 const struct bpf_func_proto *fn,
7335 struct bpf_reg_state *regs)
7337 struct bpf_reg_state *state = NULL;
7340 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7341 if (arg_type_is_dynptr(fn->arg_type[i])) {
7343 verbose(env, "verifier internal error: multiple dynptr args\n");
7346 state = ®s[BPF_REG_1 + i];
7350 verbose(env, "verifier internal error: no dynptr arg found\n");
7355 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7357 struct bpf_func_state *state = func(env, reg);
7360 if (reg->type == CONST_PTR_TO_DYNPTR)
7362 spi = dynptr_get_spi(env, reg);
7365 return state->stack[spi].spilled_ptr.id;
7368 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, 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->ref_obj_id;
7375 spi = dynptr_get_spi(env, reg);
7378 return state->stack[spi].spilled_ptr.ref_obj_id;
7381 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
7382 struct bpf_reg_state *reg)
7384 struct bpf_func_state *state = func(env, reg);
7387 if (reg->type == CONST_PTR_TO_DYNPTR)
7388 return reg->dynptr.type;
7390 spi = __get_spi(reg->off);
7392 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
7393 return BPF_DYNPTR_TYPE_INVALID;
7396 return state->stack[spi].spilled_ptr.dynptr.type;
7399 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
7400 struct bpf_call_arg_meta *meta,
7401 const struct bpf_func_proto *fn,
7404 u32 regno = BPF_REG_1 + arg;
7405 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7406 enum bpf_arg_type arg_type = fn->arg_type[arg];
7407 enum bpf_reg_type type = reg->type;
7408 u32 *arg_btf_id = NULL;
7411 if (arg_type == ARG_DONTCARE)
7414 err = check_reg_arg(env, regno, SRC_OP);
7418 if (arg_type == ARG_ANYTHING) {
7419 if (is_pointer_value(env, regno)) {
7420 verbose(env, "R%d leaks addr into helper function\n",
7427 if (type_is_pkt_pointer(type) &&
7428 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
7429 verbose(env, "helper access to the packet is not allowed\n");
7433 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
7434 err = resolve_map_arg_type(env, meta, &arg_type);
7439 if (register_is_null(reg) && type_may_be_null(arg_type))
7440 /* A NULL register has a SCALAR_VALUE type, so skip
7443 goto skip_type_check;
7445 /* arg_btf_id and arg_size are in a union. */
7446 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7447 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
7448 arg_btf_id = fn->arg_btf_id[arg];
7450 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7454 err = check_func_arg_reg_off(env, reg, regno, arg_type);
7459 if (arg_type_is_release(arg_type)) {
7460 if (arg_type_is_dynptr(arg_type)) {
7461 struct bpf_func_state *state = func(env, reg);
7464 /* Only dynptr created on stack can be released, thus
7465 * the get_spi and stack state checks for spilled_ptr
7466 * should only be done before process_dynptr_func for
7469 if (reg->type == PTR_TO_STACK) {
7470 spi = dynptr_get_spi(env, reg);
7471 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7472 verbose(env, "arg %d is an unacquired reference\n", regno);
7476 verbose(env, "cannot release unowned const bpf_dynptr\n");
7479 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
7480 verbose(env, "R%d must be referenced when passed to release function\n",
7484 if (meta->release_regno) {
7485 verbose(env, "verifier internal error: more than one release argument\n");
7488 meta->release_regno = regno;
7491 if (reg->ref_obj_id) {
7492 if (meta->ref_obj_id) {
7493 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
7494 regno, reg->ref_obj_id,
7498 meta->ref_obj_id = reg->ref_obj_id;
7501 switch (base_type(arg_type)) {
7502 case ARG_CONST_MAP_PTR:
7503 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
7504 if (meta->map_ptr) {
7505 /* Use map_uid (which is unique id of inner map) to reject:
7506 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
7507 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
7508 * if (inner_map1 && inner_map2) {
7509 * timer = bpf_map_lookup_elem(inner_map1);
7511 * // mismatch would have been allowed
7512 * bpf_timer_init(timer, inner_map2);
7515 * Comparing map_ptr is enough to distinguish normal and outer maps.
7517 if (meta->map_ptr != reg->map_ptr ||
7518 meta->map_uid != reg->map_uid) {
7520 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
7521 meta->map_uid, reg->map_uid);
7525 meta->map_ptr = reg->map_ptr;
7526 meta->map_uid = reg->map_uid;
7528 case ARG_PTR_TO_MAP_KEY:
7529 /* bpf_map_xxx(..., map_ptr, ..., key) call:
7530 * check that [key, key + map->key_size) are within
7531 * stack limits and initialized
7533 if (!meta->map_ptr) {
7534 /* in function declaration map_ptr must come before
7535 * map_key, so that it's verified and known before
7536 * we have to check map_key here. Otherwise it means
7537 * that kernel subsystem misconfigured verifier
7539 verbose(env, "invalid map_ptr to access map->key\n");
7542 err = check_helper_mem_access(env, regno,
7543 meta->map_ptr->key_size, false,
7546 case ARG_PTR_TO_MAP_VALUE:
7547 if (type_may_be_null(arg_type) && register_is_null(reg))
7550 /* bpf_map_xxx(..., map_ptr, ..., value) call:
7551 * check [value, value + map->value_size) validity
7553 if (!meta->map_ptr) {
7554 /* kernel subsystem misconfigured verifier */
7555 verbose(env, "invalid map_ptr to access map->value\n");
7558 meta->raw_mode = arg_type & MEM_UNINIT;
7559 err = check_helper_mem_access(env, regno,
7560 meta->map_ptr->value_size, false,
7563 case ARG_PTR_TO_PERCPU_BTF_ID:
7565 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
7568 meta->ret_btf = reg->btf;
7569 meta->ret_btf_id = reg->btf_id;
7571 case ARG_PTR_TO_SPIN_LOCK:
7572 if (in_rbtree_lock_required_cb(env)) {
7573 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
7576 if (meta->func_id == BPF_FUNC_spin_lock) {
7577 err = process_spin_lock(env, regno, true);
7580 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
7581 err = process_spin_lock(env, regno, false);
7585 verbose(env, "verifier internal error\n");
7589 case ARG_PTR_TO_TIMER:
7590 err = process_timer_func(env, regno, meta);
7594 case ARG_PTR_TO_FUNC:
7595 meta->subprogno = reg->subprogno;
7597 case ARG_PTR_TO_MEM:
7598 /* The access to this pointer is only checked when we hit the
7599 * next is_mem_size argument below.
7601 meta->raw_mode = arg_type & MEM_UNINIT;
7602 if (arg_type & MEM_FIXED_SIZE) {
7603 err = check_helper_mem_access(env, regno,
7604 fn->arg_size[arg], false,
7608 case ARG_CONST_SIZE:
7609 err = check_mem_size_reg(env, reg, regno, false, meta);
7611 case ARG_CONST_SIZE_OR_ZERO:
7612 err = check_mem_size_reg(env, reg, regno, true, meta);
7614 case ARG_PTR_TO_DYNPTR:
7615 err = process_dynptr_func(env, regno, insn_idx, arg_type);
7619 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
7620 if (!tnum_is_const(reg->var_off)) {
7621 verbose(env, "R%d is not a known constant'\n",
7625 meta->mem_size = reg->var_off.value;
7626 err = mark_chain_precision(env, regno);
7630 case ARG_PTR_TO_INT:
7631 case ARG_PTR_TO_LONG:
7633 int size = int_ptr_type_to_size(arg_type);
7635 err = check_helper_mem_access(env, regno, size, false, meta);
7638 err = check_ptr_alignment(env, reg, 0, size, true);
7641 case ARG_PTR_TO_CONST_STR:
7643 struct bpf_map *map = reg->map_ptr;
7648 if (!bpf_map_is_rdonly(map)) {
7649 verbose(env, "R%d does not point to a readonly map'\n", regno);
7653 if (!tnum_is_const(reg->var_off)) {
7654 verbose(env, "R%d is not a constant address'\n", regno);
7658 if (!map->ops->map_direct_value_addr) {
7659 verbose(env, "no direct value access support for this map type\n");
7663 err = check_map_access(env, regno, reg->off,
7664 map->value_size - reg->off, false,
7669 map_off = reg->off + reg->var_off.value;
7670 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
7672 verbose(env, "direct value access on string failed\n");
7676 str_ptr = (char *)(long)(map_addr);
7677 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
7678 verbose(env, "string is not zero-terminated\n");
7683 case ARG_PTR_TO_KPTR:
7684 err = process_kptr_func(env, regno, meta);
7693 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
7695 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7696 enum bpf_prog_type type = resolve_prog_type(env->prog);
7698 if (func_id != BPF_FUNC_map_update_elem)
7701 /* It's not possible to get access to a locked struct sock in these
7702 * contexts, so updating is safe.
7705 case BPF_PROG_TYPE_TRACING:
7706 if (eatype == BPF_TRACE_ITER)
7709 case BPF_PROG_TYPE_SOCKET_FILTER:
7710 case BPF_PROG_TYPE_SCHED_CLS:
7711 case BPF_PROG_TYPE_SCHED_ACT:
7712 case BPF_PROG_TYPE_XDP:
7713 case BPF_PROG_TYPE_SK_REUSEPORT:
7714 case BPF_PROG_TYPE_FLOW_DISSECTOR:
7715 case BPF_PROG_TYPE_SK_LOOKUP:
7721 verbose(env, "cannot update sockmap in this context\n");
7725 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
7727 return env->prog->jit_requested &&
7728 bpf_jit_supports_subprog_tailcalls();
7731 static int check_map_func_compatibility(struct bpf_verifier_env *env,
7732 struct bpf_map *map, int func_id)
7737 /* We need a two way check, first is from map perspective ... */
7738 switch (map->map_type) {
7739 case BPF_MAP_TYPE_PROG_ARRAY:
7740 if (func_id != BPF_FUNC_tail_call)
7743 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
7744 if (func_id != BPF_FUNC_perf_event_read &&
7745 func_id != BPF_FUNC_perf_event_output &&
7746 func_id != BPF_FUNC_skb_output &&
7747 func_id != BPF_FUNC_perf_event_read_value &&
7748 func_id != BPF_FUNC_xdp_output)
7751 case BPF_MAP_TYPE_RINGBUF:
7752 if (func_id != BPF_FUNC_ringbuf_output &&
7753 func_id != BPF_FUNC_ringbuf_reserve &&
7754 func_id != BPF_FUNC_ringbuf_query &&
7755 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
7756 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
7757 func_id != BPF_FUNC_ringbuf_discard_dynptr)
7760 case BPF_MAP_TYPE_USER_RINGBUF:
7761 if (func_id != BPF_FUNC_user_ringbuf_drain)
7764 case BPF_MAP_TYPE_STACK_TRACE:
7765 if (func_id != BPF_FUNC_get_stackid)
7768 case BPF_MAP_TYPE_CGROUP_ARRAY:
7769 if (func_id != BPF_FUNC_skb_under_cgroup &&
7770 func_id != BPF_FUNC_current_task_under_cgroup)
7773 case BPF_MAP_TYPE_CGROUP_STORAGE:
7774 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
7775 if (func_id != BPF_FUNC_get_local_storage)
7778 case BPF_MAP_TYPE_DEVMAP:
7779 case BPF_MAP_TYPE_DEVMAP_HASH:
7780 if (func_id != BPF_FUNC_redirect_map &&
7781 func_id != BPF_FUNC_map_lookup_elem)
7784 /* Restrict bpf side of cpumap and xskmap, open when use-cases
7787 case BPF_MAP_TYPE_CPUMAP:
7788 if (func_id != BPF_FUNC_redirect_map)
7791 case BPF_MAP_TYPE_XSKMAP:
7792 if (func_id != BPF_FUNC_redirect_map &&
7793 func_id != BPF_FUNC_map_lookup_elem)
7796 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
7797 case BPF_MAP_TYPE_HASH_OF_MAPS:
7798 if (func_id != BPF_FUNC_map_lookup_elem)
7801 case BPF_MAP_TYPE_SOCKMAP:
7802 if (func_id != BPF_FUNC_sk_redirect_map &&
7803 func_id != BPF_FUNC_sock_map_update &&
7804 func_id != BPF_FUNC_map_delete_elem &&
7805 func_id != BPF_FUNC_msg_redirect_map &&
7806 func_id != BPF_FUNC_sk_select_reuseport &&
7807 func_id != BPF_FUNC_map_lookup_elem &&
7808 !may_update_sockmap(env, func_id))
7811 case BPF_MAP_TYPE_SOCKHASH:
7812 if (func_id != BPF_FUNC_sk_redirect_hash &&
7813 func_id != BPF_FUNC_sock_hash_update &&
7814 func_id != BPF_FUNC_map_delete_elem &&
7815 func_id != BPF_FUNC_msg_redirect_hash &&
7816 func_id != BPF_FUNC_sk_select_reuseport &&
7817 func_id != BPF_FUNC_map_lookup_elem &&
7818 !may_update_sockmap(env, func_id))
7821 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
7822 if (func_id != BPF_FUNC_sk_select_reuseport)
7825 case BPF_MAP_TYPE_QUEUE:
7826 case BPF_MAP_TYPE_STACK:
7827 if (func_id != BPF_FUNC_map_peek_elem &&
7828 func_id != BPF_FUNC_map_pop_elem &&
7829 func_id != BPF_FUNC_map_push_elem)
7832 case BPF_MAP_TYPE_SK_STORAGE:
7833 if (func_id != BPF_FUNC_sk_storage_get &&
7834 func_id != BPF_FUNC_sk_storage_delete &&
7835 func_id != BPF_FUNC_kptr_xchg)
7838 case BPF_MAP_TYPE_INODE_STORAGE:
7839 if (func_id != BPF_FUNC_inode_storage_get &&
7840 func_id != BPF_FUNC_inode_storage_delete &&
7841 func_id != BPF_FUNC_kptr_xchg)
7844 case BPF_MAP_TYPE_TASK_STORAGE:
7845 if (func_id != BPF_FUNC_task_storage_get &&
7846 func_id != BPF_FUNC_task_storage_delete &&
7847 func_id != BPF_FUNC_kptr_xchg)
7850 case BPF_MAP_TYPE_CGRP_STORAGE:
7851 if (func_id != BPF_FUNC_cgrp_storage_get &&
7852 func_id != BPF_FUNC_cgrp_storage_delete &&
7853 func_id != BPF_FUNC_kptr_xchg)
7856 case BPF_MAP_TYPE_BLOOM_FILTER:
7857 if (func_id != BPF_FUNC_map_peek_elem &&
7858 func_id != BPF_FUNC_map_push_elem)
7865 /* ... and second from the function itself. */
7867 case BPF_FUNC_tail_call:
7868 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
7870 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
7871 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
7875 case BPF_FUNC_perf_event_read:
7876 case BPF_FUNC_perf_event_output:
7877 case BPF_FUNC_perf_event_read_value:
7878 case BPF_FUNC_skb_output:
7879 case BPF_FUNC_xdp_output:
7880 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
7883 case BPF_FUNC_ringbuf_output:
7884 case BPF_FUNC_ringbuf_reserve:
7885 case BPF_FUNC_ringbuf_query:
7886 case BPF_FUNC_ringbuf_reserve_dynptr:
7887 case BPF_FUNC_ringbuf_submit_dynptr:
7888 case BPF_FUNC_ringbuf_discard_dynptr:
7889 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
7892 case BPF_FUNC_user_ringbuf_drain:
7893 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
7896 case BPF_FUNC_get_stackid:
7897 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
7900 case BPF_FUNC_current_task_under_cgroup:
7901 case BPF_FUNC_skb_under_cgroup:
7902 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
7905 case BPF_FUNC_redirect_map:
7906 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
7907 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
7908 map->map_type != BPF_MAP_TYPE_CPUMAP &&
7909 map->map_type != BPF_MAP_TYPE_XSKMAP)
7912 case BPF_FUNC_sk_redirect_map:
7913 case BPF_FUNC_msg_redirect_map:
7914 case BPF_FUNC_sock_map_update:
7915 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
7918 case BPF_FUNC_sk_redirect_hash:
7919 case BPF_FUNC_msg_redirect_hash:
7920 case BPF_FUNC_sock_hash_update:
7921 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
7924 case BPF_FUNC_get_local_storage:
7925 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
7926 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
7929 case BPF_FUNC_sk_select_reuseport:
7930 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
7931 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
7932 map->map_type != BPF_MAP_TYPE_SOCKHASH)
7935 case BPF_FUNC_map_pop_elem:
7936 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7937 map->map_type != BPF_MAP_TYPE_STACK)
7940 case BPF_FUNC_map_peek_elem:
7941 case BPF_FUNC_map_push_elem:
7942 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7943 map->map_type != BPF_MAP_TYPE_STACK &&
7944 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
7947 case BPF_FUNC_map_lookup_percpu_elem:
7948 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
7949 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7950 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
7953 case BPF_FUNC_sk_storage_get:
7954 case BPF_FUNC_sk_storage_delete:
7955 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
7958 case BPF_FUNC_inode_storage_get:
7959 case BPF_FUNC_inode_storage_delete:
7960 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
7963 case BPF_FUNC_task_storage_get:
7964 case BPF_FUNC_task_storage_delete:
7965 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
7968 case BPF_FUNC_cgrp_storage_get:
7969 case BPF_FUNC_cgrp_storage_delete:
7970 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
7979 verbose(env, "cannot pass map_type %d into func %s#%d\n",
7980 map->map_type, func_id_name(func_id), func_id);
7984 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
7988 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
7990 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
7992 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
7994 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
7996 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
7999 /* We only support one arg being in raw mode at the moment,
8000 * which is sufficient for the helper functions we have
8006 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8008 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8009 bool has_size = fn->arg_size[arg] != 0;
8010 bool is_next_size = false;
8012 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8013 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8015 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8016 return is_next_size;
8018 return has_size == is_next_size || is_next_size == is_fixed;
8021 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8023 /* bpf_xxx(..., buf, len) call will access 'len'
8024 * bytes from memory 'buf'. Both arg types need
8025 * to be paired, so make sure there's no buggy
8026 * helper function specification.
8028 if (arg_type_is_mem_size(fn->arg1_type) ||
8029 check_args_pair_invalid(fn, 0) ||
8030 check_args_pair_invalid(fn, 1) ||
8031 check_args_pair_invalid(fn, 2) ||
8032 check_args_pair_invalid(fn, 3) ||
8033 check_args_pair_invalid(fn, 4))
8039 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8043 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8044 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8045 return !!fn->arg_btf_id[i];
8046 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8047 return fn->arg_btf_id[i] == BPF_PTR_POISON;
8048 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8049 /* arg_btf_id and arg_size are in a union. */
8050 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8051 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8058 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8060 return check_raw_mode_ok(fn) &&
8061 check_arg_pair_ok(fn) &&
8062 check_btf_id_ok(fn) ? 0 : -EINVAL;
8065 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8066 * are now invalid, so turn them into unknown SCALAR_VALUE.
8068 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8069 * since these slices point to packet data.
8071 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8073 struct bpf_func_state *state;
8074 struct bpf_reg_state *reg;
8076 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8077 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8078 mark_reg_invalid(env, reg);
8084 BEYOND_PKT_END = -2,
8087 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8089 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8090 struct bpf_reg_state *reg = &state->regs[regn];
8092 if (reg->type != PTR_TO_PACKET)
8093 /* PTR_TO_PACKET_META is not supported yet */
8096 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8097 * How far beyond pkt_end it goes is unknown.
8098 * if (!range_open) it's the case of pkt >= pkt_end
8099 * if (range_open) it's the case of pkt > pkt_end
8100 * hence this pointer is at least 1 byte bigger than pkt_end
8103 reg->range = BEYOND_PKT_END;
8105 reg->range = AT_PKT_END;
8108 /* The pointer with the specified id has released its reference to kernel
8109 * resources. Identify all copies of the same pointer and clear the reference.
8111 static int release_reference(struct bpf_verifier_env *env,
8114 struct bpf_func_state *state;
8115 struct bpf_reg_state *reg;
8118 err = release_reference_state(cur_func(env), ref_obj_id);
8122 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8123 if (reg->ref_obj_id == ref_obj_id)
8124 mark_reg_invalid(env, reg);
8130 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8132 struct bpf_func_state *unused;
8133 struct bpf_reg_state *reg;
8135 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8136 if (type_is_non_owning_ref(reg->type))
8137 mark_reg_invalid(env, reg);
8141 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8142 struct bpf_reg_state *regs)
8146 /* after the call registers r0 - r5 were scratched */
8147 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8148 mark_reg_not_init(env, regs, caller_saved[i]);
8149 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8153 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8154 struct bpf_func_state *caller,
8155 struct bpf_func_state *callee,
8158 static int set_callee_state(struct bpf_verifier_env *env,
8159 struct bpf_func_state *caller,
8160 struct bpf_func_state *callee, int insn_idx);
8162 static bool is_callback_calling_kfunc(u32 btf_id);
8164 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8165 int *insn_idx, int subprog,
8166 set_callee_state_fn set_callee_state_cb)
8168 struct bpf_verifier_state *state = env->cur_state;
8169 struct bpf_func_info_aux *func_info_aux;
8170 struct bpf_func_state *caller, *callee;
8172 bool is_global = false;
8174 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8175 verbose(env, "the call stack of %d frames is too deep\n",
8176 state->curframe + 2);
8180 caller = state->frame[state->curframe];
8181 if (state->frame[state->curframe + 1]) {
8182 verbose(env, "verifier bug. Frame %d already allocated\n",
8183 state->curframe + 1);
8187 func_info_aux = env->prog->aux->func_info_aux;
8189 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
8190 err = btf_check_subprog_call(env, subprog, caller->regs);
8195 verbose(env, "Caller passes invalid args into func#%d\n",
8199 if (env->log.level & BPF_LOG_LEVEL)
8201 "Func#%d is global and valid. Skipping.\n",
8203 clear_caller_saved_regs(env, caller->regs);
8205 /* All global functions return a 64-bit SCALAR_VALUE */
8206 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8207 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8209 /* continue with next insn after call */
8214 /* set_callee_state is used for direct subprog calls, but we are
8215 * interested in validating only BPF helpers that can call subprogs as
8218 if (set_callee_state_cb != set_callee_state) {
8219 if (bpf_pseudo_kfunc_call(insn) &&
8220 !is_callback_calling_kfunc(insn->imm)) {
8221 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8222 func_id_name(insn->imm), insn->imm);
8224 } else if (!bpf_pseudo_kfunc_call(insn) &&
8225 !is_callback_calling_function(insn->imm)) { /* helper */
8226 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8227 func_id_name(insn->imm), insn->imm);
8232 if (insn->code == (BPF_JMP | BPF_CALL) &&
8233 insn->src_reg == 0 &&
8234 insn->imm == BPF_FUNC_timer_set_callback) {
8235 struct bpf_verifier_state *async_cb;
8237 /* there is no real recursion here. timer callbacks are async */
8238 env->subprog_info[subprog].is_async_cb = true;
8239 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8240 *insn_idx, subprog);
8243 callee = async_cb->frame[0];
8244 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8246 /* Convert bpf_timer_set_callback() args into timer callback args */
8247 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8251 clear_caller_saved_regs(env, caller->regs);
8252 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8253 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8254 /* continue with next insn after call */
8258 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8261 state->frame[state->curframe + 1] = callee;
8263 /* callee cannot access r0, r6 - r9 for reading and has to write
8264 * into its own stack before reading from it.
8265 * callee can read/write into caller's stack
8267 init_func_state(env, callee,
8268 /* remember the callsite, it will be used by bpf_exit */
8269 *insn_idx /* callsite */,
8270 state->curframe + 1 /* frameno within this callchain */,
8271 subprog /* subprog number within this prog */);
8273 /* Transfer references to the callee */
8274 err = copy_reference_state(callee, caller);
8278 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8282 clear_caller_saved_regs(env, caller->regs);
8284 /* only increment it after check_reg_arg() finished */
8287 /* and go analyze first insn of the callee */
8288 *insn_idx = env->subprog_info[subprog].start - 1;
8290 if (env->log.level & BPF_LOG_LEVEL) {
8291 verbose(env, "caller:\n");
8292 print_verifier_state(env, caller, true);
8293 verbose(env, "callee:\n");
8294 print_verifier_state(env, callee, true);
8299 free_func_state(callee);
8300 state->frame[state->curframe + 1] = NULL;
8304 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8305 struct bpf_func_state *caller,
8306 struct bpf_func_state *callee)
8308 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8309 * void *callback_ctx, u64 flags);
8310 * callback_fn(struct bpf_map *map, void *key, void *value,
8311 * void *callback_ctx);
8313 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8315 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8316 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8317 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8319 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8320 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8321 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8323 /* pointer to stack or null */
8324 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8327 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8331 static int set_callee_state(struct bpf_verifier_env *env,
8332 struct bpf_func_state *caller,
8333 struct bpf_func_state *callee, int insn_idx)
8337 /* copy r1 - r5 args that callee can access. The copy includes parent
8338 * pointers, which connects us up to the liveness chain
8340 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8341 callee->regs[i] = caller->regs[i];
8345 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8348 int subprog, target_insn;
8350 target_insn = *insn_idx + insn->imm + 1;
8351 subprog = find_subprog(env, target_insn);
8353 verbose(env, "verifier bug. No program starts at insn %d\n",
8358 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8361 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8362 struct bpf_func_state *caller,
8363 struct bpf_func_state *callee,
8366 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8367 struct bpf_map *map;
8370 if (bpf_map_ptr_poisoned(insn_aux)) {
8371 verbose(env, "tail_call abusing map_ptr\n");
8375 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8376 if (!map->ops->map_set_for_each_callback_args ||
8377 !map->ops->map_for_each_callback) {
8378 verbose(env, "callback function not allowed for map\n");
8382 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
8386 callee->in_callback_fn = true;
8387 callee->callback_ret_range = tnum_range(0, 1);
8391 static int set_loop_callback_state(struct bpf_verifier_env *env,
8392 struct bpf_func_state *caller,
8393 struct bpf_func_state *callee,
8396 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
8398 * callback_fn(u32 index, void *callback_ctx);
8400 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
8401 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8404 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8405 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8406 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8408 callee->in_callback_fn = true;
8409 callee->callback_ret_range = tnum_range(0, 1);
8413 static int set_timer_callback_state(struct bpf_verifier_env *env,
8414 struct bpf_func_state *caller,
8415 struct bpf_func_state *callee,
8418 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
8420 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
8421 * callback_fn(struct bpf_map *map, void *key, void *value);
8423 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
8424 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
8425 callee->regs[BPF_REG_1].map_ptr = map_ptr;
8427 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8428 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8429 callee->regs[BPF_REG_2].map_ptr = map_ptr;
8431 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8432 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8433 callee->regs[BPF_REG_3].map_ptr = map_ptr;
8436 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8437 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8438 callee->in_async_callback_fn = true;
8439 callee->callback_ret_range = tnum_range(0, 1);
8443 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
8444 struct bpf_func_state *caller,
8445 struct bpf_func_state *callee,
8448 /* bpf_find_vma(struct task_struct *task, u64 addr,
8449 * void *callback_fn, void *callback_ctx, u64 flags)
8450 * (callback_fn)(struct task_struct *task,
8451 * struct vm_area_struct *vma, void *callback_ctx);
8453 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8455 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8456 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8457 callee->regs[BPF_REG_2].btf = btf_vmlinux;
8458 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8460 /* pointer to stack or null */
8461 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8464 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8465 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8466 callee->in_callback_fn = true;
8467 callee->callback_ret_range = tnum_range(0, 1);
8471 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8472 struct bpf_func_state *caller,
8473 struct bpf_func_state *callee,
8476 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8477 * callback_ctx, u64 flags);
8478 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8480 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
8481 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
8482 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8485 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8486 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8487 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8489 callee->in_callback_fn = true;
8490 callee->callback_ret_range = tnum_range(0, 1);
8494 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
8495 struct bpf_func_state *caller,
8496 struct bpf_func_state *callee,
8499 /* void bpf_rbtree_add(struct bpf_rb_root *root, struct bpf_rb_node *node,
8500 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
8502 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add is the same PTR_TO_BTF_ID w/ offset
8503 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
8504 * by this point, so look at 'root'
8506 struct btf_field *field;
8508 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
8510 if (!field || !field->graph_root.value_btf_id)
8513 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
8514 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
8515 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
8516 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
8518 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8519 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8520 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8521 callee->in_callback_fn = true;
8522 callee->callback_ret_range = tnum_range(0, 1);
8526 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
8528 /* Are we currently verifying the callback for a rbtree helper that must
8529 * be called with lock held? If so, no need to complain about unreleased
8532 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
8534 struct bpf_verifier_state *state = env->cur_state;
8535 struct bpf_insn *insn = env->prog->insnsi;
8536 struct bpf_func_state *callee;
8539 if (!state->curframe)
8542 callee = state->frame[state->curframe];
8544 if (!callee->in_callback_fn)
8547 kfunc_btf_id = insn[callee->callsite].imm;
8548 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
8551 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
8553 struct bpf_verifier_state *state = env->cur_state;
8554 struct bpf_func_state *caller, *callee;
8555 struct bpf_reg_state *r0;
8558 callee = state->frame[state->curframe];
8559 r0 = &callee->regs[BPF_REG_0];
8560 if (r0->type == PTR_TO_STACK) {
8561 /* technically it's ok to return caller's stack pointer
8562 * (or caller's caller's pointer) back to the caller,
8563 * since these pointers are valid. Only current stack
8564 * pointer will be invalid as soon as function exits,
8565 * but let's be conservative
8567 verbose(env, "cannot return stack pointer to the caller\n");
8571 caller = state->frame[state->curframe - 1];
8572 if (callee->in_callback_fn) {
8573 /* enforce R0 return value range [0, 1]. */
8574 struct tnum range = callee->callback_ret_range;
8576 if (r0->type != SCALAR_VALUE) {
8577 verbose(env, "R0 not a scalar value\n");
8580 if (!tnum_in(range, r0->var_off)) {
8581 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
8585 /* return to the caller whatever r0 had in the callee */
8586 caller->regs[BPF_REG_0] = *r0;
8589 /* callback_fn frame should have released its own additions to parent's
8590 * reference state at this point, or check_reference_leak would
8591 * complain, hence it must be the same as the caller. There is no need
8594 if (!callee->in_callback_fn) {
8595 /* Transfer references to the caller */
8596 err = copy_reference_state(caller, callee);
8601 *insn_idx = callee->callsite + 1;
8602 if (env->log.level & BPF_LOG_LEVEL) {
8603 verbose(env, "returning from callee:\n");
8604 print_verifier_state(env, callee, true);
8605 verbose(env, "to caller at %d:\n", *insn_idx);
8606 print_verifier_state(env, caller, true);
8608 /* clear everything in the callee */
8609 free_func_state(callee);
8610 state->frame[state->curframe--] = NULL;
8614 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
8616 struct bpf_call_arg_meta *meta)
8618 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
8620 if (ret_type != RET_INTEGER ||
8621 (func_id != BPF_FUNC_get_stack &&
8622 func_id != BPF_FUNC_get_task_stack &&
8623 func_id != BPF_FUNC_probe_read_str &&
8624 func_id != BPF_FUNC_probe_read_kernel_str &&
8625 func_id != BPF_FUNC_probe_read_user_str))
8628 ret_reg->smax_value = meta->msize_max_value;
8629 ret_reg->s32_max_value = meta->msize_max_value;
8630 ret_reg->smin_value = -MAX_ERRNO;
8631 ret_reg->s32_min_value = -MAX_ERRNO;
8632 reg_bounds_sync(ret_reg);
8636 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8637 int func_id, int insn_idx)
8639 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8640 struct bpf_map *map = meta->map_ptr;
8642 if (func_id != BPF_FUNC_tail_call &&
8643 func_id != BPF_FUNC_map_lookup_elem &&
8644 func_id != BPF_FUNC_map_update_elem &&
8645 func_id != BPF_FUNC_map_delete_elem &&
8646 func_id != BPF_FUNC_map_push_elem &&
8647 func_id != BPF_FUNC_map_pop_elem &&
8648 func_id != BPF_FUNC_map_peek_elem &&
8649 func_id != BPF_FUNC_for_each_map_elem &&
8650 func_id != BPF_FUNC_redirect_map &&
8651 func_id != BPF_FUNC_map_lookup_percpu_elem)
8655 verbose(env, "kernel subsystem misconfigured verifier\n");
8659 /* In case of read-only, some additional restrictions
8660 * need to be applied in order to prevent altering the
8661 * state of the map from program side.
8663 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
8664 (func_id == BPF_FUNC_map_delete_elem ||
8665 func_id == BPF_FUNC_map_update_elem ||
8666 func_id == BPF_FUNC_map_push_elem ||
8667 func_id == BPF_FUNC_map_pop_elem)) {
8668 verbose(env, "write into map forbidden\n");
8672 if (!BPF_MAP_PTR(aux->map_ptr_state))
8673 bpf_map_ptr_store(aux, meta->map_ptr,
8674 !meta->map_ptr->bypass_spec_v1);
8675 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
8676 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
8677 !meta->map_ptr->bypass_spec_v1);
8682 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8683 int func_id, int insn_idx)
8685 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8686 struct bpf_reg_state *regs = cur_regs(env), *reg;
8687 struct bpf_map *map = meta->map_ptr;
8691 if (func_id != BPF_FUNC_tail_call)
8693 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
8694 verbose(env, "kernel subsystem misconfigured verifier\n");
8698 reg = ®s[BPF_REG_3];
8699 val = reg->var_off.value;
8700 max = map->max_entries;
8702 if (!(register_is_const(reg) && val < max)) {
8703 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8707 err = mark_chain_precision(env, BPF_REG_3);
8710 if (bpf_map_key_unseen(aux))
8711 bpf_map_key_store(aux, val);
8712 else if (!bpf_map_key_poisoned(aux) &&
8713 bpf_map_key_immediate(aux) != val)
8714 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8718 static int check_reference_leak(struct bpf_verifier_env *env)
8720 struct bpf_func_state *state = cur_func(env);
8721 bool refs_lingering = false;
8724 if (state->frameno && !state->in_callback_fn)
8727 for (i = 0; i < state->acquired_refs; i++) {
8728 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
8730 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
8731 state->refs[i].id, state->refs[i].insn_idx);
8732 refs_lingering = true;
8734 return refs_lingering ? -EINVAL : 0;
8737 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
8738 struct bpf_reg_state *regs)
8740 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
8741 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
8742 struct bpf_map *fmt_map = fmt_reg->map_ptr;
8743 struct bpf_bprintf_data data = {};
8744 int err, fmt_map_off, num_args;
8748 /* data must be an array of u64 */
8749 if (data_len_reg->var_off.value % 8)
8751 num_args = data_len_reg->var_off.value / 8;
8753 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
8754 * and map_direct_value_addr is set.
8756 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
8757 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
8760 verbose(env, "verifier bug\n");
8763 fmt = (char *)(long)fmt_addr + fmt_map_off;
8765 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
8766 * can focus on validating the format specifiers.
8768 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
8770 verbose(env, "Invalid format string\n");
8775 static int check_get_func_ip(struct bpf_verifier_env *env)
8777 enum bpf_prog_type type = resolve_prog_type(env->prog);
8778 int func_id = BPF_FUNC_get_func_ip;
8780 if (type == BPF_PROG_TYPE_TRACING) {
8781 if (!bpf_prog_has_trampoline(env->prog)) {
8782 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
8783 func_id_name(func_id), func_id);
8787 } else if (type == BPF_PROG_TYPE_KPROBE) {
8791 verbose(env, "func %s#%d not supported for program type %d\n",
8792 func_id_name(func_id), func_id, type);
8796 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
8798 return &env->insn_aux_data[env->insn_idx];
8801 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
8803 struct bpf_reg_state *regs = cur_regs(env);
8804 struct bpf_reg_state *reg = ®s[BPF_REG_4];
8805 bool reg_is_null = register_is_null(reg);
8808 mark_chain_precision(env, BPF_REG_4);
8813 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
8815 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
8817 if (!state->initialized) {
8818 state->initialized = 1;
8819 state->fit_for_inline = loop_flag_is_zero(env);
8820 state->callback_subprogno = subprogno;
8824 if (!state->fit_for_inline)
8827 state->fit_for_inline = (loop_flag_is_zero(env) &&
8828 state->callback_subprogno == subprogno);
8831 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8834 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8835 const struct bpf_func_proto *fn = NULL;
8836 enum bpf_return_type ret_type;
8837 enum bpf_type_flag ret_flag;
8838 struct bpf_reg_state *regs;
8839 struct bpf_call_arg_meta meta;
8840 int insn_idx = *insn_idx_p;
8842 int i, err, func_id;
8844 /* find function prototype */
8845 func_id = insn->imm;
8846 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
8847 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
8852 if (env->ops->get_func_proto)
8853 fn = env->ops->get_func_proto(func_id, env->prog);
8855 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
8860 /* eBPF programs must be GPL compatible to use GPL-ed functions */
8861 if (!env->prog->gpl_compatible && fn->gpl_only) {
8862 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
8866 if (fn->allowed && !fn->allowed(env->prog)) {
8867 verbose(env, "helper call is not allowed in probe\n");
8871 if (!env->prog->aux->sleepable && fn->might_sleep) {
8872 verbose(env, "helper call might sleep in a non-sleepable prog\n");
8876 /* With LD_ABS/IND some JITs save/restore skb from r1. */
8877 changes_data = bpf_helper_changes_pkt_data(fn->func);
8878 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
8879 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
8880 func_id_name(func_id), func_id);
8884 memset(&meta, 0, sizeof(meta));
8885 meta.pkt_access = fn->pkt_access;
8887 err = check_func_proto(fn, func_id);
8889 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
8890 func_id_name(func_id), func_id);
8894 if (env->cur_state->active_rcu_lock) {
8895 if (fn->might_sleep) {
8896 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
8897 func_id_name(func_id), func_id);
8901 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
8902 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
8905 meta.func_id = func_id;
8907 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8908 err = check_func_arg(env, i, &meta, fn, insn_idx);
8913 err = record_func_map(env, &meta, func_id, insn_idx);
8917 err = record_func_key(env, &meta, func_id, insn_idx);
8921 /* Mark slots with STACK_MISC in case of raw mode, stack offset
8922 * is inferred from register state.
8924 for (i = 0; i < meta.access_size; i++) {
8925 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
8926 BPF_WRITE, -1, false);
8931 regs = cur_regs(env);
8933 if (meta.release_regno) {
8935 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8936 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
8937 * is safe to do directly.
8939 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
8940 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
8941 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
8944 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
8945 } else if (meta.ref_obj_id) {
8946 err = release_reference(env, meta.ref_obj_id);
8947 } else if (register_is_null(®s[meta.release_regno])) {
8948 /* meta.ref_obj_id can only be 0 if register that is meant to be
8949 * released is NULL, which must be > R0.
8954 verbose(env, "func %s#%d reference has not been acquired before\n",
8955 func_id_name(func_id), func_id);
8961 case BPF_FUNC_tail_call:
8962 err = check_reference_leak(env);
8964 verbose(env, "tail_call would lead to reference leak\n");
8968 case BPF_FUNC_get_local_storage:
8969 /* check that flags argument in get_local_storage(map, flags) is 0,
8970 * this is required because get_local_storage() can't return an error.
8972 if (!register_is_null(®s[BPF_REG_2])) {
8973 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
8977 case BPF_FUNC_for_each_map_elem:
8978 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8979 set_map_elem_callback_state);
8981 case BPF_FUNC_timer_set_callback:
8982 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8983 set_timer_callback_state);
8985 case BPF_FUNC_find_vma:
8986 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8987 set_find_vma_callback_state);
8989 case BPF_FUNC_snprintf:
8990 err = check_bpf_snprintf_call(env, regs);
8993 update_loop_inline_state(env, meta.subprogno);
8994 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8995 set_loop_callback_state);
8997 case BPF_FUNC_dynptr_from_mem:
8998 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
8999 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9000 reg_type_str(env, regs[BPF_REG_1].type));
9004 case BPF_FUNC_set_retval:
9005 if (prog_type == BPF_PROG_TYPE_LSM &&
9006 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9007 if (!env->prog->aux->attach_func_proto->type) {
9008 /* Make sure programs that attach to void
9009 * hooks don't try to modify return value.
9011 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9016 case BPF_FUNC_dynptr_data:
9018 struct bpf_reg_state *reg;
9021 reg = get_dynptr_arg_reg(env, fn, regs);
9026 if (meta.dynptr_id) {
9027 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9030 if (meta.ref_obj_id) {
9031 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9035 id = dynptr_id(env, reg);
9037 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9041 ref_obj_id = dynptr_ref_obj_id(env, reg);
9042 if (ref_obj_id < 0) {
9043 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9047 meta.dynptr_id = id;
9048 meta.ref_obj_id = ref_obj_id;
9052 case BPF_FUNC_dynptr_write:
9054 enum bpf_dynptr_type dynptr_type;
9055 struct bpf_reg_state *reg;
9057 reg = get_dynptr_arg_reg(env, fn, regs);
9061 dynptr_type = dynptr_get_type(env, reg);
9062 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9065 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9066 /* this will trigger clear_all_pkt_pointers(), which will
9067 * invalidate all dynptr slices associated with the skb
9069 changes_data = true;
9073 case BPF_FUNC_user_ringbuf_drain:
9074 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9075 set_user_ringbuf_callback_state);
9082 /* reset caller saved regs */
9083 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9084 mark_reg_not_init(env, regs, caller_saved[i]);
9085 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9088 /* helper call returns 64-bit value. */
9089 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9091 /* update return register (already marked as written above) */
9092 ret_type = fn->ret_type;
9093 ret_flag = type_flag(ret_type);
9095 switch (base_type(ret_type)) {
9097 /* sets type to SCALAR_VALUE */
9098 mark_reg_unknown(env, regs, BPF_REG_0);
9101 regs[BPF_REG_0].type = NOT_INIT;
9103 case RET_PTR_TO_MAP_VALUE:
9104 /* There is no offset yet applied, variable or fixed */
9105 mark_reg_known_zero(env, regs, BPF_REG_0);
9106 /* remember map_ptr, so that check_map_access()
9107 * can check 'value_size' boundary of memory access
9108 * to map element returned from bpf_map_lookup_elem()
9110 if (meta.map_ptr == NULL) {
9112 "kernel subsystem misconfigured verifier\n");
9115 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9116 regs[BPF_REG_0].map_uid = meta.map_uid;
9117 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9118 if (!type_may_be_null(ret_type) &&
9119 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9120 regs[BPF_REG_0].id = ++env->id_gen;
9123 case RET_PTR_TO_SOCKET:
9124 mark_reg_known_zero(env, regs, BPF_REG_0);
9125 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9127 case RET_PTR_TO_SOCK_COMMON:
9128 mark_reg_known_zero(env, regs, BPF_REG_0);
9129 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9131 case RET_PTR_TO_TCP_SOCK:
9132 mark_reg_known_zero(env, regs, BPF_REG_0);
9133 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9135 case RET_PTR_TO_MEM:
9136 mark_reg_known_zero(env, regs, BPF_REG_0);
9137 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9138 regs[BPF_REG_0].mem_size = meta.mem_size;
9140 case RET_PTR_TO_MEM_OR_BTF_ID:
9142 const struct btf_type *t;
9144 mark_reg_known_zero(env, regs, BPF_REG_0);
9145 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9146 if (!btf_type_is_struct(t)) {
9148 const struct btf_type *ret;
9151 /* resolve the type size of ksym. */
9152 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9154 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9155 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9156 tname, PTR_ERR(ret));
9159 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9160 regs[BPF_REG_0].mem_size = tsize;
9162 /* MEM_RDONLY may be carried from ret_flag, but it
9163 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9164 * it will confuse the check of PTR_TO_BTF_ID in
9165 * check_mem_access().
9167 ret_flag &= ~MEM_RDONLY;
9169 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9170 regs[BPF_REG_0].btf = meta.ret_btf;
9171 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9175 case RET_PTR_TO_BTF_ID:
9177 struct btf *ret_btf;
9180 mark_reg_known_zero(env, regs, BPF_REG_0);
9181 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9182 if (func_id == BPF_FUNC_kptr_xchg) {
9183 ret_btf = meta.kptr_field->kptr.btf;
9184 ret_btf_id = meta.kptr_field->kptr.btf_id;
9185 if (!btf_is_kernel(ret_btf))
9186 regs[BPF_REG_0].type |= MEM_ALLOC;
9188 if (fn->ret_btf_id == BPF_PTR_POISON) {
9189 verbose(env, "verifier internal error:");
9190 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9191 func_id_name(func_id));
9194 ret_btf = btf_vmlinux;
9195 ret_btf_id = *fn->ret_btf_id;
9197 if (ret_btf_id == 0) {
9198 verbose(env, "invalid return type %u of func %s#%d\n",
9199 base_type(ret_type), func_id_name(func_id),
9203 regs[BPF_REG_0].btf = ret_btf;
9204 regs[BPF_REG_0].btf_id = ret_btf_id;
9208 verbose(env, "unknown return type %u of func %s#%d\n",
9209 base_type(ret_type), func_id_name(func_id), func_id);
9213 if (type_may_be_null(regs[BPF_REG_0].type))
9214 regs[BPF_REG_0].id = ++env->id_gen;
9216 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9217 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9218 func_id_name(func_id), func_id);
9222 if (is_dynptr_ref_function(func_id))
9223 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9225 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9226 /* For release_reference() */
9227 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9228 } else if (is_acquire_function(func_id, meta.map_ptr)) {
9229 int id = acquire_reference_state(env, insn_idx);
9233 /* For mark_ptr_or_null_reg() */
9234 regs[BPF_REG_0].id = id;
9235 /* For release_reference() */
9236 regs[BPF_REG_0].ref_obj_id = id;
9239 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9241 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9245 if ((func_id == BPF_FUNC_get_stack ||
9246 func_id == BPF_FUNC_get_task_stack) &&
9247 !env->prog->has_callchain_buf) {
9248 const char *err_str;
9250 #ifdef CONFIG_PERF_EVENTS
9251 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9252 err_str = "cannot get callchain buffer for func %s#%d\n";
9255 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9258 verbose(env, err_str, func_id_name(func_id), func_id);
9262 env->prog->has_callchain_buf = true;
9265 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9266 env->prog->call_get_stack = true;
9268 if (func_id == BPF_FUNC_get_func_ip) {
9269 if (check_get_func_ip(env))
9271 env->prog->call_get_func_ip = true;
9275 clear_all_pkt_pointers(env);
9279 /* mark_btf_func_reg_size() is used when the reg size is determined by
9280 * the BTF func_proto's return value size and argument.
9282 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9285 struct bpf_reg_state *reg = &cur_regs(env)[regno];
9287 if (regno == BPF_REG_0) {
9288 /* Function return value */
9289 reg->live |= REG_LIVE_WRITTEN;
9290 reg->subreg_def = reg_size == sizeof(u64) ?
9291 DEF_NOT_SUBREG : env->insn_idx + 1;
9293 /* Function argument */
9294 if (reg_size == sizeof(u64)) {
9295 mark_insn_zext(env, reg);
9296 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9298 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9303 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9305 return meta->kfunc_flags & KF_ACQUIRE;
9308 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
9310 return meta->kfunc_flags & KF_RET_NULL;
9313 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9315 return meta->kfunc_flags & KF_RELEASE;
9318 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9320 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
9323 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9325 return meta->kfunc_flags & KF_SLEEPABLE;
9328 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9330 return meta->kfunc_flags & KF_DESTRUCTIVE;
9333 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9335 return meta->kfunc_flags & KF_RCU;
9338 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
9340 return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
9343 static bool __kfunc_param_match_suffix(const struct btf *btf,
9344 const struct btf_param *arg,
9347 int suffix_len = strlen(suffix), len;
9348 const char *param_name;
9350 /* In the future, this can be ported to use BTF tagging */
9351 param_name = btf_name_by_offset(btf, arg->name_off);
9352 if (str_is_empty(param_name))
9354 len = strlen(param_name);
9355 if (len < suffix_len)
9357 param_name += len - suffix_len;
9358 return !strncmp(param_name, suffix, suffix_len);
9361 static bool is_kfunc_arg_mem_size(const struct btf *btf,
9362 const struct btf_param *arg,
9363 const struct bpf_reg_state *reg)
9365 const struct btf_type *t;
9367 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9368 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9371 return __kfunc_param_match_suffix(btf, arg, "__sz");
9374 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9375 const struct btf_param *arg,
9376 const struct bpf_reg_state *reg)
9378 const struct btf_type *t;
9380 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9381 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9384 return __kfunc_param_match_suffix(btf, arg, "__szk");
9387 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
9389 return __kfunc_param_match_suffix(btf, arg, "__k");
9392 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
9394 return __kfunc_param_match_suffix(btf, arg, "__ign");
9397 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
9399 return __kfunc_param_match_suffix(btf, arg, "__alloc");
9402 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
9404 return __kfunc_param_match_suffix(btf, arg, "__uninit");
9407 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9408 const struct btf_param *arg,
9411 int len, target_len = strlen(name);
9412 const char *param_name;
9414 param_name = btf_name_by_offset(btf, arg->name_off);
9415 if (str_is_empty(param_name))
9417 len = strlen(param_name);
9418 if (len != target_len)
9420 if (strcmp(param_name, name))
9428 KF_ARG_LIST_HEAD_ID,
9429 KF_ARG_LIST_NODE_ID,
9434 BTF_ID_LIST(kf_arg_btf_ids)
9435 BTF_ID(struct, bpf_dynptr_kern)
9436 BTF_ID(struct, bpf_list_head)
9437 BTF_ID(struct, bpf_list_node)
9438 BTF_ID(struct, bpf_rb_root)
9439 BTF_ID(struct, bpf_rb_node)
9441 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
9442 const struct btf_param *arg, int type)
9444 const struct btf_type *t;
9447 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9450 if (!btf_type_is_ptr(t))
9452 t = btf_type_skip_modifiers(btf, t->type, &res_id);
9455 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9458 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9460 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9463 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9465 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9468 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
9470 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
9473 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9475 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9478 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
9480 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
9483 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
9484 const struct btf_param *arg)
9486 const struct btf_type *t;
9488 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
9495 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
9496 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
9497 const struct btf *btf,
9498 const struct btf_type *t, int rec)
9500 const struct btf_type *member_type;
9501 const struct btf_member *member;
9504 if (!btf_type_is_struct(t))
9507 for_each_member(i, t, member) {
9508 const struct btf_array *array;
9510 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
9511 if (btf_type_is_struct(member_type)) {
9513 verbose(env, "max struct nesting depth exceeded\n");
9516 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
9520 if (btf_type_is_array(member_type)) {
9521 array = btf_array(member_type);
9524 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
9525 if (!btf_type_is_scalar(member_type))
9529 if (!btf_type_is_scalar(member_type))
9536 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
9538 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
9539 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9540 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
9544 enum kfunc_ptr_arg_type {
9546 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
9547 KF_ARG_PTR_TO_KPTR, /* PTR_TO_KPTR but type specific */
9548 KF_ARG_PTR_TO_DYNPTR,
9550 KF_ARG_PTR_TO_LIST_HEAD,
9551 KF_ARG_PTR_TO_LIST_NODE,
9552 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
9554 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
9555 KF_ARG_PTR_TO_CALLBACK,
9556 KF_ARG_PTR_TO_RB_ROOT,
9557 KF_ARG_PTR_TO_RB_NODE,
9560 enum special_kfunc_type {
9561 KF_bpf_obj_new_impl,
9562 KF_bpf_obj_drop_impl,
9563 KF_bpf_list_push_front,
9564 KF_bpf_list_push_back,
9565 KF_bpf_list_pop_front,
9566 KF_bpf_list_pop_back,
9567 KF_bpf_cast_to_kern_ctx,
9569 KF_bpf_rcu_read_lock,
9570 KF_bpf_rcu_read_unlock,
9571 KF_bpf_rbtree_remove,
9573 KF_bpf_rbtree_first,
9574 KF_bpf_dynptr_from_skb,
9575 KF_bpf_dynptr_from_xdp,
9576 KF_bpf_dynptr_slice,
9577 KF_bpf_dynptr_slice_rdwr,
9580 BTF_SET_START(special_kfunc_set)
9581 BTF_ID(func, bpf_obj_new_impl)
9582 BTF_ID(func, bpf_obj_drop_impl)
9583 BTF_ID(func, bpf_list_push_front)
9584 BTF_ID(func, bpf_list_push_back)
9585 BTF_ID(func, bpf_list_pop_front)
9586 BTF_ID(func, bpf_list_pop_back)
9587 BTF_ID(func, bpf_cast_to_kern_ctx)
9588 BTF_ID(func, bpf_rdonly_cast)
9589 BTF_ID(func, bpf_rbtree_remove)
9590 BTF_ID(func, bpf_rbtree_add)
9591 BTF_ID(func, bpf_rbtree_first)
9592 BTF_ID(func, bpf_dynptr_from_skb)
9593 BTF_ID(func, bpf_dynptr_from_xdp)
9594 BTF_ID(func, bpf_dynptr_slice)
9595 BTF_ID(func, bpf_dynptr_slice_rdwr)
9596 BTF_SET_END(special_kfunc_set)
9598 BTF_ID_LIST(special_kfunc_list)
9599 BTF_ID(func, bpf_obj_new_impl)
9600 BTF_ID(func, bpf_obj_drop_impl)
9601 BTF_ID(func, bpf_list_push_front)
9602 BTF_ID(func, bpf_list_push_back)
9603 BTF_ID(func, bpf_list_pop_front)
9604 BTF_ID(func, bpf_list_pop_back)
9605 BTF_ID(func, bpf_cast_to_kern_ctx)
9606 BTF_ID(func, bpf_rdonly_cast)
9607 BTF_ID(func, bpf_rcu_read_lock)
9608 BTF_ID(func, bpf_rcu_read_unlock)
9609 BTF_ID(func, bpf_rbtree_remove)
9610 BTF_ID(func, bpf_rbtree_add)
9611 BTF_ID(func, bpf_rbtree_first)
9612 BTF_ID(func, bpf_dynptr_from_skb)
9613 BTF_ID(func, bpf_dynptr_from_xdp)
9614 BTF_ID(func, bpf_dynptr_slice)
9615 BTF_ID(func, bpf_dynptr_slice_rdwr)
9617 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
9619 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
9622 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
9624 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
9627 static enum kfunc_ptr_arg_type
9628 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
9629 struct bpf_kfunc_call_arg_meta *meta,
9630 const struct btf_type *t, const struct btf_type *ref_t,
9631 const char *ref_tname, const struct btf_param *args,
9632 int argno, int nargs)
9634 u32 regno = argno + 1;
9635 struct bpf_reg_state *regs = cur_regs(env);
9636 struct bpf_reg_state *reg = ®s[regno];
9637 bool arg_mem_size = false;
9639 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
9640 return KF_ARG_PTR_TO_CTX;
9642 /* In this function, we verify the kfunc's BTF as per the argument type,
9643 * leaving the rest of the verification with respect to the register
9644 * type to our caller. When a set of conditions hold in the BTF type of
9645 * arguments, we resolve it to a known kfunc_ptr_arg_type.
9647 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
9648 return KF_ARG_PTR_TO_CTX;
9650 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
9651 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
9653 if (is_kfunc_arg_kptr_get(meta, argno)) {
9654 if (!btf_type_is_ptr(ref_t)) {
9655 verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
9658 ref_t = btf_type_by_id(meta->btf, ref_t->type);
9659 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
9660 if (!btf_type_is_struct(ref_t)) {
9661 verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
9662 meta->func_name, btf_type_str(ref_t), ref_tname);
9665 return KF_ARG_PTR_TO_KPTR;
9668 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
9669 return KF_ARG_PTR_TO_DYNPTR;
9671 if (is_kfunc_arg_iter(meta, argno))
9672 return KF_ARG_PTR_TO_ITER;
9674 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
9675 return KF_ARG_PTR_TO_LIST_HEAD;
9677 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
9678 return KF_ARG_PTR_TO_LIST_NODE;
9680 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
9681 return KF_ARG_PTR_TO_RB_ROOT;
9683 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
9684 return KF_ARG_PTR_TO_RB_NODE;
9686 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
9687 if (!btf_type_is_struct(ref_t)) {
9688 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
9689 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9692 return KF_ARG_PTR_TO_BTF_ID;
9695 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
9696 return KF_ARG_PTR_TO_CALLBACK;
9699 if (argno + 1 < nargs &&
9700 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
9701 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
9702 arg_mem_size = true;
9704 /* This is the catch all argument type of register types supported by
9705 * check_helper_mem_access. However, we only allow when argument type is
9706 * pointer to scalar, or struct composed (recursively) of scalars. When
9707 * arg_mem_size is true, the pointer can be void *.
9709 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
9710 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
9711 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
9712 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
9715 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
9718 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
9719 struct bpf_reg_state *reg,
9720 const struct btf_type *ref_t,
9721 const char *ref_tname, u32 ref_id,
9722 struct bpf_kfunc_call_arg_meta *meta,
9725 const struct btf_type *reg_ref_t;
9726 bool strict_type_match = false;
9727 const struct btf *reg_btf;
9728 const char *reg_ref_tname;
9731 if (base_type(reg->type) == PTR_TO_BTF_ID) {
9733 reg_ref_id = reg->btf_id;
9735 reg_btf = btf_vmlinux;
9736 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
9739 /* Enforce strict type matching for calls to kfuncs that are acquiring
9740 * or releasing a reference, or are no-cast aliases. We do _not_
9741 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
9742 * as we want to enable BPF programs to pass types that are bitwise
9743 * equivalent without forcing them to explicitly cast with something
9744 * like bpf_cast_to_kern_ctx().
9746 * For example, say we had a type like the following:
9748 * struct bpf_cpumask {
9749 * cpumask_t cpumask;
9753 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
9754 * to a struct cpumask, so it would be safe to pass a struct
9755 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
9757 * The philosophy here is similar to how we allow scalars of different
9758 * types to be passed to kfuncs as long as the size is the same. The
9759 * only difference here is that we're simply allowing
9760 * btf_struct_ids_match() to walk the struct at the 0th offset, and
9763 if (is_kfunc_acquire(meta) ||
9764 (is_kfunc_release(meta) && reg->ref_obj_id) ||
9765 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
9766 strict_type_match = true;
9768 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
9770 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
9771 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
9772 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
9773 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
9774 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
9775 btf_type_str(reg_ref_t), reg_ref_tname);
9781 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
9782 struct bpf_reg_state *reg,
9783 const struct btf_type *ref_t,
9784 const char *ref_tname,
9785 struct bpf_kfunc_call_arg_meta *meta,
9788 struct btf_field *kptr_field;
9790 /* check_func_arg_reg_off allows var_off for
9791 * PTR_TO_MAP_VALUE, but we need fixed offset to find
9794 if (!tnum_is_const(reg->var_off)) {
9795 verbose(env, "arg#0 must have constant offset\n");
9799 kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
9800 if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
9801 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
9802 reg->off + reg->var_off.value);
9806 if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
9807 kptr_field->kptr.btf_id, true)) {
9808 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
9809 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9815 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9817 struct bpf_verifier_state *state = env->cur_state;
9819 if (!state->active_lock.ptr) {
9820 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
9824 if (type_flag(reg->type) & NON_OWN_REF) {
9825 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
9829 reg->type |= NON_OWN_REF;
9833 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
9835 struct bpf_func_state *state, *unused;
9836 struct bpf_reg_state *reg;
9839 state = cur_func(env);
9842 verbose(env, "verifier internal error: ref_obj_id is zero for "
9843 "owning -> non-owning conversion\n");
9847 for (i = 0; i < state->acquired_refs; i++) {
9848 if (state->refs[i].id != ref_obj_id)
9851 /* Clear ref_obj_id here so release_reference doesn't clobber
9854 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9855 if (reg->ref_obj_id == ref_obj_id) {
9856 reg->ref_obj_id = 0;
9857 ref_set_non_owning(env, reg);
9863 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
9867 /* Implementation details:
9869 * Each register points to some region of memory, which we define as an
9870 * allocation. Each allocation may embed a bpf_spin_lock which protects any
9871 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
9872 * allocation. The lock and the data it protects are colocated in the same
9875 * Hence, everytime a register holds a pointer value pointing to such
9876 * allocation, the verifier preserves a unique reg->id for it.
9878 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
9879 * bpf_spin_lock is called.
9881 * To enable this, lock state in the verifier captures two values:
9882 * active_lock.ptr = Register's type specific pointer
9883 * active_lock.id = A unique ID for each register pointer value
9885 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
9886 * supported register types.
9888 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
9889 * allocated objects is the reg->btf pointer.
9891 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
9892 * can establish the provenance of the map value statically for each distinct
9893 * lookup into such maps. They always contain a single map value hence unique
9894 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
9896 * So, in case of global variables, they use array maps with max_entries = 1,
9897 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
9898 * into the same map value as max_entries is 1, as described above).
9900 * In case of inner map lookups, the inner map pointer has same map_ptr as the
9901 * outer map pointer (in verifier context), but each lookup into an inner map
9902 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
9903 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
9904 * will get different reg->id assigned to each lookup, hence different
9907 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
9908 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
9909 * returned from bpf_obj_new. Each allocation receives a new reg->id.
9911 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9916 switch ((int)reg->type) {
9917 case PTR_TO_MAP_VALUE:
9920 case PTR_TO_BTF_ID | MEM_ALLOC:
9924 verbose(env, "verifier internal error: unknown reg type for lock check\n");
9929 if (!env->cur_state->active_lock.ptr)
9931 if (env->cur_state->active_lock.ptr != ptr ||
9932 env->cur_state->active_lock.id != id) {
9933 verbose(env, "held lock and object are not in the same allocation\n");
9939 static bool is_bpf_list_api_kfunc(u32 btf_id)
9941 return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9942 btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
9943 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9944 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
9947 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
9949 return btf_id == special_kfunc_list[KF_bpf_rbtree_add] ||
9950 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9951 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
9954 static bool is_bpf_graph_api_kfunc(u32 btf_id)
9956 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id);
9959 static bool is_callback_calling_kfunc(u32 btf_id)
9961 return btf_id == special_kfunc_list[KF_bpf_rbtree_add];
9964 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
9966 return is_bpf_rbtree_api_kfunc(btf_id);
9969 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
9970 enum btf_field_type head_field_type,
9975 switch (head_field_type) {
9977 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
9980 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
9983 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
9984 btf_field_type_name(head_field_type));
9989 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
9990 btf_field_type_name(head_field_type));
9994 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
9995 enum btf_field_type node_field_type,
10000 switch (node_field_type) {
10001 case BPF_LIST_NODE:
10002 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
10003 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back]);
10006 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10007 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add]);
10010 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10011 btf_field_type_name(node_field_type));
10016 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10017 btf_field_type_name(node_field_type));
10022 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10023 struct bpf_reg_state *reg, u32 regno,
10024 struct bpf_kfunc_call_arg_meta *meta,
10025 enum btf_field_type head_field_type,
10026 struct btf_field **head_field)
10028 const char *head_type_name;
10029 struct btf_field *field;
10030 struct btf_record *rec;
10033 if (meta->btf != btf_vmlinux) {
10034 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10038 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10041 head_type_name = btf_field_type_name(head_field_type);
10042 if (!tnum_is_const(reg->var_off)) {
10044 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10045 regno, head_type_name);
10049 rec = reg_btf_record(reg);
10050 head_off = reg->off + reg->var_off.value;
10051 field = btf_record_find(rec, head_off, head_field_type);
10053 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10057 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10058 if (check_reg_allocation_locked(env, reg)) {
10059 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10060 rec->spin_lock_off, head_type_name);
10065 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10068 *head_field = field;
10072 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10073 struct bpf_reg_state *reg, u32 regno,
10074 struct bpf_kfunc_call_arg_meta *meta)
10076 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10077 &meta->arg_list_head.field);
10080 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10081 struct bpf_reg_state *reg, u32 regno,
10082 struct bpf_kfunc_call_arg_meta *meta)
10084 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10085 &meta->arg_rbtree_root.field);
10089 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10090 struct bpf_reg_state *reg, u32 regno,
10091 struct bpf_kfunc_call_arg_meta *meta,
10092 enum btf_field_type head_field_type,
10093 enum btf_field_type node_field_type,
10094 struct btf_field **node_field)
10096 const char *node_type_name;
10097 const struct btf_type *et, *t;
10098 struct btf_field *field;
10101 if (meta->btf != btf_vmlinux) {
10102 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10106 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10109 node_type_name = btf_field_type_name(node_field_type);
10110 if (!tnum_is_const(reg->var_off)) {
10112 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10113 regno, node_type_name);
10117 node_off = reg->off + reg->var_off.value;
10118 field = reg_find_field_offset(reg, node_off, node_field_type);
10119 if (!field || field->offset != node_off) {
10120 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10124 field = *node_field;
10126 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10127 t = btf_type_by_id(reg->btf, reg->btf_id);
10128 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10129 field->graph_root.value_btf_id, true)) {
10130 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10131 "in struct %s, but arg is at offset=%d in struct %s\n",
10132 btf_field_type_name(head_field_type),
10133 btf_field_type_name(node_field_type),
10134 field->graph_root.node_offset,
10135 btf_name_by_offset(field->graph_root.btf, et->name_off),
10136 node_off, btf_name_by_offset(reg->btf, t->name_off));
10140 if (node_off != field->graph_root.node_offset) {
10141 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10142 node_off, btf_field_type_name(node_field_type),
10143 field->graph_root.node_offset,
10144 btf_name_by_offset(field->graph_root.btf, et->name_off));
10151 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10152 struct bpf_reg_state *reg, u32 regno,
10153 struct bpf_kfunc_call_arg_meta *meta)
10155 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10156 BPF_LIST_HEAD, BPF_LIST_NODE,
10157 &meta->arg_list_head.field);
10160 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10161 struct bpf_reg_state *reg, u32 regno,
10162 struct bpf_kfunc_call_arg_meta *meta)
10164 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10165 BPF_RB_ROOT, BPF_RB_NODE,
10166 &meta->arg_rbtree_root.field);
10169 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10172 const char *func_name = meta->func_name, *ref_tname;
10173 const struct btf *btf = meta->btf;
10174 const struct btf_param *args;
10178 args = (const struct btf_param *)(meta->func_proto + 1);
10179 nargs = btf_type_vlen(meta->func_proto);
10180 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10181 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10182 MAX_BPF_FUNC_REG_ARGS);
10186 /* Check that BTF function arguments match actual types that the
10189 for (i = 0; i < nargs; i++) {
10190 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
10191 const struct btf_type *t, *ref_t, *resolve_ret;
10192 enum bpf_arg_type arg_type = ARG_DONTCARE;
10193 u32 regno = i + 1, ref_id, type_size;
10194 bool is_ret_buf_sz = false;
10197 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10199 if (is_kfunc_arg_ignore(btf, &args[i]))
10202 if (btf_type_is_scalar(t)) {
10203 if (reg->type != SCALAR_VALUE) {
10204 verbose(env, "R%d is not a scalar\n", regno);
10208 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10209 if (meta->arg_constant.found) {
10210 verbose(env, "verifier internal error: only one constant argument permitted\n");
10213 if (!tnum_is_const(reg->var_off)) {
10214 verbose(env, "R%d must be a known constant\n", regno);
10217 ret = mark_chain_precision(env, regno);
10220 meta->arg_constant.found = true;
10221 meta->arg_constant.value = reg->var_off.value;
10222 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10223 meta->r0_rdonly = true;
10224 is_ret_buf_sz = true;
10225 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10226 is_ret_buf_sz = true;
10229 if (is_ret_buf_sz) {
10230 if (meta->r0_size) {
10231 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10235 if (!tnum_is_const(reg->var_off)) {
10236 verbose(env, "R%d is not a const\n", regno);
10240 meta->r0_size = reg->var_off.value;
10241 ret = mark_chain_precision(env, regno);
10248 if (!btf_type_is_ptr(t)) {
10249 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10253 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10254 (register_is_null(reg) || type_may_be_null(reg->type))) {
10255 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10259 if (reg->ref_obj_id) {
10260 if (is_kfunc_release(meta) && meta->ref_obj_id) {
10261 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10262 regno, reg->ref_obj_id,
10266 meta->ref_obj_id = reg->ref_obj_id;
10267 if (is_kfunc_release(meta))
10268 meta->release_regno = regno;
10271 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10272 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10274 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10275 if (kf_arg_type < 0)
10276 return kf_arg_type;
10278 switch (kf_arg_type) {
10279 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10280 case KF_ARG_PTR_TO_BTF_ID:
10281 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10284 if (!is_trusted_reg(reg)) {
10285 if (!is_kfunc_rcu(meta)) {
10286 verbose(env, "R%d must be referenced or trusted\n", regno);
10289 if (!is_rcu_reg(reg)) {
10290 verbose(env, "R%d must be a rcu pointer\n", regno);
10296 case KF_ARG_PTR_TO_CTX:
10297 /* Trusted arguments have the same offset checks as release arguments */
10298 arg_type |= OBJ_RELEASE;
10300 case KF_ARG_PTR_TO_KPTR:
10301 case KF_ARG_PTR_TO_DYNPTR:
10302 case KF_ARG_PTR_TO_ITER:
10303 case KF_ARG_PTR_TO_LIST_HEAD:
10304 case KF_ARG_PTR_TO_LIST_NODE:
10305 case KF_ARG_PTR_TO_RB_ROOT:
10306 case KF_ARG_PTR_TO_RB_NODE:
10307 case KF_ARG_PTR_TO_MEM:
10308 case KF_ARG_PTR_TO_MEM_SIZE:
10309 case KF_ARG_PTR_TO_CALLBACK:
10310 /* Trusted by default */
10317 if (is_kfunc_release(meta) && reg->ref_obj_id)
10318 arg_type |= OBJ_RELEASE;
10319 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10323 switch (kf_arg_type) {
10324 case KF_ARG_PTR_TO_CTX:
10325 if (reg->type != PTR_TO_CTX) {
10326 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10330 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10331 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10334 meta->ret_btf_id = ret;
10337 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10338 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10339 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10342 if (!reg->ref_obj_id) {
10343 verbose(env, "allocated object must be referenced\n");
10346 if (meta->btf == btf_vmlinux &&
10347 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10348 meta->arg_obj_drop.btf = reg->btf;
10349 meta->arg_obj_drop.btf_id = reg->btf_id;
10352 case KF_ARG_PTR_TO_KPTR:
10353 if (reg->type != PTR_TO_MAP_VALUE) {
10354 verbose(env, "arg#0 expected pointer to map value\n");
10357 ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
10361 case KF_ARG_PTR_TO_DYNPTR:
10363 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
10365 if (reg->type != PTR_TO_STACK &&
10366 reg->type != CONST_PTR_TO_DYNPTR) {
10367 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
10371 if (reg->type == CONST_PTR_TO_DYNPTR)
10372 dynptr_arg_type |= MEM_RDONLY;
10374 if (is_kfunc_arg_uninit(btf, &args[i]))
10375 dynptr_arg_type |= MEM_UNINIT;
10377 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb])
10378 dynptr_arg_type |= DYNPTR_TYPE_SKB;
10379 else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp])
10380 dynptr_arg_type |= DYNPTR_TYPE_XDP;
10382 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type);
10386 if (!(dynptr_arg_type & MEM_UNINIT)) {
10387 int id = dynptr_id(env, reg);
10390 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10393 meta->initialized_dynptr.id = id;
10394 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
10399 case KF_ARG_PTR_TO_ITER:
10400 ret = process_iter_arg(env, regno, insn_idx, meta);
10404 case KF_ARG_PTR_TO_LIST_HEAD:
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_list_head(env, reg, regno, meta);
10418 case KF_ARG_PTR_TO_RB_ROOT:
10419 if (reg->type != PTR_TO_MAP_VALUE &&
10420 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10421 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10424 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10425 verbose(env, "allocated object must be referenced\n");
10428 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
10432 case KF_ARG_PTR_TO_LIST_NODE:
10433 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10434 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10437 if (!reg->ref_obj_id) {
10438 verbose(env, "allocated object must be referenced\n");
10441 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
10445 case KF_ARG_PTR_TO_RB_NODE:
10446 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
10447 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
10448 verbose(env, "rbtree_remove node input must be non-owning ref\n");
10451 if (in_rbtree_lock_required_cb(env)) {
10452 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
10456 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10457 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10460 if (!reg->ref_obj_id) {
10461 verbose(env, "allocated object must be referenced\n");
10466 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10470 case KF_ARG_PTR_TO_BTF_ID:
10471 /* Only base_type is checked, further checks are done here */
10472 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10473 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10474 !reg2btf_ids[base_type(reg->type)]) {
10475 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10476 verbose(env, "expected %s or socket\n",
10477 reg_type_str(env, base_type(reg->type) |
10478 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10481 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10485 case KF_ARG_PTR_TO_MEM:
10486 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10487 if (IS_ERR(resolve_ret)) {
10488 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10489 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10492 ret = check_mem_reg(env, reg, regno, type_size);
10496 case KF_ARG_PTR_TO_MEM_SIZE:
10498 struct bpf_reg_state *size_reg = ®s[regno + 1];
10499 const struct btf_param *size_arg = &args[i + 1];
10501 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
10503 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
10507 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
10508 if (meta->arg_constant.found) {
10509 verbose(env, "verifier internal error: only one constant argument permitted\n");
10512 if (!tnum_is_const(size_reg->var_off)) {
10513 verbose(env, "R%d must be a known constant\n", regno + 1);
10516 meta->arg_constant.found = true;
10517 meta->arg_constant.value = size_reg->var_off.value;
10520 /* Skip next '__sz' or '__szk' argument */
10524 case KF_ARG_PTR_TO_CALLBACK:
10525 meta->subprogno = reg->subprogno;
10530 if (is_kfunc_release(meta) && !meta->release_regno) {
10531 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
10539 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
10540 struct bpf_insn *insn,
10541 struct bpf_kfunc_call_arg_meta *meta,
10542 const char **kfunc_name)
10544 const struct btf_type *func, *func_proto;
10545 u32 func_id, *kfunc_flags;
10546 const char *func_name;
10547 struct btf *desc_btf;
10550 *kfunc_name = NULL;
10555 desc_btf = find_kfunc_desc_btf(env, insn->off);
10556 if (IS_ERR(desc_btf))
10557 return PTR_ERR(desc_btf);
10559 func_id = insn->imm;
10560 func = btf_type_by_id(desc_btf, func_id);
10561 func_name = btf_name_by_offset(desc_btf, func->name_off);
10563 *kfunc_name = func_name;
10564 func_proto = btf_type_by_id(desc_btf, func->type);
10566 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
10567 if (!kfunc_flags) {
10571 memset(meta, 0, sizeof(*meta));
10572 meta->btf = desc_btf;
10573 meta->func_id = func_id;
10574 meta->kfunc_flags = *kfunc_flags;
10575 meta->func_proto = func_proto;
10576 meta->func_name = func_name;
10581 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10584 const struct btf_type *t, *ptr_type;
10585 u32 i, nargs, ptr_type_id, release_ref_obj_id;
10586 struct bpf_reg_state *regs = cur_regs(env);
10587 const char *func_name, *ptr_type_name;
10588 bool sleepable, rcu_lock, rcu_unlock;
10589 struct bpf_kfunc_call_arg_meta meta;
10590 struct bpf_insn_aux_data *insn_aux;
10591 int err, insn_idx = *insn_idx_p;
10592 const struct btf_param *args;
10593 const struct btf_type *ret_t;
10594 struct btf *desc_btf;
10596 /* skip for now, but return error when we find this in fixup_kfunc_call */
10600 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
10601 if (err == -EACCES && func_name)
10602 verbose(env, "calling kernel function %s is not allowed\n", func_name);
10605 desc_btf = meta.btf;
10606 insn_aux = &env->insn_aux_data[insn_idx];
10608 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
10610 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
10611 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
10615 sleepable = is_kfunc_sleepable(&meta);
10616 if (sleepable && !env->prog->aux->sleepable) {
10617 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
10621 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
10622 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
10624 if (env->cur_state->active_rcu_lock) {
10625 struct bpf_func_state *state;
10626 struct bpf_reg_state *reg;
10629 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
10631 } else if (rcu_unlock) {
10632 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10633 if (reg->type & MEM_RCU) {
10634 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
10635 reg->type |= PTR_UNTRUSTED;
10638 env->cur_state->active_rcu_lock = false;
10639 } else if (sleepable) {
10640 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
10643 } else if (rcu_lock) {
10644 env->cur_state->active_rcu_lock = true;
10645 } else if (rcu_unlock) {
10646 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
10650 /* Check the arguments */
10651 err = check_kfunc_args(env, &meta, insn_idx);
10654 /* In case of release function, we get register number of refcounted
10655 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
10657 if (meta.release_regno) {
10658 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
10660 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10661 func_name, meta.func_id);
10666 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front] ||
10667 meta.func_id == special_kfunc_list[KF_bpf_list_push_back] ||
10668 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
10669 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
10670 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
10672 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
10673 func_name, meta.func_id);
10677 err = release_reference(env, release_ref_obj_id);
10679 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10680 func_name, meta.func_id);
10685 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
10686 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10687 set_rbtree_add_callback_state);
10689 verbose(env, "kfunc %s#%d failed callback verification\n",
10690 func_name, meta.func_id);
10695 for (i = 0; i < CALLER_SAVED_REGS; i++)
10696 mark_reg_not_init(env, regs, caller_saved[i]);
10698 /* Check return type */
10699 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
10701 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
10702 /* Only exception is bpf_obj_new_impl */
10703 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
10704 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
10709 if (btf_type_is_scalar(t)) {
10710 mark_reg_unknown(env, regs, BPF_REG_0);
10711 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
10712 } else if (btf_type_is_ptr(t)) {
10713 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
10715 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
10716 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
10717 struct btf *ret_btf;
10720 if (unlikely(!bpf_global_ma_set))
10723 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
10724 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
10728 ret_btf = env->prog->aux->btf;
10729 ret_btf_id = meta.arg_constant.value;
10731 /* This may be NULL due to user not supplying a BTF */
10733 verbose(env, "bpf_obj_new requires prog BTF\n");
10737 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
10738 if (!ret_t || !__btf_type_is_struct(ret_t)) {
10739 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
10743 mark_reg_known_zero(env, regs, BPF_REG_0);
10744 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
10745 regs[BPF_REG_0].btf = ret_btf;
10746 regs[BPF_REG_0].btf_id = ret_btf_id;
10748 insn_aux->obj_new_size = ret_t->size;
10749 insn_aux->kptr_struct_meta =
10750 btf_find_struct_meta(ret_btf, ret_btf_id);
10751 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10752 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
10753 struct btf_field *field = meta.arg_list_head.field;
10755 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10756 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10757 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10758 struct btf_field *field = meta.arg_rbtree_root.field;
10760 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10761 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10762 mark_reg_known_zero(env, regs, BPF_REG_0);
10763 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
10764 regs[BPF_REG_0].btf = desc_btf;
10765 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10766 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
10767 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
10768 if (!ret_t || !btf_type_is_struct(ret_t)) {
10770 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
10774 mark_reg_known_zero(env, regs, BPF_REG_0);
10775 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
10776 regs[BPF_REG_0].btf = desc_btf;
10777 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
10778 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
10779 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
10780 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
10782 mark_reg_known_zero(env, regs, BPF_REG_0);
10784 if (!meta.arg_constant.found) {
10785 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
10789 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
10791 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
10792 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
10794 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
10795 regs[BPF_REG_0].type |= MEM_RDONLY;
10797 /* this will set env->seen_direct_write to true */
10798 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
10799 verbose(env, "the prog does not allow writes to packet data\n");
10804 if (!meta.initialized_dynptr.id) {
10805 verbose(env, "verifier internal error: no dynptr id\n");
10808 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
10810 /* we don't need to set BPF_REG_0's ref obj id
10811 * because packet slices are not refcounted (see
10812 * dynptr_type_refcounted)
10815 verbose(env, "kernel function %s unhandled dynamic return type\n",
10819 } else if (!__btf_type_is_struct(ptr_type)) {
10820 if (!meta.r0_size) {
10823 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
10825 meta.r0_rdonly = true;
10828 if (!meta.r0_size) {
10829 ptr_type_name = btf_name_by_offset(desc_btf,
10830 ptr_type->name_off);
10832 "kernel function %s returns pointer type %s %s is not supported\n",
10834 btf_type_str(ptr_type),
10839 mark_reg_known_zero(env, regs, BPF_REG_0);
10840 regs[BPF_REG_0].type = PTR_TO_MEM;
10841 regs[BPF_REG_0].mem_size = meta.r0_size;
10843 if (meta.r0_rdonly)
10844 regs[BPF_REG_0].type |= MEM_RDONLY;
10846 /* Ensures we don't access the memory after a release_reference() */
10847 if (meta.ref_obj_id)
10848 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10850 mark_reg_known_zero(env, regs, BPF_REG_0);
10851 regs[BPF_REG_0].btf = desc_btf;
10852 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
10853 regs[BPF_REG_0].btf_id = ptr_type_id;
10856 if (is_kfunc_ret_null(&meta)) {
10857 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
10858 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
10859 regs[BPF_REG_0].id = ++env->id_gen;
10861 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
10862 if (is_kfunc_acquire(&meta)) {
10863 int id = acquire_reference_state(env, insn_idx);
10867 if (is_kfunc_ret_null(&meta))
10868 regs[BPF_REG_0].id = id;
10869 regs[BPF_REG_0].ref_obj_id = id;
10870 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10871 ref_set_non_owning(env, ®s[BPF_REG_0]);
10874 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove])
10875 invalidate_non_owning_refs(env);
10877 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
10878 regs[BPF_REG_0].id = ++env->id_gen;
10879 } else if (btf_type_is_void(t)) {
10880 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
10881 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10882 insn_aux->kptr_struct_meta =
10883 btf_find_struct_meta(meta.arg_obj_drop.btf,
10884 meta.arg_obj_drop.btf_id);
10889 nargs = btf_type_vlen(meta.func_proto);
10890 args = (const struct btf_param *)(meta.func_proto + 1);
10891 for (i = 0; i < nargs; i++) {
10894 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
10895 if (btf_type_is_ptr(t))
10896 mark_btf_func_reg_size(env, regno, sizeof(void *));
10898 /* scalar. ensured by btf_check_kfunc_arg_match() */
10899 mark_btf_func_reg_size(env, regno, t->size);
10902 if (is_iter_next_kfunc(&meta)) {
10903 err = process_iter_next_call(env, insn_idx, &meta);
10911 static bool signed_add_overflows(s64 a, s64 b)
10913 /* Do the add in u64, where overflow is well-defined */
10914 s64 res = (s64)((u64)a + (u64)b);
10921 static bool signed_add32_overflows(s32 a, s32 b)
10923 /* Do the add in u32, where overflow is well-defined */
10924 s32 res = (s32)((u32)a + (u32)b);
10931 static bool signed_sub_overflows(s64 a, s64 b)
10933 /* Do the sub in u64, where overflow is well-defined */
10934 s64 res = (s64)((u64)a - (u64)b);
10941 static bool signed_sub32_overflows(s32 a, s32 b)
10943 /* Do the sub in u32, where overflow is well-defined */
10944 s32 res = (s32)((u32)a - (u32)b);
10951 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
10952 const struct bpf_reg_state *reg,
10953 enum bpf_reg_type type)
10955 bool known = tnum_is_const(reg->var_off);
10956 s64 val = reg->var_off.value;
10957 s64 smin = reg->smin_value;
10959 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
10960 verbose(env, "math between %s pointer and %lld is not allowed\n",
10961 reg_type_str(env, type), val);
10965 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
10966 verbose(env, "%s pointer offset %d is not allowed\n",
10967 reg_type_str(env, type), reg->off);
10971 if (smin == S64_MIN) {
10972 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
10973 reg_type_str(env, type));
10977 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
10978 verbose(env, "value %lld makes %s pointer be out of bounds\n",
10979 smin, reg_type_str(env, type));
10987 REASON_BOUNDS = -1,
10994 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
10995 u32 *alu_limit, bool mask_to_left)
10997 u32 max = 0, ptr_limit = 0;
10999 switch (ptr_reg->type) {
11001 /* Offset 0 is out-of-bounds, but acceptable start for the
11002 * left direction, see BPF_REG_FP. Also, unknown scalar
11003 * offset where we would need to deal with min/max bounds is
11004 * currently prohibited for unprivileged.
11006 max = MAX_BPF_STACK + mask_to_left;
11007 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11009 case PTR_TO_MAP_VALUE:
11010 max = ptr_reg->map_ptr->value_size;
11011 ptr_limit = (mask_to_left ?
11012 ptr_reg->smin_value :
11013 ptr_reg->umax_value) + ptr_reg->off;
11016 return REASON_TYPE;
11019 if (ptr_limit >= max)
11020 return REASON_LIMIT;
11021 *alu_limit = ptr_limit;
11025 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11026 const struct bpf_insn *insn)
11028 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11031 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11032 u32 alu_state, u32 alu_limit)
11034 /* If we arrived here from different branches with different
11035 * state or limits to sanitize, then this won't work.
11037 if (aux->alu_state &&
11038 (aux->alu_state != alu_state ||
11039 aux->alu_limit != alu_limit))
11040 return REASON_PATHS;
11042 /* Corresponding fixup done in do_misc_fixups(). */
11043 aux->alu_state = alu_state;
11044 aux->alu_limit = alu_limit;
11048 static int sanitize_val_alu(struct bpf_verifier_env *env,
11049 struct bpf_insn *insn)
11051 struct bpf_insn_aux_data *aux = cur_aux(env);
11053 if (can_skip_alu_sanitation(env, insn))
11056 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11059 static bool sanitize_needed(u8 opcode)
11061 return opcode == BPF_ADD || opcode == BPF_SUB;
11064 struct bpf_sanitize_info {
11065 struct bpf_insn_aux_data aux;
11069 static struct bpf_verifier_state *
11070 sanitize_speculative_path(struct bpf_verifier_env *env,
11071 const struct bpf_insn *insn,
11072 u32 next_idx, u32 curr_idx)
11074 struct bpf_verifier_state *branch;
11075 struct bpf_reg_state *regs;
11077 branch = push_stack(env, next_idx, curr_idx, true);
11078 if (branch && insn) {
11079 regs = branch->frame[branch->curframe]->regs;
11080 if (BPF_SRC(insn->code) == BPF_K) {
11081 mark_reg_unknown(env, regs, insn->dst_reg);
11082 } else if (BPF_SRC(insn->code) == BPF_X) {
11083 mark_reg_unknown(env, regs, insn->dst_reg);
11084 mark_reg_unknown(env, regs, insn->src_reg);
11090 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11091 struct bpf_insn *insn,
11092 const struct bpf_reg_state *ptr_reg,
11093 const struct bpf_reg_state *off_reg,
11094 struct bpf_reg_state *dst_reg,
11095 struct bpf_sanitize_info *info,
11096 const bool commit_window)
11098 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11099 struct bpf_verifier_state *vstate = env->cur_state;
11100 bool off_is_imm = tnum_is_const(off_reg->var_off);
11101 bool off_is_neg = off_reg->smin_value < 0;
11102 bool ptr_is_dst_reg = ptr_reg == dst_reg;
11103 u8 opcode = BPF_OP(insn->code);
11104 u32 alu_state, alu_limit;
11105 struct bpf_reg_state tmp;
11109 if (can_skip_alu_sanitation(env, insn))
11112 /* We already marked aux for masking from non-speculative
11113 * paths, thus we got here in the first place. We only care
11114 * to explore bad access from here.
11116 if (vstate->speculative)
11119 if (!commit_window) {
11120 if (!tnum_is_const(off_reg->var_off) &&
11121 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11122 return REASON_BOUNDS;
11124 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
11125 (opcode == BPF_SUB && !off_is_neg);
11128 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11132 if (commit_window) {
11133 /* In commit phase we narrow the masking window based on
11134 * the observed pointer move after the simulated operation.
11136 alu_state = info->aux.alu_state;
11137 alu_limit = abs(info->aux.alu_limit - alu_limit);
11139 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11140 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11141 alu_state |= ptr_is_dst_reg ?
11142 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11144 /* Limit pruning on unknown scalars to enable deep search for
11145 * potential masking differences from other program paths.
11148 env->explore_alu_limits = true;
11151 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11155 /* If we're in commit phase, we're done here given we already
11156 * pushed the truncated dst_reg into the speculative verification
11159 * Also, when register is a known constant, we rewrite register-based
11160 * operation to immediate-based, and thus do not need masking (and as
11161 * a consequence, do not need to simulate the zero-truncation either).
11163 if (commit_window || off_is_imm)
11166 /* Simulate and find potential out-of-bounds access under
11167 * speculative execution from truncation as a result of
11168 * masking when off was not within expected range. If off
11169 * sits in dst, then we temporarily need to move ptr there
11170 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11171 * for cases where we use K-based arithmetic in one direction
11172 * and truncated reg-based in the other in order to explore
11175 if (!ptr_is_dst_reg) {
11177 copy_register_state(dst_reg, ptr_reg);
11179 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11181 if (!ptr_is_dst_reg && ret)
11183 return !ret ? REASON_STACK : 0;
11186 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11188 struct bpf_verifier_state *vstate = env->cur_state;
11190 /* If we simulate paths under speculation, we don't update the
11191 * insn as 'seen' such that when we verify unreachable paths in
11192 * the non-speculative domain, sanitize_dead_code() can still
11193 * rewrite/sanitize them.
11195 if (!vstate->speculative)
11196 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11199 static int sanitize_err(struct bpf_verifier_env *env,
11200 const struct bpf_insn *insn, int reason,
11201 const struct bpf_reg_state *off_reg,
11202 const struct bpf_reg_state *dst_reg)
11204 static const char *err = "pointer arithmetic with it prohibited for !root";
11205 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11206 u32 dst = insn->dst_reg, src = insn->src_reg;
11209 case REASON_BOUNDS:
11210 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11211 off_reg == dst_reg ? dst : src, err);
11214 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11215 off_reg == dst_reg ? src : dst, err);
11218 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11222 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11226 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11230 verbose(env, "verifier internal error: unknown reason (%d)\n",
11238 /* check that stack access falls within stack limits and that 'reg' doesn't
11239 * have a variable offset.
11241 * Variable offset is prohibited for unprivileged mode for simplicity since it
11242 * requires corresponding support in Spectre masking for stack ALU. See also
11243 * retrieve_ptr_limit().
11246 * 'off' includes 'reg->off'.
11248 static int check_stack_access_for_ptr_arithmetic(
11249 struct bpf_verifier_env *env,
11251 const struct bpf_reg_state *reg,
11254 if (!tnum_is_const(reg->var_off)) {
11257 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11258 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11259 regno, tn_buf, off);
11263 if (off >= 0 || off < -MAX_BPF_STACK) {
11264 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11265 "prohibited for !root; off=%d\n", regno, off);
11272 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11273 const struct bpf_insn *insn,
11274 const struct bpf_reg_state *dst_reg)
11276 u32 dst = insn->dst_reg;
11278 /* For unprivileged we require that resulting offset must be in bounds
11279 * in order to be able to sanitize access later on.
11281 if (env->bypass_spec_v1)
11284 switch (dst_reg->type) {
11286 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11287 dst_reg->off + dst_reg->var_off.value))
11290 case PTR_TO_MAP_VALUE:
11291 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
11292 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11293 "prohibited for !root\n", dst);
11304 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
11305 * Caller should also handle BPF_MOV case separately.
11306 * If we return -EACCES, caller may want to try again treating pointer as a
11307 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
11309 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11310 struct bpf_insn *insn,
11311 const struct bpf_reg_state *ptr_reg,
11312 const struct bpf_reg_state *off_reg)
11314 struct bpf_verifier_state *vstate = env->cur_state;
11315 struct bpf_func_state *state = vstate->frame[vstate->curframe];
11316 struct bpf_reg_state *regs = state->regs, *dst_reg;
11317 bool known = tnum_is_const(off_reg->var_off);
11318 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11319 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11320 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11321 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
11322 struct bpf_sanitize_info info = {};
11323 u8 opcode = BPF_OP(insn->code);
11324 u32 dst = insn->dst_reg;
11327 dst_reg = ®s[dst];
11329 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11330 smin_val > smax_val || umin_val > umax_val) {
11331 /* Taint dst register if offset had invalid bounds derived from
11332 * e.g. dead branches.
11334 __mark_reg_unknown(env, dst_reg);
11338 if (BPF_CLASS(insn->code) != BPF_ALU64) {
11339 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
11340 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11341 __mark_reg_unknown(env, dst_reg);
11346 "R%d 32-bit pointer arithmetic prohibited\n",
11351 if (ptr_reg->type & PTR_MAYBE_NULL) {
11352 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
11353 dst, reg_type_str(env, ptr_reg->type));
11357 switch (base_type(ptr_reg->type)) {
11358 case CONST_PTR_TO_MAP:
11359 /* smin_val represents the known value */
11360 if (known && smin_val == 0 && opcode == BPF_ADD)
11363 case PTR_TO_PACKET_END:
11364 case PTR_TO_SOCKET:
11365 case PTR_TO_SOCK_COMMON:
11366 case PTR_TO_TCP_SOCK:
11367 case PTR_TO_XDP_SOCK:
11368 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
11369 dst, reg_type_str(env, ptr_reg->type));
11375 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
11376 * The id may be overwritten later if we create a new variable offset.
11378 dst_reg->type = ptr_reg->type;
11379 dst_reg->id = ptr_reg->id;
11381 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
11382 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
11385 /* pointer types do not carry 32-bit bounds at the moment. */
11386 __mark_reg32_unbounded(dst_reg);
11388 if (sanitize_needed(opcode)) {
11389 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
11392 return sanitize_err(env, insn, ret, off_reg, dst_reg);
11397 /* We can take a fixed offset as long as it doesn't overflow
11398 * the s32 'off' field
11400 if (known && (ptr_reg->off + smin_val ==
11401 (s64)(s32)(ptr_reg->off + smin_val))) {
11402 /* pointer += K. Accumulate it into fixed offset */
11403 dst_reg->smin_value = smin_ptr;
11404 dst_reg->smax_value = smax_ptr;
11405 dst_reg->umin_value = umin_ptr;
11406 dst_reg->umax_value = umax_ptr;
11407 dst_reg->var_off = ptr_reg->var_off;
11408 dst_reg->off = ptr_reg->off + smin_val;
11409 dst_reg->raw = ptr_reg->raw;
11412 /* A new variable offset is created. Note that off_reg->off
11413 * == 0, since it's a scalar.
11414 * dst_reg gets the pointer type and since some positive
11415 * integer value was added to the pointer, give it a new 'id'
11416 * if it's a PTR_TO_PACKET.
11417 * this creates a new 'base' pointer, off_reg (variable) gets
11418 * added into the variable offset, and we copy the fixed offset
11421 if (signed_add_overflows(smin_ptr, smin_val) ||
11422 signed_add_overflows(smax_ptr, smax_val)) {
11423 dst_reg->smin_value = S64_MIN;
11424 dst_reg->smax_value = S64_MAX;
11426 dst_reg->smin_value = smin_ptr + smin_val;
11427 dst_reg->smax_value = smax_ptr + smax_val;
11429 if (umin_ptr + umin_val < umin_ptr ||
11430 umax_ptr + umax_val < umax_ptr) {
11431 dst_reg->umin_value = 0;
11432 dst_reg->umax_value = U64_MAX;
11434 dst_reg->umin_value = umin_ptr + umin_val;
11435 dst_reg->umax_value = umax_ptr + umax_val;
11437 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
11438 dst_reg->off = ptr_reg->off;
11439 dst_reg->raw = ptr_reg->raw;
11440 if (reg_is_pkt_pointer(ptr_reg)) {
11441 dst_reg->id = ++env->id_gen;
11442 /* something was added to pkt_ptr, set range to zero */
11443 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11447 if (dst_reg == off_reg) {
11448 /* scalar -= pointer. Creates an unknown scalar */
11449 verbose(env, "R%d tried to subtract pointer from scalar\n",
11453 /* We don't allow subtraction from FP, because (according to
11454 * test_verifier.c test "invalid fp arithmetic", JITs might not
11455 * be able to deal with it.
11457 if (ptr_reg->type == PTR_TO_STACK) {
11458 verbose(env, "R%d subtraction from stack pointer prohibited\n",
11462 if (known && (ptr_reg->off - smin_val ==
11463 (s64)(s32)(ptr_reg->off - smin_val))) {
11464 /* pointer -= K. Subtract it from fixed offset */
11465 dst_reg->smin_value = smin_ptr;
11466 dst_reg->smax_value = smax_ptr;
11467 dst_reg->umin_value = umin_ptr;
11468 dst_reg->umax_value = umax_ptr;
11469 dst_reg->var_off = ptr_reg->var_off;
11470 dst_reg->id = ptr_reg->id;
11471 dst_reg->off = ptr_reg->off - smin_val;
11472 dst_reg->raw = ptr_reg->raw;
11475 /* A new variable offset is created. If the subtrahend is known
11476 * nonnegative, then any reg->range we had before is still good.
11478 if (signed_sub_overflows(smin_ptr, smax_val) ||
11479 signed_sub_overflows(smax_ptr, smin_val)) {
11480 /* Overflow possible, we know nothing */
11481 dst_reg->smin_value = S64_MIN;
11482 dst_reg->smax_value = S64_MAX;
11484 dst_reg->smin_value = smin_ptr - smax_val;
11485 dst_reg->smax_value = smax_ptr - smin_val;
11487 if (umin_ptr < umax_val) {
11488 /* Overflow possible, we know nothing */
11489 dst_reg->umin_value = 0;
11490 dst_reg->umax_value = U64_MAX;
11492 /* Cannot overflow (as long as bounds are consistent) */
11493 dst_reg->umin_value = umin_ptr - umax_val;
11494 dst_reg->umax_value = umax_ptr - umin_val;
11496 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
11497 dst_reg->off = ptr_reg->off;
11498 dst_reg->raw = ptr_reg->raw;
11499 if (reg_is_pkt_pointer(ptr_reg)) {
11500 dst_reg->id = ++env->id_gen;
11501 /* something was added to pkt_ptr, set range to zero */
11503 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11509 /* bitwise ops on pointers are troublesome, prohibit. */
11510 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
11511 dst, bpf_alu_string[opcode >> 4]);
11514 /* other operators (e.g. MUL,LSH) produce non-pointer results */
11515 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
11516 dst, bpf_alu_string[opcode >> 4]);
11520 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
11522 reg_bounds_sync(dst_reg);
11523 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
11525 if (sanitize_needed(opcode)) {
11526 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
11529 return sanitize_err(env, insn, ret, off_reg, dst_reg);
11535 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
11536 struct bpf_reg_state *src_reg)
11538 s32 smin_val = src_reg->s32_min_value;
11539 s32 smax_val = src_reg->s32_max_value;
11540 u32 umin_val = src_reg->u32_min_value;
11541 u32 umax_val = src_reg->u32_max_value;
11543 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
11544 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
11545 dst_reg->s32_min_value = S32_MIN;
11546 dst_reg->s32_max_value = S32_MAX;
11548 dst_reg->s32_min_value += smin_val;
11549 dst_reg->s32_max_value += smax_val;
11551 if (dst_reg->u32_min_value + umin_val < umin_val ||
11552 dst_reg->u32_max_value + umax_val < umax_val) {
11553 dst_reg->u32_min_value = 0;
11554 dst_reg->u32_max_value = U32_MAX;
11556 dst_reg->u32_min_value += umin_val;
11557 dst_reg->u32_max_value += umax_val;
11561 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
11562 struct bpf_reg_state *src_reg)
11564 s64 smin_val = src_reg->smin_value;
11565 s64 smax_val = src_reg->smax_value;
11566 u64 umin_val = src_reg->umin_value;
11567 u64 umax_val = src_reg->umax_value;
11569 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
11570 signed_add_overflows(dst_reg->smax_value, smax_val)) {
11571 dst_reg->smin_value = S64_MIN;
11572 dst_reg->smax_value = S64_MAX;
11574 dst_reg->smin_value += smin_val;
11575 dst_reg->smax_value += smax_val;
11577 if (dst_reg->umin_value + umin_val < umin_val ||
11578 dst_reg->umax_value + umax_val < umax_val) {
11579 dst_reg->umin_value = 0;
11580 dst_reg->umax_value = U64_MAX;
11582 dst_reg->umin_value += umin_val;
11583 dst_reg->umax_value += umax_val;
11587 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
11588 struct bpf_reg_state *src_reg)
11590 s32 smin_val = src_reg->s32_min_value;
11591 s32 smax_val = src_reg->s32_max_value;
11592 u32 umin_val = src_reg->u32_min_value;
11593 u32 umax_val = src_reg->u32_max_value;
11595 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
11596 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
11597 /* Overflow possible, we know nothing */
11598 dst_reg->s32_min_value = S32_MIN;
11599 dst_reg->s32_max_value = S32_MAX;
11601 dst_reg->s32_min_value -= smax_val;
11602 dst_reg->s32_max_value -= smin_val;
11604 if (dst_reg->u32_min_value < umax_val) {
11605 /* Overflow possible, we know nothing */
11606 dst_reg->u32_min_value = 0;
11607 dst_reg->u32_max_value = U32_MAX;
11609 /* Cannot overflow (as long as bounds are consistent) */
11610 dst_reg->u32_min_value -= umax_val;
11611 dst_reg->u32_max_value -= umin_val;
11615 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
11616 struct bpf_reg_state *src_reg)
11618 s64 smin_val = src_reg->smin_value;
11619 s64 smax_val = src_reg->smax_value;
11620 u64 umin_val = src_reg->umin_value;
11621 u64 umax_val = src_reg->umax_value;
11623 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
11624 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
11625 /* Overflow possible, we know nothing */
11626 dst_reg->smin_value = S64_MIN;
11627 dst_reg->smax_value = S64_MAX;
11629 dst_reg->smin_value -= smax_val;
11630 dst_reg->smax_value -= smin_val;
11632 if (dst_reg->umin_value < umax_val) {
11633 /* Overflow possible, we know nothing */
11634 dst_reg->umin_value = 0;
11635 dst_reg->umax_value = U64_MAX;
11637 /* Cannot overflow (as long as bounds are consistent) */
11638 dst_reg->umin_value -= umax_val;
11639 dst_reg->umax_value -= umin_val;
11643 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
11644 struct bpf_reg_state *src_reg)
11646 s32 smin_val = src_reg->s32_min_value;
11647 u32 umin_val = src_reg->u32_min_value;
11648 u32 umax_val = src_reg->u32_max_value;
11650 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
11651 /* Ain't nobody got time to multiply that sign */
11652 __mark_reg32_unbounded(dst_reg);
11655 /* Both values are positive, so we can work with unsigned and
11656 * copy the result to signed (unless it exceeds S32_MAX).
11658 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
11659 /* Potential overflow, we know nothing */
11660 __mark_reg32_unbounded(dst_reg);
11663 dst_reg->u32_min_value *= umin_val;
11664 dst_reg->u32_max_value *= umax_val;
11665 if (dst_reg->u32_max_value > S32_MAX) {
11666 /* Overflow possible, we know nothing */
11667 dst_reg->s32_min_value = S32_MIN;
11668 dst_reg->s32_max_value = S32_MAX;
11670 dst_reg->s32_min_value = dst_reg->u32_min_value;
11671 dst_reg->s32_max_value = dst_reg->u32_max_value;
11675 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
11676 struct bpf_reg_state *src_reg)
11678 s64 smin_val = src_reg->smin_value;
11679 u64 umin_val = src_reg->umin_value;
11680 u64 umax_val = src_reg->umax_value;
11682 if (smin_val < 0 || dst_reg->smin_value < 0) {
11683 /* Ain't nobody got time to multiply that sign */
11684 __mark_reg64_unbounded(dst_reg);
11687 /* Both values are positive, so we can work with unsigned and
11688 * copy the result to signed (unless it exceeds S64_MAX).
11690 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
11691 /* Potential overflow, we know nothing */
11692 __mark_reg64_unbounded(dst_reg);
11695 dst_reg->umin_value *= umin_val;
11696 dst_reg->umax_value *= umax_val;
11697 if (dst_reg->umax_value > S64_MAX) {
11698 /* Overflow possible, we know nothing */
11699 dst_reg->smin_value = S64_MIN;
11700 dst_reg->smax_value = S64_MAX;
11702 dst_reg->smin_value = dst_reg->umin_value;
11703 dst_reg->smax_value = dst_reg->umax_value;
11707 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
11708 struct bpf_reg_state *src_reg)
11710 bool src_known = tnum_subreg_is_const(src_reg->var_off);
11711 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11712 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11713 s32 smin_val = src_reg->s32_min_value;
11714 u32 umax_val = src_reg->u32_max_value;
11716 if (src_known && dst_known) {
11717 __mark_reg32_known(dst_reg, var32_off.value);
11721 /* We get our minimum from the var_off, since that's inherently
11722 * bitwise. Our maximum is the minimum of the operands' maxima.
11724 dst_reg->u32_min_value = var32_off.value;
11725 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
11726 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11727 /* Lose signed bounds when ANDing negative numbers,
11728 * ain't nobody got time for that.
11730 dst_reg->s32_min_value = S32_MIN;
11731 dst_reg->s32_max_value = S32_MAX;
11733 /* ANDing two positives gives a positive, so safe to
11734 * cast result into s64.
11736 dst_reg->s32_min_value = dst_reg->u32_min_value;
11737 dst_reg->s32_max_value = dst_reg->u32_max_value;
11741 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
11742 struct bpf_reg_state *src_reg)
11744 bool src_known = tnum_is_const(src_reg->var_off);
11745 bool dst_known = tnum_is_const(dst_reg->var_off);
11746 s64 smin_val = src_reg->smin_value;
11747 u64 umax_val = src_reg->umax_value;
11749 if (src_known && dst_known) {
11750 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11754 /* We get our minimum from the var_off, since that's inherently
11755 * bitwise. Our maximum is the minimum of the operands' maxima.
11757 dst_reg->umin_value = dst_reg->var_off.value;
11758 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
11759 if (dst_reg->smin_value < 0 || smin_val < 0) {
11760 /* Lose signed bounds when ANDing negative numbers,
11761 * ain't nobody got time for that.
11763 dst_reg->smin_value = S64_MIN;
11764 dst_reg->smax_value = S64_MAX;
11766 /* ANDing two positives gives a positive, so safe to
11767 * cast result into s64.
11769 dst_reg->smin_value = dst_reg->umin_value;
11770 dst_reg->smax_value = dst_reg->umax_value;
11772 /* We may learn something more from the var_off */
11773 __update_reg_bounds(dst_reg);
11776 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
11777 struct bpf_reg_state *src_reg)
11779 bool src_known = tnum_subreg_is_const(src_reg->var_off);
11780 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11781 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11782 s32 smin_val = src_reg->s32_min_value;
11783 u32 umin_val = src_reg->u32_min_value;
11785 if (src_known && dst_known) {
11786 __mark_reg32_known(dst_reg, var32_off.value);
11790 /* We get our maximum from the var_off, and our minimum is the
11791 * maximum of the operands' minima
11793 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
11794 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11795 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11796 /* Lose signed bounds when ORing negative numbers,
11797 * ain't nobody got time for that.
11799 dst_reg->s32_min_value = S32_MIN;
11800 dst_reg->s32_max_value = S32_MAX;
11802 /* ORing two positives gives a positive, so safe to
11803 * cast result into s64.
11805 dst_reg->s32_min_value = dst_reg->u32_min_value;
11806 dst_reg->s32_max_value = dst_reg->u32_max_value;
11810 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
11811 struct bpf_reg_state *src_reg)
11813 bool src_known = tnum_is_const(src_reg->var_off);
11814 bool dst_known = tnum_is_const(dst_reg->var_off);
11815 s64 smin_val = src_reg->smin_value;
11816 u64 umin_val = src_reg->umin_value;
11818 if (src_known && dst_known) {
11819 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11823 /* We get our maximum from the var_off, and our minimum is the
11824 * maximum of the operands' minima
11826 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
11827 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11828 if (dst_reg->smin_value < 0 || smin_val < 0) {
11829 /* Lose signed bounds when ORing negative numbers,
11830 * ain't nobody got time for that.
11832 dst_reg->smin_value = S64_MIN;
11833 dst_reg->smax_value = S64_MAX;
11835 /* ORing two positives gives a positive, so safe to
11836 * cast result into s64.
11838 dst_reg->smin_value = dst_reg->umin_value;
11839 dst_reg->smax_value = dst_reg->umax_value;
11841 /* We may learn something more from the var_off */
11842 __update_reg_bounds(dst_reg);
11845 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
11846 struct bpf_reg_state *src_reg)
11848 bool src_known = tnum_subreg_is_const(src_reg->var_off);
11849 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11850 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11851 s32 smin_val = src_reg->s32_min_value;
11853 if (src_known && dst_known) {
11854 __mark_reg32_known(dst_reg, var32_off.value);
11858 /* We get both minimum and maximum from the var32_off. */
11859 dst_reg->u32_min_value = var32_off.value;
11860 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11862 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
11863 /* XORing two positive sign numbers gives a positive,
11864 * so safe to cast u32 result into s32.
11866 dst_reg->s32_min_value = dst_reg->u32_min_value;
11867 dst_reg->s32_max_value = dst_reg->u32_max_value;
11869 dst_reg->s32_min_value = S32_MIN;
11870 dst_reg->s32_max_value = S32_MAX;
11874 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
11875 struct bpf_reg_state *src_reg)
11877 bool src_known = tnum_is_const(src_reg->var_off);
11878 bool dst_known = tnum_is_const(dst_reg->var_off);
11879 s64 smin_val = src_reg->smin_value;
11881 if (src_known && dst_known) {
11882 /* dst_reg->var_off.value has been updated earlier */
11883 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11887 /* We get both minimum and maximum from the var_off. */
11888 dst_reg->umin_value = dst_reg->var_off.value;
11889 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11891 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
11892 /* XORing two positive sign numbers gives a positive,
11893 * so safe to cast u64 result into s64.
11895 dst_reg->smin_value = dst_reg->umin_value;
11896 dst_reg->smax_value = dst_reg->umax_value;
11898 dst_reg->smin_value = S64_MIN;
11899 dst_reg->smax_value = S64_MAX;
11902 __update_reg_bounds(dst_reg);
11905 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11906 u64 umin_val, u64 umax_val)
11908 /* We lose all sign bit information (except what we can pick
11911 dst_reg->s32_min_value = S32_MIN;
11912 dst_reg->s32_max_value = S32_MAX;
11913 /* If we might shift our top bit out, then we know nothing */
11914 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
11915 dst_reg->u32_min_value = 0;
11916 dst_reg->u32_max_value = U32_MAX;
11918 dst_reg->u32_min_value <<= umin_val;
11919 dst_reg->u32_max_value <<= umax_val;
11923 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11924 struct bpf_reg_state *src_reg)
11926 u32 umax_val = src_reg->u32_max_value;
11927 u32 umin_val = src_reg->u32_min_value;
11928 /* u32 alu operation will zext upper bits */
11929 struct tnum subreg = tnum_subreg(dst_reg->var_off);
11931 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11932 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
11933 /* Not required but being careful mark reg64 bounds as unknown so
11934 * that we are forced to pick them up from tnum and zext later and
11935 * if some path skips this step we are still safe.
11937 __mark_reg64_unbounded(dst_reg);
11938 __update_reg32_bounds(dst_reg);
11941 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
11942 u64 umin_val, u64 umax_val)
11944 /* Special case <<32 because it is a common compiler pattern to sign
11945 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
11946 * positive we know this shift will also be positive so we can track
11947 * bounds correctly. Otherwise we lose all sign bit information except
11948 * what we can pick up from var_off. Perhaps we can generalize this
11949 * later to shifts of any length.
11951 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
11952 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
11954 dst_reg->smax_value = S64_MAX;
11956 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
11957 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
11959 dst_reg->smin_value = S64_MIN;
11961 /* If we might shift our top bit out, then we know nothing */
11962 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
11963 dst_reg->umin_value = 0;
11964 dst_reg->umax_value = U64_MAX;
11966 dst_reg->umin_value <<= umin_val;
11967 dst_reg->umax_value <<= umax_val;
11971 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
11972 struct bpf_reg_state *src_reg)
11974 u64 umax_val = src_reg->umax_value;
11975 u64 umin_val = src_reg->umin_value;
11977 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
11978 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
11979 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11981 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
11982 /* We may learn something more from the var_off */
11983 __update_reg_bounds(dst_reg);
11986 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
11987 struct bpf_reg_state *src_reg)
11989 struct tnum subreg = tnum_subreg(dst_reg->var_off);
11990 u32 umax_val = src_reg->u32_max_value;
11991 u32 umin_val = src_reg->u32_min_value;
11993 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
11994 * be negative, then either:
11995 * 1) src_reg might be zero, so the sign bit of the result is
11996 * unknown, so we lose our signed bounds
11997 * 2) it's known negative, thus the unsigned bounds capture the
11999 * 3) the signed bounds cross zero, so they tell us nothing
12001 * If the value in dst_reg is known nonnegative, then again the
12002 * unsigned bounds capture the signed bounds.
12003 * Thus, in all cases it suffices to blow away our signed bounds
12004 * and rely on inferring new ones from the unsigned bounds and
12005 * var_off of the result.
12007 dst_reg->s32_min_value = S32_MIN;
12008 dst_reg->s32_max_value = S32_MAX;
12010 dst_reg->var_off = tnum_rshift(subreg, umin_val);
12011 dst_reg->u32_min_value >>= umax_val;
12012 dst_reg->u32_max_value >>= umin_val;
12014 __mark_reg64_unbounded(dst_reg);
12015 __update_reg32_bounds(dst_reg);
12018 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12019 struct bpf_reg_state *src_reg)
12021 u64 umax_val = src_reg->umax_value;
12022 u64 umin_val = src_reg->umin_value;
12024 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12025 * be negative, then either:
12026 * 1) src_reg might be zero, so the sign bit of the result is
12027 * unknown, so we lose our signed bounds
12028 * 2) it's known negative, thus the unsigned bounds capture the
12030 * 3) the signed bounds cross zero, so they tell us nothing
12032 * If the value in dst_reg is known nonnegative, then again the
12033 * unsigned bounds capture the signed bounds.
12034 * Thus, in all cases it suffices to blow away our signed bounds
12035 * and rely on inferring new ones from the unsigned bounds and
12036 * var_off of the result.
12038 dst_reg->smin_value = S64_MIN;
12039 dst_reg->smax_value = S64_MAX;
12040 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12041 dst_reg->umin_value >>= umax_val;
12042 dst_reg->umax_value >>= umin_val;
12044 /* Its not easy to operate on alu32 bounds here because it depends
12045 * on bits being shifted in. Take easy way out and mark unbounded
12046 * so we can recalculate later from tnum.
12048 __mark_reg32_unbounded(dst_reg);
12049 __update_reg_bounds(dst_reg);
12052 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12053 struct bpf_reg_state *src_reg)
12055 u64 umin_val = src_reg->u32_min_value;
12057 /* Upon reaching here, src_known is true and
12058 * umax_val is equal to umin_val.
12060 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12061 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12063 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12065 /* blow away the dst_reg umin_value/umax_value and rely on
12066 * dst_reg var_off to refine the result.
12068 dst_reg->u32_min_value = 0;
12069 dst_reg->u32_max_value = U32_MAX;
12071 __mark_reg64_unbounded(dst_reg);
12072 __update_reg32_bounds(dst_reg);
12075 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12076 struct bpf_reg_state *src_reg)
12078 u64 umin_val = src_reg->umin_value;
12080 /* Upon reaching here, src_known is true and umax_val is equal
12083 dst_reg->smin_value >>= umin_val;
12084 dst_reg->smax_value >>= umin_val;
12086 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12088 /* blow away the dst_reg umin_value/umax_value and rely on
12089 * dst_reg var_off to refine the result.
12091 dst_reg->umin_value = 0;
12092 dst_reg->umax_value = U64_MAX;
12094 /* Its not easy to operate on alu32 bounds here because it depends
12095 * on bits being shifted in from upper 32-bits. Take easy way out
12096 * and mark unbounded so we can recalculate later from tnum.
12098 __mark_reg32_unbounded(dst_reg);
12099 __update_reg_bounds(dst_reg);
12102 /* WARNING: This function does calculations on 64-bit values, but the actual
12103 * execution may occur on 32-bit values. Therefore, things like bitshifts
12104 * need extra checks in the 32-bit case.
12106 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12107 struct bpf_insn *insn,
12108 struct bpf_reg_state *dst_reg,
12109 struct bpf_reg_state src_reg)
12111 struct bpf_reg_state *regs = cur_regs(env);
12112 u8 opcode = BPF_OP(insn->code);
12114 s64 smin_val, smax_val;
12115 u64 umin_val, umax_val;
12116 s32 s32_min_val, s32_max_val;
12117 u32 u32_min_val, u32_max_val;
12118 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12119 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12122 smin_val = src_reg.smin_value;
12123 smax_val = src_reg.smax_value;
12124 umin_val = src_reg.umin_value;
12125 umax_val = src_reg.umax_value;
12127 s32_min_val = src_reg.s32_min_value;
12128 s32_max_val = src_reg.s32_max_value;
12129 u32_min_val = src_reg.u32_min_value;
12130 u32_max_val = src_reg.u32_max_value;
12133 src_known = tnum_subreg_is_const(src_reg.var_off);
12135 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12136 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12137 /* Taint dst register if offset had invalid bounds
12138 * derived from e.g. dead branches.
12140 __mark_reg_unknown(env, dst_reg);
12144 src_known = tnum_is_const(src_reg.var_off);
12146 (smin_val != smax_val || umin_val != umax_val)) ||
12147 smin_val > smax_val || umin_val > umax_val) {
12148 /* Taint dst register if offset had invalid bounds
12149 * derived from e.g. dead branches.
12151 __mark_reg_unknown(env, dst_reg);
12157 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12158 __mark_reg_unknown(env, dst_reg);
12162 if (sanitize_needed(opcode)) {
12163 ret = sanitize_val_alu(env, insn);
12165 return sanitize_err(env, insn, ret, NULL, NULL);
12168 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12169 * There are two classes of instructions: The first class we track both
12170 * alu32 and alu64 sign/unsigned bounds independently this provides the
12171 * greatest amount of precision when alu operations are mixed with jmp32
12172 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12173 * and BPF_OR. This is possible because these ops have fairly easy to
12174 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12175 * See alu32 verifier tests for examples. The second class of
12176 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12177 * with regards to tracking sign/unsigned bounds because the bits may
12178 * cross subreg boundaries in the alu64 case. When this happens we mark
12179 * the reg unbounded in the subreg bound space and use the resulting
12180 * tnum to calculate an approximation of the sign/unsigned bounds.
12184 scalar32_min_max_add(dst_reg, &src_reg);
12185 scalar_min_max_add(dst_reg, &src_reg);
12186 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12189 scalar32_min_max_sub(dst_reg, &src_reg);
12190 scalar_min_max_sub(dst_reg, &src_reg);
12191 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12194 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12195 scalar32_min_max_mul(dst_reg, &src_reg);
12196 scalar_min_max_mul(dst_reg, &src_reg);
12199 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12200 scalar32_min_max_and(dst_reg, &src_reg);
12201 scalar_min_max_and(dst_reg, &src_reg);
12204 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12205 scalar32_min_max_or(dst_reg, &src_reg);
12206 scalar_min_max_or(dst_reg, &src_reg);
12209 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12210 scalar32_min_max_xor(dst_reg, &src_reg);
12211 scalar_min_max_xor(dst_reg, &src_reg);
12214 if (umax_val >= insn_bitness) {
12215 /* Shifts greater than 31 or 63 are undefined.
12216 * This includes shifts by a negative number.
12218 mark_reg_unknown(env, regs, insn->dst_reg);
12222 scalar32_min_max_lsh(dst_reg, &src_reg);
12224 scalar_min_max_lsh(dst_reg, &src_reg);
12227 if (umax_val >= insn_bitness) {
12228 /* Shifts greater than 31 or 63 are undefined.
12229 * This includes shifts by a negative number.
12231 mark_reg_unknown(env, regs, insn->dst_reg);
12235 scalar32_min_max_rsh(dst_reg, &src_reg);
12237 scalar_min_max_rsh(dst_reg, &src_reg);
12240 if (umax_val >= insn_bitness) {
12241 /* Shifts greater than 31 or 63 are undefined.
12242 * This includes shifts by a negative number.
12244 mark_reg_unknown(env, regs, insn->dst_reg);
12248 scalar32_min_max_arsh(dst_reg, &src_reg);
12250 scalar_min_max_arsh(dst_reg, &src_reg);
12253 mark_reg_unknown(env, regs, insn->dst_reg);
12257 /* ALU32 ops are zero extended into 64bit register */
12259 zext_32_to_64(dst_reg);
12260 reg_bounds_sync(dst_reg);
12264 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12267 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12268 struct bpf_insn *insn)
12270 struct bpf_verifier_state *vstate = env->cur_state;
12271 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12272 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12273 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12274 u8 opcode = BPF_OP(insn->code);
12277 dst_reg = ®s[insn->dst_reg];
12279 if (dst_reg->type != SCALAR_VALUE)
12282 /* Make sure ID is cleared otherwise dst_reg min/max could be
12283 * incorrectly propagated into other registers by find_equal_scalars()
12286 if (BPF_SRC(insn->code) == BPF_X) {
12287 src_reg = ®s[insn->src_reg];
12288 if (src_reg->type != SCALAR_VALUE) {
12289 if (dst_reg->type != SCALAR_VALUE) {
12290 /* Combining two pointers by any ALU op yields
12291 * an arbitrary scalar. Disallow all math except
12292 * pointer subtraction
12294 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12295 mark_reg_unknown(env, regs, insn->dst_reg);
12298 verbose(env, "R%d pointer %s pointer prohibited\n",
12300 bpf_alu_string[opcode >> 4]);
12303 /* scalar += pointer
12304 * This is legal, but we have to reverse our
12305 * src/dest handling in computing the range
12307 err = mark_chain_precision(env, insn->dst_reg);
12310 return adjust_ptr_min_max_vals(env, insn,
12313 } else if (ptr_reg) {
12314 /* pointer += scalar */
12315 err = mark_chain_precision(env, insn->src_reg);
12318 return adjust_ptr_min_max_vals(env, insn,
12320 } else if (dst_reg->precise) {
12321 /* if dst_reg is precise, src_reg should be precise as well */
12322 err = mark_chain_precision(env, insn->src_reg);
12327 /* Pretend the src is a reg with a known value, since we only
12328 * need to be able to read from this state.
12330 off_reg.type = SCALAR_VALUE;
12331 __mark_reg_known(&off_reg, insn->imm);
12332 src_reg = &off_reg;
12333 if (ptr_reg) /* pointer += K */
12334 return adjust_ptr_min_max_vals(env, insn,
12338 /* Got here implies adding two SCALAR_VALUEs */
12339 if (WARN_ON_ONCE(ptr_reg)) {
12340 print_verifier_state(env, state, true);
12341 verbose(env, "verifier internal error: unexpected ptr_reg\n");
12344 if (WARN_ON(!src_reg)) {
12345 print_verifier_state(env, state, true);
12346 verbose(env, "verifier internal error: no src_reg\n");
12349 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
12352 /* check validity of 32-bit and 64-bit arithmetic operations */
12353 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
12355 struct bpf_reg_state *regs = cur_regs(env);
12356 u8 opcode = BPF_OP(insn->code);
12359 if (opcode == BPF_END || opcode == BPF_NEG) {
12360 if (opcode == BPF_NEG) {
12361 if (BPF_SRC(insn->code) != BPF_K ||
12362 insn->src_reg != BPF_REG_0 ||
12363 insn->off != 0 || insn->imm != 0) {
12364 verbose(env, "BPF_NEG uses reserved fields\n");
12368 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
12369 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
12370 BPF_CLASS(insn->code) == BPF_ALU64) {
12371 verbose(env, "BPF_END uses reserved fields\n");
12376 /* check src operand */
12377 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12381 if (is_pointer_value(env, insn->dst_reg)) {
12382 verbose(env, "R%d pointer arithmetic prohibited\n",
12387 /* check dest operand */
12388 err = check_reg_arg(env, insn->dst_reg, DST_OP);
12392 } else if (opcode == BPF_MOV) {
12394 if (BPF_SRC(insn->code) == BPF_X) {
12395 if (insn->imm != 0 || insn->off != 0) {
12396 verbose(env, "BPF_MOV uses reserved fields\n");
12400 /* check src operand */
12401 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12405 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12406 verbose(env, "BPF_MOV uses reserved fields\n");
12411 /* check dest operand, mark as required later */
12412 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12416 if (BPF_SRC(insn->code) == BPF_X) {
12417 struct bpf_reg_state *src_reg = regs + insn->src_reg;
12418 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
12420 if (BPF_CLASS(insn->code) == BPF_ALU64) {
12422 * copy register state to dest reg
12424 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
12425 /* Assign src and dst registers the same ID
12426 * that will be used by find_equal_scalars()
12427 * to propagate min/max range.
12429 src_reg->id = ++env->id_gen;
12430 copy_register_state(dst_reg, src_reg);
12431 dst_reg->live |= REG_LIVE_WRITTEN;
12432 dst_reg->subreg_def = DEF_NOT_SUBREG;
12434 /* R1 = (u32) R2 */
12435 if (is_pointer_value(env, insn->src_reg)) {
12437 "R%d partial copy of pointer\n",
12440 } else if (src_reg->type == SCALAR_VALUE) {
12441 copy_register_state(dst_reg, src_reg);
12442 /* Make sure ID is cleared otherwise
12443 * dst_reg min/max could be incorrectly
12444 * propagated into src_reg by find_equal_scalars()
12447 dst_reg->live |= REG_LIVE_WRITTEN;
12448 dst_reg->subreg_def = env->insn_idx + 1;
12450 mark_reg_unknown(env, regs,
12453 zext_32_to_64(dst_reg);
12454 reg_bounds_sync(dst_reg);
12458 * remember the value we stored into this reg
12460 /* clear any state __mark_reg_known doesn't set */
12461 mark_reg_unknown(env, regs, insn->dst_reg);
12462 regs[insn->dst_reg].type = SCALAR_VALUE;
12463 if (BPF_CLASS(insn->code) == BPF_ALU64) {
12464 __mark_reg_known(regs + insn->dst_reg,
12467 __mark_reg_known(regs + insn->dst_reg,
12472 } else if (opcode > BPF_END) {
12473 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
12476 } else { /* all other ALU ops: and, sub, xor, add, ... */
12478 if (BPF_SRC(insn->code) == BPF_X) {
12479 if (insn->imm != 0 || insn->off != 0) {
12480 verbose(env, "BPF_ALU uses reserved fields\n");
12483 /* check src1 operand */
12484 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12488 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12489 verbose(env, "BPF_ALU uses reserved fields\n");
12494 /* check src2 operand */
12495 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12499 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
12500 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
12501 verbose(env, "div by zero\n");
12505 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
12506 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
12507 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
12509 if (insn->imm < 0 || insn->imm >= size) {
12510 verbose(env, "invalid shift %d\n", insn->imm);
12515 /* check dest operand */
12516 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12520 return adjust_reg_min_max_vals(env, insn);
12526 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
12527 struct bpf_reg_state *dst_reg,
12528 enum bpf_reg_type type,
12529 bool range_right_open)
12531 struct bpf_func_state *state;
12532 struct bpf_reg_state *reg;
12535 if (dst_reg->off < 0 ||
12536 (dst_reg->off == 0 && range_right_open))
12537 /* This doesn't give us any range */
12540 if (dst_reg->umax_value > MAX_PACKET_OFF ||
12541 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
12542 /* Risk of overflow. For instance, ptr + (1<<63) may be less
12543 * than pkt_end, but that's because it's also less than pkt.
12547 new_range = dst_reg->off;
12548 if (range_right_open)
12551 /* Examples for register markings:
12553 * pkt_data in dst register:
12557 * if (r2 > pkt_end) goto <handle exception>
12562 * if (r2 < pkt_end) goto <access okay>
12563 * <handle exception>
12566 * r2 == dst_reg, pkt_end == src_reg
12567 * r2=pkt(id=n,off=8,r=0)
12568 * r3=pkt(id=n,off=0,r=0)
12570 * pkt_data in src register:
12574 * if (pkt_end >= r2) goto <access okay>
12575 * <handle exception>
12579 * if (pkt_end <= r2) goto <handle exception>
12583 * pkt_end == dst_reg, r2 == src_reg
12584 * r2=pkt(id=n,off=8,r=0)
12585 * r3=pkt(id=n,off=0,r=0)
12587 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
12588 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
12589 * and [r3, r3 + 8-1) respectively is safe to access depending on
12593 /* If our ids match, then we must have the same max_value. And we
12594 * don't care about the other reg's fixed offset, since if it's too big
12595 * the range won't allow anything.
12596 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
12598 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12599 if (reg->type == type && reg->id == dst_reg->id)
12600 /* keep the maximum range already checked */
12601 reg->range = max(reg->range, new_range);
12605 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
12607 struct tnum subreg = tnum_subreg(reg->var_off);
12608 s32 sval = (s32)val;
12612 if (tnum_is_const(subreg))
12613 return !!tnum_equals_const(subreg, val);
12616 if (tnum_is_const(subreg))
12617 return !tnum_equals_const(subreg, val);
12620 if ((~subreg.mask & subreg.value) & val)
12622 if (!((subreg.mask | subreg.value) & val))
12626 if (reg->u32_min_value > val)
12628 else if (reg->u32_max_value <= val)
12632 if (reg->s32_min_value > sval)
12634 else if (reg->s32_max_value <= sval)
12638 if (reg->u32_max_value < val)
12640 else if (reg->u32_min_value >= val)
12644 if (reg->s32_max_value < sval)
12646 else if (reg->s32_min_value >= sval)
12650 if (reg->u32_min_value >= val)
12652 else if (reg->u32_max_value < val)
12656 if (reg->s32_min_value >= sval)
12658 else if (reg->s32_max_value < sval)
12662 if (reg->u32_max_value <= val)
12664 else if (reg->u32_min_value > val)
12668 if (reg->s32_max_value <= sval)
12670 else if (reg->s32_min_value > sval)
12679 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
12681 s64 sval = (s64)val;
12685 if (tnum_is_const(reg->var_off))
12686 return !!tnum_equals_const(reg->var_off, val);
12689 if (tnum_is_const(reg->var_off))
12690 return !tnum_equals_const(reg->var_off, val);
12693 if ((~reg->var_off.mask & reg->var_off.value) & val)
12695 if (!((reg->var_off.mask | reg->var_off.value) & val))
12699 if (reg->umin_value > val)
12701 else if (reg->umax_value <= val)
12705 if (reg->smin_value > sval)
12707 else if (reg->smax_value <= sval)
12711 if (reg->umax_value < val)
12713 else if (reg->umin_value >= val)
12717 if (reg->smax_value < sval)
12719 else if (reg->smin_value >= sval)
12723 if (reg->umin_value >= val)
12725 else if (reg->umax_value < val)
12729 if (reg->smin_value >= sval)
12731 else if (reg->smax_value < sval)
12735 if (reg->umax_value <= val)
12737 else if (reg->umin_value > val)
12741 if (reg->smax_value <= sval)
12743 else if (reg->smin_value > sval)
12751 /* compute branch direction of the expression "if (reg opcode val) goto target;"
12753 * 1 - branch will be taken and "goto target" will be executed
12754 * 0 - branch will not be taken and fall-through to next insn
12755 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
12758 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
12761 if (__is_pointer_value(false, reg)) {
12762 if (!reg_type_not_null(reg->type))
12765 /* If pointer is valid tests against zero will fail so we can
12766 * use this to direct branch taken.
12782 return is_branch32_taken(reg, val, opcode);
12783 return is_branch64_taken(reg, val, opcode);
12786 static int flip_opcode(u32 opcode)
12788 /* How can we transform "a <op> b" into "b <op> a"? */
12789 static const u8 opcode_flip[16] = {
12790 /* these stay the same */
12791 [BPF_JEQ >> 4] = BPF_JEQ,
12792 [BPF_JNE >> 4] = BPF_JNE,
12793 [BPF_JSET >> 4] = BPF_JSET,
12794 /* these swap "lesser" and "greater" (L and G in the opcodes) */
12795 [BPF_JGE >> 4] = BPF_JLE,
12796 [BPF_JGT >> 4] = BPF_JLT,
12797 [BPF_JLE >> 4] = BPF_JGE,
12798 [BPF_JLT >> 4] = BPF_JGT,
12799 [BPF_JSGE >> 4] = BPF_JSLE,
12800 [BPF_JSGT >> 4] = BPF_JSLT,
12801 [BPF_JSLE >> 4] = BPF_JSGE,
12802 [BPF_JSLT >> 4] = BPF_JSGT
12804 return opcode_flip[opcode >> 4];
12807 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
12808 struct bpf_reg_state *src_reg,
12811 struct bpf_reg_state *pkt;
12813 if (src_reg->type == PTR_TO_PACKET_END) {
12815 } else if (dst_reg->type == PTR_TO_PACKET_END) {
12817 opcode = flip_opcode(opcode);
12822 if (pkt->range >= 0)
12827 /* pkt <= pkt_end */
12830 /* pkt > pkt_end */
12831 if (pkt->range == BEYOND_PKT_END)
12832 /* pkt has at last one extra byte beyond pkt_end */
12833 return opcode == BPF_JGT;
12836 /* pkt < pkt_end */
12839 /* pkt >= pkt_end */
12840 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
12841 return opcode == BPF_JGE;
12847 /* Adjusts the register min/max values in the case that the dst_reg is the
12848 * variable register that we are working on, and src_reg is a constant or we're
12849 * simply doing a BPF_K check.
12850 * In JEQ/JNE cases we also adjust the var_off values.
12852 static void reg_set_min_max(struct bpf_reg_state *true_reg,
12853 struct bpf_reg_state *false_reg,
12854 u64 val, u32 val32,
12855 u8 opcode, bool is_jmp32)
12857 struct tnum false_32off = tnum_subreg(false_reg->var_off);
12858 struct tnum false_64off = false_reg->var_off;
12859 struct tnum true_32off = tnum_subreg(true_reg->var_off);
12860 struct tnum true_64off = true_reg->var_off;
12861 s64 sval = (s64)val;
12862 s32 sval32 = (s32)val32;
12864 /* If the dst_reg is a pointer, we can't learn anything about its
12865 * variable offset from the compare (unless src_reg were a pointer into
12866 * the same object, but we don't bother with that.
12867 * Since false_reg and true_reg have the same type by construction, we
12868 * only need to check one of them for pointerness.
12870 if (__is_pointer_value(false, false_reg))
12874 /* JEQ/JNE comparison doesn't change the register equivalence.
12877 * if (r1 == 42) goto label;
12879 * label: // here both r1 and r2 are known to be 42.
12881 * Hence when marking register as known preserve it's ID.
12885 __mark_reg32_known(true_reg, val32);
12886 true_32off = tnum_subreg(true_reg->var_off);
12888 ___mark_reg_known(true_reg, val);
12889 true_64off = true_reg->var_off;
12894 __mark_reg32_known(false_reg, val32);
12895 false_32off = tnum_subreg(false_reg->var_off);
12897 ___mark_reg_known(false_reg, val);
12898 false_64off = false_reg->var_off;
12903 false_32off = tnum_and(false_32off, tnum_const(~val32));
12904 if (is_power_of_2(val32))
12905 true_32off = tnum_or(true_32off,
12906 tnum_const(val32));
12908 false_64off = tnum_and(false_64off, tnum_const(~val));
12909 if (is_power_of_2(val))
12910 true_64off = tnum_or(true_64off,
12918 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
12919 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
12921 false_reg->u32_max_value = min(false_reg->u32_max_value,
12923 true_reg->u32_min_value = max(true_reg->u32_min_value,
12926 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
12927 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
12929 false_reg->umax_value = min(false_reg->umax_value, false_umax);
12930 true_reg->umin_value = max(true_reg->umin_value, true_umin);
12938 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
12939 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
12941 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
12942 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
12944 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
12945 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
12947 false_reg->smax_value = min(false_reg->smax_value, false_smax);
12948 true_reg->smin_value = max(true_reg->smin_value, true_smin);
12956 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
12957 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
12959 false_reg->u32_min_value = max(false_reg->u32_min_value,
12961 true_reg->u32_max_value = min(true_reg->u32_max_value,
12964 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
12965 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
12967 false_reg->umin_value = max(false_reg->umin_value, false_umin);
12968 true_reg->umax_value = min(true_reg->umax_value, true_umax);
12976 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
12977 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
12979 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
12980 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
12982 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
12983 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
12985 false_reg->smin_value = max(false_reg->smin_value, false_smin);
12986 true_reg->smax_value = min(true_reg->smax_value, true_smax);
12995 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
12996 tnum_subreg(false_32off));
12997 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
12998 tnum_subreg(true_32off));
12999 __reg_combine_32_into_64(false_reg);
13000 __reg_combine_32_into_64(true_reg);
13002 false_reg->var_off = false_64off;
13003 true_reg->var_off = true_64off;
13004 __reg_combine_64_into_32(false_reg);
13005 __reg_combine_64_into_32(true_reg);
13009 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13010 * the variable reg.
13012 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13013 struct bpf_reg_state *false_reg,
13014 u64 val, u32 val32,
13015 u8 opcode, bool is_jmp32)
13017 opcode = flip_opcode(opcode);
13018 /* This uses zero as "not present in table"; luckily the zero opcode,
13019 * BPF_JA, can't get here.
13022 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13025 /* Regs are known to be equal, so intersect their min/max/var_off */
13026 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13027 struct bpf_reg_state *dst_reg)
13029 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13030 dst_reg->umin_value);
13031 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13032 dst_reg->umax_value);
13033 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13034 dst_reg->smin_value);
13035 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13036 dst_reg->smax_value);
13037 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13039 reg_bounds_sync(src_reg);
13040 reg_bounds_sync(dst_reg);
13043 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13044 struct bpf_reg_state *true_dst,
13045 struct bpf_reg_state *false_src,
13046 struct bpf_reg_state *false_dst,
13051 __reg_combine_min_max(true_src, true_dst);
13054 __reg_combine_min_max(false_src, false_dst);
13059 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13060 struct bpf_reg_state *reg, u32 id,
13063 if (type_may_be_null(reg->type) && reg->id == id &&
13064 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13065 /* Old offset (both fixed and variable parts) should have been
13066 * known-zero, because we don't allow pointer arithmetic on
13067 * pointers that might be NULL. If we see this happening, don't
13068 * convert the register.
13070 * But in some cases, some helpers that return local kptrs
13071 * advance offset for the returned pointer. In those cases, it
13072 * is fine to expect to see reg->off.
13074 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13076 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13077 WARN_ON_ONCE(reg->off))
13081 reg->type = SCALAR_VALUE;
13082 /* We don't need id and ref_obj_id from this point
13083 * onwards anymore, thus we should better reset it,
13084 * so that state pruning has chances to take effect.
13087 reg->ref_obj_id = 0;
13092 mark_ptr_not_null_reg(reg);
13094 if (!reg_may_point_to_spin_lock(reg)) {
13095 /* For not-NULL ptr, reg->ref_obj_id will be reset
13096 * in release_reference().
13098 * reg->id is still used by spin_lock ptr. Other
13099 * than spin_lock ptr type, reg->id can be reset.
13106 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13107 * be folded together at some point.
13109 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13112 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13113 struct bpf_reg_state *regs = state->regs, *reg;
13114 u32 ref_obj_id = regs[regno].ref_obj_id;
13115 u32 id = regs[regno].id;
13117 if (ref_obj_id && ref_obj_id == id && is_null)
13118 /* regs[regno] is in the " == NULL" branch.
13119 * No one could have freed the reference state before
13120 * doing the NULL check.
13122 WARN_ON_ONCE(release_reference_state(state, id));
13124 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13125 mark_ptr_or_null_reg(state, reg, id, is_null);
13129 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13130 struct bpf_reg_state *dst_reg,
13131 struct bpf_reg_state *src_reg,
13132 struct bpf_verifier_state *this_branch,
13133 struct bpf_verifier_state *other_branch)
13135 if (BPF_SRC(insn->code) != BPF_X)
13138 /* Pointers are always 64-bit. */
13139 if (BPF_CLASS(insn->code) == BPF_JMP32)
13142 switch (BPF_OP(insn->code)) {
13144 if ((dst_reg->type == PTR_TO_PACKET &&
13145 src_reg->type == PTR_TO_PACKET_END) ||
13146 (dst_reg->type == PTR_TO_PACKET_META &&
13147 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13148 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13149 find_good_pkt_pointers(this_branch, dst_reg,
13150 dst_reg->type, false);
13151 mark_pkt_end(other_branch, insn->dst_reg, true);
13152 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13153 src_reg->type == PTR_TO_PACKET) ||
13154 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13155 src_reg->type == PTR_TO_PACKET_META)) {
13156 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13157 find_good_pkt_pointers(other_branch, src_reg,
13158 src_reg->type, true);
13159 mark_pkt_end(this_branch, insn->src_reg, false);
13165 if ((dst_reg->type == PTR_TO_PACKET &&
13166 src_reg->type == PTR_TO_PACKET_END) ||
13167 (dst_reg->type == PTR_TO_PACKET_META &&
13168 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13169 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13170 find_good_pkt_pointers(other_branch, dst_reg,
13171 dst_reg->type, true);
13172 mark_pkt_end(this_branch, insn->dst_reg, false);
13173 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13174 src_reg->type == PTR_TO_PACKET) ||
13175 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13176 src_reg->type == PTR_TO_PACKET_META)) {
13177 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13178 find_good_pkt_pointers(this_branch, src_reg,
13179 src_reg->type, false);
13180 mark_pkt_end(other_branch, insn->src_reg, true);
13186 if ((dst_reg->type == PTR_TO_PACKET &&
13187 src_reg->type == PTR_TO_PACKET_END) ||
13188 (dst_reg->type == PTR_TO_PACKET_META &&
13189 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13190 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13191 find_good_pkt_pointers(this_branch, dst_reg,
13192 dst_reg->type, true);
13193 mark_pkt_end(other_branch, insn->dst_reg, false);
13194 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13195 src_reg->type == PTR_TO_PACKET) ||
13196 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13197 src_reg->type == PTR_TO_PACKET_META)) {
13198 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13199 find_good_pkt_pointers(other_branch, src_reg,
13200 src_reg->type, false);
13201 mark_pkt_end(this_branch, insn->src_reg, true);
13207 if ((dst_reg->type == PTR_TO_PACKET &&
13208 src_reg->type == PTR_TO_PACKET_END) ||
13209 (dst_reg->type == PTR_TO_PACKET_META &&
13210 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13211 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13212 find_good_pkt_pointers(other_branch, dst_reg,
13213 dst_reg->type, false);
13214 mark_pkt_end(this_branch, insn->dst_reg, true);
13215 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13216 src_reg->type == PTR_TO_PACKET) ||
13217 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13218 src_reg->type == PTR_TO_PACKET_META)) {
13219 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13220 find_good_pkt_pointers(this_branch, src_reg,
13221 src_reg->type, true);
13222 mark_pkt_end(other_branch, insn->src_reg, false);
13234 static void find_equal_scalars(struct bpf_verifier_state *vstate,
13235 struct bpf_reg_state *known_reg)
13237 struct bpf_func_state *state;
13238 struct bpf_reg_state *reg;
13240 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13241 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
13242 copy_register_state(reg, known_reg);
13246 static int check_cond_jmp_op(struct bpf_verifier_env *env,
13247 struct bpf_insn *insn, int *insn_idx)
13249 struct bpf_verifier_state *this_branch = env->cur_state;
13250 struct bpf_verifier_state *other_branch;
13251 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
13252 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
13253 struct bpf_reg_state *eq_branch_regs;
13254 u8 opcode = BPF_OP(insn->code);
13259 /* Only conditional jumps are expected to reach here. */
13260 if (opcode == BPF_JA || opcode > BPF_JSLE) {
13261 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
13265 if (BPF_SRC(insn->code) == BPF_X) {
13266 if (insn->imm != 0) {
13267 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13271 /* check src1 operand */
13272 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13276 if (is_pointer_value(env, insn->src_reg)) {
13277 verbose(env, "R%d pointer comparison prohibited\n",
13281 src_reg = ®s[insn->src_reg];
13283 if (insn->src_reg != BPF_REG_0) {
13284 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13289 /* check src2 operand */
13290 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13294 dst_reg = ®s[insn->dst_reg];
13295 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
13297 if (BPF_SRC(insn->code) == BPF_K) {
13298 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13299 } else if (src_reg->type == SCALAR_VALUE &&
13300 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13301 pred = is_branch_taken(dst_reg,
13302 tnum_subreg(src_reg->var_off).value,
13305 } else if (src_reg->type == SCALAR_VALUE &&
13306 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13307 pred = is_branch_taken(dst_reg,
13308 src_reg->var_off.value,
13311 } else if (reg_is_pkt_pointer_any(dst_reg) &&
13312 reg_is_pkt_pointer_any(src_reg) &&
13314 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
13318 /* If we get here with a dst_reg pointer type it is because
13319 * above is_branch_taken() special cased the 0 comparison.
13321 if (!__is_pointer_value(false, dst_reg))
13322 err = mark_chain_precision(env, insn->dst_reg);
13323 if (BPF_SRC(insn->code) == BPF_X && !err &&
13324 !__is_pointer_value(false, src_reg))
13325 err = mark_chain_precision(env, insn->src_reg);
13331 /* Only follow the goto, ignore fall-through. If needed, push
13332 * the fall-through branch for simulation under speculative
13335 if (!env->bypass_spec_v1 &&
13336 !sanitize_speculative_path(env, insn, *insn_idx + 1,
13339 *insn_idx += insn->off;
13341 } else if (pred == 0) {
13342 /* Only follow the fall-through branch, since that's where the
13343 * program will go. If needed, push the goto branch for
13344 * simulation under speculative execution.
13346 if (!env->bypass_spec_v1 &&
13347 !sanitize_speculative_path(env, insn,
13348 *insn_idx + insn->off + 1,
13354 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
13358 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
13360 /* detect if we are comparing against a constant value so we can adjust
13361 * our min/max values for our dst register.
13362 * this is only legit if both are scalars (or pointers to the same
13363 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
13364 * because otherwise the different base pointers mean the offsets aren't
13367 if (BPF_SRC(insn->code) == BPF_X) {
13368 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
13370 if (dst_reg->type == SCALAR_VALUE &&
13371 src_reg->type == SCALAR_VALUE) {
13372 if (tnum_is_const(src_reg->var_off) ||
13374 tnum_is_const(tnum_subreg(src_reg->var_off))))
13375 reg_set_min_max(&other_branch_regs[insn->dst_reg],
13377 src_reg->var_off.value,
13378 tnum_subreg(src_reg->var_off).value,
13380 else if (tnum_is_const(dst_reg->var_off) ||
13382 tnum_is_const(tnum_subreg(dst_reg->var_off))))
13383 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
13385 dst_reg->var_off.value,
13386 tnum_subreg(dst_reg->var_off).value,
13388 else if (!is_jmp32 &&
13389 (opcode == BPF_JEQ || opcode == BPF_JNE))
13390 /* Comparing for equality, we can combine knowledge */
13391 reg_combine_min_max(&other_branch_regs[insn->src_reg],
13392 &other_branch_regs[insn->dst_reg],
13393 src_reg, dst_reg, opcode);
13395 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
13396 find_equal_scalars(this_branch, src_reg);
13397 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
13401 } else if (dst_reg->type == SCALAR_VALUE) {
13402 reg_set_min_max(&other_branch_regs[insn->dst_reg],
13403 dst_reg, insn->imm, (u32)insn->imm,
13407 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
13408 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
13409 find_equal_scalars(this_branch, dst_reg);
13410 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
13413 /* if one pointer register is compared to another pointer
13414 * register check if PTR_MAYBE_NULL could be lifted.
13415 * E.g. register A - maybe null
13416 * register B - not null
13417 * for JNE A, B, ... - A is not null in the false branch;
13418 * for JEQ A, B, ... - A is not null in the true branch.
13420 * Since PTR_TO_BTF_ID points to a kernel struct that does
13421 * not need to be null checked by the BPF program, i.e.,
13422 * could be null even without PTR_MAYBE_NULL marking, so
13423 * only propagate nullness when neither reg is that type.
13425 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
13426 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
13427 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
13428 base_type(src_reg->type) != PTR_TO_BTF_ID &&
13429 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
13430 eq_branch_regs = NULL;
13433 eq_branch_regs = other_branch_regs;
13436 eq_branch_regs = regs;
13442 if (eq_branch_regs) {
13443 if (type_may_be_null(src_reg->type))
13444 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
13446 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
13450 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
13451 * NOTE: these optimizations below are related with pointer comparison
13452 * which will never be JMP32.
13454 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
13455 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
13456 type_may_be_null(dst_reg->type)) {
13457 /* Mark all identical registers in each branch as either
13458 * safe or unknown depending R == 0 or R != 0 conditional.
13460 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
13461 opcode == BPF_JNE);
13462 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
13463 opcode == BPF_JEQ);
13464 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
13465 this_branch, other_branch) &&
13466 is_pointer_value(env, insn->dst_reg)) {
13467 verbose(env, "R%d pointer comparison prohibited\n",
13471 if (env->log.level & BPF_LOG_LEVEL)
13472 print_insn_state(env, this_branch->frame[this_branch->curframe]);
13476 /* verify BPF_LD_IMM64 instruction */
13477 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
13479 struct bpf_insn_aux_data *aux = cur_aux(env);
13480 struct bpf_reg_state *regs = cur_regs(env);
13481 struct bpf_reg_state *dst_reg;
13482 struct bpf_map *map;
13485 if (BPF_SIZE(insn->code) != BPF_DW) {
13486 verbose(env, "invalid BPF_LD_IMM insn\n");
13489 if (insn->off != 0) {
13490 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
13494 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13498 dst_reg = ®s[insn->dst_reg];
13499 if (insn->src_reg == 0) {
13500 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
13502 dst_reg->type = SCALAR_VALUE;
13503 __mark_reg_known(®s[insn->dst_reg], imm);
13507 /* All special src_reg cases are listed below. From this point onwards
13508 * we either succeed and assign a corresponding dst_reg->type after
13509 * zeroing the offset, or fail and reject the program.
13511 mark_reg_known_zero(env, regs, insn->dst_reg);
13513 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
13514 dst_reg->type = aux->btf_var.reg_type;
13515 switch (base_type(dst_reg->type)) {
13517 dst_reg->mem_size = aux->btf_var.mem_size;
13519 case PTR_TO_BTF_ID:
13520 dst_reg->btf = aux->btf_var.btf;
13521 dst_reg->btf_id = aux->btf_var.btf_id;
13524 verbose(env, "bpf verifier is misconfigured\n");
13530 if (insn->src_reg == BPF_PSEUDO_FUNC) {
13531 struct bpf_prog_aux *aux = env->prog->aux;
13532 u32 subprogno = find_subprog(env,
13533 env->insn_idx + insn->imm + 1);
13535 if (!aux->func_info) {
13536 verbose(env, "missing btf func_info\n");
13539 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
13540 verbose(env, "callback function not static\n");
13544 dst_reg->type = PTR_TO_FUNC;
13545 dst_reg->subprogno = subprogno;
13549 map = env->used_maps[aux->map_index];
13550 dst_reg->map_ptr = map;
13552 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
13553 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
13554 dst_reg->type = PTR_TO_MAP_VALUE;
13555 dst_reg->off = aux->map_off;
13556 WARN_ON_ONCE(map->max_entries != 1);
13557 /* We want reg->id to be same (0) as map_value is not distinct */
13558 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
13559 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
13560 dst_reg->type = CONST_PTR_TO_MAP;
13562 verbose(env, "bpf verifier is misconfigured\n");
13569 static bool may_access_skb(enum bpf_prog_type type)
13572 case BPF_PROG_TYPE_SOCKET_FILTER:
13573 case BPF_PROG_TYPE_SCHED_CLS:
13574 case BPF_PROG_TYPE_SCHED_ACT:
13581 /* verify safety of LD_ABS|LD_IND instructions:
13582 * - they can only appear in the programs where ctx == skb
13583 * - since they are wrappers of function calls, they scratch R1-R5 registers,
13584 * preserve R6-R9, and store return value into R0
13587 * ctx == skb == R6 == CTX
13590 * SRC == any register
13591 * IMM == 32-bit immediate
13594 * R0 - 8/16/32-bit skb data converted to cpu endianness
13596 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
13598 struct bpf_reg_state *regs = cur_regs(env);
13599 static const int ctx_reg = BPF_REG_6;
13600 u8 mode = BPF_MODE(insn->code);
13603 if (!may_access_skb(resolve_prog_type(env->prog))) {
13604 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
13608 if (!env->ops->gen_ld_abs) {
13609 verbose(env, "bpf verifier is misconfigured\n");
13613 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
13614 BPF_SIZE(insn->code) == BPF_DW ||
13615 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
13616 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
13620 /* check whether implicit source operand (register R6) is readable */
13621 err = check_reg_arg(env, ctx_reg, SRC_OP);
13625 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
13626 * gen_ld_abs() may terminate the program at runtime, leading to
13629 err = check_reference_leak(env);
13631 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
13635 if (env->cur_state->active_lock.ptr) {
13636 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
13640 if (env->cur_state->active_rcu_lock) {
13641 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
13645 if (regs[ctx_reg].type != PTR_TO_CTX) {
13647 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
13651 if (mode == BPF_IND) {
13652 /* check explicit source operand */
13653 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13658 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
13662 /* reset caller saved regs to unreadable */
13663 for (i = 0; i < CALLER_SAVED_REGS; i++) {
13664 mark_reg_not_init(env, regs, caller_saved[i]);
13665 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
13668 /* mark destination R0 register as readable, since it contains
13669 * the value fetched from the packet.
13670 * Already marked as written above.
13672 mark_reg_unknown(env, regs, BPF_REG_0);
13673 /* ld_abs load up to 32-bit skb data. */
13674 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
13678 static int check_return_code(struct bpf_verifier_env *env)
13680 struct tnum enforce_attach_type_range = tnum_unknown;
13681 const struct bpf_prog *prog = env->prog;
13682 struct bpf_reg_state *reg;
13683 struct tnum range = tnum_range(0, 1);
13684 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13686 struct bpf_func_state *frame = env->cur_state->frame[0];
13687 const bool is_subprog = frame->subprogno;
13689 /* LSM and struct_ops func-ptr's return type could be "void" */
13691 switch (prog_type) {
13692 case BPF_PROG_TYPE_LSM:
13693 if (prog->expected_attach_type == BPF_LSM_CGROUP)
13694 /* See below, can be 0 or 0-1 depending on hook. */
13697 case BPF_PROG_TYPE_STRUCT_OPS:
13698 if (!prog->aux->attach_func_proto->type)
13706 /* eBPF calling convention is such that R0 is used
13707 * to return the value from eBPF program.
13708 * Make sure that it's readable at this time
13709 * of bpf_exit, which means that program wrote
13710 * something into it earlier
13712 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
13716 if (is_pointer_value(env, BPF_REG_0)) {
13717 verbose(env, "R0 leaks addr as return value\n");
13721 reg = cur_regs(env) + BPF_REG_0;
13723 if (frame->in_async_callback_fn) {
13724 /* enforce return zero from async callbacks like timer */
13725 if (reg->type != SCALAR_VALUE) {
13726 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
13727 reg_type_str(env, reg->type));
13731 if (!tnum_in(tnum_const(0), reg->var_off)) {
13732 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
13739 if (reg->type != SCALAR_VALUE) {
13740 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
13741 reg_type_str(env, reg->type));
13747 switch (prog_type) {
13748 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
13749 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
13750 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
13751 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
13752 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
13753 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
13754 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
13755 range = tnum_range(1, 1);
13756 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
13757 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
13758 range = tnum_range(0, 3);
13760 case BPF_PROG_TYPE_CGROUP_SKB:
13761 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
13762 range = tnum_range(0, 3);
13763 enforce_attach_type_range = tnum_range(2, 3);
13766 case BPF_PROG_TYPE_CGROUP_SOCK:
13767 case BPF_PROG_TYPE_SOCK_OPS:
13768 case BPF_PROG_TYPE_CGROUP_DEVICE:
13769 case BPF_PROG_TYPE_CGROUP_SYSCTL:
13770 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
13772 case BPF_PROG_TYPE_RAW_TRACEPOINT:
13773 if (!env->prog->aux->attach_btf_id)
13775 range = tnum_const(0);
13777 case BPF_PROG_TYPE_TRACING:
13778 switch (env->prog->expected_attach_type) {
13779 case BPF_TRACE_FENTRY:
13780 case BPF_TRACE_FEXIT:
13781 range = tnum_const(0);
13783 case BPF_TRACE_RAW_TP:
13784 case BPF_MODIFY_RETURN:
13786 case BPF_TRACE_ITER:
13792 case BPF_PROG_TYPE_SK_LOOKUP:
13793 range = tnum_range(SK_DROP, SK_PASS);
13796 case BPF_PROG_TYPE_LSM:
13797 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
13798 /* Regular BPF_PROG_TYPE_LSM programs can return
13803 if (!env->prog->aux->attach_func_proto->type) {
13804 /* Make sure programs that attach to void
13805 * hooks don't try to modify return value.
13807 range = tnum_range(1, 1);
13811 case BPF_PROG_TYPE_EXT:
13812 /* freplace program can return anything as its return value
13813 * depends on the to-be-replaced kernel func or bpf program.
13819 if (reg->type != SCALAR_VALUE) {
13820 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
13821 reg_type_str(env, reg->type));
13825 if (!tnum_in(range, reg->var_off)) {
13826 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
13827 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
13828 prog_type == BPF_PROG_TYPE_LSM &&
13829 !prog->aux->attach_func_proto->type)
13830 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
13834 if (!tnum_is_unknown(enforce_attach_type_range) &&
13835 tnum_in(enforce_attach_type_range, reg->var_off))
13836 env->prog->enforce_expected_attach_type = 1;
13840 /* non-recursive DFS pseudo code
13841 * 1 procedure DFS-iterative(G,v):
13842 * 2 label v as discovered
13843 * 3 let S be a stack
13845 * 5 while S is not empty
13847 * 7 if t is what we're looking for:
13849 * 9 for all edges e in G.adjacentEdges(t) do
13850 * 10 if edge e is already labelled
13851 * 11 continue with the next edge
13852 * 12 w <- G.adjacentVertex(t,e)
13853 * 13 if vertex w is not discovered and not explored
13854 * 14 label e as tree-edge
13855 * 15 label w as discovered
13858 * 18 else if vertex w is discovered
13859 * 19 label e as back-edge
13861 * 21 // vertex w is explored
13862 * 22 label e as forward- or cross-edge
13863 * 23 label t as explored
13867 * 0x10 - discovered
13868 * 0x11 - discovered and fall-through edge labelled
13869 * 0x12 - discovered and fall-through and branch edges labelled
13880 static u32 state_htab_size(struct bpf_verifier_env *env)
13882 return env->prog->len;
13885 static struct bpf_verifier_state_list **explored_state(
13886 struct bpf_verifier_env *env,
13889 struct bpf_verifier_state *cur = env->cur_state;
13890 struct bpf_func_state *state = cur->frame[cur->curframe];
13892 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
13895 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
13897 env->insn_aux_data[idx].prune_point = true;
13900 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
13902 return env->insn_aux_data[insn_idx].prune_point;
13905 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
13907 env->insn_aux_data[idx].force_checkpoint = true;
13910 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
13912 return env->insn_aux_data[insn_idx].force_checkpoint;
13917 DONE_EXPLORING = 0,
13918 KEEP_EXPLORING = 1,
13921 /* t, w, e - match pseudo-code above:
13922 * t - index of current instruction
13923 * w - next instruction
13926 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
13929 int *insn_stack = env->cfg.insn_stack;
13930 int *insn_state = env->cfg.insn_state;
13932 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
13933 return DONE_EXPLORING;
13935 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
13936 return DONE_EXPLORING;
13938 if (w < 0 || w >= env->prog->len) {
13939 verbose_linfo(env, t, "%d: ", t);
13940 verbose(env, "jump out of range from insn %d to %d\n", t, w);
13945 /* mark branch target for state pruning */
13946 mark_prune_point(env, w);
13947 mark_jmp_point(env, w);
13950 if (insn_state[w] == 0) {
13952 insn_state[t] = DISCOVERED | e;
13953 insn_state[w] = DISCOVERED;
13954 if (env->cfg.cur_stack >= env->prog->len)
13956 insn_stack[env->cfg.cur_stack++] = w;
13957 return KEEP_EXPLORING;
13958 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
13959 if (loop_ok && env->bpf_capable)
13960 return DONE_EXPLORING;
13961 verbose_linfo(env, t, "%d: ", t);
13962 verbose_linfo(env, w, "%d: ", w);
13963 verbose(env, "back-edge from insn %d to %d\n", t, w);
13965 } else if (insn_state[w] == EXPLORED) {
13966 /* forward- or cross-edge */
13967 insn_state[t] = DISCOVERED | e;
13969 verbose(env, "insn state internal bug\n");
13972 return DONE_EXPLORING;
13975 static int visit_func_call_insn(int t, struct bpf_insn *insns,
13976 struct bpf_verifier_env *env,
13981 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
13985 mark_prune_point(env, t + 1);
13986 /* when we exit from subprog, we need to record non-linear history */
13987 mark_jmp_point(env, t + 1);
13989 if (visit_callee) {
13990 mark_prune_point(env, t);
13991 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
13992 /* It's ok to allow recursion from CFG point of
13993 * view. __check_func_call() will do the actual
13996 bpf_pseudo_func(insns + t));
14001 /* Visits the instruction at index t and returns one of the following:
14002 * < 0 - an error occurred
14003 * DONE_EXPLORING - the instruction was fully explored
14004 * KEEP_EXPLORING - there is still work to be done before it is fully explored
14006 static int visit_insn(int t, struct bpf_verifier_env *env)
14008 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14011 if (bpf_pseudo_func(insn))
14012 return visit_func_call_insn(t, insns, env, true);
14014 /* All non-branch instructions have a single fall-through edge. */
14015 if (BPF_CLASS(insn->code) != BPF_JMP &&
14016 BPF_CLASS(insn->code) != BPF_JMP32)
14017 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14019 switch (BPF_OP(insn->code)) {
14021 return DONE_EXPLORING;
14024 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14025 /* Mark this call insn as a prune point to trigger
14026 * is_state_visited() check before call itself is
14027 * processed by __check_func_call(). Otherwise new
14028 * async state will be pushed for further exploration.
14030 mark_prune_point(env, t);
14031 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14032 struct bpf_kfunc_call_arg_meta meta;
14034 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14035 if (ret == 0 && is_iter_next_kfunc(&meta)) {
14036 mark_prune_point(env, t);
14037 /* Checking and saving state checkpoints at iter_next() call
14038 * is crucial for fast convergence of open-coded iterator loop
14039 * logic, so we need to force it. If we don't do that,
14040 * is_state_visited() might skip saving a checkpoint, causing
14041 * unnecessarily long sequence of not checkpointed
14042 * instructions and jumps, leading to exhaustion of jump
14043 * history buffer, and potentially other undesired outcomes.
14044 * It is expected that with correct open-coded iterators
14045 * convergence will happen quickly, so we don't run a risk of
14046 * exhausting memory.
14048 mark_force_checkpoint(env, t);
14051 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14054 if (BPF_SRC(insn->code) != BPF_K)
14057 /* unconditional jump with single edge */
14058 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14063 mark_prune_point(env, t + insn->off + 1);
14064 mark_jmp_point(env, t + insn->off + 1);
14069 /* conditional jump with two edges */
14070 mark_prune_point(env, t);
14072 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14076 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14080 /* non-recursive depth-first-search to detect loops in BPF program
14081 * loop == back-edge in directed graph
14083 static int check_cfg(struct bpf_verifier_env *env)
14085 int insn_cnt = env->prog->len;
14086 int *insn_stack, *insn_state;
14090 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14094 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14096 kvfree(insn_state);
14100 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14101 insn_stack[0] = 0; /* 0 is the first instruction */
14102 env->cfg.cur_stack = 1;
14104 while (env->cfg.cur_stack > 0) {
14105 int t = insn_stack[env->cfg.cur_stack - 1];
14107 ret = visit_insn(t, env);
14109 case DONE_EXPLORING:
14110 insn_state[t] = EXPLORED;
14111 env->cfg.cur_stack--;
14113 case KEEP_EXPLORING:
14117 verbose(env, "visit_insn internal bug\n");
14124 if (env->cfg.cur_stack < 0) {
14125 verbose(env, "pop stack internal bug\n");
14130 for (i = 0; i < insn_cnt; i++) {
14131 if (insn_state[i] != EXPLORED) {
14132 verbose(env, "unreachable insn %d\n", i);
14137 ret = 0; /* cfg looks good */
14140 kvfree(insn_state);
14141 kvfree(insn_stack);
14142 env->cfg.insn_state = env->cfg.insn_stack = NULL;
14146 static int check_abnormal_return(struct bpf_verifier_env *env)
14150 for (i = 1; i < env->subprog_cnt; i++) {
14151 if (env->subprog_info[i].has_ld_abs) {
14152 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14155 if (env->subprog_info[i].has_tail_call) {
14156 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14163 /* The minimum supported BTF func info size */
14164 #define MIN_BPF_FUNCINFO_SIZE 8
14165 #define MAX_FUNCINFO_REC_SIZE 252
14167 static int check_btf_func(struct bpf_verifier_env *env,
14168 const union bpf_attr *attr,
14171 const struct btf_type *type, *func_proto, *ret_type;
14172 u32 i, nfuncs, urec_size, min_size;
14173 u32 krec_size = sizeof(struct bpf_func_info);
14174 struct bpf_func_info *krecord;
14175 struct bpf_func_info_aux *info_aux = NULL;
14176 struct bpf_prog *prog;
14177 const struct btf *btf;
14179 u32 prev_offset = 0;
14180 bool scalar_return;
14183 nfuncs = attr->func_info_cnt;
14185 if (check_abnormal_return(env))
14190 if (nfuncs != env->subprog_cnt) {
14191 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14195 urec_size = attr->func_info_rec_size;
14196 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14197 urec_size > MAX_FUNCINFO_REC_SIZE ||
14198 urec_size % sizeof(u32)) {
14199 verbose(env, "invalid func info rec size %u\n", urec_size);
14204 btf = prog->aux->btf;
14206 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14207 min_size = min_t(u32, krec_size, urec_size);
14209 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14212 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14216 for (i = 0; i < nfuncs; i++) {
14217 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14219 if (ret == -E2BIG) {
14220 verbose(env, "nonzero tailing record in func info");
14221 /* set the size kernel expects so loader can zero
14222 * out the rest of the record.
14224 if (copy_to_bpfptr_offset(uattr,
14225 offsetof(union bpf_attr, func_info_rec_size),
14226 &min_size, sizeof(min_size)))
14232 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
14237 /* check insn_off */
14240 if (krecord[i].insn_off) {
14242 "nonzero insn_off %u for the first func info record",
14243 krecord[i].insn_off);
14246 } else if (krecord[i].insn_off <= prev_offset) {
14248 "same or smaller insn offset (%u) than previous func info record (%u)",
14249 krecord[i].insn_off, prev_offset);
14253 if (env->subprog_info[i].start != krecord[i].insn_off) {
14254 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
14258 /* check type_id */
14259 type = btf_type_by_id(btf, krecord[i].type_id);
14260 if (!type || !btf_type_is_func(type)) {
14261 verbose(env, "invalid type id %d in func info",
14262 krecord[i].type_id);
14265 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
14267 func_proto = btf_type_by_id(btf, type->type);
14268 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14269 /* btf_func_check() already verified it during BTF load */
14271 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14273 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
14274 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14275 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14278 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14279 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14283 prev_offset = krecord[i].insn_off;
14284 bpfptr_add(&urecord, urec_size);
14287 prog->aux->func_info = krecord;
14288 prog->aux->func_info_cnt = nfuncs;
14289 prog->aux->func_info_aux = info_aux;
14298 static void adjust_btf_func(struct bpf_verifier_env *env)
14300 struct bpf_prog_aux *aux = env->prog->aux;
14303 if (!aux->func_info)
14306 for (i = 0; i < env->subprog_cnt; i++)
14307 aux->func_info[i].insn_off = env->subprog_info[i].start;
14310 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
14311 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
14313 static int check_btf_line(struct bpf_verifier_env *env,
14314 const union bpf_attr *attr,
14317 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14318 struct bpf_subprog_info *sub;
14319 struct bpf_line_info *linfo;
14320 struct bpf_prog *prog;
14321 const struct btf *btf;
14325 nr_linfo = attr->line_info_cnt;
14328 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
14331 rec_size = attr->line_info_rec_size;
14332 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
14333 rec_size > MAX_LINEINFO_REC_SIZE ||
14334 rec_size & (sizeof(u32) - 1))
14337 /* Need to zero it in case the userspace may
14338 * pass in a smaller bpf_line_info object.
14340 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
14341 GFP_KERNEL | __GFP_NOWARN);
14346 btf = prog->aux->btf;
14349 sub = env->subprog_info;
14350 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
14351 expected_size = sizeof(struct bpf_line_info);
14352 ncopy = min_t(u32, expected_size, rec_size);
14353 for (i = 0; i < nr_linfo; i++) {
14354 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
14356 if (err == -E2BIG) {
14357 verbose(env, "nonzero tailing record in line_info");
14358 if (copy_to_bpfptr_offset(uattr,
14359 offsetof(union bpf_attr, line_info_rec_size),
14360 &expected_size, sizeof(expected_size)))
14366 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
14372 * Check insn_off to ensure
14373 * 1) strictly increasing AND
14374 * 2) bounded by prog->len
14376 * The linfo[0].insn_off == 0 check logically falls into
14377 * the later "missing bpf_line_info for func..." case
14378 * because the first linfo[0].insn_off must be the
14379 * first sub also and the first sub must have
14380 * subprog_info[0].start == 0.
14382 if ((i && linfo[i].insn_off <= prev_offset) ||
14383 linfo[i].insn_off >= prog->len) {
14384 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
14385 i, linfo[i].insn_off, prev_offset,
14391 if (!prog->insnsi[linfo[i].insn_off].code) {
14393 "Invalid insn code at line_info[%u].insn_off\n",
14399 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
14400 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
14401 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
14406 if (s != env->subprog_cnt) {
14407 if (linfo[i].insn_off == sub[s].start) {
14408 sub[s].linfo_idx = i;
14410 } else if (sub[s].start < linfo[i].insn_off) {
14411 verbose(env, "missing bpf_line_info for func#%u\n", s);
14417 prev_offset = linfo[i].insn_off;
14418 bpfptr_add(&ulinfo, rec_size);
14421 if (s != env->subprog_cnt) {
14422 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
14423 env->subprog_cnt - s, s);
14428 prog->aux->linfo = linfo;
14429 prog->aux->nr_linfo = nr_linfo;
14438 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
14439 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
14441 static int check_core_relo(struct bpf_verifier_env *env,
14442 const union bpf_attr *attr,
14445 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
14446 struct bpf_core_relo core_relo = {};
14447 struct bpf_prog *prog = env->prog;
14448 const struct btf *btf = prog->aux->btf;
14449 struct bpf_core_ctx ctx = {
14453 bpfptr_t u_core_relo;
14456 nr_core_relo = attr->core_relo_cnt;
14459 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
14462 rec_size = attr->core_relo_rec_size;
14463 if (rec_size < MIN_CORE_RELO_SIZE ||
14464 rec_size > MAX_CORE_RELO_SIZE ||
14465 rec_size % sizeof(u32))
14468 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
14469 expected_size = sizeof(struct bpf_core_relo);
14470 ncopy = min_t(u32, expected_size, rec_size);
14472 /* Unlike func_info and line_info, copy and apply each CO-RE
14473 * relocation record one at a time.
14475 for (i = 0; i < nr_core_relo; i++) {
14476 /* future proofing when sizeof(bpf_core_relo) changes */
14477 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
14479 if (err == -E2BIG) {
14480 verbose(env, "nonzero tailing record in core_relo");
14481 if (copy_to_bpfptr_offset(uattr,
14482 offsetof(union bpf_attr, core_relo_rec_size),
14483 &expected_size, sizeof(expected_size)))
14489 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
14494 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
14495 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
14496 i, core_relo.insn_off, prog->len);
14501 err = bpf_core_apply(&ctx, &core_relo, i,
14502 &prog->insnsi[core_relo.insn_off / 8]);
14505 bpfptr_add(&u_core_relo, rec_size);
14510 static int check_btf_info(struct bpf_verifier_env *env,
14511 const union bpf_attr *attr,
14517 if (!attr->func_info_cnt && !attr->line_info_cnt) {
14518 if (check_abnormal_return(env))
14523 btf = btf_get_by_fd(attr->prog_btf_fd);
14525 return PTR_ERR(btf);
14526 if (btf_is_kernel(btf)) {
14530 env->prog->aux->btf = btf;
14532 err = check_btf_func(env, attr, uattr);
14536 err = check_btf_line(env, attr, uattr);
14540 err = check_core_relo(env, attr, uattr);
14547 /* check %cur's range satisfies %old's */
14548 static bool range_within(struct bpf_reg_state *old,
14549 struct bpf_reg_state *cur)
14551 return old->umin_value <= cur->umin_value &&
14552 old->umax_value >= cur->umax_value &&
14553 old->smin_value <= cur->smin_value &&
14554 old->smax_value >= cur->smax_value &&
14555 old->u32_min_value <= cur->u32_min_value &&
14556 old->u32_max_value >= cur->u32_max_value &&
14557 old->s32_min_value <= cur->s32_min_value &&
14558 old->s32_max_value >= cur->s32_max_value;
14561 /* If in the old state two registers had the same id, then they need to have
14562 * the same id in the new state as well. But that id could be different from
14563 * the old state, so we need to track the mapping from old to new ids.
14564 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
14565 * regs with old id 5 must also have new id 9 for the new state to be safe. But
14566 * regs with a different old id could still have new id 9, we don't care about
14568 * So we look through our idmap to see if this old id has been seen before. If
14569 * so, we require the new id to match; otherwise, we add the id pair to the map.
14571 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
14575 /* either both IDs should be set or both should be zero */
14576 if (!!old_id != !!cur_id)
14579 if (old_id == 0) /* cur_id == 0 as well */
14582 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
14583 if (!idmap[i].old) {
14584 /* Reached an empty slot; haven't seen this id before */
14585 idmap[i].old = old_id;
14586 idmap[i].cur = cur_id;
14589 if (idmap[i].old == old_id)
14590 return idmap[i].cur == cur_id;
14592 /* We ran out of idmap slots, which should be impossible */
14597 static void clean_func_state(struct bpf_verifier_env *env,
14598 struct bpf_func_state *st)
14600 enum bpf_reg_liveness live;
14603 for (i = 0; i < BPF_REG_FP; i++) {
14604 live = st->regs[i].live;
14605 /* liveness must not touch this register anymore */
14606 st->regs[i].live |= REG_LIVE_DONE;
14607 if (!(live & REG_LIVE_READ))
14608 /* since the register is unused, clear its state
14609 * to make further comparison simpler
14611 __mark_reg_not_init(env, &st->regs[i]);
14614 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
14615 live = st->stack[i].spilled_ptr.live;
14616 /* liveness must not touch this stack slot anymore */
14617 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
14618 if (!(live & REG_LIVE_READ)) {
14619 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
14620 for (j = 0; j < BPF_REG_SIZE; j++)
14621 st->stack[i].slot_type[j] = STACK_INVALID;
14626 static void clean_verifier_state(struct bpf_verifier_env *env,
14627 struct bpf_verifier_state *st)
14631 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
14632 /* all regs in this state in all frames were already marked */
14635 for (i = 0; i <= st->curframe; i++)
14636 clean_func_state(env, st->frame[i]);
14639 /* the parentage chains form a tree.
14640 * the verifier states are added to state lists at given insn and
14641 * pushed into state stack for future exploration.
14642 * when the verifier reaches bpf_exit insn some of the verifer states
14643 * stored in the state lists have their final liveness state already,
14644 * but a lot of states will get revised from liveness point of view when
14645 * the verifier explores other branches.
14648 * 2: if r1 == 100 goto pc+1
14651 * when the verifier reaches exit insn the register r0 in the state list of
14652 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
14653 * of insn 2 and goes exploring further. At the insn 4 it will walk the
14654 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
14656 * Since the verifier pushes the branch states as it sees them while exploring
14657 * the program the condition of walking the branch instruction for the second
14658 * time means that all states below this branch were already explored and
14659 * their final liveness marks are already propagated.
14660 * Hence when the verifier completes the search of state list in is_state_visited()
14661 * we can call this clean_live_states() function to mark all liveness states
14662 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
14663 * will not be used.
14664 * This function also clears the registers and stack for states that !READ
14665 * to simplify state merging.
14667 * Important note here that walking the same branch instruction in the callee
14668 * doesn't meant that the states are DONE. The verifier has to compare
14671 static void clean_live_states(struct bpf_verifier_env *env, int insn,
14672 struct bpf_verifier_state *cur)
14674 struct bpf_verifier_state_list *sl;
14677 sl = *explored_state(env, insn);
14679 if (sl->state.branches)
14681 if (sl->state.insn_idx != insn ||
14682 sl->state.curframe != cur->curframe)
14684 for (i = 0; i <= cur->curframe; i++)
14685 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
14687 clean_verifier_state(env, &sl->state);
14693 static bool regs_exact(const struct bpf_reg_state *rold,
14694 const struct bpf_reg_state *rcur,
14695 struct bpf_id_pair *idmap)
14697 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
14698 check_ids(rold->id, rcur->id, idmap) &&
14699 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
14702 /* Returns true if (rold safe implies rcur safe) */
14703 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
14704 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
14706 if (!(rold->live & REG_LIVE_READ))
14707 /* explored state didn't use this */
14709 if (rold->type == NOT_INIT)
14710 /* explored state can't have used this */
14712 if (rcur->type == NOT_INIT)
14715 /* Enforce that register types have to match exactly, including their
14716 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
14719 * One can make a point that using a pointer register as unbounded
14720 * SCALAR would be technically acceptable, but this could lead to
14721 * pointer leaks because scalars are allowed to leak while pointers
14722 * are not. We could make this safe in special cases if root is
14723 * calling us, but it's probably not worth the hassle.
14725 * Also, register types that are *not* MAYBE_NULL could technically be
14726 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
14727 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
14728 * to the same map).
14729 * However, if the old MAYBE_NULL register then got NULL checked,
14730 * doing so could have affected others with the same id, and we can't
14731 * check for that because we lost the id when we converted to
14732 * a non-MAYBE_NULL variant.
14733 * So, as a general rule we don't allow mixing MAYBE_NULL and
14734 * non-MAYBE_NULL registers as well.
14736 if (rold->type != rcur->type)
14739 switch (base_type(rold->type)) {
14741 if (regs_exact(rold, rcur, idmap))
14743 if (env->explore_alu_limits)
14745 if (!rold->precise)
14747 /* new val must satisfy old val knowledge */
14748 return range_within(rold, rcur) &&
14749 tnum_in(rold->var_off, rcur->var_off);
14750 case PTR_TO_MAP_KEY:
14751 case PTR_TO_MAP_VALUE:
14754 case PTR_TO_TP_BUFFER:
14755 /* If the new min/max/var_off satisfy the old ones and
14756 * everything else matches, we are OK.
14758 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
14759 range_within(rold, rcur) &&
14760 tnum_in(rold->var_off, rcur->var_off) &&
14761 check_ids(rold->id, rcur->id, idmap) &&
14762 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
14763 case PTR_TO_PACKET_META:
14764 case PTR_TO_PACKET:
14765 /* We must have at least as much range as the old ptr
14766 * did, so that any accesses which were safe before are
14767 * still safe. This is true even if old range < old off,
14768 * since someone could have accessed through (ptr - k), or
14769 * even done ptr -= k in a register, to get a safe access.
14771 if (rold->range > rcur->range)
14773 /* If the offsets don't match, we can't trust our alignment;
14774 * nor can we be sure that we won't fall out of range.
14776 if (rold->off != rcur->off)
14778 /* id relations must be preserved */
14779 if (!check_ids(rold->id, rcur->id, idmap))
14781 /* new val must satisfy old val knowledge */
14782 return range_within(rold, rcur) &&
14783 tnum_in(rold->var_off, rcur->var_off);
14785 /* two stack pointers are equal only if they're pointing to
14786 * the same stack frame, since fp-8 in foo != fp-8 in bar
14788 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
14790 return regs_exact(rold, rcur, idmap);
14794 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
14795 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
14799 /* walk slots of the explored stack and ignore any additional
14800 * slots in the current stack, since explored(safe) state
14803 for (i = 0; i < old->allocated_stack; i++) {
14804 struct bpf_reg_state *old_reg, *cur_reg;
14806 spi = i / BPF_REG_SIZE;
14808 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
14809 i += BPF_REG_SIZE - 1;
14810 /* explored state didn't use this */
14814 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
14817 if (env->allow_uninit_stack &&
14818 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
14821 /* explored stack has more populated slots than current stack
14822 * and these slots were used
14824 if (i >= cur->allocated_stack)
14827 /* if old state was safe with misc data in the stack
14828 * it will be safe with zero-initialized stack.
14829 * The opposite is not true
14831 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
14832 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
14834 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
14835 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
14836 /* Ex: old explored (safe) state has STACK_SPILL in
14837 * this stack slot, but current has STACK_MISC ->
14838 * this verifier states are not equivalent,
14839 * return false to continue verification of this path
14842 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
14844 /* Both old and cur are having same slot_type */
14845 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
14847 /* when explored and current stack slot are both storing
14848 * spilled registers, check that stored pointers types
14849 * are the same as well.
14850 * Ex: explored safe path could have stored
14851 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
14852 * but current path has stored:
14853 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
14854 * such verifier states are not equivalent.
14855 * return false to continue verification of this path
14857 if (!regsafe(env, &old->stack[spi].spilled_ptr,
14858 &cur->stack[spi].spilled_ptr, idmap))
14862 old_reg = &old->stack[spi].spilled_ptr;
14863 cur_reg = &cur->stack[spi].spilled_ptr;
14864 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
14865 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
14866 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
14870 old_reg = &old->stack[spi].spilled_ptr;
14871 cur_reg = &cur->stack[spi].spilled_ptr;
14872 /* iter.depth is not compared between states as it
14873 * doesn't matter for correctness and would otherwise
14874 * prevent convergence; we maintain it only to prevent
14875 * infinite loop check triggering, see
14876 * iter_active_depths_differ()
14878 if (old_reg->iter.btf != cur_reg->iter.btf ||
14879 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
14880 old_reg->iter.state != cur_reg->iter.state ||
14881 /* ignore {old_reg,cur_reg}->iter.depth, see above */
14882 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
14887 case STACK_INVALID:
14889 /* Ensure that new unhandled slot types return false by default */
14897 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
14898 struct bpf_id_pair *idmap)
14902 if (old->acquired_refs != cur->acquired_refs)
14905 for (i = 0; i < old->acquired_refs; i++) {
14906 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
14913 /* compare two verifier states
14915 * all states stored in state_list are known to be valid, since
14916 * verifier reached 'bpf_exit' instruction through them
14918 * this function is called when verifier exploring different branches of
14919 * execution popped from the state stack. If it sees an old state that has
14920 * more strict register state and more strict stack state then this execution
14921 * branch doesn't need to be explored further, since verifier already
14922 * concluded that more strict state leads to valid finish.
14924 * Therefore two states are equivalent if register state is more conservative
14925 * and explored stack state is more conservative than the current one.
14928 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
14929 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
14931 * In other words if current stack state (one being explored) has more
14932 * valid slots than old one that already passed validation, it means
14933 * the verifier can stop exploring and conclude that current state is valid too
14935 * Similarly with registers. If explored state has register type as invalid
14936 * whereas register type in current state is meaningful, it means that
14937 * the current state will reach 'bpf_exit' instruction safely
14939 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
14940 struct bpf_func_state *cur)
14944 for (i = 0; i < MAX_BPF_REG; i++)
14945 if (!regsafe(env, &old->regs[i], &cur->regs[i],
14946 env->idmap_scratch))
14949 if (!stacksafe(env, old, cur, env->idmap_scratch))
14952 if (!refsafe(old, cur, env->idmap_scratch))
14958 static bool states_equal(struct bpf_verifier_env *env,
14959 struct bpf_verifier_state *old,
14960 struct bpf_verifier_state *cur)
14964 if (old->curframe != cur->curframe)
14967 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
14969 /* Verification state from speculative execution simulation
14970 * must never prune a non-speculative execution one.
14972 if (old->speculative && !cur->speculative)
14975 if (old->active_lock.ptr != cur->active_lock.ptr)
14978 /* Old and cur active_lock's have to be either both present
14981 if (!!old->active_lock.id != !!cur->active_lock.id)
14984 if (old->active_lock.id &&
14985 !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
14988 if (old->active_rcu_lock != cur->active_rcu_lock)
14991 /* for states to be equal callsites have to be the same
14992 * and all frame states need to be equivalent
14994 for (i = 0; i <= old->curframe; i++) {
14995 if (old->frame[i]->callsite != cur->frame[i]->callsite)
14997 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15003 /* Return 0 if no propagation happened. Return negative error code if error
15004 * happened. Otherwise, return the propagated bit.
15006 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15007 struct bpf_reg_state *reg,
15008 struct bpf_reg_state *parent_reg)
15010 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15011 u8 flag = reg->live & REG_LIVE_READ;
15014 /* When comes here, read flags of PARENT_REG or REG could be any of
15015 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15016 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15018 if (parent_flag == REG_LIVE_READ64 ||
15019 /* Or if there is no read flag from REG. */
15021 /* Or if the read flag from REG is the same as PARENT_REG. */
15022 parent_flag == flag)
15025 err = mark_reg_read(env, reg, parent_reg, flag);
15032 /* A write screens off any subsequent reads; but write marks come from the
15033 * straight-line code between a state and its parent. When we arrive at an
15034 * equivalent state (jump target or such) we didn't arrive by the straight-line
15035 * code, so read marks in the state must propagate to the parent regardless
15036 * of the state's write marks. That's what 'parent == state->parent' comparison
15037 * in mark_reg_read() is for.
15039 static int propagate_liveness(struct bpf_verifier_env *env,
15040 const struct bpf_verifier_state *vstate,
15041 struct bpf_verifier_state *vparent)
15043 struct bpf_reg_state *state_reg, *parent_reg;
15044 struct bpf_func_state *state, *parent;
15045 int i, frame, err = 0;
15047 if (vparent->curframe != vstate->curframe) {
15048 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15049 vparent->curframe, vstate->curframe);
15052 /* Propagate read liveness of registers... */
15053 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15054 for (frame = 0; frame <= vstate->curframe; frame++) {
15055 parent = vparent->frame[frame];
15056 state = vstate->frame[frame];
15057 parent_reg = parent->regs;
15058 state_reg = state->regs;
15059 /* We don't need to worry about FP liveness, it's read-only */
15060 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15061 err = propagate_liveness_reg(env, &state_reg[i],
15065 if (err == REG_LIVE_READ64)
15066 mark_insn_zext(env, &parent_reg[i]);
15069 /* Propagate stack slots. */
15070 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15071 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15072 parent_reg = &parent->stack[i].spilled_ptr;
15073 state_reg = &state->stack[i].spilled_ptr;
15074 err = propagate_liveness_reg(env, state_reg,
15083 /* find precise scalars in the previous equivalent state and
15084 * propagate them into the current state
15086 static int propagate_precision(struct bpf_verifier_env *env,
15087 const struct bpf_verifier_state *old)
15089 struct bpf_reg_state *state_reg;
15090 struct bpf_func_state *state;
15091 int i, err = 0, fr;
15093 for (fr = old->curframe; fr >= 0; fr--) {
15094 state = old->frame[fr];
15095 state_reg = state->regs;
15096 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15097 if (state_reg->type != SCALAR_VALUE ||
15098 !state_reg->precise ||
15099 !(state_reg->live & REG_LIVE_READ))
15101 if (env->log.level & BPF_LOG_LEVEL2)
15102 verbose(env, "frame %d: propagating r%d\n", fr, i);
15103 err = mark_chain_precision_frame(env, fr, i);
15108 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15109 if (!is_spilled_reg(&state->stack[i]))
15111 state_reg = &state->stack[i].spilled_ptr;
15112 if (state_reg->type != SCALAR_VALUE ||
15113 !state_reg->precise ||
15114 !(state_reg->live & REG_LIVE_READ))
15116 if (env->log.level & BPF_LOG_LEVEL2)
15117 verbose(env, "frame %d: propagating fp%d\n",
15118 fr, (-i - 1) * BPF_REG_SIZE);
15119 err = mark_chain_precision_stack_frame(env, fr, i);
15127 static bool states_maybe_looping(struct bpf_verifier_state *old,
15128 struct bpf_verifier_state *cur)
15130 struct bpf_func_state *fold, *fcur;
15131 int i, fr = cur->curframe;
15133 if (old->curframe != fr)
15136 fold = old->frame[fr];
15137 fcur = cur->frame[fr];
15138 for (i = 0; i < MAX_BPF_REG; i++)
15139 if (memcmp(&fold->regs[i], &fcur->regs[i],
15140 offsetof(struct bpf_reg_state, parent)))
15145 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15147 return env->insn_aux_data[insn_idx].is_iter_next;
15150 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15151 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15152 * states to match, which otherwise would look like an infinite loop. So while
15153 * iter_next() calls are taken care of, we still need to be careful and
15154 * prevent erroneous and too eager declaration of "ininite loop", when
15155 * iterators are involved.
15157 * Here's a situation in pseudo-BPF assembly form:
15159 * 0: again: ; set up iter_next() call args
15160 * 1: r1 = &it ; <CHECKPOINT HERE>
15161 * 2: call bpf_iter_num_next ; this is iter_next() call
15162 * 3: if r0 == 0 goto done
15163 * 4: ... something useful here ...
15164 * 5: goto again ; another iteration
15167 * 8: call bpf_iter_num_destroy ; clean up iter state
15170 * This is a typical loop. Let's assume that we have a prune point at 1:,
15171 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15172 * again`, assuming other heuristics don't get in a way).
15174 * When we first time come to 1:, let's say we have some state X. We proceed
15175 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15176 * Now we come back to validate that forked ACTIVE state. We proceed through
15177 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15178 * are converging. But the problem is that we don't know that yet, as this
15179 * convergence has to happen at iter_next() call site only. So if nothing is
15180 * done, at 1: verifier will use bounded loop logic and declare infinite
15181 * looping (and would be *technically* correct, if not for iterator's
15182 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15183 * don't want that. So what we do in process_iter_next_call() when we go on
15184 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15185 * a different iteration. So when we suspect an infinite loop, we additionally
15186 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15187 * pretend we are not looping and wait for next iter_next() call.
15189 * This only applies to ACTIVE state. In DRAINED state we don't expect to
15190 * loop, because that would actually mean infinite loop, as DRAINED state is
15191 * "sticky", and so we'll keep returning into the same instruction with the
15192 * same state (at least in one of possible code paths).
15194 * This approach allows to keep infinite loop heuristic even in the face of
15195 * active iterator. E.g., C snippet below is and will be detected as
15196 * inifintely looping:
15198 * struct bpf_iter_num it;
15201 * bpf_iter_num_new(&it, 0, 10);
15202 * while ((p = bpf_iter_num_next(&t))) {
15204 * while (x--) {} // <<-- infinite loop here
15208 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15210 struct bpf_reg_state *slot, *cur_slot;
15211 struct bpf_func_state *state;
15214 for (fr = old->curframe; fr >= 0; fr--) {
15215 state = old->frame[fr];
15216 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15217 if (state->stack[i].slot_type[0] != STACK_ITER)
15220 slot = &state->stack[i].spilled_ptr;
15221 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15224 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15225 if (cur_slot->iter.depth != slot->iter.depth)
15232 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
15234 struct bpf_verifier_state_list *new_sl;
15235 struct bpf_verifier_state_list *sl, **pprev;
15236 struct bpf_verifier_state *cur = env->cur_state, *new;
15237 int i, j, err, states_cnt = 0;
15238 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15239 bool add_new_state = force_new_state;
15241 /* bpf progs typically have pruning point every 4 instructions
15242 * http://vger.kernel.org/bpfconf2019.html#session-1
15243 * Do not add new state for future pruning if the verifier hasn't seen
15244 * at least 2 jumps and at least 8 instructions.
15245 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15246 * In tests that amounts to up to 50% reduction into total verifier
15247 * memory consumption and 20% verifier time speedup.
15249 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15250 env->insn_processed - env->prev_insn_processed >= 8)
15251 add_new_state = true;
15253 pprev = explored_state(env, insn_idx);
15256 clean_live_states(env, insn_idx, cur);
15260 if (sl->state.insn_idx != insn_idx)
15263 if (sl->state.branches) {
15264 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15266 if (frame->in_async_callback_fn &&
15267 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
15268 /* Different async_entry_cnt means that the verifier is
15269 * processing another entry into async callback.
15270 * Seeing the same state is not an indication of infinite
15271 * loop or infinite recursion.
15272 * But finding the same state doesn't mean that it's safe
15273 * to stop processing the current state. The previous state
15274 * hasn't yet reached bpf_exit, since state.branches > 0.
15275 * Checking in_async_callback_fn alone is not enough either.
15276 * Since the verifier still needs to catch infinite loops
15277 * inside async callbacks.
15279 goto skip_inf_loop_check;
15281 /* BPF open-coded iterators loop detection is special.
15282 * states_maybe_looping() logic is too simplistic in detecting
15283 * states that *might* be equivalent, because it doesn't know
15284 * about ID remapping, so don't even perform it.
15285 * See process_iter_next_call() and iter_active_depths_differ()
15286 * for overview of the logic. When current and one of parent
15287 * states are detected as equivalent, it's a good thing: we prove
15288 * convergence and can stop simulating further iterations.
15289 * It's safe to assume that iterator loop will finish, taking into
15290 * account iter_next() contract of eventually returning
15291 * sticky NULL result.
15293 if (is_iter_next_insn(env, insn_idx)) {
15294 if (states_equal(env, &sl->state, cur)) {
15295 struct bpf_func_state *cur_frame;
15296 struct bpf_reg_state *iter_state, *iter_reg;
15299 cur_frame = cur->frame[cur->curframe];
15300 /* btf_check_iter_kfuncs() enforces that
15301 * iter state pointer is always the first arg
15303 iter_reg = &cur_frame->regs[BPF_REG_1];
15304 /* current state is valid due to states_equal(),
15305 * so we can assume valid iter and reg state,
15306 * no need for extra (re-)validations
15308 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
15309 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
15310 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
15313 goto skip_inf_loop_check;
15315 /* attempt to detect infinite loop to avoid unnecessary doomed work */
15316 if (states_maybe_looping(&sl->state, cur) &&
15317 states_equal(env, &sl->state, cur) &&
15318 !iter_active_depths_differ(&sl->state, cur)) {
15319 verbose_linfo(env, insn_idx, "; ");
15320 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
15323 /* if the verifier is processing a loop, avoid adding new state
15324 * too often, since different loop iterations have distinct
15325 * states and may not help future pruning.
15326 * This threshold shouldn't be too low to make sure that
15327 * a loop with large bound will be rejected quickly.
15328 * The most abusive loop will be:
15330 * if r1 < 1000000 goto pc-2
15331 * 1M insn_procssed limit / 100 == 10k peak states.
15332 * This threshold shouldn't be too high either, since states
15333 * at the end of the loop are likely to be useful in pruning.
15335 skip_inf_loop_check:
15336 if (!force_new_state &&
15337 env->jmps_processed - env->prev_jmps_processed < 20 &&
15338 env->insn_processed - env->prev_insn_processed < 100)
15339 add_new_state = false;
15342 if (states_equal(env, &sl->state, cur)) {
15345 /* reached equivalent register/stack state,
15346 * prune the search.
15347 * Registers read by the continuation are read by us.
15348 * If we have any write marks in env->cur_state, they
15349 * will prevent corresponding reads in the continuation
15350 * from reaching our parent (an explored_state). Our
15351 * own state will get the read marks recorded, but
15352 * they'll be immediately forgotten as we're pruning
15353 * this state and will pop a new one.
15355 err = propagate_liveness(env, &sl->state, cur);
15357 /* if previous state reached the exit with precision and
15358 * current state is equivalent to it (except precsion marks)
15359 * the precision needs to be propagated back in
15360 * the current state.
15362 err = err ? : push_jmp_history(env, cur);
15363 err = err ? : propagate_precision(env, &sl->state);
15369 /* when new state is not going to be added do not increase miss count.
15370 * Otherwise several loop iterations will remove the state
15371 * recorded earlier. The goal of these heuristics is to have
15372 * states from some iterations of the loop (some in the beginning
15373 * and some at the end) to help pruning.
15377 /* heuristic to determine whether this state is beneficial
15378 * to keep checking from state equivalence point of view.
15379 * Higher numbers increase max_states_per_insn and verification time,
15380 * but do not meaningfully decrease insn_processed.
15382 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
15383 /* the state is unlikely to be useful. Remove it to
15384 * speed up verification
15387 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
15388 u32 br = sl->state.branches;
15391 "BUG live_done but branches_to_explore %d\n",
15393 free_verifier_state(&sl->state, false);
15395 env->peak_states--;
15397 /* cannot free this state, since parentage chain may
15398 * walk it later. Add it for free_list instead to
15399 * be freed at the end of verification
15401 sl->next = env->free_list;
15402 env->free_list = sl;
15412 if (env->max_states_per_insn < states_cnt)
15413 env->max_states_per_insn = states_cnt;
15415 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
15418 if (!add_new_state)
15421 /* There were no equivalent states, remember the current one.
15422 * Technically the current state is not proven to be safe yet,
15423 * but it will either reach outer most bpf_exit (which means it's safe)
15424 * or it will be rejected. When there are no loops the verifier won't be
15425 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
15426 * again on the way to bpf_exit.
15427 * When looping the sl->state.branches will be > 0 and this state
15428 * will not be considered for equivalence until branches == 0.
15430 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
15433 env->total_states++;
15434 env->peak_states++;
15435 env->prev_jmps_processed = env->jmps_processed;
15436 env->prev_insn_processed = env->insn_processed;
15438 /* forget precise markings we inherited, see __mark_chain_precision */
15439 if (env->bpf_capable)
15440 mark_all_scalars_imprecise(env, cur);
15442 /* add new state to the head of linked list */
15443 new = &new_sl->state;
15444 err = copy_verifier_state(new, cur);
15446 free_verifier_state(new, false);
15450 new->insn_idx = insn_idx;
15451 WARN_ONCE(new->branches != 1,
15452 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
15455 cur->first_insn_idx = insn_idx;
15456 clear_jmp_history(cur);
15457 new_sl->next = *explored_state(env, insn_idx);
15458 *explored_state(env, insn_idx) = new_sl;
15459 /* connect new state to parentage chain. Current frame needs all
15460 * registers connected. Only r6 - r9 of the callers are alive (pushed
15461 * to the stack implicitly by JITs) so in callers' frames connect just
15462 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
15463 * the state of the call instruction (with WRITTEN set), and r0 comes
15464 * from callee with its full parentage chain, anyway.
15466 /* clear write marks in current state: the writes we did are not writes
15467 * our child did, so they don't screen off its reads from us.
15468 * (There are no read marks in current state, because reads always mark
15469 * their parent and current state never has children yet. Only
15470 * explored_states can get read marks.)
15472 for (j = 0; j <= cur->curframe; j++) {
15473 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
15474 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
15475 for (i = 0; i < BPF_REG_FP; i++)
15476 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
15479 /* all stack frames are accessible from callee, clear them all */
15480 for (j = 0; j <= cur->curframe; j++) {
15481 struct bpf_func_state *frame = cur->frame[j];
15482 struct bpf_func_state *newframe = new->frame[j];
15484 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
15485 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
15486 frame->stack[i].spilled_ptr.parent =
15487 &newframe->stack[i].spilled_ptr;
15493 /* Return true if it's OK to have the same insn return a different type. */
15494 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
15496 switch (base_type(type)) {
15498 case PTR_TO_SOCKET:
15499 case PTR_TO_SOCK_COMMON:
15500 case PTR_TO_TCP_SOCK:
15501 case PTR_TO_XDP_SOCK:
15502 case PTR_TO_BTF_ID:
15509 /* If an instruction was previously used with particular pointer types, then we
15510 * need to be careful to avoid cases such as the below, where it may be ok
15511 * for one branch accessing the pointer, but not ok for the other branch:
15516 * R1 = some_other_valid_ptr;
15519 * R2 = *(u32 *)(R1 + 0);
15521 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
15523 return src != prev && (!reg_type_mismatch_ok(src) ||
15524 !reg_type_mismatch_ok(prev));
15527 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
15528 bool allow_trust_missmatch)
15530 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
15532 if (*prev_type == NOT_INIT) {
15533 /* Saw a valid insn
15534 * dst_reg = *(u32 *)(src_reg + off)
15535 * save type to validate intersecting paths
15538 } else if (reg_type_mismatch(type, *prev_type)) {
15539 /* Abuser program is trying to use the same insn
15540 * dst_reg = *(u32*) (src_reg + off)
15541 * with different pointer types:
15542 * src_reg == ctx in one branch and
15543 * src_reg == stack|map in some other branch.
15546 if (allow_trust_missmatch &&
15547 base_type(type) == PTR_TO_BTF_ID &&
15548 base_type(*prev_type) == PTR_TO_BTF_ID) {
15550 * Have to support a use case when one path through
15551 * the program yields TRUSTED pointer while another
15552 * is UNTRUSTED. Fallback to UNTRUSTED to generate
15555 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
15557 verbose(env, "same insn cannot be used with different pointers\n");
15565 static int do_check(struct bpf_verifier_env *env)
15567 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
15568 struct bpf_verifier_state *state = env->cur_state;
15569 struct bpf_insn *insns = env->prog->insnsi;
15570 struct bpf_reg_state *regs;
15571 int insn_cnt = env->prog->len;
15572 bool do_print_state = false;
15573 int prev_insn_idx = -1;
15576 struct bpf_insn *insn;
15580 env->prev_insn_idx = prev_insn_idx;
15581 if (env->insn_idx >= insn_cnt) {
15582 verbose(env, "invalid insn idx %d insn_cnt %d\n",
15583 env->insn_idx, insn_cnt);
15587 insn = &insns[env->insn_idx];
15588 class = BPF_CLASS(insn->code);
15590 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
15592 "BPF program is too large. Processed %d insn\n",
15593 env->insn_processed);
15597 state->last_insn_idx = env->prev_insn_idx;
15599 if (is_prune_point(env, env->insn_idx)) {
15600 err = is_state_visited(env, env->insn_idx);
15604 /* found equivalent state, can prune the search */
15605 if (env->log.level & BPF_LOG_LEVEL) {
15606 if (do_print_state)
15607 verbose(env, "\nfrom %d to %d%s: safe\n",
15608 env->prev_insn_idx, env->insn_idx,
15609 env->cur_state->speculative ?
15610 " (speculative execution)" : "");
15612 verbose(env, "%d: safe\n", env->insn_idx);
15614 goto process_bpf_exit;
15618 if (is_jmp_point(env, env->insn_idx)) {
15619 err = push_jmp_history(env, state);
15624 if (signal_pending(current))
15627 if (need_resched())
15630 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
15631 verbose(env, "\nfrom %d to %d%s:",
15632 env->prev_insn_idx, env->insn_idx,
15633 env->cur_state->speculative ?
15634 " (speculative execution)" : "");
15635 print_verifier_state(env, state->frame[state->curframe], true);
15636 do_print_state = false;
15639 if (env->log.level & BPF_LOG_LEVEL) {
15640 const struct bpf_insn_cbs cbs = {
15641 .cb_call = disasm_kfunc_name,
15642 .cb_print = verbose,
15643 .private_data = env,
15646 if (verifier_state_scratched(env))
15647 print_insn_state(env, state->frame[state->curframe]);
15649 verbose_linfo(env, env->insn_idx, "; ");
15650 env->prev_log_len = env->log.len_used;
15651 verbose(env, "%d: ", env->insn_idx);
15652 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
15653 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
15654 env->prev_log_len = env->log.len_used;
15657 if (bpf_prog_is_offloaded(env->prog->aux)) {
15658 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
15659 env->prev_insn_idx);
15664 regs = cur_regs(env);
15665 sanitize_mark_insn_seen(env);
15666 prev_insn_idx = env->insn_idx;
15668 if (class == BPF_ALU || class == BPF_ALU64) {
15669 err = check_alu_op(env, insn);
15673 } else if (class == BPF_LDX) {
15674 enum bpf_reg_type src_reg_type;
15676 /* check for reserved fields is already done */
15678 /* check src operand */
15679 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15683 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15687 src_reg_type = regs[insn->src_reg].type;
15689 /* check that memory (src_reg + off) is readable,
15690 * the state of dst_reg will be updated by this func
15692 err = check_mem_access(env, env->insn_idx, insn->src_reg,
15693 insn->off, BPF_SIZE(insn->code),
15694 BPF_READ, insn->dst_reg, false);
15698 err = save_aux_ptr_type(env, src_reg_type, true);
15701 } else if (class == BPF_STX) {
15702 enum bpf_reg_type dst_reg_type;
15704 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
15705 err = check_atomic(env, env->insn_idx, insn);
15712 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
15713 verbose(env, "BPF_STX uses reserved fields\n");
15717 /* check src1 operand */
15718 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15721 /* check src2 operand */
15722 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15726 dst_reg_type = regs[insn->dst_reg].type;
15728 /* check that memory (dst_reg + off) is writeable */
15729 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15730 insn->off, BPF_SIZE(insn->code),
15731 BPF_WRITE, insn->src_reg, false);
15735 err = save_aux_ptr_type(env, dst_reg_type, false);
15738 } else if (class == BPF_ST) {
15739 enum bpf_reg_type dst_reg_type;
15741 if (BPF_MODE(insn->code) != BPF_MEM ||
15742 insn->src_reg != BPF_REG_0) {
15743 verbose(env, "BPF_ST uses reserved fields\n");
15746 /* check src operand */
15747 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15751 dst_reg_type = regs[insn->dst_reg].type;
15753 /* check that memory (dst_reg + off) is writeable */
15754 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15755 insn->off, BPF_SIZE(insn->code),
15756 BPF_WRITE, -1, false);
15760 err = save_aux_ptr_type(env, dst_reg_type, false);
15763 } else if (class == BPF_JMP || class == BPF_JMP32) {
15764 u8 opcode = BPF_OP(insn->code);
15766 env->jmps_processed++;
15767 if (opcode == BPF_CALL) {
15768 if (BPF_SRC(insn->code) != BPF_K ||
15769 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
15770 && insn->off != 0) ||
15771 (insn->src_reg != BPF_REG_0 &&
15772 insn->src_reg != BPF_PSEUDO_CALL &&
15773 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
15774 insn->dst_reg != BPF_REG_0 ||
15775 class == BPF_JMP32) {
15776 verbose(env, "BPF_CALL uses reserved fields\n");
15780 if (env->cur_state->active_lock.ptr) {
15781 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
15782 (insn->src_reg == BPF_PSEUDO_CALL) ||
15783 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
15784 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
15785 verbose(env, "function calls are not allowed while holding a lock\n");
15789 if (insn->src_reg == BPF_PSEUDO_CALL)
15790 err = check_func_call(env, insn, &env->insn_idx);
15791 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
15792 err = check_kfunc_call(env, insn, &env->insn_idx);
15794 err = check_helper_call(env, insn, &env->insn_idx);
15798 mark_reg_scratched(env, BPF_REG_0);
15799 } else if (opcode == BPF_JA) {
15800 if (BPF_SRC(insn->code) != BPF_K ||
15802 insn->src_reg != BPF_REG_0 ||
15803 insn->dst_reg != BPF_REG_0 ||
15804 class == BPF_JMP32) {
15805 verbose(env, "BPF_JA uses reserved fields\n");
15809 env->insn_idx += insn->off + 1;
15812 } else if (opcode == BPF_EXIT) {
15813 if (BPF_SRC(insn->code) != BPF_K ||
15815 insn->src_reg != BPF_REG_0 ||
15816 insn->dst_reg != BPF_REG_0 ||
15817 class == BPF_JMP32) {
15818 verbose(env, "BPF_EXIT uses reserved fields\n");
15822 if (env->cur_state->active_lock.ptr &&
15823 !in_rbtree_lock_required_cb(env)) {
15824 verbose(env, "bpf_spin_unlock is missing\n");
15828 if (env->cur_state->active_rcu_lock) {
15829 verbose(env, "bpf_rcu_read_unlock is missing\n");
15833 /* We must do check_reference_leak here before
15834 * prepare_func_exit to handle the case when
15835 * state->curframe > 0, it may be a callback
15836 * function, for which reference_state must
15837 * match caller reference state when it exits.
15839 err = check_reference_leak(env);
15843 if (state->curframe) {
15844 /* exit from nested function */
15845 err = prepare_func_exit(env, &env->insn_idx);
15848 do_print_state = true;
15852 err = check_return_code(env);
15856 mark_verifier_state_scratched(env);
15857 update_branch_counts(env, env->cur_state);
15858 err = pop_stack(env, &prev_insn_idx,
15859 &env->insn_idx, pop_log);
15861 if (err != -ENOENT)
15865 do_print_state = true;
15869 err = check_cond_jmp_op(env, insn, &env->insn_idx);
15873 } else if (class == BPF_LD) {
15874 u8 mode = BPF_MODE(insn->code);
15876 if (mode == BPF_ABS || mode == BPF_IND) {
15877 err = check_ld_abs(env, insn);
15881 } else if (mode == BPF_IMM) {
15882 err = check_ld_imm(env, insn);
15887 sanitize_mark_insn_seen(env);
15889 verbose(env, "invalid BPF_LD mode\n");
15893 verbose(env, "unknown insn class %d\n", class);
15903 static int find_btf_percpu_datasec(struct btf *btf)
15905 const struct btf_type *t;
15910 * Both vmlinux and module each have their own ".data..percpu"
15911 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
15912 * types to look at only module's own BTF types.
15914 n = btf_nr_types(btf);
15915 if (btf_is_module(btf))
15916 i = btf_nr_types(btf_vmlinux);
15920 for(; i < n; i++) {
15921 t = btf_type_by_id(btf, i);
15922 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
15925 tname = btf_name_by_offset(btf, t->name_off);
15926 if (!strcmp(tname, ".data..percpu"))
15933 /* replace pseudo btf_id with kernel symbol address */
15934 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
15935 struct bpf_insn *insn,
15936 struct bpf_insn_aux_data *aux)
15938 const struct btf_var_secinfo *vsi;
15939 const struct btf_type *datasec;
15940 struct btf_mod_pair *btf_mod;
15941 const struct btf_type *t;
15942 const char *sym_name;
15943 bool percpu = false;
15944 u32 type, id = insn->imm;
15948 int i, btf_fd, err;
15950 btf_fd = insn[1].imm;
15952 btf = btf_get_by_fd(btf_fd);
15954 verbose(env, "invalid module BTF object FD specified.\n");
15958 if (!btf_vmlinux) {
15959 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
15966 t = btf_type_by_id(btf, id);
15968 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
15973 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
15974 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
15979 sym_name = btf_name_by_offset(btf, t->name_off);
15980 addr = kallsyms_lookup_name(sym_name);
15982 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
15987 insn[0].imm = (u32)addr;
15988 insn[1].imm = addr >> 32;
15990 if (btf_type_is_func(t)) {
15991 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
15992 aux->btf_var.mem_size = 0;
15996 datasec_id = find_btf_percpu_datasec(btf);
15997 if (datasec_id > 0) {
15998 datasec = btf_type_by_id(btf, datasec_id);
15999 for_each_vsi(i, datasec, vsi) {
16000 if (vsi->type == id) {
16008 t = btf_type_skip_modifiers(btf, type, NULL);
16010 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16011 aux->btf_var.btf = btf;
16012 aux->btf_var.btf_id = type;
16013 } else if (!btf_type_is_struct(t)) {
16014 const struct btf_type *ret;
16018 /* resolve the type size of ksym. */
16019 ret = btf_resolve_size(btf, t, &tsize);
16021 tname = btf_name_by_offset(btf, t->name_off);
16022 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16023 tname, PTR_ERR(ret));
16027 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16028 aux->btf_var.mem_size = tsize;
16030 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16031 aux->btf_var.btf = btf;
16032 aux->btf_var.btf_id = type;
16035 /* check whether we recorded this BTF (and maybe module) already */
16036 for (i = 0; i < env->used_btf_cnt; i++) {
16037 if (env->used_btfs[i].btf == btf) {
16043 if (env->used_btf_cnt >= MAX_USED_BTFS) {
16048 btf_mod = &env->used_btfs[env->used_btf_cnt];
16049 btf_mod->btf = btf;
16050 btf_mod->module = NULL;
16052 /* if we reference variables from kernel module, bump its refcount */
16053 if (btf_is_module(btf)) {
16054 btf_mod->module = btf_try_get_module(btf);
16055 if (!btf_mod->module) {
16061 env->used_btf_cnt++;
16069 static bool is_tracing_prog_type(enum bpf_prog_type type)
16072 case BPF_PROG_TYPE_KPROBE:
16073 case BPF_PROG_TYPE_TRACEPOINT:
16074 case BPF_PROG_TYPE_PERF_EVENT:
16075 case BPF_PROG_TYPE_RAW_TRACEPOINT:
16076 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16083 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16084 struct bpf_map *map,
16085 struct bpf_prog *prog)
16088 enum bpf_prog_type prog_type = resolve_prog_type(prog);
16090 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16091 btf_record_has_field(map->record, BPF_RB_ROOT)) {
16092 if (is_tracing_prog_type(prog_type)) {
16093 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16098 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16099 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16100 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16104 if (is_tracing_prog_type(prog_type)) {
16105 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16109 if (prog->aux->sleepable) {
16110 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16115 if (btf_record_has_field(map->record, BPF_TIMER)) {
16116 if (is_tracing_prog_type(prog_type)) {
16117 verbose(env, "tracing progs cannot use bpf_timer yet\n");
16122 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16123 !bpf_offload_prog_map_match(prog, map)) {
16124 verbose(env, "offload device mismatch between prog and map\n");
16128 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16129 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16133 if (prog->aux->sleepable)
16134 switch (map->map_type) {
16135 case BPF_MAP_TYPE_HASH:
16136 case BPF_MAP_TYPE_LRU_HASH:
16137 case BPF_MAP_TYPE_ARRAY:
16138 case BPF_MAP_TYPE_PERCPU_HASH:
16139 case BPF_MAP_TYPE_PERCPU_ARRAY:
16140 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16141 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16142 case BPF_MAP_TYPE_HASH_OF_MAPS:
16143 case BPF_MAP_TYPE_RINGBUF:
16144 case BPF_MAP_TYPE_USER_RINGBUF:
16145 case BPF_MAP_TYPE_INODE_STORAGE:
16146 case BPF_MAP_TYPE_SK_STORAGE:
16147 case BPF_MAP_TYPE_TASK_STORAGE:
16148 case BPF_MAP_TYPE_CGRP_STORAGE:
16152 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16159 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16161 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16162 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16165 /* find and rewrite pseudo imm in ld_imm64 instructions:
16167 * 1. if it accesses map FD, replace it with actual map pointer.
16168 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16170 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
16172 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
16174 struct bpf_insn *insn = env->prog->insnsi;
16175 int insn_cnt = env->prog->len;
16178 err = bpf_prog_calc_tag(env->prog);
16182 for (i = 0; i < insn_cnt; i++, insn++) {
16183 if (BPF_CLASS(insn->code) == BPF_LDX &&
16184 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
16185 verbose(env, "BPF_LDX uses reserved fields\n");
16189 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
16190 struct bpf_insn_aux_data *aux;
16191 struct bpf_map *map;
16196 if (i == insn_cnt - 1 || insn[1].code != 0 ||
16197 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16198 insn[1].off != 0) {
16199 verbose(env, "invalid bpf_ld_imm64 insn\n");
16203 if (insn[0].src_reg == 0)
16204 /* valid generic load 64-bit imm */
16207 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16208 aux = &env->insn_aux_data[i];
16209 err = check_pseudo_btf_id(env, insn, aux);
16215 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16216 aux = &env->insn_aux_data[i];
16217 aux->ptr_type = PTR_TO_FUNC;
16221 /* In final convert_pseudo_ld_imm64() step, this is
16222 * converted into regular 64-bit imm load insn.
16224 switch (insn[0].src_reg) {
16225 case BPF_PSEUDO_MAP_VALUE:
16226 case BPF_PSEUDO_MAP_IDX_VALUE:
16228 case BPF_PSEUDO_MAP_FD:
16229 case BPF_PSEUDO_MAP_IDX:
16230 if (insn[1].imm == 0)
16234 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
16238 switch (insn[0].src_reg) {
16239 case BPF_PSEUDO_MAP_IDX_VALUE:
16240 case BPF_PSEUDO_MAP_IDX:
16241 if (bpfptr_is_null(env->fd_array)) {
16242 verbose(env, "fd_idx without fd_array is invalid\n");
16245 if (copy_from_bpfptr_offset(&fd, env->fd_array,
16246 insn[0].imm * sizeof(fd),
16256 map = __bpf_map_get(f);
16258 verbose(env, "fd %d is not pointing to valid bpf_map\n",
16260 return PTR_ERR(map);
16263 err = check_map_prog_compatibility(env, map, env->prog);
16269 aux = &env->insn_aux_data[i];
16270 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
16271 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
16272 addr = (unsigned long)map;
16274 u32 off = insn[1].imm;
16276 if (off >= BPF_MAX_VAR_OFF) {
16277 verbose(env, "direct value offset of %u is not allowed\n", off);
16282 if (!map->ops->map_direct_value_addr) {
16283 verbose(env, "no direct value access support for this map type\n");
16288 err = map->ops->map_direct_value_addr(map, &addr, off);
16290 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
16291 map->value_size, off);
16296 aux->map_off = off;
16300 insn[0].imm = (u32)addr;
16301 insn[1].imm = addr >> 32;
16303 /* check whether we recorded this map already */
16304 for (j = 0; j < env->used_map_cnt; j++) {
16305 if (env->used_maps[j] == map) {
16306 aux->map_index = j;
16312 if (env->used_map_cnt >= MAX_USED_MAPS) {
16317 /* hold the map. If the program is rejected by verifier,
16318 * the map will be released by release_maps() or it
16319 * will be used by the valid program until it's unloaded
16320 * and all maps are released in free_used_maps()
16324 aux->map_index = env->used_map_cnt;
16325 env->used_maps[env->used_map_cnt++] = map;
16327 if (bpf_map_is_cgroup_storage(map) &&
16328 bpf_cgroup_storage_assign(env->prog->aux, map)) {
16329 verbose(env, "only one cgroup storage of each type is allowed\n");
16341 /* Basic sanity check before we invest more work here. */
16342 if (!bpf_opcode_in_insntable(insn->code)) {
16343 verbose(env, "unknown opcode %02x\n", insn->code);
16348 /* now all pseudo BPF_LD_IMM64 instructions load valid
16349 * 'struct bpf_map *' into a register instead of user map_fd.
16350 * These pointers will be used later by verifier to validate map access.
16355 /* drop refcnt of maps used by the rejected program */
16356 static void release_maps(struct bpf_verifier_env *env)
16358 __bpf_free_used_maps(env->prog->aux, env->used_maps,
16359 env->used_map_cnt);
16362 /* drop refcnt of maps used by the rejected program */
16363 static void release_btfs(struct bpf_verifier_env *env)
16365 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
16366 env->used_btf_cnt);
16369 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
16370 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
16372 struct bpf_insn *insn = env->prog->insnsi;
16373 int insn_cnt = env->prog->len;
16376 for (i = 0; i < insn_cnt; i++, insn++) {
16377 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
16379 if (insn->src_reg == BPF_PSEUDO_FUNC)
16385 /* single env->prog->insni[off] instruction was replaced with the range
16386 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
16387 * [0, off) and [off, end) to new locations, so the patched range stays zero
16389 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
16390 struct bpf_insn_aux_data *new_data,
16391 struct bpf_prog *new_prog, u32 off, u32 cnt)
16393 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
16394 struct bpf_insn *insn = new_prog->insnsi;
16395 u32 old_seen = old_data[off].seen;
16399 /* aux info at OFF always needs adjustment, no matter fast path
16400 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
16401 * original insn at old prog.
16403 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
16407 prog_len = new_prog->len;
16409 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
16410 memcpy(new_data + off + cnt - 1, old_data + off,
16411 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
16412 for (i = off; i < off + cnt - 1; i++) {
16413 /* Expand insni[off]'s seen count to the patched range. */
16414 new_data[i].seen = old_seen;
16415 new_data[i].zext_dst = insn_has_def32(env, insn + i);
16417 env->insn_aux_data = new_data;
16421 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
16427 /* NOTE: fake 'exit' subprog should be updated as well. */
16428 for (i = 0; i <= env->subprog_cnt; i++) {
16429 if (env->subprog_info[i].start <= off)
16431 env->subprog_info[i].start += len - 1;
16435 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
16437 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
16438 int i, sz = prog->aux->size_poke_tab;
16439 struct bpf_jit_poke_descriptor *desc;
16441 for (i = 0; i < sz; i++) {
16443 if (desc->insn_idx <= off)
16445 desc->insn_idx += len - 1;
16449 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
16450 const struct bpf_insn *patch, u32 len)
16452 struct bpf_prog *new_prog;
16453 struct bpf_insn_aux_data *new_data = NULL;
16456 new_data = vzalloc(array_size(env->prog->len + len - 1,
16457 sizeof(struct bpf_insn_aux_data)));
16462 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
16463 if (IS_ERR(new_prog)) {
16464 if (PTR_ERR(new_prog) == -ERANGE)
16466 "insn %d cannot be patched due to 16-bit range\n",
16467 env->insn_aux_data[off].orig_idx);
16471 adjust_insn_aux_data(env, new_data, new_prog, off, len);
16472 adjust_subprog_starts(env, off, len);
16473 adjust_poke_descs(new_prog, off, len);
16477 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
16482 /* find first prog starting at or after off (first to remove) */
16483 for (i = 0; i < env->subprog_cnt; i++)
16484 if (env->subprog_info[i].start >= off)
16486 /* find first prog starting at or after off + cnt (first to stay) */
16487 for (j = i; j < env->subprog_cnt; j++)
16488 if (env->subprog_info[j].start >= off + cnt)
16490 /* if j doesn't start exactly at off + cnt, we are just removing
16491 * the front of previous prog
16493 if (env->subprog_info[j].start != off + cnt)
16497 struct bpf_prog_aux *aux = env->prog->aux;
16500 /* move fake 'exit' subprog as well */
16501 move = env->subprog_cnt + 1 - j;
16503 memmove(env->subprog_info + i,
16504 env->subprog_info + j,
16505 sizeof(*env->subprog_info) * move);
16506 env->subprog_cnt -= j - i;
16508 /* remove func_info */
16509 if (aux->func_info) {
16510 move = aux->func_info_cnt - j;
16512 memmove(aux->func_info + i,
16513 aux->func_info + j,
16514 sizeof(*aux->func_info) * move);
16515 aux->func_info_cnt -= j - i;
16516 /* func_info->insn_off is set after all code rewrites,
16517 * in adjust_btf_func() - no need to adjust
16521 /* convert i from "first prog to remove" to "first to adjust" */
16522 if (env->subprog_info[i].start == off)
16526 /* update fake 'exit' subprog as well */
16527 for (; i <= env->subprog_cnt; i++)
16528 env->subprog_info[i].start -= cnt;
16533 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
16536 struct bpf_prog *prog = env->prog;
16537 u32 i, l_off, l_cnt, nr_linfo;
16538 struct bpf_line_info *linfo;
16540 nr_linfo = prog->aux->nr_linfo;
16544 linfo = prog->aux->linfo;
16546 /* find first line info to remove, count lines to be removed */
16547 for (i = 0; i < nr_linfo; i++)
16548 if (linfo[i].insn_off >= off)
16553 for (; i < nr_linfo; i++)
16554 if (linfo[i].insn_off < off + cnt)
16559 /* First live insn doesn't match first live linfo, it needs to "inherit"
16560 * last removed linfo. prog is already modified, so prog->len == off
16561 * means no live instructions after (tail of the program was removed).
16563 if (prog->len != off && l_cnt &&
16564 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
16566 linfo[--i].insn_off = off + cnt;
16569 /* remove the line info which refer to the removed instructions */
16571 memmove(linfo + l_off, linfo + i,
16572 sizeof(*linfo) * (nr_linfo - i));
16574 prog->aux->nr_linfo -= l_cnt;
16575 nr_linfo = prog->aux->nr_linfo;
16578 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
16579 for (i = l_off; i < nr_linfo; i++)
16580 linfo[i].insn_off -= cnt;
16582 /* fix up all subprogs (incl. 'exit') which start >= off */
16583 for (i = 0; i <= env->subprog_cnt; i++)
16584 if (env->subprog_info[i].linfo_idx > l_off) {
16585 /* program may have started in the removed region but
16586 * may not be fully removed
16588 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
16589 env->subprog_info[i].linfo_idx -= l_cnt;
16591 env->subprog_info[i].linfo_idx = l_off;
16597 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
16599 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16600 unsigned int orig_prog_len = env->prog->len;
16603 if (bpf_prog_is_offloaded(env->prog->aux))
16604 bpf_prog_offload_remove_insns(env, off, cnt);
16606 err = bpf_remove_insns(env->prog, off, cnt);
16610 err = adjust_subprog_starts_after_remove(env, off, cnt);
16614 err = bpf_adj_linfo_after_remove(env, off, cnt);
16618 memmove(aux_data + off, aux_data + off + cnt,
16619 sizeof(*aux_data) * (orig_prog_len - off - cnt));
16624 /* The verifier does more data flow analysis than llvm and will not
16625 * explore branches that are dead at run time. Malicious programs can
16626 * have dead code too. Therefore replace all dead at-run-time code
16629 * Just nops are not optimal, e.g. if they would sit at the end of the
16630 * program and through another bug we would manage to jump there, then
16631 * we'd execute beyond program memory otherwise. Returning exception
16632 * code also wouldn't work since we can have subprogs where the dead
16633 * code could be located.
16635 static void sanitize_dead_code(struct bpf_verifier_env *env)
16637 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16638 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
16639 struct bpf_insn *insn = env->prog->insnsi;
16640 const int insn_cnt = env->prog->len;
16643 for (i = 0; i < insn_cnt; i++) {
16644 if (aux_data[i].seen)
16646 memcpy(insn + i, &trap, sizeof(trap));
16647 aux_data[i].zext_dst = false;
16651 static bool insn_is_cond_jump(u8 code)
16655 if (BPF_CLASS(code) == BPF_JMP32)
16658 if (BPF_CLASS(code) != BPF_JMP)
16662 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
16665 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
16667 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16668 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
16669 struct bpf_insn *insn = env->prog->insnsi;
16670 const int insn_cnt = env->prog->len;
16673 for (i = 0; i < insn_cnt; i++, insn++) {
16674 if (!insn_is_cond_jump(insn->code))
16677 if (!aux_data[i + 1].seen)
16678 ja.off = insn->off;
16679 else if (!aux_data[i + 1 + insn->off].seen)
16684 if (bpf_prog_is_offloaded(env->prog->aux))
16685 bpf_prog_offload_replace_insn(env, i, &ja);
16687 memcpy(insn, &ja, sizeof(ja));
16691 static int opt_remove_dead_code(struct bpf_verifier_env *env)
16693 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16694 int insn_cnt = env->prog->len;
16697 for (i = 0; i < insn_cnt; i++) {
16701 while (i + j < insn_cnt && !aux_data[i + j].seen)
16706 err = verifier_remove_insns(env, i, j);
16709 insn_cnt = env->prog->len;
16715 static int opt_remove_nops(struct bpf_verifier_env *env)
16717 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
16718 struct bpf_insn *insn = env->prog->insnsi;
16719 int insn_cnt = env->prog->len;
16722 for (i = 0; i < insn_cnt; i++) {
16723 if (memcmp(&insn[i], &ja, sizeof(ja)))
16726 err = verifier_remove_insns(env, i, 1);
16736 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
16737 const union bpf_attr *attr)
16739 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
16740 struct bpf_insn_aux_data *aux = env->insn_aux_data;
16741 int i, patch_len, delta = 0, len = env->prog->len;
16742 struct bpf_insn *insns = env->prog->insnsi;
16743 struct bpf_prog *new_prog;
16746 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
16747 zext_patch[1] = BPF_ZEXT_REG(0);
16748 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
16749 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
16750 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
16751 for (i = 0; i < len; i++) {
16752 int adj_idx = i + delta;
16753 struct bpf_insn insn;
16756 insn = insns[adj_idx];
16757 load_reg = insn_def_regno(&insn);
16758 if (!aux[adj_idx].zext_dst) {
16766 class = BPF_CLASS(code);
16767 if (load_reg == -1)
16770 /* NOTE: arg "reg" (the fourth one) is only used for
16771 * BPF_STX + SRC_OP, so it is safe to pass NULL
16774 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
16775 if (class == BPF_LD &&
16776 BPF_MODE(code) == BPF_IMM)
16781 /* ctx load could be transformed into wider load. */
16782 if (class == BPF_LDX &&
16783 aux[adj_idx].ptr_type == PTR_TO_CTX)
16786 imm_rnd = get_random_u32();
16787 rnd_hi32_patch[0] = insn;
16788 rnd_hi32_patch[1].imm = imm_rnd;
16789 rnd_hi32_patch[3].dst_reg = load_reg;
16790 patch = rnd_hi32_patch;
16792 goto apply_patch_buffer;
16795 /* Add in an zero-extend instruction if a) the JIT has requested
16796 * it or b) it's a CMPXCHG.
16798 * The latter is because: BPF_CMPXCHG always loads a value into
16799 * R0, therefore always zero-extends. However some archs'
16800 * equivalent instruction only does this load when the
16801 * comparison is successful. This detail of CMPXCHG is
16802 * orthogonal to the general zero-extension behaviour of the
16803 * CPU, so it's treated independently of bpf_jit_needs_zext.
16805 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
16808 /* Zero-extension is done by the caller. */
16809 if (bpf_pseudo_kfunc_call(&insn))
16812 if (WARN_ON(load_reg == -1)) {
16813 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
16817 zext_patch[0] = insn;
16818 zext_patch[1].dst_reg = load_reg;
16819 zext_patch[1].src_reg = load_reg;
16820 patch = zext_patch;
16822 apply_patch_buffer:
16823 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
16826 env->prog = new_prog;
16827 insns = new_prog->insnsi;
16828 aux = env->insn_aux_data;
16829 delta += patch_len - 1;
16835 /* convert load instructions that access fields of a context type into a
16836 * sequence of instructions that access fields of the underlying structure:
16837 * struct __sk_buff -> struct sk_buff
16838 * struct bpf_sock_ops -> struct sock
16840 static int convert_ctx_accesses(struct bpf_verifier_env *env)
16842 const struct bpf_verifier_ops *ops = env->ops;
16843 int i, cnt, size, ctx_field_size, delta = 0;
16844 const int insn_cnt = env->prog->len;
16845 struct bpf_insn insn_buf[16], *insn;
16846 u32 target_size, size_default, off;
16847 struct bpf_prog *new_prog;
16848 enum bpf_access_type type;
16849 bool is_narrower_load;
16851 if (ops->gen_prologue || env->seen_direct_write) {
16852 if (!ops->gen_prologue) {
16853 verbose(env, "bpf verifier is misconfigured\n");
16856 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
16858 if (cnt >= ARRAY_SIZE(insn_buf)) {
16859 verbose(env, "bpf verifier is misconfigured\n");
16862 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
16866 env->prog = new_prog;
16871 if (bpf_prog_is_offloaded(env->prog->aux))
16874 insn = env->prog->insnsi + delta;
16876 for (i = 0; i < insn_cnt; i++, insn++) {
16877 bpf_convert_ctx_access_t convert_ctx_access;
16879 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
16880 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
16881 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
16882 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
16884 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
16885 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
16886 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
16887 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
16888 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
16889 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
16890 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
16891 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
16897 if (type == BPF_WRITE &&
16898 env->insn_aux_data[i + delta].sanitize_stack_spill) {
16899 struct bpf_insn patch[] = {
16904 cnt = ARRAY_SIZE(patch);
16905 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
16910 env->prog = new_prog;
16911 insn = new_prog->insnsi + i + delta;
16915 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
16917 if (!ops->convert_ctx_access)
16919 convert_ctx_access = ops->convert_ctx_access;
16921 case PTR_TO_SOCKET:
16922 case PTR_TO_SOCK_COMMON:
16923 convert_ctx_access = bpf_sock_convert_ctx_access;
16925 case PTR_TO_TCP_SOCK:
16926 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
16928 case PTR_TO_XDP_SOCK:
16929 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
16931 case PTR_TO_BTF_ID:
16932 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
16933 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
16934 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
16935 * be said once it is marked PTR_UNTRUSTED, hence we must handle
16936 * any faults for loads into such types. BPF_WRITE is disallowed
16939 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
16940 if (type == BPF_READ) {
16941 insn->code = BPF_LDX | BPF_PROBE_MEM |
16942 BPF_SIZE((insn)->code);
16943 env->prog->aux->num_exentries++;
16950 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
16951 size = BPF_LDST_BYTES(insn);
16953 /* If the read access is a narrower load of the field,
16954 * convert to a 4/8-byte load, to minimum program type specific
16955 * convert_ctx_access changes. If conversion is successful,
16956 * we will apply proper mask to the result.
16958 is_narrower_load = size < ctx_field_size;
16959 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
16961 if (is_narrower_load) {
16964 if (type == BPF_WRITE) {
16965 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
16970 if (ctx_field_size == 4)
16972 else if (ctx_field_size == 8)
16973 size_code = BPF_DW;
16975 insn->off = off & ~(size_default - 1);
16976 insn->code = BPF_LDX | BPF_MEM | size_code;
16980 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
16982 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
16983 (ctx_field_size && !target_size)) {
16984 verbose(env, "bpf verifier is misconfigured\n");
16988 if (is_narrower_load && size < target_size) {
16989 u8 shift = bpf_ctx_narrow_access_offset(
16990 off, size, size_default) * 8;
16991 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
16992 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
16995 if (ctx_field_size <= 4) {
16997 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17000 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17001 (1 << size * 8) - 1);
17004 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17007 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
17008 (1ULL << size * 8) - 1);
17012 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17018 /* keep walking new program and skip insns we just inserted */
17019 env->prog = new_prog;
17020 insn = new_prog->insnsi + i + delta;
17026 static int jit_subprogs(struct bpf_verifier_env *env)
17028 struct bpf_prog *prog = env->prog, **func, *tmp;
17029 int i, j, subprog_start, subprog_end = 0, len, subprog;
17030 struct bpf_map *map_ptr;
17031 struct bpf_insn *insn;
17032 void *old_bpf_func;
17033 int err, num_exentries;
17035 if (env->subprog_cnt <= 1)
17038 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17039 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17042 /* Upon error here we cannot fall back to interpreter but
17043 * need a hard reject of the program. Thus -EFAULT is
17044 * propagated in any case.
17046 subprog = find_subprog(env, i + insn->imm + 1);
17048 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17049 i + insn->imm + 1);
17052 /* temporarily remember subprog id inside insn instead of
17053 * aux_data, since next loop will split up all insns into funcs
17055 insn->off = subprog;
17056 /* remember original imm in case JIT fails and fallback
17057 * to interpreter will be needed
17059 env->insn_aux_data[i].call_imm = insn->imm;
17060 /* point imm to __bpf_call_base+1 from JITs point of view */
17062 if (bpf_pseudo_func(insn))
17063 /* jit (e.g. x86_64) may emit fewer instructions
17064 * if it learns a u32 imm is the same as a u64 imm.
17065 * Force a non zero here.
17070 err = bpf_prog_alloc_jited_linfo(prog);
17072 goto out_undo_insn;
17075 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17077 goto out_undo_insn;
17079 for (i = 0; i < env->subprog_cnt; i++) {
17080 subprog_start = subprog_end;
17081 subprog_end = env->subprog_info[i + 1].start;
17083 len = subprog_end - subprog_start;
17084 /* bpf_prog_run() doesn't call subprogs directly,
17085 * hence main prog stats include the runtime of subprogs.
17086 * subprogs don't have IDs and not reachable via prog_get_next_id
17087 * func[i]->stats will never be accessed and stays NULL
17089 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17092 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17093 len * sizeof(struct bpf_insn));
17094 func[i]->type = prog->type;
17095 func[i]->len = len;
17096 if (bpf_prog_calc_tag(func[i]))
17098 func[i]->is_func = 1;
17099 func[i]->aux->func_idx = i;
17100 /* Below members will be freed only at prog->aux */
17101 func[i]->aux->btf = prog->aux->btf;
17102 func[i]->aux->func_info = prog->aux->func_info;
17103 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17104 func[i]->aux->poke_tab = prog->aux->poke_tab;
17105 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17107 for (j = 0; j < prog->aux->size_poke_tab; j++) {
17108 struct bpf_jit_poke_descriptor *poke;
17110 poke = &prog->aux->poke_tab[j];
17111 if (poke->insn_idx < subprog_end &&
17112 poke->insn_idx >= subprog_start)
17113 poke->aux = func[i]->aux;
17116 func[i]->aux->name[0] = 'F';
17117 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17118 func[i]->jit_requested = 1;
17119 func[i]->blinding_requested = prog->blinding_requested;
17120 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17121 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17122 func[i]->aux->linfo = prog->aux->linfo;
17123 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17124 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17125 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17127 insn = func[i]->insnsi;
17128 for (j = 0; j < func[i]->len; j++, insn++) {
17129 if (BPF_CLASS(insn->code) == BPF_LDX &&
17130 BPF_MODE(insn->code) == BPF_PROBE_MEM)
17133 func[i]->aux->num_exentries = num_exentries;
17134 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17135 func[i] = bpf_int_jit_compile(func[i]);
17136 if (!func[i]->jited) {
17143 /* at this point all bpf functions were successfully JITed
17144 * now populate all bpf_calls with correct addresses and
17145 * run last pass of JIT
17147 for (i = 0; i < env->subprog_cnt; i++) {
17148 insn = func[i]->insnsi;
17149 for (j = 0; j < func[i]->len; j++, insn++) {
17150 if (bpf_pseudo_func(insn)) {
17151 subprog = insn->off;
17152 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17153 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17156 if (!bpf_pseudo_call(insn))
17158 subprog = insn->off;
17159 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
17162 /* we use the aux data to keep a list of the start addresses
17163 * of the JITed images for each function in the program
17165 * for some architectures, such as powerpc64, the imm field
17166 * might not be large enough to hold the offset of the start
17167 * address of the callee's JITed image from __bpf_call_base
17169 * in such cases, we can lookup the start address of a callee
17170 * by using its subprog id, available from the off field of
17171 * the call instruction, as an index for this list
17173 func[i]->aux->func = func;
17174 func[i]->aux->func_cnt = env->subprog_cnt;
17176 for (i = 0; i < env->subprog_cnt; i++) {
17177 old_bpf_func = func[i]->bpf_func;
17178 tmp = bpf_int_jit_compile(func[i]);
17179 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17180 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
17187 /* finally lock prog and jit images for all functions and
17188 * populate kallsysm
17190 for (i = 0; i < env->subprog_cnt; i++) {
17191 bpf_prog_lock_ro(func[i]);
17192 bpf_prog_kallsyms_add(func[i]);
17195 /* Last step: make now unused interpreter insns from main
17196 * prog consistent for later dump requests, so they can
17197 * later look the same as if they were interpreted only.
17199 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17200 if (bpf_pseudo_func(insn)) {
17201 insn[0].imm = env->insn_aux_data[i].call_imm;
17202 insn[1].imm = insn->off;
17206 if (!bpf_pseudo_call(insn))
17208 insn->off = env->insn_aux_data[i].call_imm;
17209 subprog = find_subprog(env, i + insn->off + 1);
17210 insn->imm = subprog;
17214 prog->bpf_func = func[0]->bpf_func;
17215 prog->jited_len = func[0]->jited_len;
17216 prog->aux->func = func;
17217 prog->aux->func_cnt = env->subprog_cnt;
17218 bpf_prog_jit_attempt_done(prog);
17221 /* We failed JIT'ing, so at this point we need to unregister poke
17222 * descriptors from subprogs, so that kernel is not attempting to
17223 * patch it anymore as we're freeing the subprog JIT memory.
17225 for (i = 0; i < prog->aux->size_poke_tab; i++) {
17226 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17227 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17229 /* At this point we're guaranteed that poke descriptors are not
17230 * live anymore. We can just unlink its descriptor table as it's
17231 * released with the main prog.
17233 for (i = 0; i < env->subprog_cnt; i++) {
17236 func[i]->aux->poke_tab = NULL;
17237 bpf_jit_free(func[i]);
17241 /* cleanup main prog to be interpreted */
17242 prog->jit_requested = 0;
17243 prog->blinding_requested = 0;
17244 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17245 if (!bpf_pseudo_call(insn))
17248 insn->imm = env->insn_aux_data[i].call_imm;
17250 bpf_prog_jit_attempt_done(prog);
17254 static int fixup_call_args(struct bpf_verifier_env *env)
17256 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17257 struct bpf_prog *prog = env->prog;
17258 struct bpf_insn *insn = prog->insnsi;
17259 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
17264 if (env->prog->jit_requested &&
17265 !bpf_prog_is_offloaded(env->prog->aux)) {
17266 err = jit_subprogs(env);
17269 if (err == -EFAULT)
17272 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17273 if (has_kfunc_call) {
17274 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
17277 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
17278 /* When JIT fails the progs with bpf2bpf calls and tail_calls
17279 * have to be rejected, since interpreter doesn't support them yet.
17281 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
17284 for (i = 0; i < prog->len; i++, insn++) {
17285 if (bpf_pseudo_func(insn)) {
17286 /* When JIT fails the progs with callback calls
17287 * have to be rejected, since interpreter doesn't support them yet.
17289 verbose(env, "callbacks are not allowed in non-JITed programs\n");
17293 if (!bpf_pseudo_call(insn))
17295 depth = get_callee_stack_depth(env, insn, i);
17298 bpf_patch_call_args(insn, depth);
17305 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
17306 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
17308 const struct bpf_kfunc_desc *desc;
17312 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
17318 if (bpf_dev_bound_kfunc_id(insn->imm)) {
17319 xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm);
17321 insn->imm = BPF_CALL_IMM(xdp_kfunc);
17325 /* fallback to default kfunc when not supported by netdev */
17328 /* insn->imm has the btf func_id. Replace it with
17329 * an address (relative to __bpf_call_base).
17331 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
17333 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
17338 insn->imm = desc->imm;
17341 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
17342 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17343 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17344 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
17346 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
17347 insn_buf[1] = addr[0];
17348 insn_buf[2] = addr[1];
17349 insn_buf[3] = *insn;
17351 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
17352 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17353 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17355 insn_buf[0] = addr[0];
17356 insn_buf[1] = addr[1];
17357 insn_buf[2] = *insn;
17359 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
17360 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
17361 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
17363 } else if (desc->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
17364 bool seen_direct_write = env->seen_direct_write;
17365 bool is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
17368 insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly);
17370 /* restore env->seen_direct_write to its original value, since
17371 * may_access_direct_pkt_data mutates it
17373 env->seen_direct_write = seen_direct_write;
17378 /* Do various post-verification rewrites in a single program pass.
17379 * These rewrites simplify JIT and interpreter implementations.
17381 static int do_misc_fixups(struct bpf_verifier_env *env)
17383 struct bpf_prog *prog = env->prog;
17384 enum bpf_attach_type eatype = prog->expected_attach_type;
17385 enum bpf_prog_type prog_type = resolve_prog_type(prog);
17386 struct bpf_insn *insn = prog->insnsi;
17387 const struct bpf_func_proto *fn;
17388 const int insn_cnt = prog->len;
17389 const struct bpf_map_ops *ops;
17390 struct bpf_insn_aux_data *aux;
17391 struct bpf_insn insn_buf[16];
17392 struct bpf_prog *new_prog;
17393 struct bpf_map *map_ptr;
17394 int i, ret, cnt, delta = 0;
17396 for (i = 0; i < insn_cnt; i++, insn++) {
17397 /* Make divide-by-zero exceptions impossible. */
17398 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
17399 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
17400 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
17401 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
17402 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
17403 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
17404 struct bpf_insn *patchlet;
17405 struct bpf_insn chk_and_div[] = {
17406 /* [R,W]x div 0 -> 0 */
17407 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17408 BPF_JNE | BPF_K, insn->src_reg,
17410 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
17411 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17414 struct bpf_insn chk_and_mod[] = {
17415 /* [R,W]x mod 0 -> [R,W]x */
17416 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17417 BPF_JEQ | BPF_K, insn->src_reg,
17418 0, 1 + (is64 ? 0 : 1), 0),
17420 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17421 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
17424 patchlet = isdiv ? chk_and_div : chk_and_mod;
17425 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
17426 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
17428 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
17433 env->prog = prog = new_prog;
17434 insn = new_prog->insnsi + i + delta;
17438 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
17439 if (BPF_CLASS(insn->code) == BPF_LD &&
17440 (BPF_MODE(insn->code) == BPF_ABS ||
17441 BPF_MODE(insn->code) == BPF_IND)) {
17442 cnt = env->ops->gen_ld_abs(insn, insn_buf);
17443 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
17444 verbose(env, "bpf verifier is misconfigured\n");
17448 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17453 env->prog = prog = new_prog;
17454 insn = new_prog->insnsi + i + delta;
17458 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
17459 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
17460 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
17461 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
17462 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
17463 struct bpf_insn *patch = &insn_buf[0];
17464 bool issrc, isneg, isimm;
17467 aux = &env->insn_aux_data[i + delta];
17468 if (!aux->alu_state ||
17469 aux->alu_state == BPF_ALU_NON_POINTER)
17472 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
17473 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
17474 BPF_ALU_SANITIZE_SRC;
17475 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
17477 off_reg = issrc ? insn->src_reg : insn->dst_reg;
17479 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17482 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17483 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17484 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
17485 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
17486 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
17487 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
17488 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
17491 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
17492 insn->src_reg = BPF_REG_AX;
17494 insn->code = insn->code == code_add ?
17495 code_sub : code_add;
17497 if (issrc && isneg && !isimm)
17498 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17499 cnt = patch - insn_buf;
17501 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17506 env->prog = prog = new_prog;
17507 insn = new_prog->insnsi + i + delta;
17511 if (insn->code != (BPF_JMP | BPF_CALL))
17513 if (insn->src_reg == BPF_PSEUDO_CALL)
17515 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17516 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
17522 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17527 env->prog = prog = new_prog;
17528 insn = new_prog->insnsi + i + delta;
17532 if (insn->imm == BPF_FUNC_get_route_realm)
17533 prog->dst_needed = 1;
17534 if (insn->imm == BPF_FUNC_get_prandom_u32)
17535 bpf_user_rnd_init_once();
17536 if (insn->imm == BPF_FUNC_override_return)
17537 prog->kprobe_override = 1;
17538 if (insn->imm == BPF_FUNC_tail_call) {
17539 /* If we tail call into other programs, we
17540 * cannot make any assumptions since they can
17541 * be replaced dynamically during runtime in
17542 * the program array.
17544 prog->cb_access = 1;
17545 if (!allow_tail_call_in_subprogs(env))
17546 prog->aux->stack_depth = MAX_BPF_STACK;
17547 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
17549 /* mark bpf_tail_call as different opcode to avoid
17550 * conditional branch in the interpreter for every normal
17551 * call and to prevent accidental JITing by JIT compiler
17552 * that doesn't support bpf_tail_call yet
17555 insn->code = BPF_JMP | BPF_TAIL_CALL;
17557 aux = &env->insn_aux_data[i + delta];
17558 if (env->bpf_capable && !prog->blinding_requested &&
17559 prog->jit_requested &&
17560 !bpf_map_key_poisoned(aux) &&
17561 !bpf_map_ptr_poisoned(aux) &&
17562 !bpf_map_ptr_unpriv(aux)) {
17563 struct bpf_jit_poke_descriptor desc = {
17564 .reason = BPF_POKE_REASON_TAIL_CALL,
17565 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
17566 .tail_call.key = bpf_map_key_immediate(aux),
17567 .insn_idx = i + delta,
17570 ret = bpf_jit_add_poke_descriptor(prog, &desc);
17572 verbose(env, "adding tail call poke descriptor failed\n");
17576 insn->imm = ret + 1;
17580 if (!bpf_map_ptr_unpriv(aux))
17583 /* instead of changing every JIT dealing with tail_call
17584 * emit two extra insns:
17585 * if (index >= max_entries) goto out;
17586 * index &= array->index_mask;
17587 * to avoid out-of-bounds cpu speculation
17589 if (bpf_map_ptr_poisoned(aux)) {
17590 verbose(env, "tail_call abusing map_ptr\n");
17594 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
17595 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
17596 map_ptr->max_entries, 2);
17597 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
17598 container_of(map_ptr,
17601 insn_buf[2] = *insn;
17603 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17608 env->prog = prog = new_prog;
17609 insn = new_prog->insnsi + i + delta;
17613 if (insn->imm == BPF_FUNC_timer_set_callback) {
17614 /* The verifier will process callback_fn as many times as necessary
17615 * with different maps and the register states prepared by
17616 * set_timer_callback_state will be accurate.
17618 * The following use case is valid:
17619 * map1 is shared by prog1, prog2, prog3.
17620 * prog1 calls bpf_timer_init for some map1 elements
17621 * prog2 calls bpf_timer_set_callback for some map1 elements.
17622 * Those that were not bpf_timer_init-ed will return -EINVAL.
17623 * prog3 calls bpf_timer_start for some map1 elements.
17624 * Those that were not both bpf_timer_init-ed and
17625 * bpf_timer_set_callback-ed will return -EINVAL.
17627 struct bpf_insn ld_addrs[2] = {
17628 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
17631 insn_buf[0] = ld_addrs[0];
17632 insn_buf[1] = ld_addrs[1];
17633 insn_buf[2] = *insn;
17636 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17641 env->prog = prog = new_prog;
17642 insn = new_prog->insnsi + i + delta;
17643 goto patch_call_imm;
17646 if (is_storage_get_function(insn->imm)) {
17647 if (!env->prog->aux->sleepable ||
17648 env->insn_aux_data[i + delta].storage_get_func_atomic)
17649 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
17651 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
17652 insn_buf[1] = *insn;
17655 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17660 env->prog = prog = new_prog;
17661 insn = new_prog->insnsi + i + delta;
17662 goto patch_call_imm;
17665 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
17666 * and other inlining handlers are currently limited to 64 bit
17669 if (prog->jit_requested && BITS_PER_LONG == 64 &&
17670 (insn->imm == BPF_FUNC_map_lookup_elem ||
17671 insn->imm == BPF_FUNC_map_update_elem ||
17672 insn->imm == BPF_FUNC_map_delete_elem ||
17673 insn->imm == BPF_FUNC_map_push_elem ||
17674 insn->imm == BPF_FUNC_map_pop_elem ||
17675 insn->imm == BPF_FUNC_map_peek_elem ||
17676 insn->imm == BPF_FUNC_redirect_map ||
17677 insn->imm == BPF_FUNC_for_each_map_elem ||
17678 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
17679 aux = &env->insn_aux_data[i + delta];
17680 if (bpf_map_ptr_poisoned(aux))
17681 goto patch_call_imm;
17683 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
17684 ops = map_ptr->ops;
17685 if (insn->imm == BPF_FUNC_map_lookup_elem &&
17686 ops->map_gen_lookup) {
17687 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
17688 if (cnt == -EOPNOTSUPP)
17689 goto patch_map_ops_generic;
17690 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
17691 verbose(env, "bpf verifier is misconfigured\n");
17695 new_prog = bpf_patch_insn_data(env, i + delta,
17701 env->prog = prog = new_prog;
17702 insn = new_prog->insnsi + i + delta;
17706 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
17707 (void *(*)(struct bpf_map *map, void *key))NULL));
17708 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
17709 (long (*)(struct bpf_map *map, void *key))NULL));
17710 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
17711 (long (*)(struct bpf_map *map, void *key, void *value,
17713 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
17714 (long (*)(struct bpf_map *map, void *value,
17716 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
17717 (long (*)(struct bpf_map *map, void *value))NULL));
17718 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
17719 (long (*)(struct bpf_map *map, void *value))NULL));
17720 BUILD_BUG_ON(!__same_type(ops->map_redirect,
17721 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
17722 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
17723 (long (*)(struct bpf_map *map,
17724 bpf_callback_t callback_fn,
17725 void *callback_ctx,
17727 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
17728 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
17730 patch_map_ops_generic:
17731 switch (insn->imm) {
17732 case BPF_FUNC_map_lookup_elem:
17733 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
17735 case BPF_FUNC_map_update_elem:
17736 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
17738 case BPF_FUNC_map_delete_elem:
17739 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
17741 case BPF_FUNC_map_push_elem:
17742 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
17744 case BPF_FUNC_map_pop_elem:
17745 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
17747 case BPF_FUNC_map_peek_elem:
17748 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
17750 case BPF_FUNC_redirect_map:
17751 insn->imm = BPF_CALL_IMM(ops->map_redirect);
17753 case BPF_FUNC_for_each_map_elem:
17754 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
17756 case BPF_FUNC_map_lookup_percpu_elem:
17757 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
17761 goto patch_call_imm;
17764 /* Implement bpf_jiffies64 inline. */
17765 if (prog->jit_requested && BITS_PER_LONG == 64 &&
17766 insn->imm == BPF_FUNC_jiffies64) {
17767 struct bpf_insn ld_jiffies_addr[2] = {
17768 BPF_LD_IMM64(BPF_REG_0,
17769 (unsigned long)&jiffies),
17772 insn_buf[0] = ld_jiffies_addr[0];
17773 insn_buf[1] = ld_jiffies_addr[1];
17774 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
17778 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
17784 env->prog = prog = new_prog;
17785 insn = new_prog->insnsi + i + delta;
17789 /* Implement bpf_get_func_arg inline. */
17790 if (prog_type == BPF_PROG_TYPE_TRACING &&
17791 insn->imm == BPF_FUNC_get_func_arg) {
17792 /* Load nr_args from ctx - 8 */
17793 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17794 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
17795 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
17796 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
17797 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
17798 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17799 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
17800 insn_buf[7] = BPF_JMP_A(1);
17801 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
17804 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17809 env->prog = prog = new_prog;
17810 insn = new_prog->insnsi + i + delta;
17814 /* Implement bpf_get_func_ret inline. */
17815 if (prog_type == BPF_PROG_TYPE_TRACING &&
17816 insn->imm == BPF_FUNC_get_func_ret) {
17817 if (eatype == BPF_TRACE_FEXIT ||
17818 eatype == BPF_MODIFY_RETURN) {
17819 /* Load nr_args from ctx - 8 */
17820 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17821 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
17822 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
17823 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17824 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
17825 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
17828 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
17832 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17837 env->prog = prog = new_prog;
17838 insn = new_prog->insnsi + i + delta;
17842 /* Implement get_func_arg_cnt inline. */
17843 if (prog_type == BPF_PROG_TYPE_TRACING &&
17844 insn->imm == BPF_FUNC_get_func_arg_cnt) {
17845 /* Load nr_args from ctx - 8 */
17846 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17848 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17852 env->prog = prog = new_prog;
17853 insn = new_prog->insnsi + i + delta;
17857 /* Implement bpf_get_func_ip inline. */
17858 if (prog_type == BPF_PROG_TYPE_TRACING &&
17859 insn->imm == BPF_FUNC_get_func_ip) {
17860 /* Load IP address from ctx - 16 */
17861 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
17863 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17867 env->prog = prog = new_prog;
17868 insn = new_prog->insnsi + i + delta;
17873 fn = env->ops->get_func_proto(insn->imm, env->prog);
17874 /* all functions that have prototype and verifier allowed
17875 * programs to call them, must be real in-kernel functions
17879 "kernel subsystem misconfigured func %s#%d\n",
17880 func_id_name(insn->imm), insn->imm);
17883 insn->imm = fn->func - __bpf_call_base;
17886 /* Since poke tab is now finalized, publish aux to tracker. */
17887 for (i = 0; i < prog->aux->size_poke_tab; i++) {
17888 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17889 if (!map_ptr->ops->map_poke_track ||
17890 !map_ptr->ops->map_poke_untrack ||
17891 !map_ptr->ops->map_poke_run) {
17892 verbose(env, "bpf verifier is misconfigured\n");
17896 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
17898 verbose(env, "tracking tail call prog failed\n");
17903 sort_kfunc_descs_by_imm(env->prog);
17908 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
17911 u32 callback_subprogno,
17914 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
17915 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
17916 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
17917 int reg_loop_max = BPF_REG_6;
17918 int reg_loop_cnt = BPF_REG_7;
17919 int reg_loop_ctx = BPF_REG_8;
17921 struct bpf_prog *new_prog;
17922 u32 callback_start;
17923 u32 call_insn_offset;
17924 s32 callback_offset;
17926 /* This represents an inlined version of bpf_iter.c:bpf_loop,
17927 * be careful to modify this code in sync.
17929 struct bpf_insn insn_buf[] = {
17930 /* Return error and jump to the end of the patch if
17931 * expected number of iterations is too big.
17933 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
17934 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
17935 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
17936 /* spill R6, R7, R8 to use these as loop vars */
17937 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
17938 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
17939 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
17940 /* initialize loop vars */
17941 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
17942 BPF_MOV32_IMM(reg_loop_cnt, 0),
17943 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
17945 * if reg_loop_cnt >= reg_loop_max skip the loop body
17947 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
17949 * correct callback offset would be set after patching
17951 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
17952 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
17954 /* increment loop counter */
17955 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
17956 /* jump to loop header if callback returned 0 */
17957 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
17958 /* return value of bpf_loop,
17959 * set R0 to the number of iterations
17961 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
17962 /* restore original values of R6, R7, R8 */
17963 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
17964 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
17965 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
17968 *cnt = ARRAY_SIZE(insn_buf);
17969 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
17973 /* callback start is known only after patching */
17974 callback_start = env->subprog_info[callback_subprogno].start;
17975 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
17976 call_insn_offset = position + 12;
17977 callback_offset = callback_start - call_insn_offset - 1;
17978 new_prog->insnsi[call_insn_offset].imm = callback_offset;
17983 static bool is_bpf_loop_call(struct bpf_insn *insn)
17985 return insn->code == (BPF_JMP | BPF_CALL) &&
17986 insn->src_reg == 0 &&
17987 insn->imm == BPF_FUNC_loop;
17990 /* For all sub-programs in the program (including main) check
17991 * insn_aux_data to see if there are bpf_loop calls that require
17992 * inlining. If such calls are found the calls are replaced with a
17993 * sequence of instructions produced by `inline_bpf_loop` function and
17994 * subprog stack_depth is increased by the size of 3 registers.
17995 * This stack space is used to spill values of the R6, R7, R8. These
17996 * registers are used to store the loop bound, counter and context
17999 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18001 struct bpf_subprog_info *subprogs = env->subprog_info;
18002 int i, cur_subprog = 0, cnt, delta = 0;
18003 struct bpf_insn *insn = env->prog->insnsi;
18004 int insn_cnt = env->prog->len;
18005 u16 stack_depth = subprogs[cur_subprog].stack_depth;
18006 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18007 u16 stack_depth_extra = 0;
18009 for (i = 0; i < insn_cnt; i++, insn++) {
18010 struct bpf_loop_inline_state *inline_state =
18011 &env->insn_aux_data[i + delta].loop_inline_state;
18013 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18014 struct bpf_prog *new_prog;
18016 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18017 new_prog = inline_bpf_loop(env,
18019 -(stack_depth + stack_depth_extra),
18020 inline_state->callback_subprogno,
18026 env->prog = new_prog;
18027 insn = new_prog->insnsi + i + delta;
18030 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18031 subprogs[cur_subprog].stack_depth += stack_depth_extra;
18033 stack_depth = subprogs[cur_subprog].stack_depth;
18034 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18035 stack_depth_extra = 0;
18039 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18044 static void free_states(struct bpf_verifier_env *env)
18046 struct bpf_verifier_state_list *sl, *sln;
18049 sl = env->free_list;
18052 free_verifier_state(&sl->state, false);
18056 env->free_list = NULL;
18058 if (!env->explored_states)
18061 for (i = 0; i < state_htab_size(env); i++) {
18062 sl = env->explored_states[i];
18066 free_verifier_state(&sl->state, false);
18070 env->explored_states[i] = NULL;
18074 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18076 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18077 struct bpf_verifier_state *state;
18078 struct bpf_reg_state *regs;
18081 env->prev_linfo = NULL;
18084 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18087 state->curframe = 0;
18088 state->speculative = false;
18089 state->branches = 1;
18090 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18091 if (!state->frame[0]) {
18095 env->cur_state = state;
18096 init_func_state(env, state->frame[0],
18097 BPF_MAIN_FUNC /* callsite */,
18100 state->first_insn_idx = env->subprog_info[subprog].start;
18101 state->last_insn_idx = -1;
18103 regs = state->frame[state->curframe]->regs;
18104 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18105 ret = btf_prepare_func_args(env, subprog, regs);
18108 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18109 if (regs[i].type == PTR_TO_CTX)
18110 mark_reg_known_zero(env, regs, i);
18111 else if (regs[i].type == SCALAR_VALUE)
18112 mark_reg_unknown(env, regs, i);
18113 else if (base_type(regs[i].type) == PTR_TO_MEM) {
18114 const u32 mem_size = regs[i].mem_size;
18116 mark_reg_known_zero(env, regs, i);
18117 regs[i].mem_size = mem_size;
18118 regs[i].id = ++env->id_gen;
18122 /* 1st arg to a function */
18123 regs[BPF_REG_1].type = PTR_TO_CTX;
18124 mark_reg_known_zero(env, regs, BPF_REG_1);
18125 ret = btf_check_subprog_arg_match(env, subprog, regs);
18126 if (ret == -EFAULT)
18127 /* unlikely verifier bug. abort.
18128 * ret == 0 and ret < 0 are sadly acceptable for
18129 * main() function due to backward compatibility.
18130 * Like socket filter program may be written as:
18131 * int bpf_prog(struct pt_regs *ctx)
18132 * and never dereference that ctx in the program.
18133 * 'struct pt_regs' is a type mismatch for socket
18134 * filter that should be using 'struct __sk_buff'.
18139 ret = do_check(env);
18141 /* check for NULL is necessary, since cur_state can be freed inside
18142 * do_check() under memory pressure.
18144 if (env->cur_state) {
18145 free_verifier_state(env->cur_state, true);
18146 env->cur_state = NULL;
18148 while (!pop_stack(env, NULL, NULL, false));
18149 if (!ret && pop_log)
18150 bpf_vlog_reset(&env->log, 0);
18155 /* Verify all global functions in a BPF program one by one based on their BTF.
18156 * All global functions must pass verification. Otherwise the whole program is rejected.
18167 * foo() will be verified first for R1=any_scalar_value. During verification it
18168 * will be assumed that bar() already verified successfully and call to bar()
18169 * from foo() will be checked for type match only. Later bar() will be verified
18170 * independently to check that it's safe for R1=any_scalar_value.
18172 static int do_check_subprogs(struct bpf_verifier_env *env)
18174 struct bpf_prog_aux *aux = env->prog->aux;
18177 if (!aux->func_info)
18180 for (i = 1; i < env->subprog_cnt; i++) {
18181 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18183 env->insn_idx = env->subprog_info[i].start;
18184 WARN_ON_ONCE(env->insn_idx == 0);
18185 ret = do_check_common(env, i);
18188 } else if (env->log.level & BPF_LOG_LEVEL) {
18190 "Func#%d is safe for any args that match its prototype\n",
18197 static int do_check_main(struct bpf_verifier_env *env)
18202 ret = do_check_common(env, 0);
18204 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18209 static void print_verification_stats(struct bpf_verifier_env *env)
18213 if (env->log.level & BPF_LOG_STATS) {
18214 verbose(env, "verification time %lld usec\n",
18215 div_u64(env->verification_time, 1000));
18216 verbose(env, "stack depth ");
18217 for (i = 0; i < env->subprog_cnt; i++) {
18218 u32 depth = env->subprog_info[i].stack_depth;
18220 verbose(env, "%d", depth);
18221 if (i + 1 < env->subprog_cnt)
18224 verbose(env, "\n");
18226 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18227 "total_states %d peak_states %d mark_read %d\n",
18228 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18229 env->max_states_per_insn, env->total_states,
18230 env->peak_states, env->longest_mark_read_walk);
18233 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18235 const struct btf_type *t, *func_proto;
18236 const struct bpf_struct_ops *st_ops;
18237 const struct btf_member *member;
18238 struct bpf_prog *prog = env->prog;
18239 u32 btf_id, member_idx;
18242 if (!prog->gpl_compatible) {
18243 verbose(env, "struct ops programs must have a GPL compatible license\n");
18247 btf_id = prog->aux->attach_btf_id;
18248 st_ops = bpf_struct_ops_find(btf_id);
18250 verbose(env, "attach_btf_id %u is not a supported struct\n",
18256 member_idx = prog->expected_attach_type;
18257 if (member_idx >= btf_type_vlen(t)) {
18258 verbose(env, "attach to invalid member idx %u of struct %s\n",
18259 member_idx, st_ops->name);
18263 member = &btf_type_member(t)[member_idx];
18264 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
18265 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
18268 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18269 mname, member_idx, st_ops->name);
18273 if (st_ops->check_member) {
18274 int err = st_ops->check_member(t, member, prog);
18277 verbose(env, "attach to unsupported member %s of struct %s\n",
18278 mname, st_ops->name);
18283 prog->aux->attach_func_proto = func_proto;
18284 prog->aux->attach_func_name = mname;
18285 env->ops = st_ops->verifier_ops;
18289 #define SECURITY_PREFIX "security_"
18291 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18293 if (within_error_injection_list(addr) ||
18294 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18300 /* list of non-sleepable functions that are otherwise on
18301 * ALLOW_ERROR_INJECTION list
18303 BTF_SET_START(btf_non_sleepable_error_inject)
18304 /* Three functions below can be called from sleepable and non-sleepable context.
18305 * Assume non-sleepable from bpf safety point of view.
18307 BTF_ID(func, __filemap_add_folio)
18308 BTF_ID(func, should_fail_alloc_page)
18309 BTF_ID(func, should_failslab)
18310 BTF_SET_END(btf_non_sleepable_error_inject)
18312 static int check_non_sleepable_error_inject(u32 btf_id)
18314 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18317 int bpf_check_attach_target(struct bpf_verifier_log *log,
18318 const struct bpf_prog *prog,
18319 const struct bpf_prog *tgt_prog,
18321 struct bpf_attach_target_info *tgt_info)
18323 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
18324 const char prefix[] = "btf_trace_";
18325 int ret = 0, subprog = -1, i;
18326 const struct btf_type *t;
18327 bool conservative = true;
18331 struct module *mod = NULL;
18334 bpf_log(log, "Tracing programs must provide btf_id\n");
18337 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
18340 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
18343 t = btf_type_by_id(btf, btf_id);
18345 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
18348 tname = btf_name_by_offset(btf, t->name_off);
18350 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
18354 struct bpf_prog_aux *aux = tgt_prog->aux;
18356 if (bpf_prog_is_dev_bound(prog->aux) &&
18357 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
18358 bpf_log(log, "Target program bound device mismatch");
18362 for (i = 0; i < aux->func_info_cnt; i++)
18363 if (aux->func_info[i].type_id == btf_id) {
18367 if (subprog == -1) {
18368 bpf_log(log, "Subprog %s doesn't exist\n", tname);
18371 conservative = aux->func_info_aux[subprog].unreliable;
18372 if (prog_extension) {
18373 if (conservative) {
18375 "Cannot replace static functions\n");
18378 if (!prog->jit_requested) {
18380 "Extension programs should be JITed\n");
18384 if (!tgt_prog->jited) {
18385 bpf_log(log, "Can attach to only JITed progs\n");
18388 if (tgt_prog->type == prog->type) {
18389 /* Cannot fentry/fexit another fentry/fexit program.
18390 * Cannot attach program extension to another extension.
18391 * It's ok to attach fentry/fexit to extension program.
18393 bpf_log(log, "Cannot recursively attach\n");
18396 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
18398 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
18399 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
18400 /* Program extensions can extend all program types
18401 * except fentry/fexit. The reason is the following.
18402 * The fentry/fexit programs are used for performance
18403 * analysis, stats and can be attached to any program
18404 * type except themselves. When extension program is
18405 * replacing XDP function it is necessary to allow
18406 * performance analysis of all functions. Both original
18407 * XDP program and its program extension. Hence
18408 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
18409 * allowed. If extending of fentry/fexit was allowed it
18410 * would be possible to create long call chain
18411 * fentry->extension->fentry->extension beyond
18412 * reasonable stack size. Hence extending fentry is not
18415 bpf_log(log, "Cannot extend fentry/fexit\n");
18419 if (prog_extension) {
18420 bpf_log(log, "Cannot replace kernel functions\n");
18425 switch (prog->expected_attach_type) {
18426 case BPF_TRACE_RAW_TP:
18429 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
18432 if (!btf_type_is_typedef(t)) {
18433 bpf_log(log, "attach_btf_id %u is not a typedef\n",
18437 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
18438 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
18442 tname += sizeof(prefix) - 1;
18443 t = btf_type_by_id(btf, t->type);
18444 if (!btf_type_is_ptr(t))
18445 /* should never happen in valid vmlinux build */
18447 t = btf_type_by_id(btf, t->type);
18448 if (!btf_type_is_func_proto(t))
18449 /* should never happen in valid vmlinux build */
18453 case BPF_TRACE_ITER:
18454 if (!btf_type_is_func(t)) {
18455 bpf_log(log, "attach_btf_id %u is not a function\n",
18459 t = btf_type_by_id(btf, t->type);
18460 if (!btf_type_is_func_proto(t))
18462 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
18467 if (!prog_extension)
18470 case BPF_MODIFY_RETURN:
18472 case BPF_LSM_CGROUP:
18473 case BPF_TRACE_FENTRY:
18474 case BPF_TRACE_FEXIT:
18475 if (!btf_type_is_func(t)) {
18476 bpf_log(log, "attach_btf_id %u is not a function\n",
18480 if (prog_extension &&
18481 btf_check_type_match(log, prog, btf, t))
18483 t = btf_type_by_id(btf, t->type);
18484 if (!btf_type_is_func_proto(t))
18487 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
18488 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
18489 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
18492 if (tgt_prog && conservative)
18495 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
18501 addr = (long) tgt_prog->bpf_func;
18503 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
18505 if (btf_is_module(btf)) {
18506 mod = btf_try_get_module(btf);
18508 addr = find_kallsyms_symbol_value(mod, tname);
18512 addr = kallsyms_lookup_name(tname);
18517 "The address of function %s cannot be found\n",
18523 if (prog->aux->sleepable) {
18525 switch (prog->type) {
18526 case BPF_PROG_TYPE_TRACING:
18528 /* fentry/fexit/fmod_ret progs can be sleepable if they are
18529 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
18531 if (!check_non_sleepable_error_inject(btf_id) &&
18532 within_error_injection_list(addr))
18534 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
18535 * in the fmodret id set with the KF_SLEEPABLE flag.
18538 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
18540 if (flags && (*flags & KF_SLEEPABLE))
18544 case BPF_PROG_TYPE_LSM:
18545 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
18546 * Only some of them are sleepable.
18548 if (bpf_lsm_is_sleepable_hook(btf_id))
18556 bpf_log(log, "%s is not sleepable\n", tname);
18559 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
18562 bpf_log(log, "can't modify return codes of BPF programs\n");
18566 if (btf_kfunc_is_modify_return(btf, btf_id) ||
18567 !check_attach_modify_return(addr, tname))
18571 bpf_log(log, "%s() is not modifiable\n", tname);
18578 tgt_info->tgt_addr = addr;
18579 tgt_info->tgt_name = tname;
18580 tgt_info->tgt_type = t;
18581 tgt_info->tgt_mod = mod;
18585 BTF_SET_START(btf_id_deny)
18588 BTF_ID(func, migrate_disable)
18589 BTF_ID(func, migrate_enable)
18591 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
18592 BTF_ID(func, rcu_read_unlock_strict)
18594 BTF_SET_END(btf_id_deny)
18596 static bool can_be_sleepable(struct bpf_prog *prog)
18598 if (prog->type == BPF_PROG_TYPE_TRACING) {
18599 switch (prog->expected_attach_type) {
18600 case BPF_TRACE_FENTRY:
18601 case BPF_TRACE_FEXIT:
18602 case BPF_MODIFY_RETURN:
18603 case BPF_TRACE_ITER:
18609 return prog->type == BPF_PROG_TYPE_LSM ||
18610 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
18611 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
18614 static int check_attach_btf_id(struct bpf_verifier_env *env)
18616 struct bpf_prog *prog = env->prog;
18617 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
18618 struct bpf_attach_target_info tgt_info = {};
18619 u32 btf_id = prog->aux->attach_btf_id;
18620 struct bpf_trampoline *tr;
18624 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
18625 if (prog->aux->sleepable)
18626 /* attach_btf_id checked to be zero already */
18628 verbose(env, "Syscall programs can only be sleepable\n");
18632 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
18633 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
18637 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
18638 return check_struct_ops_btf_id(env);
18640 if (prog->type != BPF_PROG_TYPE_TRACING &&
18641 prog->type != BPF_PROG_TYPE_LSM &&
18642 prog->type != BPF_PROG_TYPE_EXT)
18645 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
18649 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
18650 /* to make freplace equivalent to their targets, they need to
18651 * inherit env->ops and expected_attach_type for the rest of the
18654 env->ops = bpf_verifier_ops[tgt_prog->type];
18655 prog->expected_attach_type = tgt_prog->expected_attach_type;
18658 /* store info about the attachment target that will be used later */
18659 prog->aux->attach_func_proto = tgt_info.tgt_type;
18660 prog->aux->attach_func_name = tgt_info.tgt_name;
18661 prog->aux->mod = tgt_info.tgt_mod;
18664 prog->aux->saved_dst_prog_type = tgt_prog->type;
18665 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
18668 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
18669 prog->aux->attach_btf_trace = true;
18671 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
18672 if (!bpf_iter_prog_supported(prog))
18677 if (prog->type == BPF_PROG_TYPE_LSM) {
18678 ret = bpf_lsm_verify_prog(&env->log, prog);
18681 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
18682 btf_id_set_contains(&btf_id_deny, btf_id)) {
18686 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
18687 tr = bpf_trampoline_get(key, &tgt_info);
18691 prog->aux->dst_trampoline = tr;
18695 struct btf *bpf_get_btf_vmlinux(void)
18697 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
18698 mutex_lock(&bpf_verifier_lock);
18700 btf_vmlinux = btf_parse_vmlinux();
18701 mutex_unlock(&bpf_verifier_lock);
18703 return btf_vmlinux;
18706 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
18708 u64 start_time = ktime_get_ns();
18709 struct bpf_verifier_env *env;
18710 struct bpf_verifier_log *log;
18711 int i, len, ret = -EINVAL;
18714 /* no program is valid */
18715 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
18718 /* 'struct bpf_verifier_env' can be global, but since it's not small,
18719 * allocate/free it every time bpf_check() is called
18721 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
18726 len = (*prog)->len;
18727 env->insn_aux_data =
18728 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
18730 if (!env->insn_aux_data)
18732 for (i = 0; i < len; i++)
18733 env->insn_aux_data[i].orig_idx = i;
18735 env->ops = bpf_verifier_ops[env->prog->type];
18736 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
18737 is_priv = bpf_capable();
18739 bpf_get_btf_vmlinux();
18741 /* grab the mutex to protect few globals used by verifier */
18743 mutex_lock(&bpf_verifier_lock);
18745 if (attr->log_level || attr->log_buf || attr->log_size) {
18746 /* user requested verbose verifier output
18747 * and supplied buffer to store the verification trace
18749 log->level = attr->log_level;
18750 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
18751 log->len_total = attr->log_size;
18753 /* log attributes have to be sane */
18754 if (!bpf_verifier_log_attr_valid(log)) {
18760 mark_verifier_state_clean(env);
18762 if (IS_ERR(btf_vmlinux)) {
18763 /* Either gcc or pahole or kernel are broken. */
18764 verbose(env, "in-kernel BTF is malformed\n");
18765 ret = PTR_ERR(btf_vmlinux);
18766 goto skip_full_check;
18769 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
18770 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
18771 env->strict_alignment = true;
18772 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
18773 env->strict_alignment = false;
18775 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
18776 env->allow_uninit_stack = bpf_allow_uninit_stack();
18777 env->bypass_spec_v1 = bpf_bypass_spec_v1();
18778 env->bypass_spec_v4 = bpf_bypass_spec_v4();
18779 env->bpf_capable = bpf_capable();
18782 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
18784 env->explored_states = kvcalloc(state_htab_size(env),
18785 sizeof(struct bpf_verifier_state_list *),
18788 if (!env->explored_states)
18789 goto skip_full_check;
18791 ret = add_subprog_and_kfunc(env);
18793 goto skip_full_check;
18795 ret = check_subprogs(env);
18797 goto skip_full_check;
18799 ret = check_btf_info(env, attr, uattr);
18801 goto skip_full_check;
18803 ret = check_attach_btf_id(env);
18805 goto skip_full_check;
18807 ret = resolve_pseudo_ldimm64(env);
18809 goto skip_full_check;
18811 if (bpf_prog_is_offloaded(env->prog->aux)) {
18812 ret = bpf_prog_offload_verifier_prep(env->prog);
18814 goto skip_full_check;
18817 ret = check_cfg(env);
18819 goto skip_full_check;
18821 ret = do_check_subprogs(env);
18822 ret = ret ?: do_check_main(env);
18824 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
18825 ret = bpf_prog_offload_finalize(env);
18828 kvfree(env->explored_states);
18831 ret = check_max_stack_depth(env);
18833 /* instruction rewrites happen after this point */
18835 ret = optimize_bpf_loop(env);
18839 opt_hard_wire_dead_code_branches(env);
18841 ret = opt_remove_dead_code(env);
18843 ret = opt_remove_nops(env);
18846 sanitize_dead_code(env);
18850 /* program is valid, convert *(u32*)(ctx + off) accesses */
18851 ret = convert_ctx_accesses(env);
18854 ret = do_misc_fixups(env);
18856 /* do 32-bit optimization after insn patching has done so those patched
18857 * insns could be handled correctly.
18859 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
18860 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
18861 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
18866 ret = fixup_call_args(env);
18868 env->verification_time = ktime_get_ns() - start_time;
18869 print_verification_stats(env);
18870 env->prog->aux->verified_insns = env->insn_processed;
18872 if (log->level && bpf_verifier_log_full(log))
18874 if (log->level && !log->ubuf) {
18876 goto err_release_maps;
18880 goto err_release_maps;
18882 if (env->used_map_cnt) {
18883 /* if program passed verifier, update used_maps in bpf_prog_info */
18884 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
18885 sizeof(env->used_maps[0]),
18888 if (!env->prog->aux->used_maps) {
18890 goto err_release_maps;
18893 memcpy(env->prog->aux->used_maps, env->used_maps,
18894 sizeof(env->used_maps[0]) * env->used_map_cnt);
18895 env->prog->aux->used_map_cnt = env->used_map_cnt;
18897 if (env->used_btf_cnt) {
18898 /* if program passed verifier, update used_btfs in bpf_prog_aux */
18899 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
18900 sizeof(env->used_btfs[0]),
18902 if (!env->prog->aux->used_btfs) {
18904 goto err_release_maps;
18907 memcpy(env->prog->aux->used_btfs, env->used_btfs,
18908 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
18909 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
18911 if (env->used_map_cnt || env->used_btf_cnt) {
18912 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
18913 * bpf_ld_imm64 instructions
18915 convert_pseudo_ld_imm64(env);
18918 adjust_btf_func(env);
18921 if (!env->prog->aux->used_maps)
18922 /* if we didn't copy map pointers into bpf_prog_info, release
18923 * them now. Otherwise free_used_maps() will release them.
18926 if (!env->prog->aux->used_btfs)
18929 /* extension progs temporarily inherit the attach_type of their targets
18930 for verification purposes, so set it back to zero before returning
18932 if (env->prog->type == BPF_PROG_TYPE_EXT)
18933 env->prog->expected_attach_type = 0;
18938 mutex_unlock(&bpf_verifier_lock);
18939 vfree(env->insn_aux_data);