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>
29 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
30 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
31 [_id] = & _name ## _verifier_ops,
32 #define BPF_MAP_TYPE(_id, _ops)
33 #define BPF_LINK_TYPE(_id, _name)
34 #include <linux/bpf_types.h>
40 /* bpf_check() is a static code analyzer that walks eBPF program
41 * instruction by instruction and updates register/stack state.
42 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44 * The first pass is depth-first-search to check that the program is a DAG.
45 * It rejects the following programs:
46 * - larger than BPF_MAXINSNS insns
47 * - if loop is present (detected via back-edge)
48 * - unreachable insns exist (shouldn't be a forest. program = one function)
49 * - out of bounds or malformed jumps
50 * The second pass is all possible path descent from the 1st insn.
51 * Since it's analyzing all paths through the program, the length of the
52 * analysis is limited to 64k insn, which may be hit even if total number of
53 * insn is less then 4K, but there are too many branches that change stack/regs.
54 * Number of 'branches to be analyzed' is limited to 1k
56 * On entry to each instruction, each register has a type, and the instruction
57 * changes the types of the registers depending on instruction semantics.
58 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
61 * All registers are 64-bit.
62 * R0 - return register
63 * R1-R5 argument passing registers
64 * R6-R9 callee saved registers
65 * R10 - frame pointer read-only
67 * At the start of BPF program the register R1 contains a pointer to bpf_context
68 * and has type PTR_TO_CTX.
70 * Verifier tracks arithmetic operations on pointers in case:
71 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
72 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
73 * 1st insn copies R10 (which has FRAME_PTR) type into R1
74 * and 2nd arithmetic instruction is pattern matched to recognize
75 * that it wants to construct a pointer to some element within stack.
76 * So after 2nd insn, the register R1 has type PTR_TO_STACK
77 * (and -20 constant is saved for further stack bounds checking).
78 * Meaning that this reg is a pointer to stack plus known immediate constant.
80 * Most of the time the registers have SCALAR_VALUE type, which
81 * means the register has some value, but it's not a valid pointer.
82 * (like pointer plus pointer becomes SCALAR_VALUE type)
84 * When verifier sees load or store instructions the type of base register
85 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
86 * four pointer types recognized by check_mem_access() function.
88 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
89 * and the range of [ptr, ptr + map's value_size) is accessible.
91 * registers used to pass values to function calls are checked against
92 * function argument constraints.
94 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
95 * It means that the register type passed to this function must be
96 * PTR_TO_STACK and it will be used inside the function as
97 * 'pointer to map element key'
99 * For example the argument constraints for bpf_map_lookup_elem():
100 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
101 * .arg1_type = ARG_CONST_MAP_PTR,
102 * .arg2_type = ARG_PTR_TO_MAP_KEY,
104 * ret_type says that this function returns 'pointer to map elem value or null'
105 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
106 * 2nd argument should be a pointer to stack, which will be used inside
107 * the helper function as a pointer to map element key.
109 * On the kernel side the helper function looks like:
110 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
113 * void *key = (void *) (unsigned long) r2;
116 * here kernel can access 'key' and 'map' pointers safely, knowing that
117 * [key, key + map->key_size) bytes are valid and were initialized on
118 * the stack of eBPF program.
121 * Corresponding eBPF program may look like:
122 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
123 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
124 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
125 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
126 * here verifier looks at prototype of map_lookup_elem() and sees:
127 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
128 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
131 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
132 * and were initialized prior to this call.
133 * If it's ok, then verifier allows this BPF_CALL insn and looks at
134 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
135 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
136 * returns either pointer to map value or NULL.
138 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
139 * insn, the register holding that pointer in the true branch changes state to
140 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
141 * branch. See check_cond_jmp_op().
143 * After the call R0 is set to return type of the function and registers R1-R5
144 * are set to NOT_INIT to indicate that they are no longer readable.
146 * The following reference types represent a potential reference to a kernel
147 * resource which, after first being allocated, must be checked and freed by
149 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151 * When the verifier sees a helper call return a reference type, it allocates a
152 * pointer id for the reference and stores it in the current function state.
153 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
154 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
155 * passes through a NULL-check conditional. For the branch wherein the state is
156 * changed to CONST_IMM, the verifier releases the reference.
158 * For each helper function that allocates a reference, such as
159 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
160 * bpf_sk_release(). When a reference type passes into the release function,
161 * the verifier also releases the reference. If any unchecked or unreleased
162 * reference remains at the end of the program, the verifier rejects it.
165 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
166 struct bpf_verifier_stack_elem {
167 /* verifer state is 'st'
168 * before processing instruction 'insn_idx'
169 * and after processing instruction 'prev_insn_idx'
171 struct bpf_verifier_state st;
174 struct bpf_verifier_stack_elem *next;
175 /* length of verifier log at the time this state was pushed on stack */
179 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
180 #define BPF_COMPLEXITY_LIMIT_STATES 64
182 #define BPF_MAP_KEY_POISON (1ULL << 63)
183 #define BPF_MAP_KEY_SEEN (1ULL << 62)
185 #define BPF_MAP_PTR_UNPRIV 1UL
186 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
187 POISON_POINTER_DELTA))
188 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
191 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
195 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
198 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
200 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
203 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
204 const struct bpf_map *map, bool unpriv)
206 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
207 unpriv |= bpf_map_ptr_unpriv(aux);
208 aux->map_ptr_state = (unsigned long)map |
209 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
212 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
214 return aux->map_key_state & BPF_MAP_KEY_POISON;
217 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
219 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
222 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
224 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
227 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
229 bool poisoned = bpf_map_key_poisoned(aux);
231 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
232 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
235 static bool bpf_pseudo_call(const struct bpf_insn *insn)
237 return insn->code == (BPF_JMP | BPF_CALL) &&
238 insn->src_reg == BPF_PSEUDO_CALL;
241 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
243 return insn->code == (BPF_JMP | BPF_CALL) &&
244 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
247 struct bpf_call_arg_meta {
248 struct bpf_map *map_ptr;
264 struct bpf_map_value_off_desc *kptr_off_desc;
265 u8 uninit_dynptr_regno;
268 struct btf *btf_vmlinux;
270 static DEFINE_MUTEX(bpf_verifier_lock);
272 static const struct bpf_line_info *
273 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
275 const struct bpf_line_info *linfo;
276 const struct bpf_prog *prog;
280 nr_linfo = prog->aux->nr_linfo;
282 if (!nr_linfo || insn_off >= prog->len)
285 linfo = prog->aux->linfo;
286 for (i = 1; i < nr_linfo; i++)
287 if (insn_off < linfo[i].insn_off)
290 return &linfo[i - 1];
293 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
298 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
300 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
301 "verifier log line truncated - local buffer too short\n");
303 if (log->level == BPF_LOG_KERNEL) {
304 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
306 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
310 n = min(log->len_total - log->len_used - 1, n);
312 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
318 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
322 if (!bpf_verifier_log_needed(log))
325 log->len_used = new_pos;
326 if (put_user(zero, log->ubuf + new_pos))
330 /* log_level controls verbosity level of eBPF verifier.
331 * bpf_verifier_log_write() is used to dump the verification trace to the log,
332 * so the user can figure out what's wrong with the program
334 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
335 const char *fmt, ...)
339 if (!bpf_verifier_log_needed(&env->log))
343 bpf_verifier_vlog(&env->log, fmt, args);
346 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
348 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
350 struct bpf_verifier_env *env = private_data;
353 if (!bpf_verifier_log_needed(&env->log))
357 bpf_verifier_vlog(&env->log, fmt, args);
361 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
362 const char *fmt, ...)
366 if (!bpf_verifier_log_needed(log))
370 bpf_verifier_vlog(log, fmt, args);
374 static const char *ltrim(const char *s)
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
384 const char *prefix_fmt, ...)
386 const struct bpf_line_info *linfo;
388 if (!bpf_verifier_log_needed(&env->log))
391 linfo = find_linfo(env, insn_off);
392 if (!linfo || linfo == env->prev_linfo)
398 va_start(args, prefix_fmt);
399 bpf_verifier_vlog(&env->log, prefix_fmt, args);
404 ltrim(btf_name_by_offset(env->prog->aux->btf,
407 env->prev_linfo = linfo;
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411 struct bpf_reg_state *reg,
412 struct tnum *range, const char *ctx,
413 const char *reg_name)
417 verbose(env, "At %s the register %s ", ctx, reg_name);
418 if (!tnum_is_unknown(reg->var_off)) {
419 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420 verbose(env, "has value %s", tn_buf);
422 verbose(env, "has unknown scalar value");
424 tnum_strn(tn_buf, sizeof(tn_buf), *range);
425 verbose(env, " should have been in %s\n", tn_buf);
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
430 return type == PTR_TO_PACKET ||
431 type == PTR_TO_PACKET_META;
434 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 return type == PTR_TO_SOCKET ||
437 type == PTR_TO_SOCK_COMMON ||
438 type == PTR_TO_TCP_SOCK ||
439 type == PTR_TO_XDP_SOCK;
442 static bool reg_type_not_null(enum bpf_reg_type type)
444 return type == PTR_TO_SOCKET ||
445 type == PTR_TO_TCP_SOCK ||
446 type == PTR_TO_MAP_VALUE ||
447 type == PTR_TO_MAP_KEY ||
448 type == PTR_TO_SOCK_COMMON;
451 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
453 return reg->type == PTR_TO_MAP_VALUE &&
454 map_value_has_spin_lock(reg->map_ptr);
457 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
459 return base_type(type) == PTR_TO_SOCKET ||
460 base_type(type) == PTR_TO_TCP_SOCK ||
461 base_type(type) == PTR_TO_MEM ||
462 base_type(type) == PTR_TO_BTF_ID;
465 static bool type_is_rdonly_mem(u32 type)
467 return type & MEM_RDONLY;
470 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
472 return type == ARG_PTR_TO_SOCK_COMMON;
475 static bool type_may_be_null(u32 type)
477 return type & PTR_MAYBE_NULL;
480 static bool may_be_acquire_function(enum bpf_func_id func_id)
482 return func_id == BPF_FUNC_sk_lookup_tcp ||
483 func_id == BPF_FUNC_sk_lookup_udp ||
484 func_id == BPF_FUNC_skc_lookup_tcp ||
485 func_id == BPF_FUNC_map_lookup_elem ||
486 func_id == BPF_FUNC_ringbuf_reserve;
489 static bool is_acquire_function(enum bpf_func_id func_id,
490 const struct bpf_map *map)
492 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
494 if (func_id == BPF_FUNC_sk_lookup_tcp ||
495 func_id == BPF_FUNC_sk_lookup_udp ||
496 func_id == BPF_FUNC_skc_lookup_tcp ||
497 func_id == BPF_FUNC_ringbuf_reserve ||
498 func_id == BPF_FUNC_kptr_xchg)
501 if (func_id == BPF_FUNC_map_lookup_elem &&
502 (map_type == BPF_MAP_TYPE_SOCKMAP ||
503 map_type == BPF_MAP_TYPE_SOCKHASH))
509 static bool is_ptr_cast_function(enum bpf_func_id func_id)
511 return func_id == BPF_FUNC_tcp_sock ||
512 func_id == BPF_FUNC_sk_fullsock ||
513 func_id == BPF_FUNC_skc_to_tcp_sock ||
514 func_id == BPF_FUNC_skc_to_tcp6_sock ||
515 func_id == BPF_FUNC_skc_to_udp6_sock ||
516 func_id == BPF_FUNC_skc_to_mptcp_sock ||
517 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
518 func_id == BPF_FUNC_skc_to_tcp_request_sock;
521 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
523 return BPF_CLASS(insn->code) == BPF_STX &&
524 BPF_MODE(insn->code) == BPF_ATOMIC &&
525 insn->imm == BPF_CMPXCHG;
528 /* string representation of 'enum bpf_reg_type'
530 * Note that reg_type_str() can not appear more than once in a single verbose()
533 static const char *reg_type_str(struct bpf_verifier_env *env,
534 enum bpf_reg_type type)
536 char postfix[16] = {0}, prefix[32] = {0};
537 static const char * const str[] = {
539 [SCALAR_VALUE] = "scalar",
540 [PTR_TO_CTX] = "ctx",
541 [CONST_PTR_TO_MAP] = "map_ptr",
542 [PTR_TO_MAP_VALUE] = "map_value",
543 [PTR_TO_STACK] = "fp",
544 [PTR_TO_PACKET] = "pkt",
545 [PTR_TO_PACKET_META] = "pkt_meta",
546 [PTR_TO_PACKET_END] = "pkt_end",
547 [PTR_TO_FLOW_KEYS] = "flow_keys",
548 [PTR_TO_SOCKET] = "sock",
549 [PTR_TO_SOCK_COMMON] = "sock_common",
550 [PTR_TO_TCP_SOCK] = "tcp_sock",
551 [PTR_TO_TP_BUFFER] = "tp_buffer",
552 [PTR_TO_XDP_SOCK] = "xdp_sock",
553 [PTR_TO_BTF_ID] = "ptr_",
554 [PTR_TO_MEM] = "mem",
555 [PTR_TO_BUF] = "buf",
556 [PTR_TO_FUNC] = "func",
557 [PTR_TO_MAP_KEY] = "map_key",
560 if (type & PTR_MAYBE_NULL) {
561 if (base_type(type) == PTR_TO_BTF_ID)
562 strncpy(postfix, "or_null_", 16);
564 strncpy(postfix, "_or_null", 16);
567 if (type & MEM_RDONLY)
568 strncpy(prefix, "rdonly_", 32);
569 if (type & MEM_ALLOC)
570 strncpy(prefix, "alloc_", 32);
572 strncpy(prefix, "user_", 32);
573 if (type & MEM_PERCPU)
574 strncpy(prefix, "percpu_", 32);
575 if (type & PTR_UNTRUSTED)
576 strncpy(prefix, "untrusted_", 32);
578 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
579 prefix, str[base_type(type)], postfix);
580 return env->type_str_buf;
583 static char slot_type_char[] = {
584 [STACK_INVALID] = '?',
588 [STACK_DYNPTR] = 'd',
591 static void print_liveness(struct bpf_verifier_env *env,
592 enum bpf_reg_liveness live)
594 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
596 if (live & REG_LIVE_READ)
598 if (live & REG_LIVE_WRITTEN)
600 if (live & REG_LIVE_DONE)
604 static int get_spi(s32 off)
606 return (-off - 1) / BPF_REG_SIZE;
609 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
611 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
613 /* We need to check that slots between [spi - nr_slots + 1, spi] are
614 * within [0, allocated_stack).
616 * Please note that the spi grows downwards. For example, a dynptr
617 * takes the size of two stack slots; the first slot will be at
618 * spi and the second slot will be at spi - 1.
620 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
623 static struct bpf_func_state *func(struct bpf_verifier_env *env,
624 const struct bpf_reg_state *reg)
626 struct bpf_verifier_state *cur = env->cur_state;
628 return cur->frame[reg->frameno];
631 static const char *kernel_type_name(const struct btf* btf, u32 id)
633 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
636 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
638 env->scratched_regs |= 1U << regno;
641 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
643 env->scratched_stack_slots |= 1ULL << spi;
646 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
648 return (env->scratched_regs >> regno) & 1;
651 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
653 return (env->scratched_stack_slots >> regno) & 1;
656 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
658 return env->scratched_regs || env->scratched_stack_slots;
661 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
663 env->scratched_regs = 0U;
664 env->scratched_stack_slots = 0ULL;
667 /* Used for printing the entire verifier state. */
668 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
670 env->scratched_regs = ~0U;
671 env->scratched_stack_slots = ~0ULL;
674 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
676 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
677 case DYNPTR_TYPE_LOCAL:
678 return BPF_DYNPTR_TYPE_LOCAL;
679 case DYNPTR_TYPE_RINGBUF:
680 return BPF_DYNPTR_TYPE_RINGBUF;
682 return BPF_DYNPTR_TYPE_INVALID;
686 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
688 return type == BPF_DYNPTR_TYPE_RINGBUF;
691 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
692 enum bpf_arg_type arg_type, int insn_idx)
694 struct bpf_func_state *state = func(env, reg);
695 enum bpf_dynptr_type type;
698 spi = get_spi(reg->off);
700 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
703 for (i = 0; i < BPF_REG_SIZE; i++) {
704 state->stack[spi].slot_type[i] = STACK_DYNPTR;
705 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
708 type = arg_to_dynptr_type(arg_type);
709 if (type == BPF_DYNPTR_TYPE_INVALID)
712 state->stack[spi].spilled_ptr.dynptr.first_slot = true;
713 state->stack[spi].spilled_ptr.dynptr.type = type;
714 state->stack[spi - 1].spilled_ptr.dynptr.type = type;
716 if (dynptr_type_refcounted(type)) {
717 /* The id is used to track proper releasing */
718 id = acquire_reference_state(env, insn_idx);
722 state->stack[spi].spilled_ptr.id = id;
723 state->stack[spi - 1].spilled_ptr.id = id;
729 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
731 struct bpf_func_state *state = func(env, reg);
734 spi = get_spi(reg->off);
736 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
739 for (i = 0; i < BPF_REG_SIZE; i++) {
740 state->stack[spi].slot_type[i] = STACK_INVALID;
741 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
744 /* Invalidate any slices associated with this dynptr */
745 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
746 release_reference(env, state->stack[spi].spilled_ptr.id);
747 state->stack[spi].spilled_ptr.id = 0;
748 state->stack[spi - 1].spilled_ptr.id = 0;
751 state->stack[spi].spilled_ptr.dynptr.first_slot = false;
752 state->stack[spi].spilled_ptr.dynptr.type = 0;
753 state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
758 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
760 struct bpf_func_state *state = func(env, reg);
761 int spi = get_spi(reg->off);
764 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
767 for (i = 0; i < BPF_REG_SIZE; i++) {
768 if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
769 state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
776 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
777 enum bpf_arg_type arg_type)
779 struct bpf_func_state *state = func(env, reg);
780 int spi = get_spi(reg->off);
783 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
784 !state->stack[spi].spilled_ptr.dynptr.first_slot)
787 for (i = 0; i < BPF_REG_SIZE; i++) {
788 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
789 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
793 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
794 if (arg_type == ARG_PTR_TO_DYNPTR)
797 return state->stack[spi].spilled_ptr.dynptr.type == arg_to_dynptr_type(arg_type);
800 /* The reg state of a pointer or a bounded scalar was saved when
801 * it was spilled to the stack.
803 static bool is_spilled_reg(const struct bpf_stack_state *stack)
805 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
808 static void scrub_spilled_slot(u8 *stype)
810 if (*stype != STACK_INVALID)
814 static void print_verifier_state(struct bpf_verifier_env *env,
815 const struct bpf_func_state *state,
818 const struct bpf_reg_state *reg;
823 verbose(env, " frame%d:", state->frameno);
824 for (i = 0; i < MAX_BPF_REG; i++) {
825 reg = &state->regs[i];
829 if (!print_all && !reg_scratched(env, i))
831 verbose(env, " R%d", i);
832 print_liveness(env, reg->live);
834 if (t == SCALAR_VALUE && reg->precise)
836 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
837 tnum_is_const(reg->var_off)) {
838 /* reg->off should be 0 for SCALAR_VALUE */
839 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
840 verbose(env, "%lld", reg->var_off.value + reg->off);
842 const char *sep = "";
844 verbose(env, "%s", reg_type_str(env, t));
845 if (base_type(t) == PTR_TO_BTF_ID)
846 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
849 * _a stands for append, was shortened to avoid multiline statements below.
850 * This macro is used to output a comma separated list of attributes.
852 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
855 verbose_a("id=%d", reg->id);
856 if (reg_type_may_be_refcounted_or_null(t) && reg->ref_obj_id)
857 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
858 if (t != SCALAR_VALUE)
859 verbose_a("off=%d", reg->off);
860 if (type_is_pkt_pointer(t))
861 verbose_a("r=%d", reg->range);
862 else if (base_type(t) == CONST_PTR_TO_MAP ||
863 base_type(t) == PTR_TO_MAP_KEY ||
864 base_type(t) == PTR_TO_MAP_VALUE)
865 verbose_a("ks=%d,vs=%d",
866 reg->map_ptr->key_size,
867 reg->map_ptr->value_size);
868 if (tnum_is_const(reg->var_off)) {
869 /* Typically an immediate SCALAR_VALUE, but
870 * could be a pointer whose offset is too big
873 verbose_a("imm=%llx", reg->var_off.value);
875 if (reg->smin_value != reg->umin_value &&
876 reg->smin_value != S64_MIN)
877 verbose_a("smin=%lld", (long long)reg->smin_value);
878 if (reg->smax_value != reg->umax_value &&
879 reg->smax_value != S64_MAX)
880 verbose_a("smax=%lld", (long long)reg->smax_value);
881 if (reg->umin_value != 0)
882 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
883 if (reg->umax_value != U64_MAX)
884 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
885 if (!tnum_is_unknown(reg->var_off)) {
888 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
889 verbose_a("var_off=%s", tn_buf);
891 if (reg->s32_min_value != reg->smin_value &&
892 reg->s32_min_value != S32_MIN)
893 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
894 if (reg->s32_max_value != reg->smax_value &&
895 reg->s32_max_value != S32_MAX)
896 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
897 if (reg->u32_min_value != reg->umin_value &&
898 reg->u32_min_value != U32_MIN)
899 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
900 if (reg->u32_max_value != reg->umax_value &&
901 reg->u32_max_value != U32_MAX)
902 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
909 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
910 char types_buf[BPF_REG_SIZE + 1];
914 for (j = 0; j < BPF_REG_SIZE; j++) {
915 if (state->stack[i].slot_type[j] != STACK_INVALID)
917 types_buf[j] = slot_type_char[
918 state->stack[i].slot_type[j]];
920 types_buf[BPF_REG_SIZE] = 0;
923 if (!print_all && !stack_slot_scratched(env, i))
925 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
926 print_liveness(env, state->stack[i].spilled_ptr.live);
927 if (is_spilled_reg(&state->stack[i])) {
928 reg = &state->stack[i].spilled_ptr;
930 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
931 if (t == SCALAR_VALUE && reg->precise)
933 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
934 verbose(env, "%lld", reg->var_off.value + reg->off);
936 verbose(env, "=%s", types_buf);
939 if (state->acquired_refs && state->refs[0].id) {
940 verbose(env, " refs=%d", state->refs[0].id);
941 for (i = 1; i < state->acquired_refs; i++)
942 if (state->refs[i].id)
943 verbose(env, ",%d", state->refs[i].id);
945 if (state->in_callback_fn)
947 if (state->in_async_callback_fn)
948 verbose(env, " async_cb");
950 mark_verifier_state_clean(env);
953 static inline u32 vlog_alignment(u32 pos)
955 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
956 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
959 static void print_insn_state(struct bpf_verifier_env *env,
960 const struct bpf_func_state *state)
962 if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
963 /* remove new line character */
964 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
965 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
967 verbose(env, "%d:", env->insn_idx);
969 print_verifier_state(env, state, false);
972 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
973 * small to hold src. This is different from krealloc since we don't want to preserve
974 * the contents of dst.
976 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
979 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
983 if (ZERO_OR_NULL_PTR(src))
986 if (unlikely(check_mul_overflow(n, size, &bytes)))
989 if (ksize(dst) < bytes) {
991 dst = kmalloc_track_caller(bytes, flags);
996 memcpy(dst, src, bytes);
998 return dst ? dst : ZERO_SIZE_PTR;
1001 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1002 * small to hold new_n items. new items are zeroed out if the array grows.
1004 * Contrary to krealloc_array, does not free arr if new_n is zero.
1006 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1008 if (!new_n || old_n == new_n)
1011 arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
1016 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1019 return arr ? arr : ZERO_SIZE_PTR;
1022 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1024 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1025 sizeof(struct bpf_reference_state), GFP_KERNEL);
1029 dst->acquired_refs = src->acquired_refs;
1033 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1035 size_t n = src->allocated_stack / BPF_REG_SIZE;
1037 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1042 dst->allocated_stack = src->allocated_stack;
1046 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1048 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1049 sizeof(struct bpf_reference_state));
1053 state->acquired_refs = n;
1057 static int grow_stack_state(struct bpf_func_state *state, int size)
1059 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1064 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1068 state->allocated_stack = size;
1072 /* Acquire a pointer id from the env and update the state->refs to include
1073 * this new pointer reference.
1074 * On success, returns a valid pointer id to associate with the register
1075 * On failure, returns a negative errno.
1077 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1079 struct bpf_func_state *state = cur_func(env);
1080 int new_ofs = state->acquired_refs;
1083 err = resize_reference_state(state, state->acquired_refs + 1);
1087 state->refs[new_ofs].id = id;
1088 state->refs[new_ofs].insn_idx = insn_idx;
1093 /* release function corresponding to acquire_reference_state(). Idempotent. */
1094 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1098 last_idx = state->acquired_refs - 1;
1099 for (i = 0; i < state->acquired_refs; i++) {
1100 if (state->refs[i].id == ptr_id) {
1101 if (last_idx && i != last_idx)
1102 memcpy(&state->refs[i], &state->refs[last_idx],
1103 sizeof(*state->refs));
1104 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1105 state->acquired_refs--;
1112 static void free_func_state(struct bpf_func_state *state)
1117 kfree(state->stack);
1121 static void clear_jmp_history(struct bpf_verifier_state *state)
1123 kfree(state->jmp_history);
1124 state->jmp_history = NULL;
1125 state->jmp_history_cnt = 0;
1128 static void free_verifier_state(struct bpf_verifier_state *state,
1133 for (i = 0; i <= state->curframe; i++) {
1134 free_func_state(state->frame[i]);
1135 state->frame[i] = NULL;
1137 clear_jmp_history(state);
1142 /* copy verifier state from src to dst growing dst stack space
1143 * when necessary to accommodate larger src stack
1145 static int copy_func_state(struct bpf_func_state *dst,
1146 const struct bpf_func_state *src)
1150 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1151 err = copy_reference_state(dst, src);
1154 return copy_stack_state(dst, src);
1157 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1158 const struct bpf_verifier_state *src)
1160 struct bpf_func_state *dst;
1163 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1164 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1166 if (!dst_state->jmp_history)
1168 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1170 /* if dst has more stack frames then src frame, free them */
1171 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1172 free_func_state(dst_state->frame[i]);
1173 dst_state->frame[i] = NULL;
1175 dst_state->speculative = src->speculative;
1176 dst_state->curframe = src->curframe;
1177 dst_state->active_spin_lock = src->active_spin_lock;
1178 dst_state->branches = src->branches;
1179 dst_state->parent = src->parent;
1180 dst_state->first_insn_idx = src->first_insn_idx;
1181 dst_state->last_insn_idx = src->last_insn_idx;
1182 for (i = 0; i <= src->curframe; i++) {
1183 dst = dst_state->frame[i];
1185 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1188 dst_state->frame[i] = dst;
1190 err = copy_func_state(dst, src->frame[i]);
1197 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1200 u32 br = --st->branches;
1202 /* WARN_ON(br > 1) technically makes sense here,
1203 * but see comment in push_stack(), hence:
1205 WARN_ONCE((int)br < 0,
1206 "BUG update_branch_counts:branches_to_explore=%d\n",
1214 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1215 int *insn_idx, bool pop_log)
1217 struct bpf_verifier_state *cur = env->cur_state;
1218 struct bpf_verifier_stack_elem *elem, *head = env->head;
1221 if (env->head == NULL)
1225 err = copy_verifier_state(cur, &head->st);
1230 bpf_vlog_reset(&env->log, head->log_pos);
1232 *insn_idx = head->insn_idx;
1234 *prev_insn_idx = head->prev_insn_idx;
1236 free_verifier_state(&head->st, false);
1243 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1244 int insn_idx, int prev_insn_idx,
1247 struct bpf_verifier_state *cur = env->cur_state;
1248 struct bpf_verifier_stack_elem *elem;
1251 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1255 elem->insn_idx = insn_idx;
1256 elem->prev_insn_idx = prev_insn_idx;
1257 elem->next = env->head;
1258 elem->log_pos = env->log.len_used;
1261 err = copy_verifier_state(&elem->st, cur);
1264 elem->st.speculative |= speculative;
1265 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1266 verbose(env, "The sequence of %d jumps is too complex.\n",
1270 if (elem->st.parent) {
1271 ++elem->st.parent->branches;
1272 /* WARN_ON(branches > 2) technically makes sense here,
1274 * 1. speculative states will bump 'branches' for non-branch
1276 * 2. is_state_visited() heuristics may decide not to create
1277 * a new state for a sequence of branches and all such current
1278 * and cloned states will be pointing to a single parent state
1279 * which might have large 'branches' count.
1284 free_verifier_state(env->cur_state, true);
1285 env->cur_state = NULL;
1286 /* pop all elements and return */
1287 while (!pop_stack(env, NULL, NULL, false));
1291 #define CALLER_SAVED_REGS 6
1292 static const int caller_saved[CALLER_SAVED_REGS] = {
1293 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1296 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1297 struct bpf_reg_state *reg);
1299 /* This helper doesn't clear reg->id */
1300 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1302 reg->var_off = tnum_const(imm);
1303 reg->smin_value = (s64)imm;
1304 reg->smax_value = (s64)imm;
1305 reg->umin_value = imm;
1306 reg->umax_value = imm;
1308 reg->s32_min_value = (s32)imm;
1309 reg->s32_max_value = (s32)imm;
1310 reg->u32_min_value = (u32)imm;
1311 reg->u32_max_value = (u32)imm;
1314 /* Mark the unknown part of a register (variable offset or scalar value) as
1315 * known to have the value @imm.
1317 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1319 /* Clear id, off, and union(map_ptr, range) */
1320 memset(((u8 *)reg) + sizeof(reg->type), 0,
1321 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1322 ___mark_reg_known(reg, imm);
1325 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1327 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1328 reg->s32_min_value = (s32)imm;
1329 reg->s32_max_value = (s32)imm;
1330 reg->u32_min_value = (u32)imm;
1331 reg->u32_max_value = (u32)imm;
1334 /* Mark the 'variable offset' part of a register as zero. This should be
1335 * used only on registers holding a pointer type.
1337 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1339 __mark_reg_known(reg, 0);
1342 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1344 __mark_reg_known(reg, 0);
1345 reg->type = SCALAR_VALUE;
1348 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1349 struct bpf_reg_state *regs, u32 regno)
1351 if (WARN_ON(regno >= MAX_BPF_REG)) {
1352 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1353 /* Something bad happened, let's kill all regs */
1354 for (regno = 0; regno < MAX_BPF_REG; regno++)
1355 __mark_reg_not_init(env, regs + regno);
1358 __mark_reg_known_zero(regs + regno);
1361 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1363 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1364 const struct bpf_map *map = reg->map_ptr;
1366 if (map->inner_map_meta) {
1367 reg->type = CONST_PTR_TO_MAP;
1368 reg->map_ptr = map->inner_map_meta;
1369 /* transfer reg's id which is unique for every map_lookup_elem
1370 * as UID of the inner map.
1372 if (map_value_has_timer(map->inner_map_meta))
1373 reg->map_uid = reg->id;
1374 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1375 reg->type = PTR_TO_XDP_SOCK;
1376 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1377 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1378 reg->type = PTR_TO_SOCKET;
1380 reg->type = PTR_TO_MAP_VALUE;
1385 reg->type &= ~PTR_MAYBE_NULL;
1388 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1390 return type_is_pkt_pointer(reg->type);
1393 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1395 return reg_is_pkt_pointer(reg) ||
1396 reg->type == PTR_TO_PACKET_END;
1399 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1400 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1401 enum bpf_reg_type which)
1403 /* The register can already have a range from prior markings.
1404 * This is fine as long as it hasn't been advanced from its
1407 return reg->type == which &&
1410 tnum_equals_const(reg->var_off, 0);
1413 /* Reset the min/max bounds of a register */
1414 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1416 reg->smin_value = S64_MIN;
1417 reg->smax_value = S64_MAX;
1418 reg->umin_value = 0;
1419 reg->umax_value = U64_MAX;
1421 reg->s32_min_value = S32_MIN;
1422 reg->s32_max_value = S32_MAX;
1423 reg->u32_min_value = 0;
1424 reg->u32_max_value = U32_MAX;
1427 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1429 reg->smin_value = S64_MIN;
1430 reg->smax_value = S64_MAX;
1431 reg->umin_value = 0;
1432 reg->umax_value = U64_MAX;
1435 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1437 reg->s32_min_value = S32_MIN;
1438 reg->s32_max_value = S32_MAX;
1439 reg->u32_min_value = 0;
1440 reg->u32_max_value = U32_MAX;
1443 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1445 struct tnum var32_off = tnum_subreg(reg->var_off);
1447 /* min signed is max(sign bit) | min(other bits) */
1448 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1449 var32_off.value | (var32_off.mask & S32_MIN));
1450 /* max signed is min(sign bit) | max(other bits) */
1451 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1452 var32_off.value | (var32_off.mask & S32_MAX));
1453 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1454 reg->u32_max_value = min(reg->u32_max_value,
1455 (u32)(var32_off.value | var32_off.mask));
1458 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1460 /* min signed is max(sign bit) | min(other bits) */
1461 reg->smin_value = max_t(s64, reg->smin_value,
1462 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1463 /* max signed is min(sign bit) | max(other bits) */
1464 reg->smax_value = min_t(s64, reg->smax_value,
1465 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1466 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1467 reg->umax_value = min(reg->umax_value,
1468 reg->var_off.value | reg->var_off.mask);
1471 static void __update_reg_bounds(struct bpf_reg_state *reg)
1473 __update_reg32_bounds(reg);
1474 __update_reg64_bounds(reg);
1477 /* Uses signed min/max values to inform unsigned, and vice-versa */
1478 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1480 /* Learn sign from signed bounds.
1481 * If we cannot cross the sign boundary, then signed and unsigned bounds
1482 * are the same, so combine. This works even in the negative case, e.g.
1483 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1485 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1486 reg->s32_min_value = reg->u32_min_value =
1487 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1488 reg->s32_max_value = reg->u32_max_value =
1489 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1492 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1493 * boundary, so we must be careful.
1495 if ((s32)reg->u32_max_value >= 0) {
1496 /* Positive. We can't learn anything from the smin, but smax
1497 * is positive, hence safe.
1499 reg->s32_min_value = reg->u32_min_value;
1500 reg->s32_max_value = reg->u32_max_value =
1501 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1502 } else if ((s32)reg->u32_min_value < 0) {
1503 /* Negative. We can't learn anything from the smax, but smin
1504 * is negative, hence safe.
1506 reg->s32_min_value = reg->u32_min_value =
1507 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1508 reg->s32_max_value = reg->u32_max_value;
1512 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1514 /* Learn sign from signed bounds.
1515 * If we cannot cross the sign boundary, then signed and unsigned bounds
1516 * are the same, so combine. This works even in the negative case, e.g.
1517 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1519 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1520 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1522 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1526 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1527 * boundary, so we must be careful.
1529 if ((s64)reg->umax_value >= 0) {
1530 /* Positive. We can't learn anything from the smin, but smax
1531 * is positive, hence safe.
1533 reg->smin_value = reg->umin_value;
1534 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1536 } else if ((s64)reg->umin_value < 0) {
1537 /* Negative. We can't learn anything from the smax, but smin
1538 * is negative, hence safe.
1540 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1542 reg->smax_value = reg->umax_value;
1546 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1548 __reg32_deduce_bounds(reg);
1549 __reg64_deduce_bounds(reg);
1552 /* Attempts to improve var_off based on unsigned min/max information */
1553 static void __reg_bound_offset(struct bpf_reg_state *reg)
1555 struct tnum var64_off = tnum_intersect(reg->var_off,
1556 tnum_range(reg->umin_value,
1558 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1559 tnum_range(reg->u32_min_value,
1560 reg->u32_max_value));
1562 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1565 static void reg_bounds_sync(struct bpf_reg_state *reg)
1567 /* We might have learned new bounds from the var_off. */
1568 __update_reg_bounds(reg);
1569 /* We might have learned something about the sign bit. */
1570 __reg_deduce_bounds(reg);
1571 /* We might have learned some bits from the bounds. */
1572 __reg_bound_offset(reg);
1573 /* Intersecting with the old var_off might have improved our bounds
1574 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1575 * then new var_off is (0; 0x7f...fc) which improves our umax.
1577 __update_reg_bounds(reg);
1580 static bool __reg32_bound_s64(s32 a)
1582 return a >= 0 && a <= S32_MAX;
1585 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1587 reg->umin_value = reg->u32_min_value;
1588 reg->umax_value = reg->u32_max_value;
1590 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1591 * be positive otherwise set to worse case bounds and refine later
1594 if (__reg32_bound_s64(reg->s32_min_value) &&
1595 __reg32_bound_s64(reg->s32_max_value)) {
1596 reg->smin_value = reg->s32_min_value;
1597 reg->smax_value = reg->s32_max_value;
1599 reg->smin_value = 0;
1600 reg->smax_value = U32_MAX;
1604 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1606 /* special case when 64-bit register has upper 32-bit register
1607 * zeroed. Typically happens after zext or <<32, >>32 sequence
1608 * allowing us to use 32-bit bounds directly,
1610 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1611 __reg_assign_32_into_64(reg);
1613 /* Otherwise the best we can do is push lower 32bit known and
1614 * unknown bits into register (var_off set from jmp logic)
1615 * then learn as much as possible from the 64-bit tnum
1616 * known and unknown bits. The previous smin/smax bounds are
1617 * invalid here because of jmp32 compare so mark them unknown
1618 * so they do not impact tnum bounds calculation.
1620 __mark_reg64_unbounded(reg);
1622 reg_bounds_sync(reg);
1625 static bool __reg64_bound_s32(s64 a)
1627 return a >= S32_MIN && a <= S32_MAX;
1630 static bool __reg64_bound_u32(u64 a)
1632 return a >= U32_MIN && a <= U32_MAX;
1635 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1637 __mark_reg32_unbounded(reg);
1638 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1639 reg->s32_min_value = (s32)reg->smin_value;
1640 reg->s32_max_value = (s32)reg->smax_value;
1642 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1643 reg->u32_min_value = (u32)reg->umin_value;
1644 reg->u32_max_value = (u32)reg->umax_value;
1646 reg_bounds_sync(reg);
1649 /* Mark a register as having a completely unknown (scalar) value. */
1650 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1651 struct bpf_reg_state *reg)
1654 * Clear type, id, off, and union(map_ptr, range) and
1655 * padding between 'type' and union
1657 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1658 reg->type = SCALAR_VALUE;
1659 reg->var_off = tnum_unknown;
1661 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1662 __mark_reg_unbounded(reg);
1665 static void mark_reg_unknown(struct bpf_verifier_env *env,
1666 struct bpf_reg_state *regs, u32 regno)
1668 if (WARN_ON(regno >= MAX_BPF_REG)) {
1669 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1670 /* Something bad happened, let's kill all regs except FP */
1671 for (regno = 0; regno < BPF_REG_FP; regno++)
1672 __mark_reg_not_init(env, regs + regno);
1675 __mark_reg_unknown(env, regs + regno);
1678 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1679 struct bpf_reg_state *reg)
1681 __mark_reg_unknown(env, reg);
1682 reg->type = NOT_INIT;
1685 static void mark_reg_not_init(struct bpf_verifier_env *env,
1686 struct bpf_reg_state *regs, u32 regno)
1688 if (WARN_ON(regno >= MAX_BPF_REG)) {
1689 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1690 /* Something bad happened, let's kill all regs except FP */
1691 for (regno = 0; regno < BPF_REG_FP; regno++)
1692 __mark_reg_not_init(env, regs + regno);
1695 __mark_reg_not_init(env, regs + regno);
1698 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1699 struct bpf_reg_state *regs, u32 regno,
1700 enum bpf_reg_type reg_type,
1701 struct btf *btf, u32 btf_id,
1702 enum bpf_type_flag flag)
1704 if (reg_type == SCALAR_VALUE) {
1705 mark_reg_unknown(env, regs, regno);
1708 mark_reg_known_zero(env, regs, regno);
1709 regs[regno].type = PTR_TO_BTF_ID | flag;
1710 regs[regno].btf = btf;
1711 regs[regno].btf_id = btf_id;
1714 #define DEF_NOT_SUBREG (0)
1715 static void init_reg_state(struct bpf_verifier_env *env,
1716 struct bpf_func_state *state)
1718 struct bpf_reg_state *regs = state->regs;
1721 for (i = 0; i < MAX_BPF_REG; i++) {
1722 mark_reg_not_init(env, regs, i);
1723 regs[i].live = REG_LIVE_NONE;
1724 regs[i].parent = NULL;
1725 regs[i].subreg_def = DEF_NOT_SUBREG;
1729 regs[BPF_REG_FP].type = PTR_TO_STACK;
1730 mark_reg_known_zero(env, regs, BPF_REG_FP);
1731 regs[BPF_REG_FP].frameno = state->frameno;
1734 #define BPF_MAIN_FUNC (-1)
1735 static void init_func_state(struct bpf_verifier_env *env,
1736 struct bpf_func_state *state,
1737 int callsite, int frameno, int subprogno)
1739 state->callsite = callsite;
1740 state->frameno = frameno;
1741 state->subprogno = subprogno;
1742 init_reg_state(env, state);
1743 mark_verifier_state_scratched(env);
1746 /* Similar to push_stack(), but for async callbacks */
1747 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1748 int insn_idx, int prev_insn_idx,
1751 struct bpf_verifier_stack_elem *elem;
1752 struct bpf_func_state *frame;
1754 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1758 elem->insn_idx = insn_idx;
1759 elem->prev_insn_idx = prev_insn_idx;
1760 elem->next = env->head;
1761 elem->log_pos = env->log.len_used;
1764 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1766 "The sequence of %d jumps is too complex for async cb.\n",
1770 /* Unlike push_stack() do not copy_verifier_state().
1771 * The caller state doesn't matter.
1772 * This is async callback. It starts in a fresh stack.
1773 * Initialize it similar to do_check_common().
1775 elem->st.branches = 1;
1776 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1779 init_func_state(env, frame,
1780 BPF_MAIN_FUNC /* callsite */,
1781 0 /* frameno within this callchain */,
1782 subprog /* subprog number within this prog */);
1783 elem->st.frame[0] = frame;
1786 free_verifier_state(env->cur_state, true);
1787 env->cur_state = NULL;
1788 /* pop all elements and return */
1789 while (!pop_stack(env, NULL, NULL, false));
1795 SRC_OP, /* register is used as source operand */
1796 DST_OP, /* register is used as destination operand */
1797 DST_OP_NO_MARK /* same as above, check only, don't mark */
1800 static int cmp_subprogs(const void *a, const void *b)
1802 return ((struct bpf_subprog_info *)a)->start -
1803 ((struct bpf_subprog_info *)b)->start;
1806 static int find_subprog(struct bpf_verifier_env *env, int off)
1808 struct bpf_subprog_info *p;
1810 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1811 sizeof(env->subprog_info[0]), cmp_subprogs);
1814 return p - env->subprog_info;
1818 static int add_subprog(struct bpf_verifier_env *env, int off)
1820 int insn_cnt = env->prog->len;
1823 if (off >= insn_cnt || off < 0) {
1824 verbose(env, "call to invalid destination\n");
1827 ret = find_subprog(env, off);
1830 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1831 verbose(env, "too many subprograms\n");
1834 /* determine subprog starts. The end is one before the next starts */
1835 env->subprog_info[env->subprog_cnt++].start = off;
1836 sort(env->subprog_info, env->subprog_cnt,
1837 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1838 return env->subprog_cnt - 1;
1841 #define MAX_KFUNC_DESCS 256
1842 #define MAX_KFUNC_BTFS 256
1844 struct bpf_kfunc_desc {
1845 struct btf_func_model func_model;
1851 struct bpf_kfunc_btf {
1853 struct module *module;
1857 struct bpf_kfunc_desc_tab {
1858 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1862 struct bpf_kfunc_btf_tab {
1863 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1867 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1869 const struct bpf_kfunc_desc *d0 = a;
1870 const struct bpf_kfunc_desc *d1 = b;
1872 /* func_id is not greater than BTF_MAX_TYPE */
1873 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1876 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1878 const struct bpf_kfunc_btf *d0 = a;
1879 const struct bpf_kfunc_btf *d1 = b;
1881 return d0->offset - d1->offset;
1884 static const struct bpf_kfunc_desc *
1885 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1887 struct bpf_kfunc_desc desc = {
1891 struct bpf_kfunc_desc_tab *tab;
1893 tab = prog->aux->kfunc_tab;
1894 return bsearch(&desc, tab->descs, tab->nr_descs,
1895 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1898 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1901 struct bpf_kfunc_btf kf_btf = { .offset = offset };
1902 struct bpf_kfunc_btf_tab *tab;
1903 struct bpf_kfunc_btf *b;
1908 tab = env->prog->aux->kfunc_btf_tab;
1909 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1910 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1912 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1913 verbose(env, "too many different module BTFs\n");
1914 return ERR_PTR(-E2BIG);
1917 if (bpfptr_is_null(env->fd_array)) {
1918 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1919 return ERR_PTR(-EPROTO);
1922 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1923 offset * sizeof(btf_fd),
1925 return ERR_PTR(-EFAULT);
1927 btf = btf_get_by_fd(btf_fd);
1929 verbose(env, "invalid module BTF fd specified\n");
1933 if (!btf_is_module(btf)) {
1934 verbose(env, "BTF fd for kfunc is not a module BTF\n");
1936 return ERR_PTR(-EINVAL);
1939 mod = btf_try_get_module(btf);
1942 return ERR_PTR(-ENXIO);
1945 b = &tab->descs[tab->nr_descs++];
1950 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1951 kfunc_btf_cmp_by_off, NULL);
1956 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1961 while (tab->nr_descs--) {
1962 module_put(tab->descs[tab->nr_descs].module);
1963 btf_put(tab->descs[tab->nr_descs].btf);
1968 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
1972 /* In the future, this can be allowed to increase limit
1973 * of fd index into fd_array, interpreted as u16.
1975 verbose(env, "negative offset disallowed for kernel module function call\n");
1976 return ERR_PTR(-EINVAL);
1979 return __find_kfunc_desc_btf(env, offset);
1981 return btf_vmlinux ?: ERR_PTR(-ENOENT);
1984 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
1986 const struct btf_type *func, *func_proto;
1987 struct bpf_kfunc_btf_tab *btf_tab;
1988 struct bpf_kfunc_desc_tab *tab;
1989 struct bpf_prog_aux *prog_aux;
1990 struct bpf_kfunc_desc *desc;
1991 const char *func_name;
1992 struct btf *desc_btf;
1993 unsigned long call_imm;
1997 prog_aux = env->prog->aux;
1998 tab = prog_aux->kfunc_tab;
1999 btf_tab = prog_aux->kfunc_btf_tab;
2002 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2006 if (!env->prog->jit_requested) {
2007 verbose(env, "JIT is required for calling kernel function\n");
2011 if (!bpf_jit_supports_kfunc_call()) {
2012 verbose(env, "JIT does not support calling kernel function\n");
2016 if (!env->prog->gpl_compatible) {
2017 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2021 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2024 prog_aux->kfunc_tab = tab;
2027 /* func_id == 0 is always invalid, but instead of returning an error, be
2028 * conservative and wait until the code elimination pass before returning
2029 * error, so that invalid calls that get pruned out can be in BPF programs
2030 * loaded from userspace. It is also required that offset be untouched
2033 if (!func_id && !offset)
2036 if (!btf_tab && offset) {
2037 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2040 prog_aux->kfunc_btf_tab = btf_tab;
2043 desc_btf = find_kfunc_desc_btf(env, offset);
2044 if (IS_ERR(desc_btf)) {
2045 verbose(env, "failed to find BTF for kernel function\n");
2046 return PTR_ERR(desc_btf);
2049 if (find_kfunc_desc(env->prog, func_id, offset))
2052 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2053 verbose(env, "too many different kernel function calls\n");
2057 func = btf_type_by_id(desc_btf, func_id);
2058 if (!func || !btf_type_is_func(func)) {
2059 verbose(env, "kernel btf_id %u is not a function\n",
2063 func_proto = btf_type_by_id(desc_btf, func->type);
2064 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2065 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2070 func_name = btf_name_by_offset(desc_btf, func->name_off);
2071 addr = kallsyms_lookup_name(func_name);
2073 verbose(env, "cannot find address for kernel function %s\n",
2078 call_imm = BPF_CALL_IMM(addr);
2079 /* Check whether or not the relative offset overflows desc->imm */
2080 if ((unsigned long)(s32)call_imm != call_imm) {
2081 verbose(env, "address of kernel function %s is out of range\n",
2086 desc = &tab->descs[tab->nr_descs++];
2087 desc->func_id = func_id;
2088 desc->imm = call_imm;
2089 desc->offset = offset;
2090 err = btf_distill_func_proto(&env->log, desc_btf,
2091 func_proto, func_name,
2094 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2095 kfunc_desc_cmp_by_id_off, NULL);
2099 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2101 const struct bpf_kfunc_desc *d0 = a;
2102 const struct bpf_kfunc_desc *d1 = b;
2104 if (d0->imm > d1->imm)
2106 else if (d0->imm < d1->imm)
2111 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2113 struct bpf_kfunc_desc_tab *tab;
2115 tab = prog->aux->kfunc_tab;
2119 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2120 kfunc_desc_cmp_by_imm, NULL);
2123 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2125 return !!prog->aux->kfunc_tab;
2128 const struct btf_func_model *
2129 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2130 const struct bpf_insn *insn)
2132 const struct bpf_kfunc_desc desc = {
2135 const struct bpf_kfunc_desc *res;
2136 struct bpf_kfunc_desc_tab *tab;
2138 tab = prog->aux->kfunc_tab;
2139 res = bsearch(&desc, tab->descs, tab->nr_descs,
2140 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2142 return res ? &res->func_model : NULL;
2145 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2147 struct bpf_subprog_info *subprog = env->subprog_info;
2148 struct bpf_insn *insn = env->prog->insnsi;
2149 int i, ret, insn_cnt = env->prog->len;
2151 /* Add entry function. */
2152 ret = add_subprog(env, 0);
2156 for (i = 0; i < insn_cnt; i++, insn++) {
2157 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2158 !bpf_pseudo_kfunc_call(insn))
2161 if (!env->bpf_capable) {
2162 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2166 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2167 ret = add_subprog(env, i + insn->imm + 1);
2169 ret = add_kfunc_call(env, insn->imm, insn->off);
2175 /* Add a fake 'exit' subprog which could simplify subprog iteration
2176 * logic. 'subprog_cnt' should not be increased.
2178 subprog[env->subprog_cnt].start = insn_cnt;
2180 if (env->log.level & BPF_LOG_LEVEL2)
2181 for (i = 0; i < env->subprog_cnt; i++)
2182 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2187 static int check_subprogs(struct bpf_verifier_env *env)
2189 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2190 struct bpf_subprog_info *subprog = env->subprog_info;
2191 struct bpf_insn *insn = env->prog->insnsi;
2192 int insn_cnt = env->prog->len;
2194 /* now check that all jumps are within the same subprog */
2195 subprog_start = subprog[cur_subprog].start;
2196 subprog_end = subprog[cur_subprog + 1].start;
2197 for (i = 0; i < insn_cnt; i++) {
2198 u8 code = insn[i].code;
2200 if (code == (BPF_JMP | BPF_CALL) &&
2201 insn[i].imm == BPF_FUNC_tail_call &&
2202 insn[i].src_reg != BPF_PSEUDO_CALL)
2203 subprog[cur_subprog].has_tail_call = true;
2204 if (BPF_CLASS(code) == BPF_LD &&
2205 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2206 subprog[cur_subprog].has_ld_abs = true;
2207 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2209 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2211 off = i + insn[i].off + 1;
2212 if (off < subprog_start || off >= subprog_end) {
2213 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2217 if (i == subprog_end - 1) {
2218 /* to avoid fall-through from one subprog into another
2219 * the last insn of the subprog should be either exit
2220 * or unconditional jump back
2222 if (code != (BPF_JMP | BPF_EXIT) &&
2223 code != (BPF_JMP | BPF_JA)) {
2224 verbose(env, "last insn is not an exit or jmp\n");
2227 subprog_start = subprog_end;
2229 if (cur_subprog < env->subprog_cnt)
2230 subprog_end = subprog[cur_subprog + 1].start;
2236 /* Parentage chain of this register (or stack slot) should take care of all
2237 * issues like callee-saved registers, stack slot allocation time, etc.
2239 static int mark_reg_read(struct bpf_verifier_env *env,
2240 const struct bpf_reg_state *state,
2241 struct bpf_reg_state *parent, u8 flag)
2243 bool writes = parent == state->parent; /* Observe write marks */
2247 /* if read wasn't screened by an earlier write ... */
2248 if (writes && state->live & REG_LIVE_WRITTEN)
2250 if (parent->live & REG_LIVE_DONE) {
2251 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2252 reg_type_str(env, parent->type),
2253 parent->var_off.value, parent->off);
2256 /* The first condition is more likely to be true than the
2257 * second, checked it first.
2259 if ((parent->live & REG_LIVE_READ) == flag ||
2260 parent->live & REG_LIVE_READ64)
2261 /* The parentage chain never changes and
2262 * this parent was already marked as LIVE_READ.
2263 * There is no need to keep walking the chain again and
2264 * keep re-marking all parents as LIVE_READ.
2265 * This case happens when the same register is read
2266 * multiple times without writes into it in-between.
2267 * Also, if parent has the stronger REG_LIVE_READ64 set,
2268 * then no need to set the weak REG_LIVE_READ32.
2271 /* ... then we depend on parent's value */
2272 parent->live |= flag;
2273 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2274 if (flag == REG_LIVE_READ64)
2275 parent->live &= ~REG_LIVE_READ32;
2277 parent = state->parent;
2282 if (env->longest_mark_read_walk < cnt)
2283 env->longest_mark_read_walk = cnt;
2287 /* This function is supposed to be used by the following 32-bit optimization
2288 * code only. It returns TRUE if the source or destination register operates
2289 * on 64-bit, otherwise return FALSE.
2291 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2292 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2297 class = BPF_CLASS(code);
2299 if (class == BPF_JMP) {
2300 /* BPF_EXIT for "main" will reach here. Return TRUE
2305 if (op == BPF_CALL) {
2306 /* BPF to BPF call will reach here because of marking
2307 * caller saved clobber with DST_OP_NO_MARK for which we
2308 * don't care the register def because they are anyway
2309 * marked as NOT_INIT already.
2311 if (insn->src_reg == BPF_PSEUDO_CALL)
2313 /* Helper call will reach here because of arg type
2314 * check, conservatively return TRUE.
2323 if (class == BPF_ALU64 || class == BPF_JMP ||
2324 /* BPF_END always use BPF_ALU class. */
2325 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2328 if (class == BPF_ALU || class == BPF_JMP32)
2331 if (class == BPF_LDX) {
2333 return BPF_SIZE(code) == BPF_DW;
2334 /* LDX source must be ptr. */
2338 if (class == BPF_STX) {
2339 /* BPF_STX (including atomic variants) has multiple source
2340 * operands, one of which is a ptr. Check whether the caller is
2343 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2345 return BPF_SIZE(code) == BPF_DW;
2348 if (class == BPF_LD) {
2349 u8 mode = BPF_MODE(code);
2352 if (mode == BPF_IMM)
2355 /* Both LD_IND and LD_ABS return 32-bit data. */
2359 /* Implicit ctx ptr. */
2360 if (regno == BPF_REG_6)
2363 /* Explicit source could be any width. */
2367 if (class == BPF_ST)
2368 /* The only source register for BPF_ST is a ptr. */
2371 /* Conservatively return true at default. */
2375 /* Return the regno defined by the insn, or -1. */
2376 static int insn_def_regno(const struct bpf_insn *insn)
2378 switch (BPF_CLASS(insn->code)) {
2384 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2385 (insn->imm & BPF_FETCH)) {
2386 if (insn->imm == BPF_CMPXCHG)
2389 return insn->src_reg;
2394 return insn->dst_reg;
2398 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2399 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2401 int dst_reg = insn_def_regno(insn);
2406 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2409 static void mark_insn_zext(struct bpf_verifier_env *env,
2410 struct bpf_reg_state *reg)
2412 s32 def_idx = reg->subreg_def;
2414 if (def_idx == DEF_NOT_SUBREG)
2417 env->insn_aux_data[def_idx - 1].zext_dst = true;
2418 /* The dst will be zero extended, so won't be sub-register anymore. */
2419 reg->subreg_def = DEF_NOT_SUBREG;
2422 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2423 enum reg_arg_type t)
2425 struct bpf_verifier_state *vstate = env->cur_state;
2426 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2427 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2428 struct bpf_reg_state *reg, *regs = state->regs;
2431 if (regno >= MAX_BPF_REG) {
2432 verbose(env, "R%d is invalid\n", regno);
2436 mark_reg_scratched(env, regno);
2439 rw64 = is_reg64(env, insn, regno, reg, t);
2441 /* check whether register used as source operand can be read */
2442 if (reg->type == NOT_INIT) {
2443 verbose(env, "R%d !read_ok\n", regno);
2446 /* We don't need to worry about FP liveness because it's read-only */
2447 if (regno == BPF_REG_FP)
2451 mark_insn_zext(env, reg);
2453 return mark_reg_read(env, reg, reg->parent,
2454 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2456 /* check whether register used as dest operand can be written to */
2457 if (regno == BPF_REG_FP) {
2458 verbose(env, "frame pointer is read only\n");
2461 reg->live |= REG_LIVE_WRITTEN;
2462 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2464 mark_reg_unknown(env, regs, regno);
2469 /* for any branch, call, exit record the history of jmps in the given state */
2470 static int push_jmp_history(struct bpf_verifier_env *env,
2471 struct bpf_verifier_state *cur)
2473 u32 cnt = cur->jmp_history_cnt;
2474 struct bpf_idx_pair *p;
2477 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2480 p[cnt - 1].idx = env->insn_idx;
2481 p[cnt - 1].prev_idx = env->prev_insn_idx;
2482 cur->jmp_history = p;
2483 cur->jmp_history_cnt = cnt;
2487 /* Backtrack one insn at a time. If idx is not at the top of recorded
2488 * history then previous instruction came from straight line execution.
2490 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2495 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2496 i = st->jmp_history[cnt - 1].prev_idx;
2504 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2506 const struct btf_type *func;
2507 struct btf *desc_btf;
2509 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2512 desc_btf = find_kfunc_desc_btf(data, insn->off);
2513 if (IS_ERR(desc_btf))
2516 func = btf_type_by_id(desc_btf, insn->imm);
2517 return btf_name_by_offset(desc_btf, func->name_off);
2520 /* For given verifier state backtrack_insn() is called from the last insn to
2521 * the first insn. Its purpose is to compute a bitmask of registers and
2522 * stack slots that needs precision in the parent verifier state.
2524 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2525 u32 *reg_mask, u64 *stack_mask)
2527 const struct bpf_insn_cbs cbs = {
2528 .cb_call = disasm_kfunc_name,
2529 .cb_print = verbose,
2530 .private_data = env,
2532 struct bpf_insn *insn = env->prog->insnsi + idx;
2533 u8 class = BPF_CLASS(insn->code);
2534 u8 opcode = BPF_OP(insn->code);
2535 u8 mode = BPF_MODE(insn->code);
2536 u32 dreg = 1u << insn->dst_reg;
2537 u32 sreg = 1u << insn->src_reg;
2540 if (insn->code == 0)
2542 if (env->log.level & BPF_LOG_LEVEL2) {
2543 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2544 verbose(env, "%d: ", idx);
2545 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2548 if (class == BPF_ALU || class == BPF_ALU64) {
2549 if (!(*reg_mask & dreg))
2551 if (opcode == BPF_MOV) {
2552 if (BPF_SRC(insn->code) == BPF_X) {
2554 * dreg needs precision after this insn
2555 * sreg needs precision before this insn
2561 * dreg needs precision after this insn.
2562 * Corresponding register is already marked
2563 * as precise=true in this verifier state.
2564 * No further markings in parent are necessary
2569 if (BPF_SRC(insn->code) == BPF_X) {
2571 * both dreg and sreg need precision
2576 * dreg still needs precision before this insn
2579 } else if (class == BPF_LDX) {
2580 if (!(*reg_mask & dreg))
2584 /* scalars can only be spilled into stack w/o losing precision.
2585 * Load from any other memory can be zero extended.
2586 * The desire to keep that precision is already indicated
2587 * by 'precise' mark in corresponding register of this state.
2588 * No further tracking necessary.
2590 if (insn->src_reg != BPF_REG_FP)
2593 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2594 * that [fp - off] slot contains scalar that needs to be
2595 * tracked with precision
2597 spi = (-insn->off - 1) / BPF_REG_SIZE;
2599 verbose(env, "BUG spi %d\n", spi);
2600 WARN_ONCE(1, "verifier backtracking bug");
2603 *stack_mask |= 1ull << spi;
2604 } else if (class == BPF_STX || class == BPF_ST) {
2605 if (*reg_mask & dreg)
2606 /* stx & st shouldn't be using _scalar_ dst_reg
2607 * to access memory. It means backtracking
2608 * encountered a case of pointer subtraction.
2611 /* scalars can only be spilled into stack */
2612 if (insn->dst_reg != BPF_REG_FP)
2614 spi = (-insn->off - 1) / BPF_REG_SIZE;
2616 verbose(env, "BUG spi %d\n", spi);
2617 WARN_ONCE(1, "verifier backtracking bug");
2620 if (!(*stack_mask & (1ull << spi)))
2622 *stack_mask &= ~(1ull << spi);
2623 if (class == BPF_STX)
2625 } else if (class == BPF_JMP || class == BPF_JMP32) {
2626 if (opcode == BPF_CALL) {
2627 if (insn->src_reg == BPF_PSEUDO_CALL)
2629 /* regular helper call sets R0 */
2631 if (*reg_mask & 0x3f) {
2632 /* if backtracing was looking for registers R1-R5
2633 * they should have been found already.
2635 verbose(env, "BUG regs %x\n", *reg_mask);
2636 WARN_ONCE(1, "verifier backtracking bug");
2639 } else if (opcode == BPF_EXIT) {
2642 } else if (class == BPF_LD) {
2643 if (!(*reg_mask & dreg))
2646 /* It's ld_imm64 or ld_abs or ld_ind.
2647 * For ld_imm64 no further tracking of precision
2648 * into parent is necessary
2650 if (mode == BPF_IND || mode == BPF_ABS)
2651 /* to be analyzed */
2657 /* the scalar precision tracking algorithm:
2658 * . at the start all registers have precise=false.
2659 * . scalar ranges are tracked as normal through alu and jmp insns.
2660 * . once precise value of the scalar register is used in:
2661 * . ptr + scalar alu
2662 * . if (scalar cond K|scalar)
2663 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2664 * backtrack through the verifier states and mark all registers and
2665 * stack slots with spilled constants that these scalar regisers
2666 * should be precise.
2667 * . during state pruning two registers (or spilled stack slots)
2668 * are equivalent if both are not precise.
2670 * Note the verifier cannot simply walk register parentage chain,
2671 * since many different registers and stack slots could have been
2672 * used to compute single precise scalar.
2674 * The approach of starting with precise=true for all registers and then
2675 * backtrack to mark a register as not precise when the verifier detects
2676 * that program doesn't care about specific value (e.g., when helper
2677 * takes register as ARG_ANYTHING parameter) is not safe.
2679 * It's ok to walk single parentage chain of the verifier states.
2680 * It's possible that this backtracking will go all the way till 1st insn.
2681 * All other branches will be explored for needing precision later.
2683 * The backtracking needs to deal with cases like:
2684 * 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)
2687 * if r5 > 0x79f goto pc+7
2688 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2691 * call bpf_perf_event_output#25
2692 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2696 * call foo // uses callee's r6 inside to compute r0
2700 * to track above reg_mask/stack_mask needs to be independent for each frame.
2702 * Also if parent's curframe > frame where backtracking started,
2703 * the verifier need to mark registers in both frames, otherwise callees
2704 * may incorrectly prune callers. This is similar to
2705 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2707 * For now backtracking falls back into conservative marking.
2709 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2710 struct bpf_verifier_state *st)
2712 struct bpf_func_state *func;
2713 struct bpf_reg_state *reg;
2716 /* big hammer: mark all scalars precise in this path.
2717 * pop_stack may still get !precise scalars.
2719 for (; st; st = st->parent)
2720 for (i = 0; i <= st->curframe; i++) {
2721 func = st->frame[i];
2722 for (j = 0; j < BPF_REG_FP; j++) {
2723 reg = &func->regs[j];
2724 if (reg->type != SCALAR_VALUE)
2726 reg->precise = true;
2728 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2729 if (!is_spilled_reg(&func->stack[j]))
2731 reg = &func->stack[j].spilled_ptr;
2732 if (reg->type != SCALAR_VALUE)
2734 reg->precise = true;
2739 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2742 struct bpf_verifier_state *st = env->cur_state;
2743 int first_idx = st->first_insn_idx;
2744 int last_idx = env->insn_idx;
2745 struct bpf_func_state *func;
2746 struct bpf_reg_state *reg;
2747 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2748 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2749 bool skip_first = true;
2750 bool new_marks = false;
2753 if (!env->bpf_capable)
2756 func = st->frame[st->curframe];
2758 reg = &func->regs[regno];
2759 if (reg->type != SCALAR_VALUE) {
2760 WARN_ONCE(1, "backtracing misuse");
2767 reg->precise = true;
2771 if (!is_spilled_reg(&func->stack[spi])) {
2775 reg = &func->stack[spi].spilled_ptr;
2776 if (reg->type != SCALAR_VALUE) {
2784 reg->precise = true;
2790 if (!reg_mask && !stack_mask)
2793 DECLARE_BITMAP(mask, 64);
2794 u32 history = st->jmp_history_cnt;
2796 if (env->log.level & BPF_LOG_LEVEL2)
2797 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2798 for (i = last_idx;;) {
2803 err = backtrack_insn(env, i, ®_mask, &stack_mask);
2805 if (err == -ENOTSUPP) {
2806 mark_all_scalars_precise(env, st);
2811 if (!reg_mask && !stack_mask)
2812 /* Found assignment(s) into tracked register in this state.
2813 * Since this state is already marked, just return.
2814 * Nothing to be tracked further in the parent state.
2819 i = get_prev_insn_idx(st, i, &history);
2820 if (i >= env->prog->len) {
2821 /* This can happen if backtracking reached insn 0
2822 * and there are still reg_mask or stack_mask
2824 * It means the backtracking missed the spot where
2825 * particular register was initialized with a constant.
2827 verbose(env, "BUG backtracking idx %d\n", i);
2828 WARN_ONCE(1, "verifier backtracking bug");
2837 func = st->frame[st->curframe];
2838 bitmap_from_u64(mask, reg_mask);
2839 for_each_set_bit(i, mask, 32) {
2840 reg = &func->regs[i];
2841 if (reg->type != SCALAR_VALUE) {
2842 reg_mask &= ~(1u << i);
2847 reg->precise = true;
2850 bitmap_from_u64(mask, stack_mask);
2851 for_each_set_bit(i, mask, 64) {
2852 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2853 /* the sequence of instructions:
2855 * 3: (7b) *(u64 *)(r3 -8) = r0
2856 * 4: (79) r4 = *(u64 *)(r10 -8)
2857 * doesn't contain jmps. It's backtracked
2858 * as a single block.
2859 * During backtracking insn 3 is not recognized as
2860 * stack access, so at the end of backtracking
2861 * stack slot fp-8 is still marked in stack_mask.
2862 * However the parent state may not have accessed
2863 * fp-8 and it's "unallocated" stack space.
2864 * In such case fallback to conservative.
2866 mark_all_scalars_precise(env, st);
2870 if (!is_spilled_reg(&func->stack[i])) {
2871 stack_mask &= ~(1ull << i);
2874 reg = &func->stack[i].spilled_ptr;
2875 if (reg->type != SCALAR_VALUE) {
2876 stack_mask &= ~(1ull << i);
2881 reg->precise = true;
2883 if (env->log.level & BPF_LOG_LEVEL2) {
2884 verbose(env, "parent %s regs=%x stack=%llx marks:",
2885 new_marks ? "didn't have" : "already had",
2886 reg_mask, stack_mask);
2887 print_verifier_state(env, func, true);
2890 if (!reg_mask && !stack_mask)
2895 last_idx = st->last_insn_idx;
2896 first_idx = st->first_insn_idx;
2901 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2903 return __mark_chain_precision(env, regno, -1);
2906 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2908 return __mark_chain_precision(env, -1, spi);
2911 static bool is_spillable_regtype(enum bpf_reg_type type)
2913 switch (base_type(type)) {
2914 case PTR_TO_MAP_VALUE:
2918 case PTR_TO_PACKET_META:
2919 case PTR_TO_PACKET_END:
2920 case PTR_TO_FLOW_KEYS:
2921 case CONST_PTR_TO_MAP:
2923 case PTR_TO_SOCK_COMMON:
2924 case PTR_TO_TCP_SOCK:
2925 case PTR_TO_XDP_SOCK:
2930 case PTR_TO_MAP_KEY:
2937 /* Does this register contain a constant zero? */
2938 static bool register_is_null(struct bpf_reg_state *reg)
2940 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2943 static bool register_is_const(struct bpf_reg_state *reg)
2945 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2948 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2950 return tnum_is_unknown(reg->var_off) &&
2951 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2952 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2953 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2954 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2957 static bool register_is_bounded(struct bpf_reg_state *reg)
2959 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2962 static bool __is_pointer_value(bool allow_ptr_leaks,
2963 const struct bpf_reg_state *reg)
2965 if (allow_ptr_leaks)
2968 return reg->type != SCALAR_VALUE;
2971 static void save_register_state(struct bpf_func_state *state,
2972 int spi, struct bpf_reg_state *reg,
2977 state->stack[spi].spilled_ptr = *reg;
2978 if (size == BPF_REG_SIZE)
2979 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2981 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2982 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2984 /* size < 8 bytes spill */
2986 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2989 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2990 * stack boundary and alignment are checked in check_mem_access()
2992 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2993 /* stack frame we're writing to */
2994 struct bpf_func_state *state,
2995 int off, int size, int value_regno,
2998 struct bpf_func_state *cur; /* state of the current function */
2999 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3000 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3001 struct bpf_reg_state *reg = NULL;
3003 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3006 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3007 * so it's aligned access and [off, off + size) are within stack limits
3009 if (!env->allow_ptr_leaks &&
3010 state->stack[spi].slot_type[0] == STACK_SPILL &&
3011 size != BPF_REG_SIZE) {
3012 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3016 cur = env->cur_state->frame[env->cur_state->curframe];
3017 if (value_regno >= 0)
3018 reg = &cur->regs[value_regno];
3019 if (!env->bypass_spec_v4) {
3020 bool sanitize = reg && is_spillable_regtype(reg->type);
3022 for (i = 0; i < size; i++) {
3023 if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3030 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3033 mark_stack_slot_scratched(env, spi);
3034 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3035 !register_is_null(reg) && env->bpf_capable) {
3036 if (dst_reg != BPF_REG_FP) {
3037 /* The backtracking logic can only recognize explicit
3038 * stack slot address like [fp - 8]. Other spill of
3039 * scalar via different register has to be conservative.
3040 * Backtrack from here and mark all registers as precise
3041 * that contributed into 'reg' being a constant.
3043 err = mark_chain_precision(env, value_regno);
3047 save_register_state(state, spi, reg, size);
3048 } else if (reg && is_spillable_regtype(reg->type)) {
3049 /* register containing pointer is being spilled into stack */
3050 if (size != BPF_REG_SIZE) {
3051 verbose_linfo(env, insn_idx, "; ");
3052 verbose(env, "invalid size of register spill\n");
3055 if (state != cur && reg->type == PTR_TO_STACK) {
3056 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3059 save_register_state(state, spi, reg, size);
3061 u8 type = STACK_MISC;
3063 /* regular write of data into stack destroys any spilled ptr */
3064 state->stack[spi].spilled_ptr.type = NOT_INIT;
3065 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3066 if (is_spilled_reg(&state->stack[spi]))
3067 for (i = 0; i < BPF_REG_SIZE; i++)
3068 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3070 /* only mark the slot as written if all 8 bytes were written
3071 * otherwise read propagation may incorrectly stop too soon
3072 * when stack slots are partially written.
3073 * This heuristic means that read propagation will be
3074 * conservative, since it will add reg_live_read marks
3075 * to stack slots all the way to first state when programs
3076 * writes+reads less than 8 bytes
3078 if (size == BPF_REG_SIZE)
3079 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3081 /* when we zero initialize stack slots mark them as such */
3082 if (reg && register_is_null(reg)) {
3083 /* backtracking doesn't work for STACK_ZERO yet. */
3084 err = mark_chain_precision(env, value_regno);
3090 /* Mark slots affected by this stack write. */
3091 for (i = 0; i < size; i++)
3092 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3098 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3099 * known to contain a variable offset.
3100 * This function checks whether the write is permitted and conservatively
3101 * tracks the effects of the write, considering that each stack slot in the
3102 * dynamic range is potentially written to.
3104 * 'off' includes 'regno->off'.
3105 * 'value_regno' can be -1, meaning that an unknown value is being written to
3108 * Spilled pointers in range are not marked as written because we don't know
3109 * what's going to be actually written. This means that read propagation for
3110 * future reads cannot be terminated by this write.
3112 * For privileged programs, uninitialized stack slots are considered
3113 * initialized by this write (even though we don't know exactly what offsets
3114 * are going to be written to). The idea is that we don't want the verifier to
3115 * reject future reads that access slots written to through variable offsets.
3117 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3118 /* func where register points to */
3119 struct bpf_func_state *state,
3120 int ptr_regno, int off, int size,
3121 int value_regno, int insn_idx)
3123 struct bpf_func_state *cur; /* state of the current function */
3124 int min_off, max_off;
3126 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3127 bool writing_zero = false;
3128 /* set if the fact that we're writing a zero is used to let any
3129 * stack slots remain STACK_ZERO
3131 bool zero_used = false;
3133 cur = env->cur_state->frame[env->cur_state->curframe];
3134 ptr_reg = &cur->regs[ptr_regno];
3135 min_off = ptr_reg->smin_value + off;
3136 max_off = ptr_reg->smax_value + off + size;
3137 if (value_regno >= 0)
3138 value_reg = &cur->regs[value_regno];
3139 if (value_reg && register_is_null(value_reg))
3140 writing_zero = true;
3142 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3147 /* Variable offset writes destroy any spilled pointers in range. */
3148 for (i = min_off; i < max_off; i++) {
3149 u8 new_type, *stype;
3153 spi = slot / BPF_REG_SIZE;
3154 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3155 mark_stack_slot_scratched(env, spi);
3157 if (!env->allow_ptr_leaks
3158 && *stype != NOT_INIT
3159 && *stype != SCALAR_VALUE) {
3160 /* Reject the write if there's are spilled pointers in
3161 * range. If we didn't reject here, the ptr status
3162 * would be erased below (even though not all slots are
3163 * actually overwritten), possibly opening the door to
3166 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3171 /* Erase all spilled pointers. */
3172 state->stack[spi].spilled_ptr.type = NOT_INIT;
3174 /* Update the slot type. */
3175 new_type = STACK_MISC;
3176 if (writing_zero && *stype == STACK_ZERO) {
3177 new_type = STACK_ZERO;
3180 /* If the slot is STACK_INVALID, we check whether it's OK to
3181 * pretend that it will be initialized by this write. The slot
3182 * might not actually be written to, and so if we mark it as
3183 * initialized future reads might leak uninitialized memory.
3184 * For privileged programs, we will accept such reads to slots
3185 * that may or may not be written because, if we're reject
3186 * them, the error would be too confusing.
3188 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3189 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3196 /* backtracking doesn't work for STACK_ZERO yet. */
3197 err = mark_chain_precision(env, value_regno);
3204 /* When register 'dst_regno' is assigned some values from stack[min_off,
3205 * max_off), we set the register's type according to the types of the
3206 * respective stack slots. If all the stack values are known to be zeros, then
3207 * so is the destination reg. Otherwise, the register is considered to be
3208 * SCALAR. This function does not deal with register filling; the caller must
3209 * ensure that all spilled registers in the stack range have been marked as
3212 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3213 /* func where src register points to */
3214 struct bpf_func_state *ptr_state,
3215 int min_off, int max_off, int dst_regno)
3217 struct bpf_verifier_state *vstate = env->cur_state;
3218 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3223 for (i = min_off; i < max_off; i++) {
3225 spi = slot / BPF_REG_SIZE;
3226 stype = ptr_state->stack[spi].slot_type;
3227 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3231 if (zeros == max_off - min_off) {
3232 /* any access_size read into register is zero extended,
3233 * so the whole register == const_zero
3235 __mark_reg_const_zero(&state->regs[dst_regno]);
3236 /* backtracking doesn't support STACK_ZERO yet,
3237 * so mark it precise here, so that later
3238 * backtracking can stop here.
3239 * Backtracking may not need this if this register
3240 * doesn't participate in pointer adjustment.
3241 * Forward propagation of precise flag is not
3242 * necessary either. This mark is only to stop
3243 * backtracking. Any register that contributed
3244 * to const 0 was marked precise before spill.
3246 state->regs[dst_regno].precise = true;
3248 /* have read misc data from the stack */
3249 mark_reg_unknown(env, state->regs, dst_regno);
3251 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3254 /* Read the stack at 'off' and put the results into the register indicated by
3255 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3258 * 'dst_regno' can be -1, meaning that the read value is not going to a
3261 * The access is assumed to be within the current stack bounds.
3263 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3264 /* func where src register points to */
3265 struct bpf_func_state *reg_state,
3266 int off, int size, int dst_regno)
3268 struct bpf_verifier_state *vstate = env->cur_state;
3269 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3270 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3271 struct bpf_reg_state *reg;
3274 stype = reg_state->stack[spi].slot_type;
3275 reg = ®_state->stack[spi].spilled_ptr;
3277 if (is_spilled_reg(®_state->stack[spi])) {
3280 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3283 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3284 if (reg->type != SCALAR_VALUE) {
3285 verbose_linfo(env, env->insn_idx, "; ");
3286 verbose(env, "invalid size of register fill\n");
3290 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3294 if (!(off % BPF_REG_SIZE) && size == spill_size) {
3295 /* The earlier check_reg_arg() has decided the
3296 * subreg_def for this insn. Save it first.
3298 s32 subreg_def = state->regs[dst_regno].subreg_def;
3300 state->regs[dst_regno] = *reg;
3301 state->regs[dst_regno].subreg_def = subreg_def;
3303 for (i = 0; i < size; i++) {
3304 type = stype[(slot - i) % BPF_REG_SIZE];
3305 if (type == STACK_SPILL)
3307 if (type == STACK_MISC)
3309 verbose(env, "invalid read from stack off %d+%d size %d\n",
3313 mark_reg_unknown(env, state->regs, dst_regno);
3315 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3319 if (dst_regno >= 0) {
3320 /* restore register state from stack */
3321 state->regs[dst_regno] = *reg;
3322 /* mark reg as written since spilled pointer state likely
3323 * has its liveness marks cleared by is_state_visited()
3324 * which resets stack/reg liveness for state transitions
3326 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3327 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3328 /* If dst_regno==-1, the caller is asking us whether
3329 * it is acceptable to use this value as a SCALAR_VALUE
3331 * We must not allow unprivileged callers to do that
3332 * with spilled pointers.
3334 verbose(env, "leaking pointer from stack off %d\n",
3338 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3340 for (i = 0; i < size; i++) {
3341 type = stype[(slot - i) % BPF_REG_SIZE];
3342 if (type == STACK_MISC)
3344 if (type == STACK_ZERO)
3346 verbose(env, "invalid read from stack off %d+%d size %d\n",
3350 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3352 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3357 enum bpf_access_src {
3358 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
3359 ACCESS_HELPER = 2, /* the access is performed by a helper */
3362 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3363 int regno, int off, int access_size,
3364 bool zero_size_allowed,
3365 enum bpf_access_src type,
3366 struct bpf_call_arg_meta *meta);
3368 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3370 return cur_regs(env) + regno;
3373 /* Read the stack at 'ptr_regno + off' and put the result into the register
3375 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3376 * but not its variable offset.
3377 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3379 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3380 * filling registers (i.e. reads of spilled register cannot be detected when
3381 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3382 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3383 * offset; for a fixed offset check_stack_read_fixed_off should be used
3386 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3387 int ptr_regno, int off, int size, int dst_regno)
3389 /* The state of the source register. */
3390 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3391 struct bpf_func_state *ptr_state = func(env, reg);
3393 int min_off, max_off;
3395 /* Note that we pass a NULL meta, so raw access will not be permitted.
3397 err = check_stack_range_initialized(env, ptr_regno, off, size,
3398 false, ACCESS_DIRECT, NULL);
3402 min_off = reg->smin_value + off;
3403 max_off = reg->smax_value + off;
3404 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3408 /* check_stack_read dispatches to check_stack_read_fixed_off or
3409 * check_stack_read_var_off.
3411 * The caller must ensure that the offset falls within the allocated stack
3414 * 'dst_regno' is a register which will receive the value from the stack. It
3415 * can be -1, meaning that the read value is not going to a register.
3417 static int check_stack_read(struct bpf_verifier_env *env,
3418 int ptr_regno, int off, int size,
3421 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3422 struct bpf_func_state *state = func(env, reg);
3424 /* Some accesses are only permitted with a static offset. */
3425 bool var_off = !tnum_is_const(reg->var_off);
3427 /* The offset is required to be static when reads don't go to a
3428 * register, in order to not leak pointers (see
3429 * check_stack_read_fixed_off).
3431 if (dst_regno < 0 && var_off) {
3434 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3435 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3439 /* Variable offset is prohibited for unprivileged mode for simplicity
3440 * since it requires corresponding support in Spectre masking for stack
3441 * ALU. See also retrieve_ptr_limit().
3443 if (!env->bypass_spec_v1 && var_off) {
3446 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3447 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3453 off += reg->var_off.value;
3454 err = check_stack_read_fixed_off(env, state, off, size,
3457 /* Variable offset stack reads need more conservative handling
3458 * than fixed offset ones. Note that dst_regno >= 0 on this
3461 err = check_stack_read_var_off(env, ptr_regno, off, size,
3468 /* check_stack_write dispatches to check_stack_write_fixed_off or
3469 * check_stack_write_var_off.
3471 * 'ptr_regno' is the register used as a pointer into the stack.
3472 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3473 * 'value_regno' is the register whose value we're writing to the stack. It can
3474 * be -1, meaning that we're not writing from a register.
3476 * The caller must ensure that the offset falls within the maximum stack size.
3478 static int check_stack_write(struct bpf_verifier_env *env,
3479 int ptr_regno, int off, int size,
3480 int value_regno, int insn_idx)
3482 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3483 struct bpf_func_state *state = func(env, reg);
3486 if (tnum_is_const(reg->var_off)) {
3487 off += reg->var_off.value;
3488 err = check_stack_write_fixed_off(env, state, off, size,
3489 value_regno, insn_idx);
3491 /* Variable offset stack reads need more conservative handling
3492 * than fixed offset ones.
3494 err = check_stack_write_var_off(env, state,
3495 ptr_regno, off, size,
3496 value_regno, insn_idx);
3501 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3502 int off, int size, enum bpf_access_type type)
3504 struct bpf_reg_state *regs = cur_regs(env);
3505 struct bpf_map *map = regs[regno].map_ptr;
3506 u32 cap = bpf_map_flags_to_cap(map);
3508 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3509 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3510 map->value_size, off, size);
3514 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3515 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3516 map->value_size, off, size);
3523 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3524 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3525 int off, int size, u32 mem_size,
3526 bool zero_size_allowed)
3528 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3529 struct bpf_reg_state *reg;
3531 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3534 reg = &cur_regs(env)[regno];
3535 switch (reg->type) {
3536 case PTR_TO_MAP_KEY:
3537 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3538 mem_size, off, size);
3540 case PTR_TO_MAP_VALUE:
3541 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3542 mem_size, off, size);
3545 case PTR_TO_PACKET_META:
3546 case PTR_TO_PACKET_END:
3547 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3548 off, size, regno, reg->id, off, mem_size);
3552 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3553 mem_size, off, size);
3559 /* check read/write into a memory region with possible variable offset */
3560 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3561 int off, int size, u32 mem_size,
3562 bool zero_size_allowed)
3564 struct bpf_verifier_state *vstate = env->cur_state;
3565 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3566 struct bpf_reg_state *reg = &state->regs[regno];
3569 /* We may have adjusted the register pointing to memory region, so we
3570 * need to try adding each of min_value and max_value to off
3571 * to make sure our theoretical access will be safe.
3573 * The minimum value is only important with signed
3574 * comparisons where we can't assume the floor of a
3575 * value is 0. If we are using signed variables for our
3576 * index'es we need to make sure that whatever we use
3577 * will have a set floor within our range.
3579 if (reg->smin_value < 0 &&
3580 (reg->smin_value == S64_MIN ||
3581 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3582 reg->smin_value + off < 0)) {
3583 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3587 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3588 mem_size, zero_size_allowed);
3590 verbose(env, "R%d min value is outside of the allowed memory range\n",
3595 /* If we haven't set a max value then we need to bail since we can't be
3596 * sure we won't do bad things.
3597 * If reg->umax_value + off could overflow, treat that as unbounded too.
3599 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3600 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3604 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3605 mem_size, zero_size_allowed);
3607 verbose(env, "R%d max value is outside of the allowed memory range\n",
3615 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3616 const struct bpf_reg_state *reg, int regno,
3619 /* Access to this pointer-typed register or passing it to a helper
3620 * is only allowed in its original, unmodified form.
3624 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3625 reg_type_str(env, reg->type), regno, reg->off);
3629 if (!fixed_off_ok && reg->off) {
3630 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3631 reg_type_str(env, reg->type), regno, reg->off);
3635 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3638 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3639 verbose(env, "variable %s access var_off=%s disallowed\n",
3640 reg_type_str(env, reg->type), tn_buf);
3647 int check_ptr_off_reg(struct bpf_verifier_env *env,
3648 const struct bpf_reg_state *reg, int regno)
3650 return __check_ptr_off_reg(env, reg, regno, false);
3653 static int map_kptr_match_type(struct bpf_verifier_env *env,
3654 struct bpf_map_value_off_desc *off_desc,
3655 struct bpf_reg_state *reg, u32 regno)
3657 const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3658 int perm_flags = PTR_MAYBE_NULL;
3659 const char *reg_name = "";
3661 /* Only unreferenced case accepts untrusted pointers */
3662 if (off_desc->type == BPF_KPTR_UNREF)
3663 perm_flags |= PTR_UNTRUSTED;
3665 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3668 if (!btf_is_kernel(reg->btf)) {
3669 verbose(env, "R%d must point to kernel BTF\n", regno);
3672 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3673 reg_name = kernel_type_name(reg->btf, reg->btf_id);
3675 /* For ref_ptr case, release function check should ensure we get one
3676 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3677 * normal store of unreferenced kptr, we must ensure var_off is zero.
3678 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3679 * reg->off and reg->ref_obj_id are not needed here.
3681 if (__check_ptr_off_reg(env, reg, regno, true))
3684 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3685 * we also need to take into account the reg->off.
3687 * We want to support cases like:
3695 * v = func(); // PTR_TO_BTF_ID
3696 * val->foo = v; // reg->off is zero, btf and btf_id match type
3697 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3698 * // first member type of struct after comparison fails
3699 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3702 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3703 * is zero. We must also ensure that btf_struct_ids_match does not walk
3704 * the struct to match type against first member of struct, i.e. reject
3705 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3706 * strict mode to true for type match.
3708 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3709 off_desc->kptr.btf, off_desc->kptr.btf_id,
3710 off_desc->type == BPF_KPTR_REF))
3714 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3715 reg_type_str(env, reg->type), reg_name);
3716 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3717 if (off_desc->type == BPF_KPTR_UNREF)
3718 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3725 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3726 int value_regno, int insn_idx,
3727 struct bpf_map_value_off_desc *off_desc)
3729 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3730 int class = BPF_CLASS(insn->code);
3731 struct bpf_reg_state *val_reg;
3733 /* Things we already checked for in check_map_access and caller:
3734 * - Reject cases where variable offset may touch kptr
3735 * - size of access (must be BPF_DW)
3736 * - tnum_is_const(reg->var_off)
3737 * - off_desc->offset == off + reg->var_off.value
3739 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3740 if (BPF_MODE(insn->code) != BPF_MEM) {
3741 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3745 /* We only allow loading referenced kptr, since it will be marked as
3746 * untrusted, similar to unreferenced kptr.
3748 if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3749 verbose(env, "store to referenced kptr disallowed\n");
3753 if (class == BPF_LDX) {
3754 val_reg = reg_state(env, value_regno);
3755 /* We can simply mark the value_regno receiving the pointer
3756 * value from map as PTR_TO_BTF_ID, with the correct type.
3758 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3759 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3760 /* For mark_ptr_or_null_reg */
3761 val_reg->id = ++env->id_gen;
3762 } else if (class == BPF_STX) {
3763 val_reg = reg_state(env, value_regno);
3764 if (!register_is_null(val_reg) &&
3765 map_kptr_match_type(env, off_desc, val_reg, value_regno))
3767 } else if (class == BPF_ST) {
3769 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3774 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3780 /* check read/write into a map element with possible variable offset */
3781 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3782 int off, int size, bool zero_size_allowed,
3783 enum bpf_access_src src)
3785 struct bpf_verifier_state *vstate = env->cur_state;
3786 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3787 struct bpf_reg_state *reg = &state->regs[regno];
3788 struct bpf_map *map = reg->map_ptr;
3791 err = check_mem_region_access(env, regno, off, size, map->value_size,
3796 if (map_value_has_spin_lock(map)) {
3797 u32 lock = map->spin_lock_off;
3799 /* if any part of struct bpf_spin_lock can be touched by
3800 * load/store reject this program.
3801 * To check that [x1, x2) overlaps with [y1, y2)
3802 * it is sufficient to check x1 < y2 && y1 < x2.
3804 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3805 lock < reg->umax_value + off + size) {
3806 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3810 if (map_value_has_timer(map)) {
3811 u32 t = map->timer_off;
3813 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3814 t < reg->umax_value + off + size) {
3815 verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3819 if (map_value_has_kptrs(map)) {
3820 struct bpf_map_value_off *tab = map->kptr_off_tab;
3823 for (i = 0; i < tab->nr_off; i++) {
3824 u32 p = tab->off[i].offset;
3826 if (reg->smin_value + off < p + sizeof(u64) &&
3827 p < reg->umax_value + off + size) {
3828 if (src != ACCESS_DIRECT) {
3829 verbose(env, "kptr cannot be accessed indirectly by helper\n");
3832 if (!tnum_is_const(reg->var_off)) {
3833 verbose(env, "kptr access cannot have variable offset\n");
3836 if (p != off + reg->var_off.value) {
3837 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3838 p, off + reg->var_off.value);
3841 if (size != bpf_size_to_bytes(BPF_DW)) {
3842 verbose(env, "kptr access size must be BPF_DW\n");
3852 #define MAX_PACKET_OFF 0xffff
3854 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3855 const struct bpf_call_arg_meta *meta,
3856 enum bpf_access_type t)
3858 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3860 switch (prog_type) {
3861 /* Program types only with direct read access go here! */
3862 case BPF_PROG_TYPE_LWT_IN:
3863 case BPF_PROG_TYPE_LWT_OUT:
3864 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3865 case BPF_PROG_TYPE_SK_REUSEPORT:
3866 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3867 case BPF_PROG_TYPE_CGROUP_SKB:
3872 /* Program types with direct read + write access go here! */
3873 case BPF_PROG_TYPE_SCHED_CLS:
3874 case BPF_PROG_TYPE_SCHED_ACT:
3875 case BPF_PROG_TYPE_XDP:
3876 case BPF_PROG_TYPE_LWT_XMIT:
3877 case BPF_PROG_TYPE_SK_SKB:
3878 case BPF_PROG_TYPE_SK_MSG:
3880 return meta->pkt_access;
3882 env->seen_direct_write = true;
3885 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3887 env->seen_direct_write = true;
3896 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3897 int size, bool zero_size_allowed)
3899 struct bpf_reg_state *regs = cur_regs(env);
3900 struct bpf_reg_state *reg = ®s[regno];
3903 /* We may have added a variable offset to the packet pointer; but any
3904 * reg->range we have comes after that. We are only checking the fixed
3908 /* We don't allow negative numbers, because we aren't tracking enough
3909 * detail to prove they're safe.
3911 if (reg->smin_value < 0) {
3912 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3917 err = reg->range < 0 ? -EINVAL :
3918 __check_mem_access(env, regno, off, size, reg->range,
3921 verbose(env, "R%d offset is outside of the packet\n", regno);
3925 /* __check_mem_access has made sure "off + size - 1" is within u16.
3926 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3927 * otherwise find_good_pkt_pointers would have refused to set range info
3928 * that __check_mem_access would have rejected this pkt access.
3929 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3931 env->prog->aux->max_pkt_offset =
3932 max_t(u32, env->prog->aux->max_pkt_offset,
3933 off + reg->umax_value + size - 1);
3938 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
3939 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3940 enum bpf_access_type t, enum bpf_reg_type *reg_type,
3941 struct btf **btf, u32 *btf_id)
3943 struct bpf_insn_access_aux info = {
3944 .reg_type = *reg_type,
3948 if (env->ops->is_valid_access &&
3949 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3950 /* A non zero info.ctx_field_size indicates that this field is a
3951 * candidate for later verifier transformation to load the whole
3952 * field and then apply a mask when accessed with a narrower
3953 * access than actual ctx access size. A zero info.ctx_field_size
3954 * will only allow for whole field access and rejects any other
3955 * type of narrower access.
3957 *reg_type = info.reg_type;
3959 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3961 *btf_id = info.btf_id;
3963 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3965 /* remember the offset of last byte accessed in ctx */
3966 if (env->prog->aux->max_ctx_offset < off + size)
3967 env->prog->aux->max_ctx_offset = off + size;
3971 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3975 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3978 if (size < 0 || off < 0 ||
3979 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3980 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3987 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3988 u32 regno, int off, int size,
3989 enum bpf_access_type t)
3991 struct bpf_reg_state *regs = cur_regs(env);
3992 struct bpf_reg_state *reg = ®s[regno];
3993 struct bpf_insn_access_aux info = {};
3996 if (reg->smin_value < 0) {
3997 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4002 switch (reg->type) {
4003 case PTR_TO_SOCK_COMMON:
4004 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4007 valid = bpf_sock_is_valid_access(off, size, t, &info);
4009 case PTR_TO_TCP_SOCK:
4010 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4012 case PTR_TO_XDP_SOCK:
4013 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4021 env->insn_aux_data[insn_idx].ctx_field_size =
4022 info.ctx_field_size;
4026 verbose(env, "R%d invalid %s access off=%d size=%d\n",
4027 regno, reg_type_str(env, reg->type), off, size);
4032 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4034 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4037 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4039 const struct bpf_reg_state *reg = reg_state(env, regno);
4041 return reg->type == PTR_TO_CTX;
4044 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4046 const struct bpf_reg_state *reg = reg_state(env, regno);
4048 return type_is_sk_pointer(reg->type);
4051 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4053 const struct bpf_reg_state *reg = reg_state(env, regno);
4055 return type_is_pkt_pointer(reg->type);
4058 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4060 const struct bpf_reg_state *reg = reg_state(env, regno);
4062 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4063 return reg->type == PTR_TO_FLOW_KEYS;
4066 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4067 const struct bpf_reg_state *reg,
4068 int off, int size, bool strict)
4070 struct tnum reg_off;
4073 /* Byte size accesses are always allowed. */
4074 if (!strict || size == 1)
4077 /* For platforms that do not have a Kconfig enabling
4078 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4079 * NET_IP_ALIGN is universally set to '2'. And on platforms
4080 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4081 * to this code only in strict mode where we want to emulate
4082 * the NET_IP_ALIGN==2 checking. Therefore use an
4083 * unconditional IP align value of '2'.
4087 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4088 if (!tnum_is_aligned(reg_off, size)) {
4091 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4093 "misaligned packet access off %d+%s+%d+%d size %d\n",
4094 ip_align, tn_buf, reg->off, off, size);
4101 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4102 const struct bpf_reg_state *reg,
4103 const char *pointer_desc,
4104 int off, int size, bool strict)
4106 struct tnum reg_off;
4108 /* Byte size accesses are always allowed. */
4109 if (!strict || size == 1)
4112 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4113 if (!tnum_is_aligned(reg_off, size)) {
4116 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4117 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4118 pointer_desc, tn_buf, reg->off, off, size);
4125 static int check_ptr_alignment(struct bpf_verifier_env *env,
4126 const struct bpf_reg_state *reg, int off,
4127 int size, bool strict_alignment_once)
4129 bool strict = env->strict_alignment || strict_alignment_once;
4130 const char *pointer_desc = "";
4132 switch (reg->type) {
4134 case PTR_TO_PACKET_META:
4135 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4136 * right in front, treat it the very same way.
4138 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4139 case PTR_TO_FLOW_KEYS:
4140 pointer_desc = "flow keys ";
4142 case PTR_TO_MAP_KEY:
4143 pointer_desc = "key ";
4145 case PTR_TO_MAP_VALUE:
4146 pointer_desc = "value ";
4149 pointer_desc = "context ";
4152 pointer_desc = "stack ";
4153 /* The stack spill tracking logic in check_stack_write_fixed_off()
4154 * and check_stack_read_fixed_off() relies on stack accesses being
4160 pointer_desc = "sock ";
4162 case PTR_TO_SOCK_COMMON:
4163 pointer_desc = "sock_common ";
4165 case PTR_TO_TCP_SOCK:
4166 pointer_desc = "tcp_sock ";
4168 case PTR_TO_XDP_SOCK:
4169 pointer_desc = "xdp_sock ";
4174 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4178 static int update_stack_depth(struct bpf_verifier_env *env,
4179 const struct bpf_func_state *func,
4182 u16 stack = env->subprog_info[func->subprogno].stack_depth;
4187 /* update known max for given subprogram */
4188 env->subprog_info[func->subprogno].stack_depth = -off;
4192 /* starting from main bpf function walk all instructions of the function
4193 * and recursively walk all callees that given function can call.
4194 * Ignore jump and exit insns.
4195 * Since recursion is prevented by check_cfg() this algorithm
4196 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4198 static int check_max_stack_depth(struct bpf_verifier_env *env)
4200 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4201 struct bpf_subprog_info *subprog = env->subprog_info;
4202 struct bpf_insn *insn = env->prog->insnsi;
4203 bool tail_call_reachable = false;
4204 int ret_insn[MAX_CALL_FRAMES];
4205 int ret_prog[MAX_CALL_FRAMES];
4209 /* protect against potential stack overflow that might happen when
4210 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4211 * depth for such case down to 256 so that the worst case scenario
4212 * would result in 8k stack size (32 which is tailcall limit * 256 =
4215 * To get the idea what might happen, see an example:
4216 * func1 -> sub rsp, 128
4217 * subfunc1 -> sub rsp, 256
4218 * tailcall1 -> add rsp, 256
4219 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4220 * subfunc2 -> sub rsp, 64
4221 * subfunc22 -> sub rsp, 128
4222 * tailcall2 -> add rsp, 128
4223 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4225 * tailcall will unwind the current stack frame but it will not get rid
4226 * of caller's stack as shown on the example above.
4228 if (idx && subprog[idx].has_tail_call && depth >= 256) {
4230 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4234 /* round up to 32-bytes, since this is granularity
4235 * of interpreter stack size
4237 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4238 if (depth > MAX_BPF_STACK) {
4239 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4244 subprog_end = subprog[idx + 1].start;
4245 for (; i < subprog_end; i++) {
4248 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4250 /* remember insn and function to return to */
4251 ret_insn[frame] = i + 1;
4252 ret_prog[frame] = idx;
4254 /* find the callee */
4255 next_insn = i + insn[i].imm + 1;
4256 idx = find_subprog(env, next_insn);
4258 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4262 if (subprog[idx].is_async_cb) {
4263 if (subprog[idx].has_tail_call) {
4264 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4267 /* async callbacks don't increase bpf prog stack size */
4272 if (subprog[idx].has_tail_call)
4273 tail_call_reachable = true;
4276 if (frame >= MAX_CALL_FRAMES) {
4277 verbose(env, "the call stack of %d frames is too deep !\n",
4283 /* if tail call got detected across bpf2bpf calls then mark each of the
4284 * currently present subprog frames as tail call reachable subprogs;
4285 * this info will be utilized by JIT so that we will be preserving the
4286 * tail call counter throughout bpf2bpf calls combined with tailcalls
4288 if (tail_call_reachable)
4289 for (j = 0; j < frame; j++)
4290 subprog[ret_prog[j]].tail_call_reachable = true;
4291 if (subprog[0].tail_call_reachable)
4292 env->prog->aux->tail_call_reachable = true;
4294 /* end of for() loop means the last insn of the 'subprog'
4295 * was reached. Doesn't matter whether it was JA or EXIT
4299 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4301 i = ret_insn[frame];
4302 idx = ret_prog[frame];
4306 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4307 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4308 const struct bpf_insn *insn, int idx)
4310 int start = idx + insn->imm + 1, subprog;
4312 subprog = find_subprog(env, start);
4314 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4318 return env->subprog_info[subprog].stack_depth;
4322 static int __check_buffer_access(struct bpf_verifier_env *env,
4323 const char *buf_info,
4324 const struct bpf_reg_state *reg,
4325 int regno, int off, int size)
4329 "R%d invalid %s buffer access: off=%d, size=%d\n",
4330 regno, buf_info, off, size);
4333 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4336 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4338 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4339 regno, off, tn_buf);
4346 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4347 const struct bpf_reg_state *reg,
4348 int regno, int off, int size)
4352 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4356 if (off + size > env->prog->aux->max_tp_access)
4357 env->prog->aux->max_tp_access = off + size;
4362 static int check_buffer_access(struct bpf_verifier_env *env,
4363 const struct bpf_reg_state *reg,
4364 int regno, int off, int size,
4365 bool zero_size_allowed,
4368 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4371 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4375 if (off + size > *max_access)
4376 *max_access = off + size;
4381 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4382 static void zext_32_to_64(struct bpf_reg_state *reg)
4384 reg->var_off = tnum_subreg(reg->var_off);
4385 __reg_assign_32_into_64(reg);
4388 /* truncate register to smaller size (in bytes)
4389 * must be called with size < BPF_REG_SIZE
4391 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4395 /* clear high bits in bit representation */
4396 reg->var_off = tnum_cast(reg->var_off, size);
4398 /* fix arithmetic bounds */
4399 mask = ((u64)1 << (size * 8)) - 1;
4400 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4401 reg->umin_value &= mask;
4402 reg->umax_value &= mask;
4404 reg->umin_value = 0;
4405 reg->umax_value = mask;
4407 reg->smin_value = reg->umin_value;
4408 reg->smax_value = reg->umax_value;
4410 /* If size is smaller than 32bit register the 32bit register
4411 * values are also truncated so we push 64-bit bounds into
4412 * 32-bit bounds. Above were truncated < 32-bits already.
4416 __reg_combine_64_into_32(reg);
4419 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4421 /* A map is considered read-only if the following condition are true:
4423 * 1) BPF program side cannot change any of the map content. The
4424 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4425 * and was set at map creation time.
4426 * 2) The map value(s) have been initialized from user space by a
4427 * loader and then "frozen", such that no new map update/delete
4428 * operations from syscall side are possible for the rest of
4429 * the map's lifetime from that point onwards.
4430 * 3) Any parallel/pending map update/delete operations from syscall
4431 * side have been completed. Only after that point, it's safe to
4432 * assume that map value(s) are immutable.
4434 return (map->map_flags & BPF_F_RDONLY_PROG) &&
4435 READ_ONCE(map->frozen) &&
4436 !bpf_map_write_active(map);
4439 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4445 err = map->ops->map_direct_value_addr(map, &addr, off);
4448 ptr = (void *)(long)addr + off;
4452 *val = (u64)*(u8 *)ptr;
4455 *val = (u64)*(u16 *)ptr;
4458 *val = (u64)*(u32 *)ptr;
4469 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4470 struct bpf_reg_state *regs,
4471 int regno, int off, int size,
4472 enum bpf_access_type atype,
4475 struct bpf_reg_state *reg = regs + regno;
4476 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4477 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4478 enum bpf_type_flag flag = 0;
4484 "R%d is ptr_%s invalid negative access: off=%d\n",
4488 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4491 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4493 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4494 regno, tname, off, tn_buf);
4498 if (reg->type & MEM_USER) {
4500 "R%d is ptr_%s access user memory: off=%d\n",
4505 if (reg->type & MEM_PERCPU) {
4507 "R%d is ptr_%s access percpu memory: off=%d\n",
4512 if (env->ops->btf_struct_access) {
4513 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4514 off, size, atype, &btf_id, &flag);
4516 if (atype != BPF_READ) {
4517 verbose(env, "only read is supported\n");
4521 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4522 atype, &btf_id, &flag);
4528 /* If this is an untrusted pointer, all pointers formed by walking it
4529 * also inherit the untrusted flag.
4531 if (type_flag(reg->type) & PTR_UNTRUSTED)
4532 flag |= PTR_UNTRUSTED;
4534 if (atype == BPF_READ && value_regno >= 0)
4535 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4540 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4541 struct bpf_reg_state *regs,
4542 int regno, int off, int size,
4543 enum bpf_access_type atype,
4546 struct bpf_reg_state *reg = regs + regno;
4547 struct bpf_map *map = reg->map_ptr;
4548 enum bpf_type_flag flag = 0;
4549 const struct btf_type *t;
4555 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4559 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4560 verbose(env, "map_ptr access not supported for map type %d\n",
4565 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4566 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4568 if (!env->allow_ptr_to_map_access) {
4570 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4576 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4581 if (atype != BPF_READ) {
4582 verbose(env, "only read from %s is supported\n", tname);
4586 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4590 if (value_regno >= 0)
4591 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4596 /* Check that the stack access at the given offset is within bounds. The
4597 * maximum valid offset is -1.
4599 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4600 * -state->allocated_stack for reads.
4602 static int check_stack_slot_within_bounds(int off,
4603 struct bpf_func_state *state,
4604 enum bpf_access_type t)
4609 min_valid_off = -MAX_BPF_STACK;
4611 min_valid_off = -state->allocated_stack;
4613 if (off < min_valid_off || off > -1)
4618 /* Check that the stack access at 'regno + off' falls within the maximum stack
4621 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4623 static int check_stack_access_within_bounds(
4624 struct bpf_verifier_env *env,
4625 int regno, int off, int access_size,
4626 enum bpf_access_src src, enum bpf_access_type type)
4628 struct bpf_reg_state *regs = cur_regs(env);
4629 struct bpf_reg_state *reg = regs + regno;
4630 struct bpf_func_state *state = func(env, reg);
4631 int min_off, max_off;
4635 if (src == ACCESS_HELPER)
4636 /* We don't know if helpers are reading or writing (or both). */
4637 err_extra = " indirect access to";
4638 else if (type == BPF_READ)
4639 err_extra = " read from";
4641 err_extra = " write to";
4643 if (tnum_is_const(reg->var_off)) {
4644 min_off = reg->var_off.value + off;
4645 if (access_size > 0)
4646 max_off = min_off + access_size - 1;
4650 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4651 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4652 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4656 min_off = reg->smin_value + off;
4657 if (access_size > 0)
4658 max_off = reg->smax_value + off + access_size - 1;
4663 err = check_stack_slot_within_bounds(min_off, state, type);
4665 err = check_stack_slot_within_bounds(max_off, state, type);
4668 if (tnum_is_const(reg->var_off)) {
4669 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4670 err_extra, regno, off, access_size);
4674 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4675 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4676 err_extra, regno, tn_buf, access_size);
4682 /* check whether memory at (regno + off) is accessible for t = (read | write)
4683 * if t==write, value_regno is a register which value is stored into memory
4684 * if t==read, value_regno is a register which will receive the value from memory
4685 * if t==write && value_regno==-1, some unknown value is stored into memory
4686 * if t==read && value_regno==-1, don't care what we read from memory
4688 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4689 int off, int bpf_size, enum bpf_access_type t,
4690 int value_regno, bool strict_alignment_once)
4692 struct bpf_reg_state *regs = cur_regs(env);
4693 struct bpf_reg_state *reg = regs + regno;
4694 struct bpf_func_state *state;
4697 size = bpf_size_to_bytes(bpf_size);
4701 /* alignment checks will add in reg->off themselves */
4702 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4706 /* for access checks, reg->off is just part of off */
4709 if (reg->type == PTR_TO_MAP_KEY) {
4710 if (t == BPF_WRITE) {
4711 verbose(env, "write to change key R%d not allowed\n", regno);
4715 err = check_mem_region_access(env, regno, off, size,
4716 reg->map_ptr->key_size, false);
4719 if (value_regno >= 0)
4720 mark_reg_unknown(env, regs, value_regno);
4721 } else if (reg->type == PTR_TO_MAP_VALUE) {
4722 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4724 if (t == BPF_WRITE && value_regno >= 0 &&
4725 is_pointer_value(env, value_regno)) {
4726 verbose(env, "R%d leaks addr into map\n", value_regno);
4729 err = check_map_access_type(env, regno, off, size, t);
4732 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4735 if (tnum_is_const(reg->var_off))
4736 kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4737 off + reg->var_off.value);
4738 if (kptr_off_desc) {
4739 err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4741 } else if (t == BPF_READ && value_regno >= 0) {
4742 struct bpf_map *map = reg->map_ptr;
4744 /* if map is read-only, track its contents as scalars */
4745 if (tnum_is_const(reg->var_off) &&
4746 bpf_map_is_rdonly(map) &&
4747 map->ops->map_direct_value_addr) {
4748 int map_off = off + reg->var_off.value;
4751 err = bpf_map_direct_read(map, map_off, size,
4756 regs[value_regno].type = SCALAR_VALUE;
4757 __mark_reg_known(®s[value_regno], val);
4759 mark_reg_unknown(env, regs, value_regno);
4762 } else if (base_type(reg->type) == PTR_TO_MEM) {
4763 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4765 if (type_may_be_null(reg->type)) {
4766 verbose(env, "R%d invalid mem access '%s'\n", regno,
4767 reg_type_str(env, reg->type));
4771 if (t == BPF_WRITE && rdonly_mem) {
4772 verbose(env, "R%d cannot write into %s\n",
4773 regno, reg_type_str(env, reg->type));
4777 if (t == BPF_WRITE && value_regno >= 0 &&
4778 is_pointer_value(env, value_regno)) {
4779 verbose(env, "R%d leaks addr into mem\n", value_regno);
4783 err = check_mem_region_access(env, regno, off, size,
4784 reg->mem_size, false);
4785 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4786 mark_reg_unknown(env, regs, value_regno);
4787 } else if (reg->type == PTR_TO_CTX) {
4788 enum bpf_reg_type reg_type = SCALAR_VALUE;
4789 struct btf *btf = NULL;
4792 if (t == BPF_WRITE && value_regno >= 0 &&
4793 is_pointer_value(env, value_regno)) {
4794 verbose(env, "R%d leaks addr into ctx\n", value_regno);
4798 err = check_ptr_off_reg(env, reg, regno);
4802 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
4805 verbose_linfo(env, insn_idx, "; ");
4806 if (!err && t == BPF_READ && value_regno >= 0) {
4807 /* ctx access returns either a scalar, or a
4808 * PTR_TO_PACKET[_META,_END]. In the latter
4809 * case, we know the offset is zero.
4811 if (reg_type == SCALAR_VALUE) {
4812 mark_reg_unknown(env, regs, value_regno);
4814 mark_reg_known_zero(env, regs,
4816 if (type_may_be_null(reg_type))
4817 regs[value_regno].id = ++env->id_gen;
4818 /* A load of ctx field could have different
4819 * actual load size with the one encoded in the
4820 * insn. When the dst is PTR, it is for sure not
4823 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4824 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4825 regs[value_regno].btf = btf;
4826 regs[value_regno].btf_id = btf_id;
4829 regs[value_regno].type = reg_type;
4832 } else if (reg->type == PTR_TO_STACK) {
4833 /* Basic bounds checks. */
4834 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4838 state = func(env, reg);
4839 err = update_stack_depth(env, state, off);
4844 err = check_stack_read(env, regno, off, size,
4847 err = check_stack_write(env, regno, off, size,
4848 value_regno, insn_idx);
4849 } else if (reg_is_pkt_pointer(reg)) {
4850 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4851 verbose(env, "cannot write into packet\n");
4854 if (t == BPF_WRITE && value_regno >= 0 &&
4855 is_pointer_value(env, value_regno)) {
4856 verbose(env, "R%d leaks addr into packet\n",
4860 err = check_packet_access(env, regno, off, size, false);
4861 if (!err && t == BPF_READ && value_regno >= 0)
4862 mark_reg_unknown(env, regs, value_regno);
4863 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4864 if (t == BPF_WRITE && value_regno >= 0 &&
4865 is_pointer_value(env, value_regno)) {
4866 verbose(env, "R%d leaks addr into flow keys\n",
4871 err = check_flow_keys_access(env, off, size);
4872 if (!err && t == BPF_READ && value_regno >= 0)
4873 mark_reg_unknown(env, regs, value_regno);
4874 } else if (type_is_sk_pointer(reg->type)) {
4875 if (t == BPF_WRITE) {
4876 verbose(env, "R%d cannot write into %s\n",
4877 regno, reg_type_str(env, reg->type));
4880 err = check_sock_access(env, insn_idx, regno, off, size, t);
4881 if (!err && value_regno >= 0)
4882 mark_reg_unknown(env, regs, value_regno);
4883 } else if (reg->type == PTR_TO_TP_BUFFER) {
4884 err = check_tp_buffer_access(env, reg, regno, off, size);
4885 if (!err && t == BPF_READ && value_regno >= 0)
4886 mark_reg_unknown(env, regs, value_regno);
4887 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4888 !type_may_be_null(reg->type)) {
4889 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4891 } else if (reg->type == CONST_PTR_TO_MAP) {
4892 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4894 } else if (base_type(reg->type) == PTR_TO_BUF) {
4895 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4899 if (t == BPF_WRITE) {
4900 verbose(env, "R%d cannot write into %s\n",
4901 regno, reg_type_str(env, reg->type));
4904 max_access = &env->prog->aux->max_rdonly_access;
4906 max_access = &env->prog->aux->max_rdwr_access;
4909 err = check_buffer_access(env, reg, regno, off, size, false,
4912 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4913 mark_reg_unknown(env, regs, value_regno);
4915 verbose(env, "R%d invalid mem access '%s'\n", regno,
4916 reg_type_str(env, reg->type));
4920 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4921 regs[value_regno].type == SCALAR_VALUE) {
4922 /* b/h/w load zero-extends, mark upper bits as known 0 */
4923 coerce_reg_to_size(®s[value_regno], size);
4928 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4933 switch (insn->imm) {
4935 case BPF_ADD | BPF_FETCH:
4937 case BPF_AND | BPF_FETCH:
4939 case BPF_OR | BPF_FETCH:
4941 case BPF_XOR | BPF_FETCH:
4946 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4950 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4951 verbose(env, "invalid atomic operand size\n");
4955 /* check src1 operand */
4956 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4960 /* check src2 operand */
4961 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4965 if (insn->imm == BPF_CMPXCHG) {
4966 /* Check comparison of R0 with memory location */
4967 const u32 aux_reg = BPF_REG_0;
4969 err = check_reg_arg(env, aux_reg, SRC_OP);
4973 if (is_pointer_value(env, aux_reg)) {
4974 verbose(env, "R%d leaks addr into mem\n", aux_reg);
4979 if (is_pointer_value(env, insn->src_reg)) {
4980 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4984 if (is_ctx_reg(env, insn->dst_reg) ||
4985 is_pkt_reg(env, insn->dst_reg) ||
4986 is_flow_key_reg(env, insn->dst_reg) ||
4987 is_sk_reg(env, insn->dst_reg)) {
4988 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4990 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
4994 if (insn->imm & BPF_FETCH) {
4995 if (insn->imm == BPF_CMPXCHG)
4996 load_reg = BPF_REG_0;
4998 load_reg = insn->src_reg;
5000 /* check and record load of old value */
5001 err = check_reg_arg(env, load_reg, DST_OP);
5005 /* This instruction accesses a memory location but doesn't
5006 * actually load it into a register.
5011 /* Check whether we can read the memory, with second call for fetch
5012 * case to simulate the register fill.
5014 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5015 BPF_SIZE(insn->code), BPF_READ, -1, true);
5016 if (!err && load_reg >= 0)
5017 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5018 BPF_SIZE(insn->code), BPF_READ, load_reg,
5023 /* Check whether we can write into the same memory. */
5024 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5025 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5032 /* When register 'regno' is used to read the stack (either directly or through
5033 * a helper function) make sure that it's within stack boundary and, depending
5034 * on the access type, that all elements of the stack are initialized.
5036 * 'off' includes 'regno->off', but not its dynamic part (if any).
5038 * All registers that have been spilled on the stack in the slots within the
5039 * read offsets are marked as read.
5041 static int check_stack_range_initialized(
5042 struct bpf_verifier_env *env, int regno, int off,
5043 int access_size, bool zero_size_allowed,
5044 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5046 struct bpf_reg_state *reg = reg_state(env, regno);
5047 struct bpf_func_state *state = func(env, reg);
5048 int err, min_off, max_off, i, j, slot, spi;
5049 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5050 enum bpf_access_type bounds_check_type;
5051 /* Some accesses can write anything into the stack, others are
5054 bool clobber = false;
5056 if (access_size == 0 && !zero_size_allowed) {
5057 verbose(env, "invalid zero-sized read\n");
5061 if (type == ACCESS_HELPER) {
5062 /* The bounds checks for writes are more permissive than for
5063 * reads. However, if raw_mode is not set, we'll do extra
5066 bounds_check_type = BPF_WRITE;
5069 bounds_check_type = BPF_READ;
5071 err = check_stack_access_within_bounds(env, regno, off, access_size,
5072 type, bounds_check_type);
5077 if (tnum_is_const(reg->var_off)) {
5078 min_off = max_off = reg->var_off.value + off;
5080 /* Variable offset is prohibited for unprivileged mode for
5081 * simplicity since it requires corresponding support in
5082 * Spectre masking for stack ALU.
5083 * See also retrieve_ptr_limit().
5085 if (!env->bypass_spec_v1) {
5088 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5089 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5090 regno, err_extra, tn_buf);
5093 /* Only initialized buffer on stack is allowed to be accessed
5094 * with variable offset. With uninitialized buffer it's hard to
5095 * guarantee that whole memory is marked as initialized on
5096 * helper return since specific bounds are unknown what may
5097 * cause uninitialized stack leaking.
5099 if (meta && meta->raw_mode)
5102 min_off = reg->smin_value + off;
5103 max_off = reg->smax_value + off;
5106 if (meta && meta->raw_mode) {
5107 meta->access_size = access_size;
5108 meta->regno = regno;
5112 for (i = min_off; i < max_off + access_size; i++) {
5116 spi = slot / BPF_REG_SIZE;
5117 if (state->allocated_stack <= slot)
5119 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5120 if (*stype == STACK_MISC)
5122 if (*stype == STACK_ZERO) {
5124 /* helper can write anything into the stack */
5125 *stype = STACK_MISC;
5130 if (is_spilled_reg(&state->stack[spi]) &&
5131 base_type(state->stack[spi].spilled_ptr.type) == PTR_TO_BTF_ID)
5134 if (is_spilled_reg(&state->stack[spi]) &&
5135 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5136 env->allow_ptr_leaks)) {
5138 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5139 for (j = 0; j < BPF_REG_SIZE; j++)
5140 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5146 if (tnum_is_const(reg->var_off)) {
5147 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5148 err_extra, regno, min_off, i - min_off, access_size);
5152 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5153 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5154 err_extra, regno, tn_buf, i - min_off, access_size);
5158 /* reading any byte out of 8-byte 'spill_slot' will cause
5159 * the whole slot to be marked as 'read'
5161 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5162 state->stack[spi].spilled_ptr.parent,
5165 return update_stack_depth(env, state, min_off);
5168 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5169 int access_size, bool zero_size_allowed,
5170 struct bpf_call_arg_meta *meta)
5172 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5175 switch (base_type(reg->type)) {
5177 case PTR_TO_PACKET_META:
5178 return check_packet_access(env, regno, reg->off, access_size,
5180 case PTR_TO_MAP_KEY:
5181 if (meta && meta->raw_mode) {
5182 verbose(env, "R%d cannot write into %s\n", regno,
5183 reg_type_str(env, reg->type));
5186 return check_mem_region_access(env, regno, reg->off, access_size,
5187 reg->map_ptr->key_size, false);
5188 case PTR_TO_MAP_VALUE:
5189 if (check_map_access_type(env, regno, reg->off, access_size,
5190 meta && meta->raw_mode ? BPF_WRITE :
5193 return check_map_access(env, regno, reg->off, access_size,
5194 zero_size_allowed, ACCESS_HELPER);
5196 if (type_is_rdonly_mem(reg->type)) {
5197 if (meta && meta->raw_mode) {
5198 verbose(env, "R%d cannot write into %s\n", regno,
5199 reg_type_str(env, reg->type));
5203 return check_mem_region_access(env, regno, reg->off,
5204 access_size, reg->mem_size,
5207 if (type_is_rdonly_mem(reg->type)) {
5208 if (meta && meta->raw_mode) {
5209 verbose(env, "R%d cannot write into %s\n", regno,
5210 reg_type_str(env, reg->type));
5214 max_access = &env->prog->aux->max_rdonly_access;
5216 max_access = &env->prog->aux->max_rdwr_access;
5218 return check_buffer_access(env, reg, regno, reg->off,
5219 access_size, zero_size_allowed,
5222 return check_stack_range_initialized(
5224 regno, reg->off, access_size,
5225 zero_size_allowed, ACCESS_HELPER, meta);
5226 default: /* scalar_value or invalid ptr */
5227 /* Allow zero-byte read from NULL, regardless of pointer type */
5228 if (zero_size_allowed && access_size == 0 &&
5229 register_is_null(reg))
5232 verbose(env, "R%d type=%s ", regno,
5233 reg_type_str(env, reg->type));
5234 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5239 static int check_mem_size_reg(struct bpf_verifier_env *env,
5240 struct bpf_reg_state *reg, u32 regno,
5241 bool zero_size_allowed,
5242 struct bpf_call_arg_meta *meta)
5246 /* This is used to refine r0 return value bounds for helpers
5247 * that enforce this value as an upper bound on return values.
5248 * See do_refine_retval_range() for helpers that can refine
5249 * the return value. C type of helper is u32 so we pull register
5250 * bound from umax_value however, if negative verifier errors
5251 * out. Only upper bounds can be learned because retval is an
5252 * int type and negative retvals are allowed.
5254 meta->msize_max_value = reg->umax_value;
5256 /* The register is SCALAR_VALUE; the access check
5257 * happens using its boundaries.
5259 if (!tnum_is_const(reg->var_off))
5260 /* For unprivileged variable accesses, disable raw
5261 * mode so that the program is required to
5262 * initialize all the memory that the helper could
5263 * just partially fill up.
5267 if (reg->smin_value < 0) {
5268 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5273 if (reg->umin_value == 0) {
5274 err = check_helper_mem_access(env, regno - 1, 0,
5281 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5282 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5286 err = check_helper_mem_access(env, regno - 1,
5288 zero_size_allowed, meta);
5290 err = mark_chain_precision(env, regno);
5294 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5295 u32 regno, u32 mem_size)
5297 bool may_be_null = type_may_be_null(reg->type);
5298 struct bpf_reg_state saved_reg;
5299 struct bpf_call_arg_meta meta;
5302 if (register_is_null(reg))
5305 memset(&meta, 0, sizeof(meta));
5306 /* Assuming that the register contains a value check if the memory
5307 * access is safe. Temporarily save and restore the register's state as
5308 * the conversion shouldn't be visible to a caller.
5312 mark_ptr_not_null_reg(reg);
5315 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5316 /* Check access for BPF_WRITE */
5317 meta.raw_mode = true;
5318 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5326 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5329 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5330 bool may_be_null = type_may_be_null(mem_reg->type);
5331 struct bpf_reg_state saved_reg;
5332 struct bpf_call_arg_meta meta;
5335 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5337 memset(&meta, 0, sizeof(meta));
5340 saved_reg = *mem_reg;
5341 mark_ptr_not_null_reg(mem_reg);
5344 err = check_mem_size_reg(env, reg, regno, true, &meta);
5345 /* Check access for BPF_WRITE */
5346 meta.raw_mode = true;
5347 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5350 *mem_reg = saved_reg;
5354 /* Implementation details:
5355 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5356 * Two bpf_map_lookups (even with the same key) will have different reg->id.
5357 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5358 * value_or_null->value transition, since the verifier only cares about
5359 * the range of access to valid map value pointer and doesn't care about actual
5360 * address of the map element.
5361 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5362 * reg->id > 0 after value_or_null->value transition. By doing so
5363 * two bpf_map_lookups will be considered two different pointers that
5364 * point to different bpf_spin_locks.
5365 * The verifier allows taking only one bpf_spin_lock at a time to avoid
5367 * Since only one bpf_spin_lock is allowed the checks are simpler than
5368 * reg_is_refcounted() logic. The verifier needs to remember only
5369 * one spin_lock instead of array of acquired_refs.
5370 * cur_state->active_spin_lock remembers which map value element got locked
5371 * and clears it after bpf_spin_unlock.
5373 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5376 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5377 struct bpf_verifier_state *cur = env->cur_state;
5378 bool is_const = tnum_is_const(reg->var_off);
5379 struct bpf_map *map = reg->map_ptr;
5380 u64 val = reg->var_off.value;
5384 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5390 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5394 if (!map_value_has_spin_lock(map)) {
5395 if (map->spin_lock_off == -E2BIG)
5397 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5399 else if (map->spin_lock_off == -ENOENT)
5401 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5405 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5409 if (map->spin_lock_off != val + reg->off) {
5410 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5415 if (cur->active_spin_lock) {
5417 "Locking two bpf_spin_locks are not allowed\n");
5420 cur->active_spin_lock = reg->id;
5422 if (!cur->active_spin_lock) {
5423 verbose(env, "bpf_spin_unlock without taking a lock\n");
5426 if (cur->active_spin_lock != reg->id) {
5427 verbose(env, "bpf_spin_unlock of different lock\n");
5430 cur->active_spin_lock = 0;
5435 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5436 struct bpf_call_arg_meta *meta)
5438 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5439 bool is_const = tnum_is_const(reg->var_off);
5440 struct bpf_map *map = reg->map_ptr;
5441 u64 val = reg->var_off.value;
5445 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5450 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5454 if (!map_value_has_timer(map)) {
5455 if (map->timer_off == -E2BIG)
5457 "map '%s' has more than one 'struct bpf_timer'\n",
5459 else if (map->timer_off == -ENOENT)
5461 "map '%s' doesn't have 'struct bpf_timer'\n",
5465 "map '%s' is not a struct type or bpf_timer is mangled\n",
5469 if (map->timer_off != val + reg->off) {
5470 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5471 val + reg->off, map->timer_off);
5474 if (meta->map_ptr) {
5475 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5478 meta->map_uid = reg->map_uid;
5479 meta->map_ptr = map;
5483 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5484 struct bpf_call_arg_meta *meta)
5486 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5487 struct bpf_map_value_off_desc *off_desc;
5488 struct bpf_map *map_ptr = reg->map_ptr;
5492 if (!tnum_is_const(reg->var_off)) {
5494 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5498 if (!map_ptr->btf) {
5499 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5503 if (!map_value_has_kptrs(map_ptr)) {
5504 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5506 verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5507 BPF_MAP_VALUE_OFF_MAX);
5508 else if (ret == -EEXIST)
5509 verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5511 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5515 meta->map_ptr = map_ptr;
5516 kptr_off = reg->off + reg->var_off.value;
5517 off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5519 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5522 if (off_desc->type != BPF_KPTR_REF) {
5523 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5526 meta->kptr_off_desc = off_desc;
5530 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5532 return type == ARG_CONST_SIZE ||
5533 type == ARG_CONST_SIZE_OR_ZERO;
5536 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
5538 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
5541 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
5543 return type == ARG_PTR_TO_INT ||
5544 type == ARG_PTR_TO_LONG;
5547 static bool arg_type_is_release(enum bpf_arg_type type)
5549 return type & OBJ_RELEASE;
5552 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5554 return base_type(type) == ARG_PTR_TO_DYNPTR;
5557 static int int_ptr_type_to_size(enum bpf_arg_type type)
5559 if (type == ARG_PTR_TO_INT)
5561 else if (type == ARG_PTR_TO_LONG)
5567 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5568 const struct bpf_call_arg_meta *meta,
5569 enum bpf_arg_type *arg_type)
5571 if (!meta->map_ptr) {
5572 /* kernel subsystem misconfigured verifier */
5573 verbose(env, "invalid map_ptr to access map->type\n");
5577 switch (meta->map_ptr->map_type) {
5578 case BPF_MAP_TYPE_SOCKMAP:
5579 case BPF_MAP_TYPE_SOCKHASH:
5580 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5581 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5583 verbose(env, "invalid arg_type for sockmap/sockhash\n");
5587 case BPF_MAP_TYPE_BLOOM_FILTER:
5588 if (meta->func_id == BPF_FUNC_map_peek_elem)
5589 *arg_type = ARG_PTR_TO_MAP_VALUE;
5597 struct bpf_reg_types {
5598 const enum bpf_reg_type types[10];
5602 static const struct bpf_reg_types map_key_value_types = {
5612 static const struct bpf_reg_types sock_types = {
5622 static const struct bpf_reg_types btf_id_sock_common_types = {
5630 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5634 static const struct bpf_reg_types mem_types = {
5642 PTR_TO_MEM | MEM_ALLOC,
5647 static const struct bpf_reg_types int_ptr_types = {
5657 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5658 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5659 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5660 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5661 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5662 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5663 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5664 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5665 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5666 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5667 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5668 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5669 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5671 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5672 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
5673 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
5674 [ARG_CONST_SIZE] = &scalar_types,
5675 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
5676 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
5677 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
5678 [ARG_PTR_TO_CTX] = &context_types,
5679 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
5681 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5683 [ARG_PTR_TO_SOCKET] = &fullsock_types,
5684 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
5685 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
5686 [ARG_PTR_TO_MEM] = &mem_types,
5687 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
5688 [ARG_PTR_TO_INT] = &int_ptr_types,
5689 [ARG_PTR_TO_LONG] = &int_ptr_types,
5690 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
5691 [ARG_PTR_TO_FUNC] = &func_ptr_types,
5692 [ARG_PTR_TO_STACK] = &stack_ptr_types,
5693 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
5694 [ARG_PTR_TO_TIMER] = &timer_types,
5695 [ARG_PTR_TO_KPTR] = &kptr_types,
5696 [ARG_PTR_TO_DYNPTR] = &stack_ptr_types,
5699 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5700 enum bpf_arg_type arg_type,
5701 const u32 *arg_btf_id,
5702 struct bpf_call_arg_meta *meta)
5704 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5705 enum bpf_reg_type expected, type = reg->type;
5706 const struct bpf_reg_types *compatible;
5709 compatible = compatible_reg_types[base_type(arg_type)];
5711 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5715 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5716 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5718 * Same for MAYBE_NULL:
5720 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5721 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5723 * Therefore we fold these flags depending on the arg_type before comparison.
5725 if (arg_type & MEM_RDONLY)
5726 type &= ~MEM_RDONLY;
5727 if (arg_type & PTR_MAYBE_NULL)
5728 type &= ~PTR_MAYBE_NULL;
5730 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5731 expected = compatible->types[i];
5732 if (expected == NOT_INIT)
5735 if (type == expected)
5739 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5740 for (j = 0; j + 1 < i; j++)
5741 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5742 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5746 if (reg->type == PTR_TO_BTF_ID) {
5747 /* For bpf_sk_release, it needs to match against first member
5748 * 'struct sock_common', hence make an exception for it. This
5749 * allows bpf_sk_release to work for multiple socket types.
5751 bool strict_type_match = arg_type_is_release(arg_type) &&
5752 meta->func_id != BPF_FUNC_sk_release;
5755 if (!compatible->btf_id) {
5756 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5759 arg_btf_id = compatible->btf_id;
5762 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5763 if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5765 } else if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5766 btf_vmlinux, *arg_btf_id,
5767 strict_type_match)) {
5768 verbose(env, "R%d is of type %s but %s is expected\n",
5769 regno, kernel_type_name(reg->btf, reg->btf_id),
5770 kernel_type_name(btf_vmlinux, *arg_btf_id));
5778 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5779 const struct bpf_reg_state *reg, int regno,
5780 enum bpf_arg_type arg_type)
5782 enum bpf_reg_type type = reg->type;
5783 bool fixed_off_ok = false;
5785 switch ((u32)type) {
5786 /* Pointer types where reg offset is explicitly allowed: */
5788 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5789 verbose(env, "cannot pass in dynptr at an offset\n");
5794 case PTR_TO_PACKET_META:
5795 case PTR_TO_MAP_KEY:
5796 case PTR_TO_MAP_VALUE:
5798 case PTR_TO_MEM | MEM_RDONLY:
5799 case PTR_TO_MEM | MEM_ALLOC:
5801 case PTR_TO_BUF | MEM_RDONLY:
5803 /* Some of the argument types nevertheless require a
5804 * zero register offset.
5806 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5809 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5813 /* When referenced PTR_TO_BTF_ID is passed to release function,
5814 * it's fixed offset must be 0. In the other cases, fixed offset
5817 if (arg_type_is_release(arg_type) && reg->off) {
5818 verbose(env, "R%d must have zero offset when passed to release func\n",
5822 /* For arg is release pointer, fixed_off_ok must be false, but
5823 * we already checked and rejected reg->off != 0 above, so set
5824 * to true to allow fixed offset for all other cases.
5826 fixed_off_ok = true;
5831 return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5834 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5836 struct bpf_func_state *state = func(env, reg);
5837 int spi = get_spi(reg->off);
5839 return state->stack[spi].spilled_ptr.id;
5842 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5843 struct bpf_call_arg_meta *meta,
5844 const struct bpf_func_proto *fn)
5846 u32 regno = BPF_REG_1 + arg;
5847 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5848 enum bpf_arg_type arg_type = fn->arg_type[arg];
5849 enum bpf_reg_type type = reg->type;
5850 u32 *arg_btf_id = NULL;
5853 if (arg_type == ARG_DONTCARE)
5856 err = check_reg_arg(env, regno, SRC_OP);
5860 if (arg_type == ARG_ANYTHING) {
5861 if (is_pointer_value(env, regno)) {
5862 verbose(env, "R%d leaks addr into helper function\n",
5869 if (type_is_pkt_pointer(type) &&
5870 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5871 verbose(env, "helper access to the packet is not allowed\n");
5875 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5876 err = resolve_map_arg_type(env, meta, &arg_type);
5881 if (register_is_null(reg) && type_may_be_null(arg_type))
5882 /* A NULL register has a SCALAR_VALUE type, so skip
5885 goto skip_type_check;
5887 /* arg_btf_id and arg_size are in a union. */
5888 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5889 arg_btf_id = fn->arg_btf_id[arg];
5891 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5895 err = check_func_arg_reg_off(env, reg, regno, arg_type);
5900 if (arg_type_is_release(arg_type)) {
5901 if (arg_type_is_dynptr(arg_type)) {
5902 struct bpf_func_state *state = func(env, reg);
5903 int spi = get_spi(reg->off);
5905 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
5906 !state->stack[spi].spilled_ptr.id) {
5907 verbose(env, "arg %d is an unacquired reference\n", regno);
5910 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
5911 verbose(env, "R%d must be referenced when passed to release function\n",
5915 if (meta->release_regno) {
5916 verbose(env, "verifier internal error: more than one release argument\n");
5919 meta->release_regno = regno;
5922 if (reg->ref_obj_id) {
5923 if (meta->ref_obj_id) {
5924 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5925 regno, reg->ref_obj_id,
5929 meta->ref_obj_id = reg->ref_obj_id;
5932 if (arg_type == ARG_CONST_MAP_PTR) {
5933 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5934 if (meta->map_ptr) {
5935 /* Use map_uid (which is unique id of inner map) to reject:
5936 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5937 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5938 * if (inner_map1 && inner_map2) {
5939 * timer = bpf_map_lookup_elem(inner_map1);
5941 * // mismatch would have been allowed
5942 * bpf_timer_init(timer, inner_map2);
5945 * Comparing map_ptr is enough to distinguish normal and outer maps.
5947 if (meta->map_ptr != reg->map_ptr ||
5948 meta->map_uid != reg->map_uid) {
5950 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5951 meta->map_uid, reg->map_uid);
5955 meta->map_ptr = reg->map_ptr;
5956 meta->map_uid = reg->map_uid;
5957 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5958 /* bpf_map_xxx(..., map_ptr, ..., key) call:
5959 * check that [key, key + map->key_size) are within
5960 * stack limits and initialized
5962 if (!meta->map_ptr) {
5963 /* in function declaration map_ptr must come before
5964 * map_key, so that it's verified and known before
5965 * we have to check map_key here. Otherwise it means
5966 * that kernel subsystem misconfigured verifier
5968 verbose(env, "invalid map_ptr to access map->key\n");
5971 err = check_helper_mem_access(env, regno,
5972 meta->map_ptr->key_size, false,
5974 } else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5975 if (type_may_be_null(arg_type) && register_is_null(reg))
5978 /* bpf_map_xxx(..., map_ptr, ..., value) call:
5979 * check [value, value + map->value_size) validity
5981 if (!meta->map_ptr) {
5982 /* kernel subsystem misconfigured verifier */
5983 verbose(env, "invalid map_ptr to access map->value\n");
5986 meta->raw_mode = arg_type & MEM_UNINIT;
5987 err = check_helper_mem_access(env, regno,
5988 meta->map_ptr->value_size, false,
5990 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5992 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5995 meta->ret_btf = reg->btf;
5996 meta->ret_btf_id = reg->btf_id;
5997 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5998 if (meta->func_id == BPF_FUNC_spin_lock) {
5999 if (process_spin_lock(env, regno, true))
6001 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6002 if (process_spin_lock(env, regno, false))
6005 verbose(env, "verifier internal error\n");
6008 } else if (arg_type == ARG_PTR_TO_TIMER) {
6009 if (process_timer_func(env, regno, meta))
6011 } else if (arg_type == ARG_PTR_TO_FUNC) {
6012 meta->subprogno = reg->subprogno;
6013 } else if (base_type(arg_type) == ARG_PTR_TO_MEM) {
6014 /* The access to this pointer is only checked when we hit the
6015 * next is_mem_size argument below.
6017 meta->raw_mode = arg_type & MEM_UNINIT;
6018 if (arg_type & MEM_FIXED_SIZE) {
6019 err = check_helper_mem_access(env, regno,
6020 fn->arg_size[arg], false,
6023 } else if (arg_type_is_mem_size(arg_type)) {
6024 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
6026 err = check_mem_size_reg(env, reg, regno, zero_size_allowed, meta);
6027 } else if (arg_type_is_dynptr(arg_type)) {
6028 if (arg_type & MEM_UNINIT) {
6029 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6030 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6034 /* We only support one dynptr being uninitialized at the moment,
6035 * which is sufficient for the helper functions we have right now.
6037 if (meta->uninit_dynptr_regno) {
6038 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6042 meta->uninit_dynptr_regno = regno;
6043 } else if (!is_dynptr_reg_valid_init(env, reg, arg_type)) {
6044 const char *err_extra = "";
6046 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6047 case DYNPTR_TYPE_LOCAL:
6048 err_extra = "local ";
6050 case DYNPTR_TYPE_RINGBUF:
6051 err_extra = "ringbuf ";
6057 verbose(env, "Expected an initialized %sdynptr as arg #%d\n",
6058 err_extra, arg + 1);
6061 } else if (arg_type_is_alloc_size(arg_type)) {
6062 if (!tnum_is_const(reg->var_off)) {
6063 verbose(env, "R%d is not a known constant'\n",
6067 meta->mem_size = reg->var_off.value;
6068 } else if (arg_type_is_int_ptr(arg_type)) {
6069 int size = int_ptr_type_to_size(arg_type);
6071 err = check_helper_mem_access(env, regno, size, false, meta);
6074 err = check_ptr_alignment(env, reg, 0, size, true);
6075 } else if (arg_type == ARG_PTR_TO_CONST_STR) {
6076 struct bpf_map *map = reg->map_ptr;
6081 if (!bpf_map_is_rdonly(map)) {
6082 verbose(env, "R%d does not point to a readonly map'\n", regno);
6086 if (!tnum_is_const(reg->var_off)) {
6087 verbose(env, "R%d is not a constant address'\n", regno);
6091 if (!map->ops->map_direct_value_addr) {
6092 verbose(env, "no direct value access support for this map type\n");
6096 err = check_map_access(env, regno, reg->off,
6097 map->value_size - reg->off, false,
6102 map_off = reg->off + reg->var_off.value;
6103 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6105 verbose(env, "direct value access on string failed\n");
6109 str_ptr = (char *)(long)(map_addr);
6110 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6111 verbose(env, "string is not zero-terminated\n");
6114 } else if (arg_type == ARG_PTR_TO_KPTR) {
6115 if (process_kptr_func(env, regno, meta))
6122 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6124 enum bpf_attach_type eatype = env->prog->expected_attach_type;
6125 enum bpf_prog_type type = resolve_prog_type(env->prog);
6127 if (func_id != BPF_FUNC_map_update_elem)
6130 /* It's not possible to get access to a locked struct sock in these
6131 * contexts, so updating is safe.
6134 case BPF_PROG_TYPE_TRACING:
6135 if (eatype == BPF_TRACE_ITER)
6138 case BPF_PROG_TYPE_SOCKET_FILTER:
6139 case BPF_PROG_TYPE_SCHED_CLS:
6140 case BPF_PROG_TYPE_SCHED_ACT:
6141 case BPF_PROG_TYPE_XDP:
6142 case BPF_PROG_TYPE_SK_REUSEPORT:
6143 case BPF_PROG_TYPE_FLOW_DISSECTOR:
6144 case BPF_PROG_TYPE_SK_LOOKUP:
6150 verbose(env, "cannot update sockmap in this context\n");
6154 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6156 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
6159 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6160 struct bpf_map *map, int func_id)
6165 /* We need a two way check, first is from map perspective ... */
6166 switch (map->map_type) {
6167 case BPF_MAP_TYPE_PROG_ARRAY:
6168 if (func_id != BPF_FUNC_tail_call)
6171 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6172 if (func_id != BPF_FUNC_perf_event_read &&
6173 func_id != BPF_FUNC_perf_event_output &&
6174 func_id != BPF_FUNC_skb_output &&
6175 func_id != BPF_FUNC_perf_event_read_value &&
6176 func_id != BPF_FUNC_xdp_output)
6179 case BPF_MAP_TYPE_RINGBUF:
6180 if (func_id != BPF_FUNC_ringbuf_output &&
6181 func_id != BPF_FUNC_ringbuf_reserve &&
6182 func_id != BPF_FUNC_ringbuf_query &&
6183 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6184 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6185 func_id != BPF_FUNC_ringbuf_discard_dynptr)
6188 case BPF_MAP_TYPE_STACK_TRACE:
6189 if (func_id != BPF_FUNC_get_stackid)
6192 case BPF_MAP_TYPE_CGROUP_ARRAY:
6193 if (func_id != BPF_FUNC_skb_under_cgroup &&
6194 func_id != BPF_FUNC_current_task_under_cgroup)
6197 case BPF_MAP_TYPE_CGROUP_STORAGE:
6198 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6199 if (func_id != BPF_FUNC_get_local_storage)
6202 case BPF_MAP_TYPE_DEVMAP:
6203 case BPF_MAP_TYPE_DEVMAP_HASH:
6204 if (func_id != BPF_FUNC_redirect_map &&
6205 func_id != BPF_FUNC_map_lookup_elem)
6208 /* Restrict bpf side of cpumap and xskmap, open when use-cases
6211 case BPF_MAP_TYPE_CPUMAP:
6212 if (func_id != BPF_FUNC_redirect_map)
6215 case BPF_MAP_TYPE_XSKMAP:
6216 if (func_id != BPF_FUNC_redirect_map &&
6217 func_id != BPF_FUNC_map_lookup_elem)
6220 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6221 case BPF_MAP_TYPE_HASH_OF_MAPS:
6222 if (func_id != BPF_FUNC_map_lookup_elem)
6225 case BPF_MAP_TYPE_SOCKMAP:
6226 if (func_id != BPF_FUNC_sk_redirect_map &&
6227 func_id != BPF_FUNC_sock_map_update &&
6228 func_id != BPF_FUNC_map_delete_elem &&
6229 func_id != BPF_FUNC_msg_redirect_map &&
6230 func_id != BPF_FUNC_sk_select_reuseport &&
6231 func_id != BPF_FUNC_map_lookup_elem &&
6232 !may_update_sockmap(env, func_id))
6235 case BPF_MAP_TYPE_SOCKHASH:
6236 if (func_id != BPF_FUNC_sk_redirect_hash &&
6237 func_id != BPF_FUNC_sock_hash_update &&
6238 func_id != BPF_FUNC_map_delete_elem &&
6239 func_id != BPF_FUNC_msg_redirect_hash &&
6240 func_id != BPF_FUNC_sk_select_reuseport &&
6241 func_id != BPF_FUNC_map_lookup_elem &&
6242 !may_update_sockmap(env, func_id))
6245 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6246 if (func_id != BPF_FUNC_sk_select_reuseport)
6249 case BPF_MAP_TYPE_QUEUE:
6250 case BPF_MAP_TYPE_STACK:
6251 if (func_id != BPF_FUNC_map_peek_elem &&
6252 func_id != BPF_FUNC_map_pop_elem &&
6253 func_id != BPF_FUNC_map_push_elem)
6256 case BPF_MAP_TYPE_SK_STORAGE:
6257 if (func_id != BPF_FUNC_sk_storage_get &&
6258 func_id != BPF_FUNC_sk_storage_delete)
6261 case BPF_MAP_TYPE_INODE_STORAGE:
6262 if (func_id != BPF_FUNC_inode_storage_get &&
6263 func_id != BPF_FUNC_inode_storage_delete)
6266 case BPF_MAP_TYPE_TASK_STORAGE:
6267 if (func_id != BPF_FUNC_task_storage_get &&
6268 func_id != BPF_FUNC_task_storage_delete)
6271 case BPF_MAP_TYPE_BLOOM_FILTER:
6272 if (func_id != BPF_FUNC_map_peek_elem &&
6273 func_id != BPF_FUNC_map_push_elem)
6280 /* ... and second from the function itself. */
6282 case BPF_FUNC_tail_call:
6283 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6285 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6286 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6290 case BPF_FUNC_perf_event_read:
6291 case BPF_FUNC_perf_event_output:
6292 case BPF_FUNC_perf_event_read_value:
6293 case BPF_FUNC_skb_output:
6294 case BPF_FUNC_xdp_output:
6295 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6298 case BPF_FUNC_ringbuf_output:
6299 case BPF_FUNC_ringbuf_reserve:
6300 case BPF_FUNC_ringbuf_query:
6301 case BPF_FUNC_ringbuf_reserve_dynptr:
6302 case BPF_FUNC_ringbuf_submit_dynptr:
6303 case BPF_FUNC_ringbuf_discard_dynptr:
6304 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6307 case BPF_FUNC_get_stackid:
6308 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6311 case BPF_FUNC_current_task_under_cgroup:
6312 case BPF_FUNC_skb_under_cgroup:
6313 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6316 case BPF_FUNC_redirect_map:
6317 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6318 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6319 map->map_type != BPF_MAP_TYPE_CPUMAP &&
6320 map->map_type != BPF_MAP_TYPE_XSKMAP)
6323 case BPF_FUNC_sk_redirect_map:
6324 case BPF_FUNC_msg_redirect_map:
6325 case BPF_FUNC_sock_map_update:
6326 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6329 case BPF_FUNC_sk_redirect_hash:
6330 case BPF_FUNC_msg_redirect_hash:
6331 case BPF_FUNC_sock_hash_update:
6332 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6335 case BPF_FUNC_get_local_storage:
6336 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6337 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6340 case BPF_FUNC_sk_select_reuseport:
6341 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6342 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6343 map->map_type != BPF_MAP_TYPE_SOCKHASH)
6346 case BPF_FUNC_map_pop_elem:
6347 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6348 map->map_type != BPF_MAP_TYPE_STACK)
6351 case BPF_FUNC_map_peek_elem:
6352 case BPF_FUNC_map_push_elem:
6353 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6354 map->map_type != BPF_MAP_TYPE_STACK &&
6355 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6358 case BPF_FUNC_map_lookup_percpu_elem:
6359 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6360 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6361 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6364 case BPF_FUNC_sk_storage_get:
6365 case BPF_FUNC_sk_storage_delete:
6366 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6369 case BPF_FUNC_inode_storage_get:
6370 case BPF_FUNC_inode_storage_delete:
6371 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6374 case BPF_FUNC_task_storage_get:
6375 case BPF_FUNC_task_storage_delete:
6376 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6385 verbose(env, "cannot pass map_type %d into func %s#%d\n",
6386 map->map_type, func_id_name(func_id), func_id);
6390 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6394 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6396 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6398 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6400 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6402 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6405 /* We only support one arg being in raw mode at the moment,
6406 * which is sufficient for the helper functions we have
6412 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6414 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6415 bool has_size = fn->arg_size[arg] != 0;
6416 bool is_next_size = false;
6418 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6419 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6421 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6422 return is_next_size;
6424 return has_size == is_next_size || is_next_size == is_fixed;
6427 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6429 /* bpf_xxx(..., buf, len) call will access 'len'
6430 * bytes from memory 'buf'. Both arg types need
6431 * to be paired, so make sure there's no buggy
6432 * helper function specification.
6434 if (arg_type_is_mem_size(fn->arg1_type) ||
6435 check_args_pair_invalid(fn, 0) ||
6436 check_args_pair_invalid(fn, 1) ||
6437 check_args_pair_invalid(fn, 2) ||
6438 check_args_pair_invalid(fn, 3) ||
6439 check_args_pair_invalid(fn, 4))
6445 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
6449 if (arg_type_may_be_refcounted(fn->arg1_type))
6451 if (arg_type_may_be_refcounted(fn->arg2_type))
6453 if (arg_type_may_be_refcounted(fn->arg3_type))
6455 if (arg_type_may_be_refcounted(fn->arg4_type))
6457 if (arg_type_may_be_refcounted(fn->arg5_type))
6460 /* A reference acquiring function cannot acquire
6461 * another refcounted ptr.
6463 if (may_be_acquire_function(func_id) && count)
6466 /* We only support one arg being unreferenced at the moment,
6467 * which is sufficient for the helper functions we have right now.
6472 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6476 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6477 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6480 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6481 /* arg_btf_id and arg_size are in a union. */
6482 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6483 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6490 static int check_func_proto(const struct bpf_func_proto *fn, int func_id,
6491 struct bpf_call_arg_meta *meta)
6493 return check_raw_mode_ok(fn) &&
6494 check_arg_pair_ok(fn) &&
6495 check_btf_id_ok(fn) &&
6496 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
6499 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6500 * are now invalid, so turn them into unknown SCALAR_VALUE.
6502 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
6503 struct bpf_func_state *state)
6505 struct bpf_reg_state *regs = state->regs, *reg;
6508 for (i = 0; i < MAX_BPF_REG; i++)
6509 if (reg_is_pkt_pointer_any(®s[i]))
6510 mark_reg_unknown(env, regs, i);
6512 bpf_for_each_spilled_reg(i, state, reg) {
6515 if (reg_is_pkt_pointer_any(reg))
6516 __mark_reg_unknown(env, reg);
6520 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6522 struct bpf_verifier_state *vstate = env->cur_state;
6525 for (i = 0; i <= vstate->curframe; i++)
6526 __clear_all_pkt_pointers(env, vstate->frame[i]);
6531 BEYOND_PKT_END = -2,
6534 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6536 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6537 struct bpf_reg_state *reg = &state->regs[regn];
6539 if (reg->type != PTR_TO_PACKET)
6540 /* PTR_TO_PACKET_META is not supported yet */
6543 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6544 * How far beyond pkt_end it goes is unknown.
6545 * if (!range_open) it's the case of pkt >= pkt_end
6546 * if (range_open) it's the case of pkt > pkt_end
6547 * hence this pointer is at least 1 byte bigger than pkt_end
6550 reg->range = BEYOND_PKT_END;
6552 reg->range = AT_PKT_END;
6555 static void release_reg_references(struct bpf_verifier_env *env,
6556 struct bpf_func_state *state,
6559 struct bpf_reg_state *regs = state->regs, *reg;
6562 for (i = 0; i < MAX_BPF_REG; i++)
6563 if (regs[i].ref_obj_id == ref_obj_id)
6564 mark_reg_unknown(env, regs, i);
6566 bpf_for_each_spilled_reg(i, state, reg) {
6569 if (reg->ref_obj_id == ref_obj_id)
6570 __mark_reg_unknown(env, reg);
6574 /* The pointer with the specified id has released its reference to kernel
6575 * resources. Identify all copies of the same pointer and clear the reference.
6577 static int release_reference(struct bpf_verifier_env *env,
6580 struct bpf_verifier_state *vstate = env->cur_state;
6584 err = release_reference_state(cur_func(env), ref_obj_id);
6588 for (i = 0; i <= vstate->curframe; i++)
6589 release_reg_references(env, vstate->frame[i], ref_obj_id);
6594 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6595 struct bpf_reg_state *regs)
6599 /* after the call registers r0 - r5 were scratched */
6600 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6601 mark_reg_not_init(env, regs, caller_saved[i]);
6602 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6606 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6607 struct bpf_func_state *caller,
6608 struct bpf_func_state *callee,
6611 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6612 int *insn_idx, int subprog,
6613 set_callee_state_fn set_callee_state_cb)
6615 struct bpf_verifier_state *state = env->cur_state;
6616 struct bpf_func_info_aux *func_info_aux;
6617 struct bpf_func_state *caller, *callee;
6619 bool is_global = false;
6621 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6622 verbose(env, "the call stack of %d frames is too deep\n",
6623 state->curframe + 2);
6627 caller = state->frame[state->curframe];
6628 if (state->frame[state->curframe + 1]) {
6629 verbose(env, "verifier bug. Frame %d already allocated\n",
6630 state->curframe + 1);
6634 func_info_aux = env->prog->aux->func_info_aux;
6636 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6637 err = btf_check_subprog_arg_match(env, subprog, caller->regs);
6642 verbose(env, "Caller passes invalid args into func#%d\n",
6646 if (env->log.level & BPF_LOG_LEVEL)
6648 "Func#%d is global and valid. Skipping.\n",
6650 clear_caller_saved_regs(env, caller->regs);
6652 /* All global functions return a 64-bit SCALAR_VALUE */
6653 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6654 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6656 /* continue with next insn after call */
6661 if (insn->code == (BPF_JMP | BPF_CALL) &&
6662 insn->src_reg == 0 &&
6663 insn->imm == BPF_FUNC_timer_set_callback) {
6664 struct bpf_verifier_state *async_cb;
6666 /* there is no real recursion here. timer callbacks are async */
6667 env->subprog_info[subprog].is_async_cb = true;
6668 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6669 *insn_idx, subprog);
6672 callee = async_cb->frame[0];
6673 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6675 /* Convert bpf_timer_set_callback() args into timer callback args */
6676 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6680 clear_caller_saved_regs(env, caller->regs);
6681 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6682 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6683 /* continue with next insn after call */
6687 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6690 state->frame[state->curframe + 1] = callee;
6692 /* callee cannot access r0, r6 - r9 for reading and has to write
6693 * into its own stack before reading from it.
6694 * callee can read/write into caller's stack
6696 init_func_state(env, callee,
6697 /* remember the callsite, it will be used by bpf_exit */
6698 *insn_idx /* callsite */,
6699 state->curframe + 1 /* frameno within this callchain */,
6700 subprog /* subprog number within this prog */);
6702 /* Transfer references to the callee */
6703 err = copy_reference_state(callee, caller);
6707 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6711 clear_caller_saved_regs(env, caller->regs);
6713 /* only increment it after check_reg_arg() finished */
6716 /* and go analyze first insn of the callee */
6717 *insn_idx = env->subprog_info[subprog].start - 1;
6719 if (env->log.level & BPF_LOG_LEVEL) {
6720 verbose(env, "caller:\n");
6721 print_verifier_state(env, caller, true);
6722 verbose(env, "callee:\n");
6723 print_verifier_state(env, callee, true);
6728 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6729 struct bpf_func_state *caller,
6730 struct bpf_func_state *callee)
6732 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6733 * void *callback_ctx, u64 flags);
6734 * callback_fn(struct bpf_map *map, void *key, void *value,
6735 * void *callback_ctx);
6737 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6739 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6740 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6741 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6743 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6744 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6745 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6747 /* pointer to stack or null */
6748 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6751 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6755 static int set_callee_state(struct bpf_verifier_env *env,
6756 struct bpf_func_state *caller,
6757 struct bpf_func_state *callee, int insn_idx)
6761 /* copy r1 - r5 args that callee can access. The copy includes parent
6762 * pointers, which connects us up to the liveness chain
6764 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6765 callee->regs[i] = caller->regs[i];
6769 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6772 int subprog, target_insn;
6774 target_insn = *insn_idx + insn->imm + 1;
6775 subprog = find_subprog(env, target_insn);
6777 verbose(env, "verifier bug. No program starts at insn %d\n",
6782 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6785 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6786 struct bpf_func_state *caller,
6787 struct bpf_func_state *callee,
6790 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6791 struct bpf_map *map;
6794 if (bpf_map_ptr_poisoned(insn_aux)) {
6795 verbose(env, "tail_call abusing map_ptr\n");
6799 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6800 if (!map->ops->map_set_for_each_callback_args ||
6801 !map->ops->map_for_each_callback) {
6802 verbose(env, "callback function not allowed for map\n");
6806 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6810 callee->in_callback_fn = true;
6814 static int set_loop_callback_state(struct bpf_verifier_env *env,
6815 struct bpf_func_state *caller,
6816 struct bpf_func_state *callee,
6819 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6821 * callback_fn(u32 index, void *callback_ctx);
6823 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6824 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6827 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6828 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6829 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6831 callee->in_callback_fn = true;
6835 static int set_timer_callback_state(struct bpf_verifier_env *env,
6836 struct bpf_func_state *caller,
6837 struct bpf_func_state *callee,
6840 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6842 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6843 * callback_fn(struct bpf_map *map, void *key, void *value);
6845 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6846 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6847 callee->regs[BPF_REG_1].map_ptr = map_ptr;
6849 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6850 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6851 callee->regs[BPF_REG_2].map_ptr = map_ptr;
6853 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6854 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6855 callee->regs[BPF_REG_3].map_ptr = map_ptr;
6858 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6859 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6860 callee->in_async_callback_fn = true;
6864 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6865 struct bpf_func_state *caller,
6866 struct bpf_func_state *callee,
6869 /* bpf_find_vma(struct task_struct *task, u64 addr,
6870 * void *callback_fn, void *callback_ctx, u64 flags)
6871 * (callback_fn)(struct task_struct *task,
6872 * struct vm_area_struct *vma, void *callback_ctx);
6874 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6876 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6877 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6878 callee->regs[BPF_REG_2].btf = btf_vmlinux;
6879 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6881 /* pointer to stack or null */
6882 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6885 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6886 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6887 callee->in_callback_fn = true;
6891 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6893 struct bpf_verifier_state *state = env->cur_state;
6894 struct bpf_func_state *caller, *callee;
6895 struct bpf_reg_state *r0;
6898 callee = state->frame[state->curframe];
6899 r0 = &callee->regs[BPF_REG_0];
6900 if (r0->type == PTR_TO_STACK) {
6901 /* technically it's ok to return caller's stack pointer
6902 * (or caller's caller's pointer) back to the caller,
6903 * since these pointers are valid. Only current stack
6904 * pointer will be invalid as soon as function exits,
6905 * but let's be conservative
6907 verbose(env, "cannot return stack pointer to the caller\n");
6912 caller = state->frame[state->curframe];
6913 if (callee->in_callback_fn) {
6914 /* enforce R0 return value range [0, 1]. */
6915 struct tnum range = tnum_range(0, 1);
6917 if (r0->type != SCALAR_VALUE) {
6918 verbose(env, "R0 not a scalar value\n");
6921 if (!tnum_in(range, r0->var_off)) {
6922 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6926 /* return to the caller whatever r0 had in the callee */
6927 caller->regs[BPF_REG_0] = *r0;
6930 /* Transfer references to the caller */
6931 err = copy_reference_state(caller, callee);
6935 *insn_idx = callee->callsite + 1;
6936 if (env->log.level & BPF_LOG_LEVEL) {
6937 verbose(env, "returning from callee:\n");
6938 print_verifier_state(env, callee, true);
6939 verbose(env, "to caller at %d:\n", *insn_idx);
6940 print_verifier_state(env, caller, true);
6942 /* clear everything in the callee */
6943 free_func_state(callee);
6944 state->frame[state->curframe + 1] = NULL;
6948 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6950 struct bpf_call_arg_meta *meta)
6952 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
6954 if (ret_type != RET_INTEGER ||
6955 (func_id != BPF_FUNC_get_stack &&
6956 func_id != BPF_FUNC_get_task_stack &&
6957 func_id != BPF_FUNC_probe_read_str &&
6958 func_id != BPF_FUNC_probe_read_kernel_str &&
6959 func_id != BPF_FUNC_probe_read_user_str))
6962 ret_reg->smax_value = meta->msize_max_value;
6963 ret_reg->s32_max_value = meta->msize_max_value;
6964 ret_reg->smin_value = -MAX_ERRNO;
6965 ret_reg->s32_min_value = -MAX_ERRNO;
6966 reg_bounds_sync(ret_reg);
6970 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6971 int func_id, int insn_idx)
6973 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6974 struct bpf_map *map = meta->map_ptr;
6976 if (func_id != BPF_FUNC_tail_call &&
6977 func_id != BPF_FUNC_map_lookup_elem &&
6978 func_id != BPF_FUNC_map_update_elem &&
6979 func_id != BPF_FUNC_map_delete_elem &&
6980 func_id != BPF_FUNC_map_push_elem &&
6981 func_id != BPF_FUNC_map_pop_elem &&
6982 func_id != BPF_FUNC_map_peek_elem &&
6983 func_id != BPF_FUNC_for_each_map_elem &&
6984 func_id != BPF_FUNC_redirect_map &&
6985 func_id != BPF_FUNC_map_lookup_percpu_elem)
6989 verbose(env, "kernel subsystem misconfigured verifier\n");
6993 /* In case of read-only, some additional restrictions
6994 * need to be applied in order to prevent altering the
6995 * state of the map from program side.
6997 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6998 (func_id == BPF_FUNC_map_delete_elem ||
6999 func_id == BPF_FUNC_map_update_elem ||
7000 func_id == BPF_FUNC_map_push_elem ||
7001 func_id == BPF_FUNC_map_pop_elem)) {
7002 verbose(env, "write into map forbidden\n");
7006 if (!BPF_MAP_PTR(aux->map_ptr_state))
7007 bpf_map_ptr_store(aux, meta->map_ptr,
7008 !meta->map_ptr->bypass_spec_v1);
7009 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7010 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7011 !meta->map_ptr->bypass_spec_v1);
7016 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7017 int func_id, int insn_idx)
7019 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7020 struct bpf_reg_state *regs = cur_regs(env), *reg;
7021 struct bpf_map *map = meta->map_ptr;
7026 if (func_id != BPF_FUNC_tail_call)
7028 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7029 verbose(env, "kernel subsystem misconfigured verifier\n");
7033 range = tnum_range(0, map->max_entries - 1);
7034 reg = ®s[BPF_REG_3];
7036 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
7037 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7041 err = mark_chain_precision(env, BPF_REG_3);
7045 val = reg->var_off.value;
7046 if (bpf_map_key_unseen(aux))
7047 bpf_map_key_store(aux, val);
7048 else if (!bpf_map_key_poisoned(aux) &&
7049 bpf_map_key_immediate(aux) != val)
7050 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7054 static int check_reference_leak(struct bpf_verifier_env *env)
7056 struct bpf_func_state *state = cur_func(env);
7059 for (i = 0; i < state->acquired_refs; i++) {
7060 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7061 state->refs[i].id, state->refs[i].insn_idx);
7063 return state->acquired_refs ? -EINVAL : 0;
7066 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7067 struct bpf_reg_state *regs)
7069 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
7070 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
7071 struct bpf_map *fmt_map = fmt_reg->map_ptr;
7072 int err, fmt_map_off, num_args;
7076 /* data must be an array of u64 */
7077 if (data_len_reg->var_off.value % 8)
7079 num_args = data_len_reg->var_off.value / 8;
7081 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7082 * and map_direct_value_addr is set.
7084 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7085 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7088 verbose(env, "verifier bug\n");
7091 fmt = (char *)(long)fmt_addr + fmt_map_off;
7093 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7094 * can focus on validating the format specifiers.
7096 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7098 verbose(env, "Invalid format string\n");
7103 static int check_get_func_ip(struct bpf_verifier_env *env)
7105 enum bpf_prog_type type = resolve_prog_type(env->prog);
7106 int func_id = BPF_FUNC_get_func_ip;
7108 if (type == BPF_PROG_TYPE_TRACING) {
7109 if (!bpf_prog_has_trampoline(env->prog)) {
7110 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7111 func_id_name(func_id), func_id);
7115 } else if (type == BPF_PROG_TYPE_KPROBE) {
7119 verbose(env, "func %s#%d not supported for program type %d\n",
7120 func_id_name(func_id), func_id, type);
7124 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7127 const struct bpf_func_proto *fn = NULL;
7128 enum bpf_return_type ret_type;
7129 enum bpf_type_flag ret_flag;
7130 struct bpf_reg_state *regs;
7131 struct bpf_call_arg_meta meta;
7132 int insn_idx = *insn_idx_p;
7134 int i, err, func_id;
7136 /* find function prototype */
7137 func_id = insn->imm;
7138 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7139 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7144 if (env->ops->get_func_proto)
7145 fn = env->ops->get_func_proto(func_id, env->prog);
7147 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7152 /* eBPF programs must be GPL compatible to use GPL-ed functions */
7153 if (!env->prog->gpl_compatible && fn->gpl_only) {
7154 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7158 if (fn->allowed && !fn->allowed(env->prog)) {
7159 verbose(env, "helper call is not allowed in probe\n");
7163 /* With LD_ABS/IND some JITs save/restore skb from r1. */
7164 changes_data = bpf_helper_changes_pkt_data(fn->func);
7165 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7166 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7167 func_id_name(func_id), func_id);
7171 memset(&meta, 0, sizeof(meta));
7172 meta.pkt_access = fn->pkt_access;
7174 err = check_func_proto(fn, func_id, &meta);
7176 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7177 func_id_name(func_id), func_id);
7181 meta.func_id = func_id;
7183 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7184 err = check_func_arg(env, i, &meta, fn);
7189 err = record_func_map(env, &meta, func_id, insn_idx);
7193 err = record_func_key(env, &meta, func_id, insn_idx);
7197 /* Mark slots with STACK_MISC in case of raw mode, stack offset
7198 * is inferred from register state.
7200 for (i = 0; i < meta.access_size; i++) {
7201 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7202 BPF_WRITE, -1, false);
7207 regs = cur_regs(env);
7209 if (meta.uninit_dynptr_regno) {
7210 /* we write BPF_DW bits (8 bytes) at a time */
7211 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7212 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7213 i, BPF_DW, BPF_WRITE, -1, false);
7218 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno],
7219 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7225 if (meta.release_regno) {
7227 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7228 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
7229 else if (meta.ref_obj_id)
7230 err = release_reference(env, meta.ref_obj_id);
7231 /* meta.ref_obj_id can only be 0 if register that is meant to be
7232 * released is NULL, which must be > R0.
7234 else if (register_is_null(®s[meta.release_regno]))
7237 verbose(env, "func %s#%d reference has not been acquired before\n",
7238 func_id_name(func_id), func_id);
7244 case BPF_FUNC_tail_call:
7245 err = check_reference_leak(env);
7247 verbose(env, "tail_call would lead to reference leak\n");
7251 case BPF_FUNC_get_local_storage:
7252 /* check that flags argument in get_local_storage(map, flags) is 0,
7253 * this is required because get_local_storage() can't return an error.
7255 if (!register_is_null(®s[BPF_REG_2])) {
7256 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7260 case BPF_FUNC_for_each_map_elem:
7261 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7262 set_map_elem_callback_state);
7264 case BPF_FUNC_timer_set_callback:
7265 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7266 set_timer_callback_state);
7268 case BPF_FUNC_find_vma:
7269 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7270 set_find_vma_callback_state);
7272 case BPF_FUNC_snprintf:
7273 err = check_bpf_snprintf_call(env, regs);
7276 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7277 set_loop_callback_state);
7279 case BPF_FUNC_dynptr_from_mem:
7280 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7281 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7282 reg_type_str(env, regs[BPF_REG_1].type));
7290 /* reset caller saved regs */
7291 for (i = 0; i < CALLER_SAVED_REGS; i++) {
7292 mark_reg_not_init(env, regs, caller_saved[i]);
7293 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7296 /* helper call returns 64-bit value. */
7297 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7299 /* update return register (already marked as written above) */
7300 ret_type = fn->ret_type;
7301 ret_flag = type_flag(fn->ret_type);
7302 if (ret_type == RET_INTEGER) {
7303 /* sets type to SCALAR_VALUE */
7304 mark_reg_unknown(env, regs, BPF_REG_0);
7305 } else if (ret_type == RET_VOID) {
7306 regs[BPF_REG_0].type = NOT_INIT;
7307 } else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) {
7308 /* There is no offset yet applied, variable or fixed */
7309 mark_reg_known_zero(env, regs, BPF_REG_0);
7310 /* remember map_ptr, so that check_map_access()
7311 * can check 'value_size' boundary of memory access
7312 * to map element returned from bpf_map_lookup_elem()
7314 if (meta.map_ptr == NULL) {
7316 "kernel subsystem misconfigured verifier\n");
7319 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7320 regs[BPF_REG_0].map_uid = meta.map_uid;
7321 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7322 if (!type_may_be_null(ret_type) &&
7323 map_value_has_spin_lock(meta.map_ptr)) {
7324 regs[BPF_REG_0].id = ++env->id_gen;
7326 } else if (base_type(ret_type) == RET_PTR_TO_SOCKET) {
7327 mark_reg_known_zero(env, regs, BPF_REG_0);
7328 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7329 } else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) {
7330 mark_reg_known_zero(env, regs, BPF_REG_0);
7331 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7332 } else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) {
7333 mark_reg_known_zero(env, regs, BPF_REG_0);
7334 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7335 } else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) {
7336 mark_reg_known_zero(env, regs, BPF_REG_0);
7337 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7338 regs[BPF_REG_0].mem_size = meta.mem_size;
7339 } else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) {
7340 const struct btf_type *t;
7342 mark_reg_known_zero(env, regs, BPF_REG_0);
7343 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7344 if (!btf_type_is_struct(t)) {
7346 const struct btf_type *ret;
7349 /* resolve the type size of ksym. */
7350 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7352 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7353 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7354 tname, PTR_ERR(ret));
7357 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7358 regs[BPF_REG_0].mem_size = tsize;
7360 /* MEM_RDONLY may be carried from ret_flag, but it
7361 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7362 * it will confuse the check of PTR_TO_BTF_ID in
7363 * check_mem_access().
7365 ret_flag &= ~MEM_RDONLY;
7367 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7368 regs[BPF_REG_0].btf = meta.ret_btf;
7369 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7371 } else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) {
7372 struct btf *ret_btf;
7375 mark_reg_known_zero(env, regs, BPF_REG_0);
7376 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7377 if (func_id == BPF_FUNC_kptr_xchg) {
7378 ret_btf = meta.kptr_off_desc->kptr.btf;
7379 ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7381 ret_btf = btf_vmlinux;
7382 ret_btf_id = *fn->ret_btf_id;
7384 if (ret_btf_id == 0) {
7385 verbose(env, "invalid return type %u of func %s#%d\n",
7386 base_type(ret_type), func_id_name(func_id),
7390 regs[BPF_REG_0].btf = ret_btf;
7391 regs[BPF_REG_0].btf_id = ret_btf_id;
7393 verbose(env, "unknown return type %u of func %s#%d\n",
7394 base_type(ret_type), func_id_name(func_id), func_id);
7398 if (type_may_be_null(regs[BPF_REG_0].type))
7399 regs[BPF_REG_0].id = ++env->id_gen;
7401 if (is_ptr_cast_function(func_id)) {
7402 /* For release_reference() */
7403 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7404 } else if (is_acquire_function(func_id, meta.map_ptr)) {
7405 int id = acquire_reference_state(env, insn_idx);
7409 /* For mark_ptr_or_null_reg() */
7410 regs[BPF_REG_0].id = id;
7411 /* For release_reference() */
7412 regs[BPF_REG_0].ref_obj_id = id;
7413 } else if (func_id == BPF_FUNC_dynptr_data) {
7414 int dynptr_id = 0, i;
7416 /* Find the id of the dynptr we're acquiring a reference to */
7417 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7418 if (arg_type_is_dynptr(fn->arg_type[i])) {
7420 verbose(env, "verifier internal error: multiple dynptr args in func\n");
7423 dynptr_id = stack_slot_get_id(env, ®s[BPF_REG_1 + i]);
7426 /* For release_reference() */
7427 regs[BPF_REG_0].ref_obj_id = dynptr_id;
7430 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7432 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7436 if ((func_id == BPF_FUNC_get_stack ||
7437 func_id == BPF_FUNC_get_task_stack) &&
7438 !env->prog->has_callchain_buf) {
7439 const char *err_str;
7441 #ifdef CONFIG_PERF_EVENTS
7442 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7443 err_str = "cannot get callchain buffer for func %s#%d\n";
7446 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7449 verbose(env, err_str, func_id_name(func_id), func_id);
7453 env->prog->has_callchain_buf = true;
7456 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7457 env->prog->call_get_stack = true;
7459 if (func_id == BPF_FUNC_get_func_ip) {
7460 if (check_get_func_ip(env))
7462 env->prog->call_get_func_ip = true;
7466 clear_all_pkt_pointers(env);
7470 /* mark_btf_func_reg_size() is used when the reg size is determined by
7471 * the BTF func_proto's return value size and argument.
7473 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7476 struct bpf_reg_state *reg = &cur_regs(env)[regno];
7478 if (regno == BPF_REG_0) {
7479 /* Function return value */
7480 reg->live |= REG_LIVE_WRITTEN;
7481 reg->subreg_def = reg_size == sizeof(u64) ?
7482 DEF_NOT_SUBREG : env->insn_idx + 1;
7484 /* Function argument */
7485 if (reg_size == sizeof(u64)) {
7486 mark_insn_zext(env, reg);
7487 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7489 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7494 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7497 const struct btf_type *t, *func, *func_proto, *ptr_type;
7498 struct bpf_reg_state *regs = cur_regs(env);
7499 const char *func_name, *ptr_type_name;
7500 u32 i, nargs, func_id, ptr_type_id;
7501 int err, insn_idx = *insn_idx_p;
7502 const struct btf_param *args;
7503 struct btf *desc_btf;
7506 /* skip for now, but return error when we find this in fixup_kfunc_call */
7510 desc_btf = find_kfunc_desc_btf(env, insn->off);
7511 if (IS_ERR(desc_btf))
7512 return PTR_ERR(desc_btf);
7514 func_id = insn->imm;
7515 func = btf_type_by_id(desc_btf, func_id);
7516 func_name = btf_name_by_offset(desc_btf, func->name_off);
7517 func_proto = btf_type_by_id(desc_btf, func->type);
7519 if (!btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog),
7520 BTF_KFUNC_TYPE_CHECK, func_id)) {
7521 verbose(env, "calling kernel function %s is not allowed\n",
7526 acq = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog),
7527 BTF_KFUNC_TYPE_ACQUIRE, func_id);
7529 /* Check the arguments */
7530 err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs);
7533 /* In case of release function, we get register number of refcounted
7534 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7537 err = release_reference(env, regs[err].ref_obj_id);
7539 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7540 func_name, func_id);
7545 for (i = 0; i < CALLER_SAVED_REGS; i++)
7546 mark_reg_not_init(env, regs, caller_saved[i]);
7548 /* Check return type */
7549 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7551 if (acq && !btf_type_is_ptr(t)) {
7552 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7556 if (btf_type_is_scalar(t)) {
7557 mark_reg_unknown(env, regs, BPF_REG_0);
7558 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7559 } else if (btf_type_is_ptr(t)) {
7560 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7562 if (!btf_type_is_struct(ptr_type)) {
7563 ptr_type_name = btf_name_by_offset(desc_btf,
7564 ptr_type->name_off);
7565 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
7566 func_name, btf_type_str(ptr_type),
7570 mark_reg_known_zero(env, regs, BPF_REG_0);
7571 regs[BPF_REG_0].btf = desc_btf;
7572 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7573 regs[BPF_REG_0].btf_id = ptr_type_id;
7574 if (btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog),
7575 BTF_KFUNC_TYPE_RET_NULL, func_id)) {
7576 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7577 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7578 regs[BPF_REG_0].id = ++env->id_gen;
7580 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7582 int id = acquire_reference_state(env, insn_idx);
7586 regs[BPF_REG_0].id = id;
7587 regs[BPF_REG_0].ref_obj_id = id;
7589 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7591 nargs = btf_type_vlen(func_proto);
7592 args = (const struct btf_param *)(func_proto + 1);
7593 for (i = 0; i < nargs; i++) {
7596 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7597 if (btf_type_is_ptr(t))
7598 mark_btf_func_reg_size(env, regno, sizeof(void *));
7600 /* scalar. ensured by btf_check_kfunc_arg_match() */
7601 mark_btf_func_reg_size(env, regno, t->size);
7607 static bool signed_add_overflows(s64 a, s64 b)
7609 /* Do the add in u64, where overflow is well-defined */
7610 s64 res = (s64)((u64)a + (u64)b);
7617 static bool signed_add32_overflows(s32 a, s32 b)
7619 /* Do the add in u32, where overflow is well-defined */
7620 s32 res = (s32)((u32)a + (u32)b);
7627 static bool signed_sub_overflows(s64 a, s64 b)
7629 /* Do the sub in u64, where overflow is well-defined */
7630 s64 res = (s64)((u64)a - (u64)b);
7637 static bool signed_sub32_overflows(s32 a, s32 b)
7639 /* Do the sub in u32, where overflow is well-defined */
7640 s32 res = (s32)((u32)a - (u32)b);
7647 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7648 const struct bpf_reg_state *reg,
7649 enum bpf_reg_type type)
7651 bool known = tnum_is_const(reg->var_off);
7652 s64 val = reg->var_off.value;
7653 s64 smin = reg->smin_value;
7655 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7656 verbose(env, "math between %s pointer and %lld is not allowed\n",
7657 reg_type_str(env, type), val);
7661 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7662 verbose(env, "%s pointer offset %d is not allowed\n",
7663 reg_type_str(env, type), reg->off);
7667 if (smin == S64_MIN) {
7668 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7669 reg_type_str(env, type));
7673 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7674 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7675 smin, reg_type_str(env, type));
7682 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7684 return &env->insn_aux_data[env->insn_idx];
7695 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7696 u32 *alu_limit, bool mask_to_left)
7698 u32 max = 0, ptr_limit = 0;
7700 switch (ptr_reg->type) {
7702 /* Offset 0 is out-of-bounds, but acceptable start for the
7703 * left direction, see BPF_REG_FP. Also, unknown scalar
7704 * offset where we would need to deal with min/max bounds is
7705 * currently prohibited for unprivileged.
7707 max = MAX_BPF_STACK + mask_to_left;
7708 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7710 case PTR_TO_MAP_VALUE:
7711 max = ptr_reg->map_ptr->value_size;
7712 ptr_limit = (mask_to_left ?
7713 ptr_reg->smin_value :
7714 ptr_reg->umax_value) + ptr_reg->off;
7720 if (ptr_limit >= max)
7721 return REASON_LIMIT;
7722 *alu_limit = ptr_limit;
7726 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7727 const struct bpf_insn *insn)
7729 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7732 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7733 u32 alu_state, u32 alu_limit)
7735 /* If we arrived here from different branches with different
7736 * state or limits to sanitize, then this won't work.
7738 if (aux->alu_state &&
7739 (aux->alu_state != alu_state ||
7740 aux->alu_limit != alu_limit))
7741 return REASON_PATHS;
7743 /* Corresponding fixup done in do_misc_fixups(). */
7744 aux->alu_state = alu_state;
7745 aux->alu_limit = alu_limit;
7749 static int sanitize_val_alu(struct bpf_verifier_env *env,
7750 struct bpf_insn *insn)
7752 struct bpf_insn_aux_data *aux = cur_aux(env);
7754 if (can_skip_alu_sanitation(env, insn))
7757 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7760 static bool sanitize_needed(u8 opcode)
7762 return opcode == BPF_ADD || opcode == BPF_SUB;
7765 struct bpf_sanitize_info {
7766 struct bpf_insn_aux_data aux;
7770 static struct bpf_verifier_state *
7771 sanitize_speculative_path(struct bpf_verifier_env *env,
7772 const struct bpf_insn *insn,
7773 u32 next_idx, u32 curr_idx)
7775 struct bpf_verifier_state *branch;
7776 struct bpf_reg_state *regs;
7778 branch = push_stack(env, next_idx, curr_idx, true);
7779 if (branch && insn) {
7780 regs = branch->frame[branch->curframe]->regs;
7781 if (BPF_SRC(insn->code) == BPF_K) {
7782 mark_reg_unknown(env, regs, insn->dst_reg);
7783 } else if (BPF_SRC(insn->code) == BPF_X) {
7784 mark_reg_unknown(env, regs, insn->dst_reg);
7785 mark_reg_unknown(env, regs, insn->src_reg);
7791 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7792 struct bpf_insn *insn,
7793 const struct bpf_reg_state *ptr_reg,
7794 const struct bpf_reg_state *off_reg,
7795 struct bpf_reg_state *dst_reg,
7796 struct bpf_sanitize_info *info,
7797 const bool commit_window)
7799 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7800 struct bpf_verifier_state *vstate = env->cur_state;
7801 bool off_is_imm = tnum_is_const(off_reg->var_off);
7802 bool off_is_neg = off_reg->smin_value < 0;
7803 bool ptr_is_dst_reg = ptr_reg == dst_reg;
7804 u8 opcode = BPF_OP(insn->code);
7805 u32 alu_state, alu_limit;
7806 struct bpf_reg_state tmp;
7810 if (can_skip_alu_sanitation(env, insn))
7813 /* We already marked aux for masking from non-speculative
7814 * paths, thus we got here in the first place. We only care
7815 * to explore bad access from here.
7817 if (vstate->speculative)
7820 if (!commit_window) {
7821 if (!tnum_is_const(off_reg->var_off) &&
7822 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
7823 return REASON_BOUNDS;
7825 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
7826 (opcode == BPF_SUB && !off_is_neg);
7829 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
7833 if (commit_window) {
7834 /* In commit phase we narrow the masking window based on
7835 * the observed pointer move after the simulated operation.
7837 alu_state = info->aux.alu_state;
7838 alu_limit = abs(info->aux.alu_limit - alu_limit);
7840 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
7841 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7842 alu_state |= ptr_is_dst_reg ?
7843 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
7845 /* Limit pruning on unknown scalars to enable deep search for
7846 * potential masking differences from other program paths.
7849 env->explore_alu_limits = true;
7852 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7856 /* If we're in commit phase, we're done here given we already
7857 * pushed the truncated dst_reg into the speculative verification
7860 * Also, when register is a known constant, we rewrite register-based
7861 * operation to immediate-based, and thus do not need masking (and as
7862 * a consequence, do not need to simulate the zero-truncation either).
7864 if (commit_window || off_is_imm)
7867 /* Simulate and find potential out-of-bounds access under
7868 * speculative execution from truncation as a result of
7869 * masking when off was not within expected range. If off
7870 * sits in dst, then we temporarily need to move ptr there
7871 * to simulate dst (== 0) +/-= ptr. Needed, for example,
7872 * for cases where we use K-based arithmetic in one direction
7873 * and truncated reg-based in the other in order to explore
7876 if (!ptr_is_dst_reg) {
7878 *dst_reg = *ptr_reg;
7880 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7882 if (!ptr_is_dst_reg && ret)
7884 return !ret ? REASON_STACK : 0;
7887 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7889 struct bpf_verifier_state *vstate = env->cur_state;
7891 /* If we simulate paths under speculation, we don't update the
7892 * insn as 'seen' such that when we verify unreachable paths in
7893 * the non-speculative domain, sanitize_dead_code() can still
7894 * rewrite/sanitize them.
7896 if (!vstate->speculative)
7897 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7900 static int sanitize_err(struct bpf_verifier_env *env,
7901 const struct bpf_insn *insn, int reason,
7902 const struct bpf_reg_state *off_reg,
7903 const struct bpf_reg_state *dst_reg)
7905 static const char *err = "pointer arithmetic with it prohibited for !root";
7906 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7907 u32 dst = insn->dst_reg, src = insn->src_reg;
7911 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7912 off_reg == dst_reg ? dst : src, err);
7915 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7916 off_reg == dst_reg ? src : dst, err);
7919 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7923 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7927 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7931 verbose(env, "verifier internal error: unknown reason (%d)\n",
7939 /* check that stack access falls within stack limits and that 'reg' doesn't
7940 * have a variable offset.
7942 * Variable offset is prohibited for unprivileged mode for simplicity since it
7943 * requires corresponding support in Spectre masking for stack ALU. See also
7944 * retrieve_ptr_limit().
7947 * 'off' includes 'reg->off'.
7949 static int check_stack_access_for_ptr_arithmetic(
7950 struct bpf_verifier_env *env,
7952 const struct bpf_reg_state *reg,
7955 if (!tnum_is_const(reg->var_off)) {
7958 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7959 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
7960 regno, tn_buf, off);
7964 if (off >= 0 || off < -MAX_BPF_STACK) {
7965 verbose(env, "R%d stack pointer arithmetic goes out of range, "
7966 "prohibited for !root; off=%d\n", regno, off);
7973 static int sanitize_check_bounds(struct bpf_verifier_env *env,
7974 const struct bpf_insn *insn,
7975 const struct bpf_reg_state *dst_reg)
7977 u32 dst = insn->dst_reg;
7979 /* For unprivileged we require that resulting offset must be in bounds
7980 * in order to be able to sanitize access later on.
7982 if (env->bypass_spec_v1)
7985 switch (dst_reg->type) {
7987 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
7988 dst_reg->off + dst_reg->var_off.value))
7991 case PTR_TO_MAP_VALUE:
7992 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
7993 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
7994 "prohibited for !root\n", dst);
8005 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8006 * Caller should also handle BPF_MOV case separately.
8007 * If we return -EACCES, caller may want to try again treating pointer as a
8008 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
8010 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8011 struct bpf_insn *insn,
8012 const struct bpf_reg_state *ptr_reg,
8013 const struct bpf_reg_state *off_reg)
8015 struct bpf_verifier_state *vstate = env->cur_state;
8016 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8017 struct bpf_reg_state *regs = state->regs, *dst_reg;
8018 bool known = tnum_is_const(off_reg->var_off);
8019 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8020 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8021 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8022 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8023 struct bpf_sanitize_info info = {};
8024 u8 opcode = BPF_OP(insn->code);
8025 u32 dst = insn->dst_reg;
8028 dst_reg = ®s[dst];
8030 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8031 smin_val > smax_val || umin_val > umax_val) {
8032 /* Taint dst register if offset had invalid bounds derived from
8033 * e.g. dead branches.
8035 __mark_reg_unknown(env, dst_reg);
8039 if (BPF_CLASS(insn->code) != BPF_ALU64) {
8040 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8041 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8042 __mark_reg_unknown(env, dst_reg);
8047 "R%d 32-bit pointer arithmetic prohibited\n",
8052 if (ptr_reg->type & PTR_MAYBE_NULL) {
8053 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8054 dst, reg_type_str(env, ptr_reg->type));
8058 switch (base_type(ptr_reg->type)) {
8059 case CONST_PTR_TO_MAP:
8060 /* smin_val represents the known value */
8061 if (known && smin_val == 0 && opcode == BPF_ADD)
8064 case PTR_TO_PACKET_END:
8066 case PTR_TO_SOCK_COMMON:
8067 case PTR_TO_TCP_SOCK:
8068 case PTR_TO_XDP_SOCK:
8069 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8070 dst, reg_type_str(env, ptr_reg->type));
8076 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8077 * The id may be overwritten later if we create a new variable offset.
8079 dst_reg->type = ptr_reg->type;
8080 dst_reg->id = ptr_reg->id;
8082 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8083 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8086 /* pointer types do not carry 32-bit bounds at the moment. */
8087 __mark_reg32_unbounded(dst_reg);
8089 if (sanitize_needed(opcode)) {
8090 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8093 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8098 /* We can take a fixed offset as long as it doesn't overflow
8099 * the s32 'off' field
8101 if (known && (ptr_reg->off + smin_val ==
8102 (s64)(s32)(ptr_reg->off + smin_val))) {
8103 /* pointer += K. Accumulate it into fixed offset */
8104 dst_reg->smin_value = smin_ptr;
8105 dst_reg->smax_value = smax_ptr;
8106 dst_reg->umin_value = umin_ptr;
8107 dst_reg->umax_value = umax_ptr;
8108 dst_reg->var_off = ptr_reg->var_off;
8109 dst_reg->off = ptr_reg->off + smin_val;
8110 dst_reg->raw = ptr_reg->raw;
8113 /* A new variable offset is created. Note that off_reg->off
8114 * == 0, since it's a scalar.
8115 * dst_reg gets the pointer type and since some positive
8116 * integer value was added to the pointer, give it a new 'id'
8117 * if it's a PTR_TO_PACKET.
8118 * this creates a new 'base' pointer, off_reg (variable) gets
8119 * added into the variable offset, and we copy the fixed offset
8122 if (signed_add_overflows(smin_ptr, smin_val) ||
8123 signed_add_overflows(smax_ptr, smax_val)) {
8124 dst_reg->smin_value = S64_MIN;
8125 dst_reg->smax_value = S64_MAX;
8127 dst_reg->smin_value = smin_ptr + smin_val;
8128 dst_reg->smax_value = smax_ptr + smax_val;
8130 if (umin_ptr + umin_val < umin_ptr ||
8131 umax_ptr + umax_val < umax_ptr) {
8132 dst_reg->umin_value = 0;
8133 dst_reg->umax_value = U64_MAX;
8135 dst_reg->umin_value = umin_ptr + umin_val;
8136 dst_reg->umax_value = umax_ptr + umax_val;
8138 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8139 dst_reg->off = ptr_reg->off;
8140 dst_reg->raw = ptr_reg->raw;
8141 if (reg_is_pkt_pointer(ptr_reg)) {
8142 dst_reg->id = ++env->id_gen;
8143 /* something was added to pkt_ptr, set range to zero */
8144 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8148 if (dst_reg == off_reg) {
8149 /* scalar -= pointer. Creates an unknown scalar */
8150 verbose(env, "R%d tried to subtract pointer from scalar\n",
8154 /* We don't allow subtraction from FP, because (according to
8155 * test_verifier.c test "invalid fp arithmetic", JITs might not
8156 * be able to deal with it.
8158 if (ptr_reg->type == PTR_TO_STACK) {
8159 verbose(env, "R%d subtraction from stack pointer prohibited\n",
8163 if (known && (ptr_reg->off - smin_val ==
8164 (s64)(s32)(ptr_reg->off - smin_val))) {
8165 /* pointer -= K. Subtract it from fixed offset */
8166 dst_reg->smin_value = smin_ptr;
8167 dst_reg->smax_value = smax_ptr;
8168 dst_reg->umin_value = umin_ptr;
8169 dst_reg->umax_value = umax_ptr;
8170 dst_reg->var_off = ptr_reg->var_off;
8171 dst_reg->id = ptr_reg->id;
8172 dst_reg->off = ptr_reg->off - smin_val;
8173 dst_reg->raw = ptr_reg->raw;
8176 /* A new variable offset is created. If the subtrahend is known
8177 * nonnegative, then any reg->range we had before is still good.
8179 if (signed_sub_overflows(smin_ptr, smax_val) ||
8180 signed_sub_overflows(smax_ptr, smin_val)) {
8181 /* Overflow possible, we know nothing */
8182 dst_reg->smin_value = S64_MIN;
8183 dst_reg->smax_value = S64_MAX;
8185 dst_reg->smin_value = smin_ptr - smax_val;
8186 dst_reg->smax_value = smax_ptr - smin_val;
8188 if (umin_ptr < umax_val) {
8189 /* Overflow possible, we know nothing */
8190 dst_reg->umin_value = 0;
8191 dst_reg->umax_value = U64_MAX;
8193 /* Cannot overflow (as long as bounds are consistent) */
8194 dst_reg->umin_value = umin_ptr - umax_val;
8195 dst_reg->umax_value = umax_ptr - umin_val;
8197 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8198 dst_reg->off = ptr_reg->off;
8199 dst_reg->raw = ptr_reg->raw;
8200 if (reg_is_pkt_pointer(ptr_reg)) {
8201 dst_reg->id = ++env->id_gen;
8202 /* something was added to pkt_ptr, set range to zero */
8204 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8210 /* bitwise ops on pointers are troublesome, prohibit. */
8211 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8212 dst, bpf_alu_string[opcode >> 4]);
8215 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8216 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8217 dst, bpf_alu_string[opcode >> 4]);
8221 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8223 reg_bounds_sync(dst_reg);
8224 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8226 if (sanitize_needed(opcode)) {
8227 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8230 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8236 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8237 struct bpf_reg_state *src_reg)
8239 s32 smin_val = src_reg->s32_min_value;
8240 s32 smax_val = src_reg->s32_max_value;
8241 u32 umin_val = src_reg->u32_min_value;
8242 u32 umax_val = src_reg->u32_max_value;
8244 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8245 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8246 dst_reg->s32_min_value = S32_MIN;
8247 dst_reg->s32_max_value = S32_MAX;
8249 dst_reg->s32_min_value += smin_val;
8250 dst_reg->s32_max_value += smax_val;
8252 if (dst_reg->u32_min_value + umin_val < umin_val ||
8253 dst_reg->u32_max_value + umax_val < umax_val) {
8254 dst_reg->u32_min_value = 0;
8255 dst_reg->u32_max_value = U32_MAX;
8257 dst_reg->u32_min_value += umin_val;
8258 dst_reg->u32_max_value += umax_val;
8262 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8263 struct bpf_reg_state *src_reg)
8265 s64 smin_val = src_reg->smin_value;
8266 s64 smax_val = src_reg->smax_value;
8267 u64 umin_val = src_reg->umin_value;
8268 u64 umax_val = src_reg->umax_value;
8270 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8271 signed_add_overflows(dst_reg->smax_value, smax_val)) {
8272 dst_reg->smin_value = S64_MIN;
8273 dst_reg->smax_value = S64_MAX;
8275 dst_reg->smin_value += smin_val;
8276 dst_reg->smax_value += smax_val;
8278 if (dst_reg->umin_value + umin_val < umin_val ||
8279 dst_reg->umax_value + umax_val < umax_val) {
8280 dst_reg->umin_value = 0;
8281 dst_reg->umax_value = U64_MAX;
8283 dst_reg->umin_value += umin_val;
8284 dst_reg->umax_value += umax_val;
8288 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8289 struct bpf_reg_state *src_reg)
8291 s32 smin_val = src_reg->s32_min_value;
8292 s32 smax_val = src_reg->s32_max_value;
8293 u32 umin_val = src_reg->u32_min_value;
8294 u32 umax_val = src_reg->u32_max_value;
8296 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8297 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8298 /* Overflow possible, we know nothing */
8299 dst_reg->s32_min_value = S32_MIN;
8300 dst_reg->s32_max_value = S32_MAX;
8302 dst_reg->s32_min_value -= smax_val;
8303 dst_reg->s32_max_value -= smin_val;
8305 if (dst_reg->u32_min_value < umax_val) {
8306 /* Overflow possible, we know nothing */
8307 dst_reg->u32_min_value = 0;
8308 dst_reg->u32_max_value = U32_MAX;
8310 /* Cannot overflow (as long as bounds are consistent) */
8311 dst_reg->u32_min_value -= umax_val;
8312 dst_reg->u32_max_value -= umin_val;
8316 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8317 struct bpf_reg_state *src_reg)
8319 s64 smin_val = src_reg->smin_value;
8320 s64 smax_val = src_reg->smax_value;
8321 u64 umin_val = src_reg->umin_value;
8322 u64 umax_val = src_reg->umax_value;
8324 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8325 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8326 /* Overflow possible, we know nothing */
8327 dst_reg->smin_value = S64_MIN;
8328 dst_reg->smax_value = S64_MAX;
8330 dst_reg->smin_value -= smax_val;
8331 dst_reg->smax_value -= smin_val;
8333 if (dst_reg->umin_value < umax_val) {
8334 /* Overflow possible, we know nothing */
8335 dst_reg->umin_value = 0;
8336 dst_reg->umax_value = U64_MAX;
8338 /* Cannot overflow (as long as bounds are consistent) */
8339 dst_reg->umin_value -= umax_val;
8340 dst_reg->umax_value -= umin_val;
8344 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8345 struct bpf_reg_state *src_reg)
8347 s32 smin_val = src_reg->s32_min_value;
8348 u32 umin_val = src_reg->u32_min_value;
8349 u32 umax_val = src_reg->u32_max_value;
8351 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8352 /* Ain't nobody got time to multiply that sign */
8353 __mark_reg32_unbounded(dst_reg);
8356 /* Both values are positive, so we can work with unsigned and
8357 * copy the result to signed (unless it exceeds S32_MAX).
8359 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8360 /* Potential overflow, we know nothing */
8361 __mark_reg32_unbounded(dst_reg);
8364 dst_reg->u32_min_value *= umin_val;
8365 dst_reg->u32_max_value *= umax_val;
8366 if (dst_reg->u32_max_value > S32_MAX) {
8367 /* Overflow possible, we know nothing */
8368 dst_reg->s32_min_value = S32_MIN;
8369 dst_reg->s32_max_value = S32_MAX;
8371 dst_reg->s32_min_value = dst_reg->u32_min_value;
8372 dst_reg->s32_max_value = dst_reg->u32_max_value;
8376 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8377 struct bpf_reg_state *src_reg)
8379 s64 smin_val = src_reg->smin_value;
8380 u64 umin_val = src_reg->umin_value;
8381 u64 umax_val = src_reg->umax_value;
8383 if (smin_val < 0 || dst_reg->smin_value < 0) {
8384 /* Ain't nobody got time to multiply that sign */
8385 __mark_reg64_unbounded(dst_reg);
8388 /* Both values are positive, so we can work with unsigned and
8389 * copy the result to signed (unless it exceeds S64_MAX).
8391 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8392 /* Potential overflow, we know nothing */
8393 __mark_reg64_unbounded(dst_reg);
8396 dst_reg->umin_value *= umin_val;
8397 dst_reg->umax_value *= umax_val;
8398 if (dst_reg->umax_value > S64_MAX) {
8399 /* Overflow possible, we know nothing */
8400 dst_reg->smin_value = S64_MIN;
8401 dst_reg->smax_value = S64_MAX;
8403 dst_reg->smin_value = dst_reg->umin_value;
8404 dst_reg->smax_value = dst_reg->umax_value;
8408 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8409 struct bpf_reg_state *src_reg)
8411 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8412 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8413 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8414 s32 smin_val = src_reg->s32_min_value;
8415 u32 umax_val = src_reg->u32_max_value;
8417 if (src_known && dst_known) {
8418 __mark_reg32_known(dst_reg, var32_off.value);
8422 /* We get our minimum from the var_off, since that's inherently
8423 * bitwise. Our maximum is the minimum of the operands' maxima.
8425 dst_reg->u32_min_value = var32_off.value;
8426 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8427 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8428 /* Lose signed bounds when ANDing negative numbers,
8429 * ain't nobody got time for that.
8431 dst_reg->s32_min_value = S32_MIN;
8432 dst_reg->s32_max_value = S32_MAX;
8434 /* ANDing two positives gives a positive, so safe to
8435 * cast result into s64.
8437 dst_reg->s32_min_value = dst_reg->u32_min_value;
8438 dst_reg->s32_max_value = dst_reg->u32_max_value;
8442 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8443 struct bpf_reg_state *src_reg)
8445 bool src_known = tnum_is_const(src_reg->var_off);
8446 bool dst_known = tnum_is_const(dst_reg->var_off);
8447 s64 smin_val = src_reg->smin_value;
8448 u64 umax_val = src_reg->umax_value;
8450 if (src_known && dst_known) {
8451 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8455 /* We get our minimum from the var_off, since that's inherently
8456 * bitwise. Our maximum is the minimum of the operands' maxima.
8458 dst_reg->umin_value = dst_reg->var_off.value;
8459 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8460 if (dst_reg->smin_value < 0 || smin_val < 0) {
8461 /* Lose signed bounds when ANDing negative numbers,
8462 * ain't nobody got time for that.
8464 dst_reg->smin_value = S64_MIN;
8465 dst_reg->smax_value = S64_MAX;
8467 /* ANDing two positives gives a positive, so safe to
8468 * cast result into s64.
8470 dst_reg->smin_value = dst_reg->umin_value;
8471 dst_reg->smax_value = dst_reg->umax_value;
8473 /* We may learn something more from the var_off */
8474 __update_reg_bounds(dst_reg);
8477 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8478 struct bpf_reg_state *src_reg)
8480 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8481 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8482 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8483 s32 smin_val = src_reg->s32_min_value;
8484 u32 umin_val = src_reg->u32_min_value;
8486 if (src_known && dst_known) {
8487 __mark_reg32_known(dst_reg, var32_off.value);
8491 /* We get our maximum from the var_off, and our minimum is the
8492 * maximum of the operands' minima
8494 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8495 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8496 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8497 /* Lose signed bounds when ORing negative numbers,
8498 * ain't nobody got time for that.
8500 dst_reg->s32_min_value = S32_MIN;
8501 dst_reg->s32_max_value = S32_MAX;
8503 /* ORing two positives gives a positive, so safe to
8504 * cast result into s64.
8506 dst_reg->s32_min_value = dst_reg->u32_min_value;
8507 dst_reg->s32_max_value = dst_reg->u32_max_value;
8511 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8512 struct bpf_reg_state *src_reg)
8514 bool src_known = tnum_is_const(src_reg->var_off);
8515 bool dst_known = tnum_is_const(dst_reg->var_off);
8516 s64 smin_val = src_reg->smin_value;
8517 u64 umin_val = src_reg->umin_value;
8519 if (src_known && dst_known) {
8520 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8524 /* We get our maximum from the var_off, and our minimum is the
8525 * maximum of the operands' minima
8527 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8528 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8529 if (dst_reg->smin_value < 0 || smin_val < 0) {
8530 /* Lose signed bounds when ORing negative numbers,
8531 * ain't nobody got time for that.
8533 dst_reg->smin_value = S64_MIN;
8534 dst_reg->smax_value = S64_MAX;
8536 /* ORing two positives gives a positive, so safe to
8537 * cast result into s64.
8539 dst_reg->smin_value = dst_reg->umin_value;
8540 dst_reg->smax_value = dst_reg->umax_value;
8542 /* We may learn something more from the var_off */
8543 __update_reg_bounds(dst_reg);
8546 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8547 struct bpf_reg_state *src_reg)
8549 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8550 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8551 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8552 s32 smin_val = src_reg->s32_min_value;
8554 if (src_known && dst_known) {
8555 __mark_reg32_known(dst_reg, var32_off.value);
8559 /* We get both minimum and maximum from the var32_off. */
8560 dst_reg->u32_min_value = var32_off.value;
8561 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8563 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8564 /* XORing two positive sign numbers gives a positive,
8565 * so safe to cast u32 result into s32.
8567 dst_reg->s32_min_value = dst_reg->u32_min_value;
8568 dst_reg->s32_max_value = dst_reg->u32_max_value;
8570 dst_reg->s32_min_value = S32_MIN;
8571 dst_reg->s32_max_value = S32_MAX;
8575 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8576 struct bpf_reg_state *src_reg)
8578 bool src_known = tnum_is_const(src_reg->var_off);
8579 bool dst_known = tnum_is_const(dst_reg->var_off);
8580 s64 smin_val = src_reg->smin_value;
8582 if (src_known && dst_known) {
8583 /* dst_reg->var_off.value has been updated earlier */
8584 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8588 /* We get both minimum and maximum from the var_off. */
8589 dst_reg->umin_value = dst_reg->var_off.value;
8590 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8592 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8593 /* XORing two positive sign numbers gives a positive,
8594 * so safe to cast u64 result into s64.
8596 dst_reg->smin_value = dst_reg->umin_value;
8597 dst_reg->smax_value = dst_reg->umax_value;
8599 dst_reg->smin_value = S64_MIN;
8600 dst_reg->smax_value = S64_MAX;
8603 __update_reg_bounds(dst_reg);
8606 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8607 u64 umin_val, u64 umax_val)
8609 /* We lose all sign bit information (except what we can pick
8612 dst_reg->s32_min_value = S32_MIN;
8613 dst_reg->s32_max_value = S32_MAX;
8614 /* If we might shift our top bit out, then we know nothing */
8615 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8616 dst_reg->u32_min_value = 0;
8617 dst_reg->u32_max_value = U32_MAX;
8619 dst_reg->u32_min_value <<= umin_val;
8620 dst_reg->u32_max_value <<= umax_val;
8624 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8625 struct bpf_reg_state *src_reg)
8627 u32 umax_val = src_reg->u32_max_value;
8628 u32 umin_val = src_reg->u32_min_value;
8629 /* u32 alu operation will zext upper bits */
8630 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8632 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8633 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8634 /* Not required but being careful mark reg64 bounds as unknown so
8635 * that we are forced to pick them up from tnum and zext later and
8636 * if some path skips this step we are still safe.
8638 __mark_reg64_unbounded(dst_reg);
8639 __update_reg32_bounds(dst_reg);
8642 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8643 u64 umin_val, u64 umax_val)
8645 /* Special case <<32 because it is a common compiler pattern to sign
8646 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8647 * positive we know this shift will also be positive so we can track
8648 * bounds correctly. Otherwise we lose all sign bit information except
8649 * what we can pick up from var_off. Perhaps we can generalize this
8650 * later to shifts of any length.
8652 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8653 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8655 dst_reg->smax_value = S64_MAX;
8657 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8658 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8660 dst_reg->smin_value = S64_MIN;
8662 /* If we might shift our top bit out, then we know nothing */
8663 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8664 dst_reg->umin_value = 0;
8665 dst_reg->umax_value = U64_MAX;
8667 dst_reg->umin_value <<= umin_val;
8668 dst_reg->umax_value <<= umax_val;
8672 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8673 struct bpf_reg_state *src_reg)
8675 u64 umax_val = src_reg->umax_value;
8676 u64 umin_val = src_reg->umin_value;
8678 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8679 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8680 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8682 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8683 /* We may learn something more from the var_off */
8684 __update_reg_bounds(dst_reg);
8687 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8688 struct bpf_reg_state *src_reg)
8690 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8691 u32 umax_val = src_reg->u32_max_value;
8692 u32 umin_val = src_reg->u32_min_value;
8694 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8695 * be negative, then either:
8696 * 1) src_reg might be zero, so the sign bit of the result is
8697 * unknown, so we lose our signed bounds
8698 * 2) it's known negative, thus the unsigned bounds capture the
8700 * 3) the signed bounds cross zero, so they tell us nothing
8702 * If the value in dst_reg is known nonnegative, then again the
8703 * unsigned bounds capture the signed bounds.
8704 * Thus, in all cases it suffices to blow away our signed bounds
8705 * and rely on inferring new ones from the unsigned bounds and
8706 * var_off of the result.
8708 dst_reg->s32_min_value = S32_MIN;
8709 dst_reg->s32_max_value = S32_MAX;
8711 dst_reg->var_off = tnum_rshift(subreg, umin_val);
8712 dst_reg->u32_min_value >>= umax_val;
8713 dst_reg->u32_max_value >>= umin_val;
8715 __mark_reg64_unbounded(dst_reg);
8716 __update_reg32_bounds(dst_reg);
8719 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8720 struct bpf_reg_state *src_reg)
8722 u64 umax_val = src_reg->umax_value;
8723 u64 umin_val = src_reg->umin_value;
8725 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8726 * be negative, then either:
8727 * 1) src_reg might be zero, so the sign bit of the result is
8728 * unknown, so we lose our signed bounds
8729 * 2) it's known negative, thus the unsigned bounds capture the
8731 * 3) the signed bounds cross zero, so they tell us nothing
8733 * If the value in dst_reg is known nonnegative, then again the
8734 * unsigned bounds capture the signed bounds.
8735 * Thus, in all cases it suffices to blow away our signed bounds
8736 * and rely on inferring new ones from the unsigned bounds and
8737 * var_off of the result.
8739 dst_reg->smin_value = S64_MIN;
8740 dst_reg->smax_value = S64_MAX;
8741 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8742 dst_reg->umin_value >>= umax_val;
8743 dst_reg->umax_value >>= umin_val;
8745 /* Its not easy to operate on alu32 bounds here because it depends
8746 * on bits being shifted in. Take easy way out and mark unbounded
8747 * so we can recalculate later from tnum.
8749 __mark_reg32_unbounded(dst_reg);
8750 __update_reg_bounds(dst_reg);
8753 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8754 struct bpf_reg_state *src_reg)
8756 u64 umin_val = src_reg->u32_min_value;
8758 /* Upon reaching here, src_known is true and
8759 * umax_val is equal to umin_val.
8761 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8762 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8764 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8766 /* blow away the dst_reg umin_value/umax_value and rely on
8767 * dst_reg var_off to refine the result.
8769 dst_reg->u32_min_value = 0;
8770 dst_reg->u32_max_value = U32_MAX;
8772 __mark_reg64_unbounded(dst_reg);
8773 __update_reg32_bounds(dst_reg);
8776 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8777 struct bpf_reg_state *src_reg)
8779 u64 umin_val = src_reg->umin_value;
8781 /* Upon reaching here, src_known is true and umax_val is equal
8784 dst_reg->smin_value >>= umin_val;
8785 dst_reg->smax_value >>= umin_val;
8787 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8789 /* blow away the dst_reg umin_value/umax_value and rely on
8790 * dst_reg var_off to refine the result.
8792 dst_reg->umin_value = 0;
8793 dst_reg->umax_value = U64_MAX;
8795 /* Its not easy to operate on alu32 bounds here because it depends
8796 * on bits being shifted in from upper 32-bits. Take easy way out
8797 * and mark unbounded so we can recalculate later from tnum.
8799 __mark_reg32_unbounded(dst_reg);
8800 __update_reg_bounds(dst_reg);
8803 /* WARNING: This function does calculations on 64-bit values, but the actual
8804 * execution may occur on 32-bit values. Therefore, things like bitshifts
8805 * need extra checks in the 32-bit case.
8807 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8808 struct bpf_insn *insn,
8809 struct bpf_reg_state *dst_reg,
8810 struct bpf_reg_state src_reg)
8812 struct bpf_reg_state *regs = cur_regs(env);
8813 u8 opcode = BPF_OP(insn->code);
8815 s64 smin_val, smax_val;
8816 u64 umin_val, umax_val;
8817 s32 s32_min_val, s32_max_val;
8818 u32 u32_min_val, u32_max_val;
8819 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
8820 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
8823 smin_val = src_reg.smin_value;
8824 smax_val = src_reg.smax_value;
8825 umin_val = src_reg.umin_value;
8826 umax_val = src_reg.umax_value;
8828 s32_min_val = src_reg.s32_min_value;
8829 s32_max_val = src_reg.s32_max_value;
8830 u32_min_val = src_reg.u32_min_value;
8831 u32_max_val = src_reg.u32_max_value;
8834 src_known = tnum_subreg_is_const(src_reg.var_off);
8836 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
8837 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
8838 /* Taint dst register if offset had invalid bounds
8839 * derived from e.g. dead branches.
8841 __mark_reg_unknown(env, dst_reg);
8845 src_known = tnum_is_const(src_reg.var_off);
8847 (smin_val != smax_val || umin_val != umax_val)) ||
8848 smin_val > smax_val || umin_val > umax_val) {
8849 /* Taint dst register if offset had invalid bounds
8850 * derived from e.g. dead branches.
8852 __mark_reg_unknown(env, dst_reg);
8858 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
8859 __mark_reg_unknown(env, dst_reg);
8863 if (sanitize_needed(opcode)) {
8864 ret = sanitize_val_alu(env, insn);
8866 return sanitize_err(env, insn, ret, NULL, NULL);
8869 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8870 * There are two classes of instructions: The first class we track both
8871 * alu32 and alu64 sign/unsigned bounds independently this provides the
8872 * greatest amount of precision when alu operations are mixed with jmp32
8873 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8874 * and BPF_OR. This is possible because these ops have fairly easy to
8875 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8876 * See alu32 verifier tests for examples. The second class of
8877 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8878 * with regards to tracking sign/unsigned bounds because the bits may
8879 * cross subreg boundaries in the alu64 case. When this happens we mark
8880 * the reg unbounded in the subreg bound space and use the resulting
8881 * tnum to calculate an approximation of the sign/unsigned bounds.
8885 scalar32_min_max_add(dst_reg, &src_reg);
8886 scalar_min_max_add(dst_reg, &src_reg);
8887 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
8890 scalar32_min_max_sub(dst_reg, &src_reg);
8891 scalar_min_max_sub(dst_reg, &src_reg);
8892 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
8895 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8896 scalar32_min_max_mul(dst_reg, &src_reg);
8897 scalar_min_max_mul(dst_reg, &src_reg);
8900 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8901 scalar32_min_max_and(dst_reg, &src_reg);
8902 scalar_min_max_and(dst_reg, &src_reg);
8905 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8906 scalar32_min_max_or(dst_reg, &src_reg);
8907 scalar_min_max_or(dst_reg, &src_reg);
8910 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8911 scalar32_min_max_xor(dst_reg, &src_reg);
8912 scalar_min_max_xor(dst_reg, &src_reg);
8915 if (umax_val >= insn_bitness) {
8916 /* Shifts greater than 31 or 63 are undefined.
8917 * This includes shifts by a negative number.
8919 mark_reg_unknown(env, regs, insn->dst_reg);
8923 scalar32_min_max_lsh(dst_reg, &src_reg);
8925 scalar_min_max_lsh(dst_reg, &src_reg);
8928 if (umax_val >= insn_bitness) {
8929 /* Shifts greater than 31 or 63 are undefined.
8930 * This includes shifts by a negative number.
8932 mark_reg_unknown(env, regs, insn->dst_reg);
8936 scalar32_min_max_rsh(dst_reg, &src_reg);
8938 scalar_min_max_rsh(dst_reg, &src_reg);
8941 if (umax_val >= insn_bitness) {
8942 /* Shifts greater than 31 or 63 are undefined.
8943 * This includes shifts by a negative number.
8945 mark_reg_unknown(env, regs, insn->dst_reg);
8949 scalar32_min_max_arsh(dst_reg, &src_reg);
8951 scalar_min_max_arsh(dst_reg, &src_reg);
8954 mark_reg_unknown(env, regs, insn->dst_reg);
8958 /* ALU32 ops are zero extended into 64bit register */
8960 zext_32_to_64(dst_reg);
8961 reg_bounds_sync(dst_reg);
8965 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
8968 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
8969 struct bpf_insn *insn)
8971 struct bpf_verifier_state *vstate = env->cur_state;
8972 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8973 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
8974 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
8975 u8 opcode = BPF_OP(insn->code);
8978 dst_reg = ®s[insn->dst_reg];
8980 if (dst_reg->type != SCALAR_VALUE)
8983 /* Make sure ID is cleared otherwise dst_reg min/max could be
8984 * incorrectly propagated into other registers by find_equal_scalars()
8987 if (BPF_SRC(insn->code) == BPF_X) {
8988 src_reg = ®s[insn->src_reg];
8989 if (src_reg->type != SCALAR_VALUE) {
8990 if (dst_reg->type != SCALAR_VALUE) {
8991 /* Combining two pointers by any ALU op yields
8992 * an arbitrary scalar. Disallow all math except
8993 * pointer subtraction
8995 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8996 mark_reg_unknown(env, regs, insn->dst_reg);
8999 verbose(env, "R%d pointer %s pointer prohibited\n",
9001 bpf_alu_string[opcode >> 4]);
9004 /* scalar += pointer
9005 * This is legal, but we have to reverse our
9006 * src/dest handling in computing the range
9008 err = mark_chain_precision(env, insn->dst_reg);
9011 return adjust_ptr_min_max_vals(env, insn,
9014 } else if (ptr_reg) {
9015 /* pointer += scalar */
9016 err = mark_chain_precision(env, insn->src_reg);
9019 return adjust_ptr_min_max_vals(env, insn,
9023 /* Pretend the src is a reg with a known value, since we only
9024 * need to be able to read from this state.
9026 off_reg.type = SCALAR_VALUE;
9027 __mark_reg_known(&off_reg, insn->imm);
9029 if (ptr_reg) /* pointer += K */
9030 return adjust_ptr_min_max_vals(env, insn,
9034 /* Got here implies adding two SCALAR_VALUEs */
9035 if (WARN_ON_ONCE(ptr_reg)) {
9036 print_verifier_state(env, state, true);
9037 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9040 if (WARN_ON(!src_reg)) {
9041 print_verifier_state(env, state, true);
9042 verbose(env, "verifier internal error: no src_reg\n");
9045 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9048 /* check validity of 32-bit and 64-bit arithmetic operations */
9049 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9051 struct bpf_reg_state *regs = cur_regs(env);
9052 u8 opcode = BPF_OP(insn->code);
9055 if (opcode == BPF_END || opcode == BPF_NEG) {
9056 if (opcode == BPF_NEG) {
9057 if (BPF_SRC(insn->code) != 0 ||
9058 insn->src_reg != BPF_REG_0 ||
9059 insn->off != 0 || insn->imm != 0) {
9060 verbose(env, "BPF_NEG uses reserved fields\n");
9064 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9065 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9066 BPF_CLASS(insn->code) == BPF_ALU64) {
9067 verbose(env, "BPF_END uses reserved fields\n");
9072 /* check src operand */
9073 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9077 if (is_pointer_value(env, insn->dst_reg)) {
9078 verbose(env, "R%d pointer arithmetic prohibited\n",
9083 /* check dest operand */
9084 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9088 } else if (opcode == BPF_MOV) {
9090 if (BPF_SRC(insn->code) == BPF_X) {
9091 if (insn->imm != 0 || insn->off != 0) {
9092 verbose(env, "BPF_MOV uses reserved fields\n");
9096 /* check src operand */
9097 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9101 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9102 verbose(env, "BPF_MOV uses reserved fields\n");
9107 /* check dest operand, mark as required later */
9108 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9112 if (BPF_SRC(insn->code) == BPF_X) {
9113 struct bpf_reg_state *src_reg = regs + insn->src_reg;
9114 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9116 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9118 * copy register state to dest reg
9120 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9121 /* Assign src and dst registers the same ID
9122 * that will be used by find_equal_scalars()
9123 * to propagate min/max range.
9125 src_reg->id = ++env->id_gen;
9126 *dst_reg = *src_reg;
9127 dst_reg->live |= REG_LIVE_WRITTEN;
9128 dst_reg->subreg_def = DEF_NOT_SUBREG;
9131 if (is_pointer_value(env, insn->src_reg)) {
9133 "R%d partial copy of pointer\n",
9136 } else if (src_reg->type == SCALAR_VALUE) {
9137 *dst_reg = *src_reg;
9138 /* Make sure ID is cleared otherwise
9139 * dst_reg min/max could be incorrectly
9140 * propagated into src_reg by find_equal_scalars()
9143 dst_reg->live |= REG_LIVE_WRITTEN;
9144 dst_reg->subreg_def = env->insn_idx + 1;
9146 mark_reg_unknown(env, regs,
9149 zext_32_to_64(dst_reg);
9150 reg_bounds_sync(dst_reg);
9154 * remember the value we stored into this reg
9156 /* clear any state __mark_reg_known doesn't set */
9157 mark_reg_unknown(env, regs, insn->dst_reg);
9158 regs[insn->dst_reg].type = SCALAR_VALUE;
9159 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9160 __mark_reg_known(regs + insn->dst_reg,
9163 __mark_reg_known(regs + insn->dst_reg,
9168 } else if (opcode > BPF_END) {
9169 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9172 } else { /* all other ALU ops: and, sub, xor, add, ... */
9174 if (BPF_SRC(insn->code) == BPF_X) {
9175 if (insn->imm != 0 || insn->off != 0) {
9176 verbose(env, "BPF_ALU uses reserved fields\n");
9179 /* check src1 operand */
9180 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9184 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9185 verbose(env, "BPF_ALU uses reserved fields\n");
9190 /* check src2 operand */
9191 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9195 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9196 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9197 verbose(env, "div by zero\n");
9201 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9202 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9203 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9205 if (insn->imm < 0 || insn->imm >= size) {
9206 verbose(env, "invalid shift %d\n", insn->imm);
9211 /* check dest operand */
9212 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9216 return adjust_reg_min_max_vals(env, insn);
9222 static void __find_good_pkt_pointers(struct bpf_func_state *state,
9223 struct bpf_reg_state *dst_reg,
9224 enum bpf_reg_type type, int new_range)
9226 struct bpf_reg_state *reg;
9229 for (i = 0; i < MAX_BPF_REG; i++) {
9230 reg = &state->regs[i];
9231 if (reg->type == type && reg->id == dst_reg->id)
9232 /* keep the maximum range already checked */
9233 reg->range = max(reg->range, new_range);
9236 bpf_for_each_spilled_reg(i, state, reg) {
9239 if (reg->type == type && reg->id == dst_reg->id)
9240 reg->range = max(reg->range, new_range);
9244 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9245 struct bpf_reg_state *dst_reg,
9246 enum bpf_reg_type type,
9247 bool range_right_open)
9251 if (dst_reg->off < 0 ||
9252 (dst_reg->off == 0 && range_right_open))
9253 /* This doesn't give us any range */
9256 if (dst_reg->umax_value > MAX_PACKET_OFF ||
9257 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9258 /* Risk of overflow. For instance, ptr + (1<<63) may be less
9259 * than pkt_end, but that's because it's also less than pkt.
9263 new_range = dst_reg->off;
9264 if (range_right_open)
9267 /* Examples for register markings:
9269 * pkt_data in dst register:
9273 * if (r2 > pkt_end) goto <handle exception>
9278 * if (r2 < pkt_end) goto <access okay>
9279 * <handle exception>
9282 * r2 == dst_reg, pkt_end == src_reg
9283 * r2=pkt(id=n,off=8,r=0)
9284 * r3=pkt(id=n,off=0,r=0)
9286 * pkt_data in src register:
9290 * if (pkt_end >= r2) goto <access okay>
9291 * <handle exception>
9295 * if (pkt_end <= r2) goto <handle exception>
9299 * pkt_end == dst_reg, r2 == src_reg
9300 * r2=pkt(id=n,off=8,r=0)
9301 * r3=pkt(id=n,off=0,r=0)
9303 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9304 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9305 * and [r3, r3 + 8-1) respectively is safe to access depending on
9309 /* If our ids match, then we must have the same max_value. And we
9310 * don't care about the other reg's fixed offset, since if it's too big
9311 * the range won't allow anything.
9312 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9314 for (i = 0; i <= vstate->curframe; i++)
9315 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
9319 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9321 struct tnum subreg = tnum_subreg(reg->var_off);
9322 s32 sval = (s32)val;
9326 if (tnum_is_const(subreg))
9327 return !!tnum_equals_const(subreg, val);
9330 if (tnum_is_const(subreg))
9331 return !tnum_equals_const(subreg, val);
9334 if ((~subreg.mask & subreg.value) & val)
9336 if (!((subreg.mask | subreg.value) & val))
9340 if (reg->u32_min_value > val)
9342 else if (reg->u32_max_value <= val)
9346 if (reg->s32_min_value > sval)
9348 else if (reg->s32_max_value <= sval)
9352 if (reg->u32_max_value < val)
9354 else if (reg->u32_min_value >= val)
9358 if (reg->s32_max_value < sval)
9360 else if (reg->s32_min_value >= sval)
9364 if (reg->u32_min_value >= val)
9366 else if (reg->u32_max_value < val)
9370 if (reg->s32_min_value >= sval)
9372 else if (reg->s32_max_value < sval)
9376 if (reg->u32_max_value <= val)
9378 else if (reg->u32_min_value > val)
9382 if (reg->s32_max_value <= sval)
9384 else if (reg->s32_min_value > sval)
9393 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9395 s64 sval = (s64)val;
9399 if (tnum_is_const(reg->var_off))
9400 return !!tnum_equals_const(reg->var_off, val);
9403 if (tnum_is_const(reg->var_off))
9404 return !tnum_equals_const(reg->var_off, val);
9407 if ((~reg->var_off.mask & reg->var_off.value) & val)
9409 if (!((reg->var_off.mask | reg->var_off.value) & val))
9413 if (reg->umin_value > val)
9415 else if (reg->umax_value <= val)
9419 if (reg->smin_value > sval)
9421 else if (reg->smax_value <= sval)
9425 if (reg->umax_value < val)
9427 else if (reg->umin_value >= val)
9431 if (reg->smax_value < sval)
9433 else if (reg->smin_value >= sval)
9437 if (reg->umin_value >= val)
9439 else if (reg->umax_value < val)
9443 if (reg->smin_value >= sval)
9445 else if (reg->smax_value < sval)
9449 if (reg->umax_value <= val)
9451 else if (reg->umin_value > val)
9455 if (reg->smax_value <= sval)
9457 else if (reg->smin_value > sval)
9465 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9467 * 1 - branch will be taken and "goto target" will be executed
9468 * 0 - branch will not be taken and fall-through to next insn
9469 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9472 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9475 if (__is_pointer_value(false, reg)) {
9476 if (!reg_type_not_null(reg->type))
9479 /* If pointer is valid tests against zero will fail so we can
9480 * use this to direct branch taken.
9496 return is_branch32_taken(reg, val, opcode);
9497 return is_branch64_taken(reg, val, opcode);
9500 static int flip_opcode(u32 opcode)
9502 /* How can we transform "a <op> b" into "b <op> a"? */
9503 static const u8 opcode_flip[16] = {
9504 /* these stay the same */
9505 [BPF_JEQ >> 4] = BPF_JEQ,
9506 [BPF_JNE >> 4] = BPF_JNE,
9507 [BPF_JSET >> 4] = BPF_JSET,
9508 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9509 [BPF_JGE >> 4] = BPF_JLE,
9510 [BPF_JGT >> 4] = BPF_JLT,
9511 [BPF_JLE >> 4] = BPF_JGE,
9512 [BPF_JLT >> 4] = BPF_JGT,
9513 [BPF_JSGE >> 4] = BPF_JSLE,
9514 [BPF_JSGT >> 4] = BPF_JSLT,
9515 [BPF_JSLE >> 4] = BPF_JSGE,
9516 [BPF_JSLT >> 4] = BPF_JSGT
9518 return opcode_flip[opcode >> 4];
9521 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9522 struct bpf_reg_state *src_reg,
9525 struct bpf_reg_state *pkt;
9527 if (src_reg->type == PTR_TO_PACKET_END) {
9529 } else if (dst_reg->type == PTR_TO_PACKET_END) {
9531 opcode = flip_opcode(opcode);
9536 if (pkt->range >= 0)
9541 /* pkt <= pkt_end */
9545 if (pkt->range == BEYOND_PKT_END)
9546 /* pkt has at last one extra byte beyond pkt_end */
9547 return opcode == BPF_JGT;
9553 /* pkt >= pkt_end */
9554 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9555 return opcode == BPF_JGE;
9561 /* Adjusts the register min/max values in the case that the dst_reg is the
9562 * variable register that we are working on, and src_reg is a constant or we're
9563 * simply doing a BPF_K check.
9564 * In JEQ/JNE cases we also adjust the var_off values.
9566 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9567 struct bpf_reg_state *false_reg,
9569 u8 opcode, bool is_jmp32)
9571 struct tnum false_32off = tnum_subreg(false_reg->var_off);
9572 struct tnum false_64off = false_reg->var_off;
9573 struct tnum true_32off = tnum_subreg(true_reg->var_off);
9574 struct tnum true_64off = true_reg->var_off;
9575 s64 sval = (s64)val;
9576 s32 sval32 = (s32)val32;
9578 /* If the dst_reg is a pointer, we can't learn anything about its
9579 * variable offset from the compare (unless src_reg were a pointer into
9580 * the same object, but we don't bother with that.
9581 * Since false_reg and true_reg have the same type by construction, we
9582 * only need to check one of them for pointerness.
9584 if (__is_pointer_value(false, false_reg))
9588 /* JEQ/JNE comparison doesn't change the register equivalence.
9591 * if (r1 == 42) goto label;
9593 * label: // here both r1 and r2 are known to be 42.
9595 * Hence when marking register as known preserve it's ID.
9599 __mark_reg32_known(true_reg, val32);
9600 true_32off = tnum_subreg(true_reg->var_off);
9602 ___mark_reg_known(true_reg, val);
9603 true_64off = true_reg->var_off;
9608 __mark_reg32_known(false_reg, val32);
9609 false_32off = tnum_subreg(false_reg->var_off);
9611 ___mark_reg_known(false_reg, val);
9612 false_64off = false_reg->var_off;
9617 false_32off = tnum_and(false_32off, tnum_const(~val32));
9618 if (is_power_of_2(val32))
9619 true_32off = tnum_or(true_32off,
9622 false_64off = tnum_and(false_64off, tnum_const(~val));
9623 if (is_power_of_2(val))
9624 true_64off = tnum_or(true_64off,
9632 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
9633 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9635 false_reg->u32_max_value = min(false_reg->u32_max_value,
9637 true_reg->u32_min_value = max(true_reg->u32_min_value,
9640 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
9641 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9643 false_reg->umax_value = min(false_reg->umax_value, false_umax);
9644 true_reg->umin_value = max(true_reg->umin_value, true_umin);
9652 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
9653 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9655 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9656 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9658 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
9659 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9661 false_reg->smax_value = min(false_reg->smax_value, false_smax);
9662 true_reg->smin_value = max(true_reg->smin_value, true_smin);
9670 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
9671 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9673 false_reg->u32_min_value = max(false_reg->u32_min_value,
9675 true_reg->u32_max_value = min(true_reg->u32_max_value,
9678 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
9679 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9681 false_reg->umin_value = max(false_reg->umin_value, false_umin);
9682 true_reg->umax_value = min(true_reg->umax_value, true_umax);
9690 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
9691 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9693 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9694 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9696 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
9697 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9699 false_reg->smin_value = max(false_reg->smin_value, false_smin);
9700 true_reg->smax_value = min(true_reg->smax_value, true_smax);
9709 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9710 tnum_subreg(false_32off));
9711 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9712 tnum_subreg(true_32off));
9713 __reg_combine_32_into_64(false_reg);
9714 __reg_combine_32_into_64(true_reg);
9716 false_reg->var_off = false_64off;
9717 true_reg->var_off = true_64off;
9718 __reg_combine_64_into_32(false_reg);
9719 __reg_combine_64_into_32(true_reg);
9723 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9726 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9727 struct bpf_reg_state *false_reg,
9729 u8 opcode, bool is_jmp32)
9731 opcode = flip_opcode(opcode);
9732 /* This uses zero as "not present in table"; luckily the zero opcode,
9733 * BPF_JA, can't get here.
9736 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9739 /* Regs are known to be equal, so intersect their min/max/var_off */
9740 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9741 struct bpf_reg_state *dst_reg)
9743 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9744 dst_reg->umin_value);
9745 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9746 dst_reg->umax_value);
9747 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9748 dst_reg->smin_value);
9749 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9750 dst_reg->smax_value);
9751 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9753 reg_bounds_sync(src_reg);
9754 reg_bounds_sync(dst_reg);
9757 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9758 struct bpf_reg_state *true_dst,
9759 struct bpf_reg_state *false_src,
9760 struct bpf_reg_state *false_dst,
9765 __reg_combine_min_max(true_src, true_dst);
9768 __reg_combine_min_max(false_src, false_dst);
9773 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9774 struct bpf_reg_state *reg, u32 id,
9777 if (type_may_be_null(reg->type) && reg->id == id &&
9778 !WARN_ON_ONCE(!reg->id)) {
9779 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9780 !tnum_equals_const(reg->var_off, 0) ||
9782 /* Old offset (both fixed and variable parts) should
9783 * have been known-zero, because we don't allow pointer
9784 * arithmetic on pointers that might be NULL. If we
9785 * see this happening, don't convert the register.
9790 reg->type = SCALAR_VALUE;
9791 /* We don't need id and ref_obj_id from this point
9792 * onwards anymore, thus we should better reset it,
9793 * so that state pruning has chances to take effect.
9796 reg->ref_obj_id = 0;
9801 mark_ptr_not_null_reg(reg);
9803 if (!reg_may_point_to_spin_lock(reg)) {
9804 /* For not-NULL ptr, reg->ref_obj_id will be reset
9805 * in release_reg_references().
9807 * reg->id is still used by spin_lock ptr. Other
9808 * than spin_lock ptr type, reg->id can be reset.
9815 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
9818 struct bpf_reg_state *reg;
9821 for (i = 0; i < MAX_BPF_REG; i++)
9822 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
9824 bpf_for_each_spilled_reg(i, state, reg) {
9827 mark_ptr_or_null_reg(state, reg, id, is_null);
9831 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9832 * be folded together at some point.
9834 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9837 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9838 struct bpf_reg_state *regs = state->regs;
9839 u32 ref_obj_id = regs[regno].ref_obj_id;
9840 u32 id = regs[regno].id;
9843 if (ref_obj_id && ref_obj_id == id && is_null)
9844 /* regs[regno] is in the " == NULL" branch.
9845 * No one could have freed the reference state before
9846 * doing the NULL check.
9848 WARN_ON_ONCE(release_reference_state(state, id));
9850 for (i = 0; i <= vstate->curframe; i++)
9851 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
9854 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9855 struct bpf_reg_state *dst_reg,
9856 struct bpf_reg_state *src_reg,
9857 struct bpf_verifier_state *this_branch,
9858 struct bpf_verifier_state *other_branch)
9860 if (BPF_SRC(insn->code) != BPF_X)
9863 /* Pointers are always 64-bit. */
9864 if (BPF_CLASS(insn->code) == BPF_JMP32)
9867 switch (BPF_OP(insn->code)) {
9869 if ((dst_reg->type == PTR_TO_PACKET &&
9870 src_reg->type == PTR_TO_PACKET_END) ||
9871 (dst_reg->type == PTR_TO_PACKET_META &&
9872 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9873 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9874 find_good_pkt_pointers(this_branch, dst_reg,
9875 dst_reg->type, false);
9876 mark_pkt_end(other_branch, insn->dst_reg, true);
9877 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9878 src_reg->type == PTR_TO_PACKET) ||
9879 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9880 src_reg->type == PTR_TO_PACKET_META)) {
9881 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
9882 find_good_pkt_pointers(other_branch, src_reg,
9883 src_reg->type, true);
9884 mark_pkt_end(this_branch, insn->src_reg, false);
9890 if ((dst_reg->type == PTR_TO_PACKET &&
9891 src_reg->type == PTR_TO_PACKET_END) ||
9892 (dst_reg->type == PTR_TO_PACKET_META &&
9893 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9894 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9895 find_good_pkt_pointers(other_branch, dst_reg,
9896 dst_reg->type, true);
9897 mark_pkt_end(this_branch, insn->dst_reg, false);
9898 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9899 src_reg->type == PTR_TO_PACKET) ||
9900 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9901 src_reg->type == PTR_TO_PACKET_META)) {
9902 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
9903 find_good_pkt_pointers(this_branch, src_reg,
9904 src_reg->type, false);
9905 mark_pkt_end(other_branch, insn->src_reg, true);
9911 if ((dst_reg->type == PTR_TO_PACKET &&
9912 src_reg->type == PTR_TO_PACKET_END) ||
9913 (dst_reg->type == PTR_TO_PACKET_META &&
9914 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9915 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9916 find_good_pkt_pointers(this_branch, dst_reg,
9917 dst_reg->type, true);
9918 mark_pkt_end(other_branch, insn->dst_reg, false);
9919 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9920 src_reg->type == PTR_TO_PACKET) ||
9921 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9922 src_reg->type == PTR_TO_PACKET_META)) {
9923 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9924 find_good_pkt_pointers(other_branch, src_reg,
9925 src_reg->type, false);
9926 mark_pkt_end(this_branch, insn->src_reg, true);
9932 if ((dst_reg->type == PTR_TO_PACKET &&
9933 src_reg->type == PTR_TO_PACKET_END) ||
9934 (dst_reg->type == PTR_TO_PACKET_META &&
9935 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9936 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9937 find_good_pkt_pointers(other_branch, dst_reg,
9938 dst_reg->type, false);
9939 mark_pkt_end(this_branch, insn->dst_reg, true);
9940 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9941 src_reg->type == PTR_TO_PACKET) ||
9942 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9943 src_reg->type == PTR_TO_PACKET_META)) {
9944 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
9945 find_good_pkt_pointers(this_branch, src_reg,
9946 src_reg->type, true);
9947 mark_pkt_end(other_branch, insn->src_reg, false);
9959 static void find_equal_scalars(struct bpf_verifier_state *vstate,
9960 struct bpf_reg_state *known_reg)
9962 struct bpf_func_state *state;
9963 struct bpf_reg_state *reg;
9966 for (i = 0; i <= vstate->curframe; i++) {
9967 state = vstate->frame[i];
9968 for (j = 0; j < MAX_BPF_REG; j++) {
9969 reg = &state->regs[j];
9970 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9974 bpf_for_each_spilled_reg(j, state, reg) {
9977 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9983 static int check_cond_jmp_op(struct bpf_verifier_env *env,
9984 struct bpf_insn *insn, int *insn_idx)
9986 struct bpf_verifier_state *this_branch = env->cur_state;
9987 struct bpf_verifier_state *other_branch;
9988 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
9989 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
9990 u8 opcode = BPF_OP(insn->code);
9995 /* Only conditional jumps are expected to reach here. */
9996 if (opcode == BPF_JA || opcode > BPF_JSLE) {
9997 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10001 if (BPF_SRC(insn->code) == BPF_X) {
10002 if (insn->imm != 0) {
10003 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10007 /* check src1 operand */
10008 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10012 if (is_pointer_value(env, insn->src_reg)) {
10013 verbose(env, "R%d pointer comparison prohibited\n",
10017 src_reg = ®s[insn->src_reg];
10019 if (insn->src_reg != BPF_REG_0) {
10020 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10025 /* check src2 operand */
10026 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10030 dst_reg = ®s[insn->dst_reg];
10031 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10033 if (BPF_SRC(insn->code) == BPF_K) {
10034 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10035 } else if (src_reg->type == SCALAR_VALUE &&
10036 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10037 pred = is_branch_taken(dst_reg,
10038 tnum_subreg(src_reg->var_off).value,
10041 } else if (src_reg->type == SCALAR_VALUE &&
10042 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10043 pred = is_branch_taken(dst_reg,
10044 src_reg->var_off.value,
10047 } else if (reg_is_pkt_pointer_any(dst_reg) &&
10048 reg_is_pkt_pointer_any(src_reg) &&
10050 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10054 /* If we get here with a dst_reg pointer type it is because
10055 * above is_branch_taken() special cased the 0 comparison.
10057 if (!__is_pointer_value(false, dst_reg))
10058 err = mark_chain_precision(env, insn->dst_reg);
10059 if (BPF_SRC(insn->code) == BPF_X && !err &&
10060 !__is_pointer_value(false, src_reg))
10061 err = mark_chain_precision(env, insn->src_reg);
10067 /* Only follow the goto, ignore fall-through. If needed, push
10068 * the fall-through branch for simulation under speculative
10071 if (!env->bypass_spec_v1 &&
10072 !sanitize_speculative_path(env, insn, *insn_idx + 1,
10075 *insn_idx += insn->off;
10077 } else if (pred == 0) {
10078 /* Only follow the fall-through branch, since that's where the
10079 * program will go. If needed, push the goto branch for
10080 * simulation under speculative execution.
10082 if (!env->bypass_spec_v1 &&
10083 !sanitize_speculative_path(env, insn,
10084 *insn_idx + insn->off + 1,
10090 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10094 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10096 /* detect if we are comparing against a constant value so we can adjust
10097 * our min/max values for our dst register.
10098 * this is only legit if both are scalars (or pointers to the same
10099 * object, I suppose, but we don't support that right now), because
10100 * otherwise the different base pointers mean the offsets aren't
10103 if (BPF_SRC(insn->code) == BPF_X) {
10104 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
10106 if (dst_reg->type == SCALAR_VALUE &&
10107 src_reg->type == SCALAR_VALUE) {
10108 if (tnum_is_const(src_reg->var_off) ||
10110 tnum_is_const(tnum_subreg(src_reg->var_off))))
10111 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10113 src_reg->var_off.value,
10114 tnum_subreg(src_reg->var_off).value,
10116 else if (tnum_is_const(dst_reg->var_off) ||
10118 tnum_is_const(tnum_subreg(dst_reg->var_off))))
10119 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10121 dst_reg->var_off.value,
10122 tnum_subreg(dst_reg->var_off).value,
10124 else if (!is_jmp32 &&
10125 (opcode == BPF_JEQ || opcode == BPF_JNE))
10126 /* Comparing for equality, we can combine knowledge */
10127 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10128 &other_branch_regs[insn->dst_reg],
10129 src_reg, dst_reg, opcode);
10131 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10132 find_equal_scalars(this_branch, src_reg);
10133 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10137 } else if (dst_reg->type == SCALAR_VALUE) {
10138 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10139 dst_reg, insn->imm, (u32)insn->imm,
10143 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10144 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10145 find_equal_scalars(this_branch, dst_reg);
10146 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10149 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10150 * NOTE: these optimizations below are related with pointer comparison
10151 * which will never be JMP32.
10153 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10154 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10155 type_may_be_null(dst_reg->type)) {
10156 /* Mark all identical registers in each branch as either
10157 * safe or unknown depending R == 0 or R != 0 conditional.
10159 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10160 opcode == BPF_JNE);
10161 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10162 opcode == BPF_JEQ);
10163 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
10164 this_branch, other_branch) &&
10165 is_pointer_value(env, insn->dst_reg)) {
10166 verbose(env, "R%d pointer comparison prohibited\n",
10170 if (env->log.level & BPF_LOG_LEVEL)
10171 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10175 /* verify BPF_LD_IMM64 instruction */
10176 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10178 struct bpf_insn_aux_data *aux = cur_aux(env);
10179 struct bpf_reg_state *regs = cur_regs(env);
10180 struct bpf_reg_state *dst_reg;
10181 struct bpf_map *map;
10184 if (BPF_SIZE(insn->code) != BPF_DW) {
10185 verbose(env, "invalid BPF_LD_IMM insn\n");
10188 if (insn->off != 0) {
10189 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10193 err = check_reg_arg(env, insn->dst_reg, DST_OP);
10197 dst_reg = ®s[insn->dst_reg];
10198 if (insn->src_reg == 0) {
10199 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10201 dst_reg->type = SCALAR_VALUE;
10202 __mark_reg_known(®s[insn->dst_reg], imm);
10206 /* All special src_reg cases are listed below. From this point onwards
10207 * we either succeed and assign a corresponding dst_reg->type after
10208 * zeroing the offset, or fail and reject the program.
10210 mark_reg_known_zero(env, regs, insn->dst_reg);
10212 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10213 dst_reg->type = aux->btf_var.reg_type;
10214 switch (base_type(dst_reg->type)) {
10216 dst_reg->mem_size = aux->btf_var.mem_size;
10218 case PTR_TO_BTF_ID:
10219 dst_reg->btf = aux->btf_var.btf;
10220 dst_reg->btf_id = aux->btf_var.btf_id;
10223 verbose(env, "bpf verifier is misconfigured\n");
10229 if (insn->src_reg == BPF_PSEUDO_FUNC) {
10230 struct bpf_prog_aux *aux = env->prog->aux;
10231 u32 subprogno = find_subprog(env,
10232 env->insn_idx + insn->imm + 1);
10234 if (!aux->func_info) {
10235 verbose(env, "missing btf func_info\n");
10238 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10239 verbose(env, "callback function not static\n");
10243 dst_reg->type = PTR_TO_FUNC;
10244 dst_reg->subprogno = subprogno;
10248 map = env->used_maps[aux->map_index];
10249 dst_reg->map_ptr = map;
10251 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10252 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10253 dst_reg->type = PTR_TO_MAP_VALUE;
10254 dst_reg->off = aux->map_off;
10255 if (map_value_has_spin_lock(map))
10256 dst_reg->id = ++env->id_gen;
10257 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10258 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10259 dst_reg->type = CONST_PTR_TO_MAP;
10261 verbose(env, "bpf verifier is misconfigured\n");
10268 static bool may_access_skb(enum bpf_prog_type type)
10271 case BPF_PROG_TYPE_SOCKET_FILTER:
10272 case BPF_PROG_TYPE_SCHED_CLS:
10273 case BPF_PROG_TYPE_SCHED_ACT:
10280 /* verify safety of LD_ABS|LD_IND instructions:
10281 * - they can only appear in the programs where ctx == skb
10282 * - since they are wrappers of function calls, they scratch R1-R5 registers,
10283 * preserve R6-R9, and store return value into R0
10286 * ctx == skb == R6 == CTX
10289 * SRC == any register
10290 * IMM == 32-bit immediate
10293 * R0 - 8/16/32-bit skb data converted to cpu endianness
10295 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10297 struct bpf_reg_state *regs = cur_regs(env);
10298 static const int ctx_reg = BPF_REG_6;
10299 u8 mode = BPF_MODE(insn->code);
10302 if (!may_access_skb(resolve_prog_type(env->prog))) {
10303 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10307 if (!env->ops->gen_ld_abs) {
10308 verbose(env, "bpf verifier is misconfigured\n");
10312 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10313 BPF_SIZE(insn->code) == BPF_DW ||
10314 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10315 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10319 /* check whether implicit source operand (register R6) is readable */
10320 err = check_reg_arg(env, ctx_reg, SRC_OP);
10324 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10325 * gen_ld_abs() may terminate the program at runtime, leading to
10328 err = check_reference_leak(env);
10330 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10334 if (env->cur_state->active_spin_lock) {
10335 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10339 if (regs[ctx_reg].type != PTR_TO_CTX) {
10341 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10345 if (mode == BPF_IND) {
10346 /* check explicit source operand */
10347 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10352 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
10356 /* reset caller saved regs to unreadable */
10357 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10358 mark_reg_not_init(env, regs, caller_saved[i]);
10359 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10362 /* mark destination R0 register as readable, since it contains
10363 * the value fetched from the packet.
10364 * Already marked as written above.
10366 mark_reg_unknown(env, regs, BPF_REG_0);
10367 /* ld_abs load up to 32-bit skb data. */
10368 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10372 static int check_return_code(struct bpf_verifier_env *env)
10374 struct tnum enforce_attach_type_range = tnum_unknown;
10375 const struct bpf_prog *prog = env->prog;
10376 struct bpf_reg_state *reg;
10377 struct tnum range = tnum_range(0, 1);
10378 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10380 struct bpf_func_state *frame = env->cur_state->frame[0];
10381 const bool is_subprog = frame->subprogno;
10383 /* LSM and struct_ops func-ptr's return type could be "void" */
10385 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
10386 prog_type == BPF_PROG_TYPE_LSM) &&
10387 !prog->aux->attach_func_proto->type)
10390 /* eBPF calling convention is such that R0 is used
10391 * to return the value from eBPF program.
10392 * Make sure that it's readable at this time
10393 * of bpf_exit, which means that program wrote
10394 * something into it earlier
10396 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10400 if (is_pointer_value(env, BPF_REG_0)) {
10401 verbose(env, "R0 leaks addr as return value\n");
10405 reg = cur_regs(env) + BPF_REG_0;
10407 if (frame->in_async_callback_fn) {
10408 /* enforce return zero from async callbacks like timer */
10409 if (reg->type != SCALAR_VALUE) {
10410 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10411 reg_type_str(env, reg->type));
10415 if (!tnum_in(tnum_const(0), reg->var_off)) {
10416 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10423 if (reg->type != SCALAR_VALUE) {
10424 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10425 reg_type_str(env, reg->type));
10431 switch (prog_type) {
10432 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10433 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10434 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10435 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10436 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10437 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10438 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10439 range = tnum_range(1, 1);
10440 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10441 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10442 range = tnum_range(0, 3);
10444 case BPF_PROG_TYPE_CGROUP_SKB:
10445 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10446 range = tnum_range(0, 3);
10447 enforce_attach_type_range = tnum_range(2, 3);
10450 case BPF_PROG_TYPE_CGROUP_SOCK:
10451 case BPF_PROG_TYPE_SOCK_OPS:
10452 case BPF_PROG_TYPE_CGROUP_DEVICE:
10453 case BPF_PROG_TYPE_CGROUP_SYSCTL:
10454 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10456 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10457 if (!env->prog->aux->attach_btf_id)
10459 range = tnum_const(0);
10461 case BPF_PROG_TYPE_TRACING:
10462 switch (env->prog->expected_attach_type) {
10463 case BPF_TRACE_FENTRY:
10464 case BPF_TRACE_FEXIT:
10465 range = tnum_const(0);
10467 case BPF_TRACE_RAW_TP:
10468 case BPF_MODIFY_RETURN:
10470 case BPF_TRACE_ITER:
10476 case BPF_PROG_TYPE_SK_LOOKUP:
10477 range = tnum_range(SK_DROP, SK_PASS);
10479 case BPF_PROG_TYPE_EXT:
10480 /* freplace program can return anything as its return value
10481 * depends on the to-be-replaced kernel func or bpf program.
10487 if (reg->type != SCALAR_VALUE) {
10488 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10489 reg_type_str(env, reg->type));
10493 if (!tnum_in(range, reg->var_off)) {
10494 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10498 if (!tnum_is_unknown(enforce_attach_type_range) &&
10499 tnum_in(enforce_attach_type_range, reg->var_off))
10500 env->prog->enforce_expected_attach_type = 1;
10504 /* non-recursive DFS pseudo code
10505 * 1 procedure DFS-iterative(G,v):
10506 * 2 label v as discovered
10507 * 3 let S be a stack
10509 * 5 while S is not empty
10511 * 7 if t is what we're looking for:
10513 * 9 for all edges e in G.adjacentEdges(t) do
10514 * 10 if edge e is already labelled
10515 * 11 continue with the next edge
10516 * 12 w <- G.adjacentVertex(t,e)
10517 * 13 if vertex w is not discovered and not explored
10518 * 14 label e as tree-edge
10519 * 15 label w as discovered
10522 * 18 else if vertex w is discovered
10523 * 19 label e as back-edge
10525 * 21 // vertex w is explored
10526 * 22 label e as forward- or cross-edge
10527 * 23 label t as explored
10531 * 0x10 - discovered
10532 * 0x11 - discovered and fall-through edge labelled
10533 * 0x12 - discovered and fall-through and branch edges labelled
10544 static u32 state_htab_size(struct bpf_verifier_env *env)
10546 return env->prog->len;
10549 static struct bpf_verifier_state_list **explored_state(
10550 struct bpf_verifier_env *env,
10553 struct bpf_verifier_state *cur = env->cur_state;
10554 struct bpf_func_state *state = cur->frame[cur->curframe];
10556 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10559 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10561 env->insn_aux_data[idx].prune_point = true;
10565 DONE_EXPLORING = 0,
10566 KEEP_EXPLORING = 1,
10569 /* t, w, e - match pseudo-code above:
10570 * t - index of current instruction
10571 * w - next instruction
10574 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10577 int *insn_stack = env->cfg.insn_stack;
10578 int *insn_state = env->cfg.insn_state;
10580 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10581 return DONE_EXPLORING;
10583 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10584 return DONE_EXPLORING;
10586 if (w < 0 || w >= env->prog->len) {
10587 verbose_linfo(env, t, "%d: ", t);
10588 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10593 /* mark branch target for state pruning */
10594 init_explored_state(env, w);
10596 if (insn_state[w] == 0) {
10598 insn_state[t] = DISCOVERED | e;
10599 insn_state[w] = DISCOVERED;
10600 if (env->cfg.cur_stack >= env->prog->len)
10602 insn_stack[env->cfg.cur_stack++] = w;
10603 return KEEP_EXPLORING;
10604 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10605 if (loop_ok && env->bpf_capable)
10606 return DONE_EXPLORING;
10607 verbose_linfo(env, t, "%d: ", t);
10608 verbose_linfo(env, w, "%d: ", w);
10609 verbose(env, "back-edge from insn %d to %d\n", t, w);
10611 } else if (insn_state[w] == EXPLORED) {
10612 /* forward- or cross-edge */
10613 insn_state[t] = DISCOVERED | e;
10615 verbose(env, "insn state internal bug\n");
10618 return DONE_EXPLORING;
10621 static int visit_func_call_insn(int t, int insn_cnt,
10622 struct bpf_insn *insns,
10623 struct bpf_verifier_env *env,
10628 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10632 if (t + 1 < insn_cnt)
10633 init_explored_state(env, t + 1);
10634 if (visit_callee) {
10635 init_explored_state(env, t);
10636 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10637 /* It's ok to allow recursion from CFG point of
10638 * view. __check_func_call() will do the actual
10641 bpf_pseudo_func(insns + t));
10646 /* Visits the instruction at index t and returns one of the following:
10647 * < 0 - an error occurred
10648 * DONE_EXPLORING - the instruction was fully explored
10649 * KEEP_EXPLORING - there is still work to be done before it is fully explored
10651 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10653 struct bpf_insn *insns = env->prog->insnsi;
10656 if (bpf_pseudo_func(insns + t))
10657 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10659 /* All non-branch instructions have a single fall-through edge. */
10660 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10661 BPF_CLASS(insns[t].code) != BPF_JMP32)
10662 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10664 switch (BPF_OP(insns[t].code)) {
10666 return DONE_EXPLORING;
10669 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10670 /* Mark this call insn to trigger is_state_visited() check
10671 * before call itself is processed by __check_func_call().
10672 * Otherwise new async state will be pushed for further
10675 init_explored_state(env, t);
10676 return visit_func_call_insn(t, insn_cnt, insns, env,
10677 insns[t].src_reg == BPF_PSEUDO_CALL);
10680 if (BPF_SRC(insns[t].code) != BPF_K)
10683 /* unconditional jump with single edge */
10684 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10689 /* unconditional jmp is not a good pruning point,
10690 * but it's marked, since backtracking needs
10691 * to record jmp history in is_state_visited().
10693 init_explored_state(env, t + insns[t].off + 1);
10694 /* tell verifier to check for equivalent states
10695 * after every call and jump
10697 if (t + 1 < insn_cnt)
10698 init_explored_state(env, t + 1);
10703 /* conditional jump with two edges */
10704 init_explored_state(env, t);
10705 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10709 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10713 /* non-recursive depth-first-search to detect loops in BPF program
10714 * loop == back-edge in directed graph
10716 static int check_cfg(struct bpf_verifier_env *env)
10718 int insn_cnt = env->prog->len;
10719 int *insn_stack, *insn_state;
10723 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10727 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10729 kvfree(insn_state);
10733 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10734 insn_stack[0] = 0; /* 0 is the first instruction */
10735 env->cfg.cur_stack = 1;
10737 while (env->cfg.cur_stack > 0) {
10738 int t = insn_stack[env->cfg.cur_stack - 1];
10740 ret = visit_insn(t, insn_cnt, env);
10742 case DONE_EXPLORING:
10743 insn_state[t] = EXPLORED;
10744 env->cfg.cur_stack--;
10746 case KEEP_EXPLORING:
10750 verbose(env, "visit_insn internal bug\n");
10757 if (env->cfg.cur_stack < 0) {
10758 verbose(env, "pop stack internal bug\n");
10763 for (i = 0; i < insn_cnt; i++) {
10764 if (insn_state[i] != EXPLORED) {
10765 verbose(env, "unreachable insn %d\n", i);
10770 ret = 0; /* cfg looks good */
10773 kvfree(insn_state);
10774 kvfree(insn_stack);
10775 env->cfg.insn_state = env->cfg.insn_stack = NULL;
10779 static int check_abnormal_return(struct bpf_verifier_env *env)
10783 for (i = 1; i < env->subprog_cnt; i++) {
10784 if (env->subprog_info[i].has_ld_abs) {
10785 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10788 if (env->subprog_info[i].has_tail_call) {
10789 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10796 /* The minimum supported BTF func info size */
10797 #define MIN_BPF_FUNCINFO_SIZE 8
10798 #define MAX_FUNCINFO_REC_SIZE 252
10800 static int check_btf_func(struct bpf_verifier_env *env,
10801 const union bpf_attr *attr,
10804 const struct btf_type *type, *func_proto, *ret_type;
10805 u32 i, nfuncs, urec_size, min_size;
10806 u32 krec_size = sizeof(struct bpf_func_info);
10807 struct bpf_func_info *krecord;
10808 struct bpf_func_info_aux *info_aux = NULL;
10809 struct bpf_prog *prog;
10810 const struct btf *btf;
10812 u32 prev_offset = 0;
10813 bool scalar_return;
10816 nfuncs = attr->func_info_cnt;
10818 if (check_abnormal_return(env))
10823 if (nfuncs != env->subprog_cnt) {
10824 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10828 urec_size = attr->func_info_rec_size;
10829 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10830 urec_size > MAX_FUNCINFO_REC_SIZE ||
10831 urec_size % sizeof(u32)) {
10832 verbose(env, "invalid func info rec size %u\n", urec_size);
10837 btf = prog->aux->btf;
10839 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
10840 min_size = min_t(u32, krec_size, urec_size);
10842 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
10845 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10849 for (i = 0; i < nfuncs; i++) {
10850 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10852 if (ret == -E2BIG) {
10853 verbose(env, "nonzero tailing record in func info");
10854 /* set the size kernel expects so loader can zero
10855 * out the rest of the record.
10857 if (copy_to_bpfptr_offset(uattr,
10858 offsetof(union bpf_attr, func_info_rec_size),
10859 &min_size, sizeof(min_size)))
10865 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
10870 /* check insn_off */
10873 if (krecord[i].insn_off) {
10875 "nonzero insn_off %u for the first func info record",
10876 krecord[i].insn_off);
10879 } else if (krecord[i].insn_off <= prev_offset) {
10881 "same or smaller insn offset (%u) than previous func info record (%u)",
10882 krecord[i].insn_off, prev_offset);
10886 if (env->subprog_info[i].start != krecord[i].insn_off) {
10887 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
10891 /* check type_id */
10892 type = btf_type_by_id(btf, krecord[i].type_id);
10893 if (!type || !btf_type_is_func(type)) {
10894 verbose(env, "invalid type id %d in func info",
10895 krecord[i].type_id);
10898 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
10900 func_proto = btf_type_by_id(btf, type->type);
10901 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10902 /* btf_func_check() already verified it during BTF load */
10904 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10906 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
10907 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10908 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10911 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
10912 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
10916 prev_offset = krecord[i].insn_off;
10917 bpfptr_add(&urecord, urec_size);
10920 prog->aux->func_info = krecord;
10921 prog->aux->func_info_cnt = nfuncs;
10922 prog->aux->func_info_aux = info_aux;
10931 static void adjust_btf_func(struct bpf_verifier_env *env)
10933 struct bpf_prog_aux *aux = env->prog->aux;
10936 if (!aux->func_info)
10939 for (i = 0; i < env->subprog_cnt; i++)
10940 aux->func_info[i].insn_off = env->subprog_info[i].start;
10943 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
10944 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
10946 static int check_btf_line(struct bpf_verifier_env *env,
10947 const union bpf_attr *attr,
10950 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
10951 struct bpf_subprog_info *sub;
10952 struct bpf_line_info *linfo;
10953 struct bpf_prog *prog;
10954 const struct btf *btf;
10958 nr_linfo = attr->line_info_cnt;
10961 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
10964 rec_size = attr->line_info_rec_size;
10965 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
10966 rec_size > MAX_LINEINFO_REC_SIZE ||
10967 rec_size & (sizeof(u32) - 1))
10970 /* Need to zero it in case the userspace may
10971 * pass in a smaller bpf_line_info object.
10973 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
10974 GFP_KERNEL | __GFP_NOWARN);
10979 btf = prog->aux->btf;
10982 sub = env->subprog_info;
10983 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
10984 expected_size = sizeof(struct bpf_line_info);
10985 ncopy = min_t(u32, expected_size, rec_size);
10986 for (i = 0; i < nr_linfo; i++) {
10987 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
10989 if (err == -E2BIG) {
10990 verbose(env, "nonzero tailing record in line_info");
10991 if (copy_to_bpfptr_offset(uattr,
10992 offsetof(union bpf_attr, line_info_rec_size),
10993 &expected_size, sizeof(expected_size)))
10999 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11005 * Check insn_off to ensure
11006 * 1) strictly increasing AND
11007 * 2) bounded by prog->len
11009 * The linfo[0].insn_off == 0 check logically falls into
11010 * the later "missing bpf_line_info for func..." case
11011 * because the first linfo[0].insn_off must be the
11012 * first sub also and the first sub must have
11013 * subprog_info[0].start == 0.
11015 if ((i && linfo[i].insn_off <= prev_offset) ||
11016 linfo[i].insn_off >= prog->len) {
11017 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11018 i, linfo[i].insn_off, prev_offset,
11024 if (!prog->insnsi[linfo[i].insn_off].code) {
11026 "Invalid insn code at line_info[%u].insn_off\n",
11032 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11033 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11034 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11039 if (s != env->subprog_cnt) {
11040 if (linfo[i].insn_off == sub[s].start) {
11041 sub[s].linfo_idx = i;
11043 } else if (sub[s].start < linfo[i].insn_off) {
11044 verbose(env, "missing bpf_line_info for func#%u\n", s);
11050 prev_offset = linfo[i].insn_off;
11051 bpfptr_add(&ulinfo, rec_size);
11054 if (s != env->subprog_cnt) {
11055 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11056 env->subprog_cnt - s, s);
11061 prog->aux->linfo = linfo;
11062 prog->aux->nr_linfo = nr_linfo;
11071 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
11072 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
11074 static int check_core_relo(struct bpf_verifier_env *env,
11075 const union bpf_attr *attr,
11078 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11079 struct bpf_core_relo core_relo = {};
11080 struct bpf_prog *prog = env->prog;
11081 const struct btf *btf = prog->aux->btf;
11082 struct bpf_core_ctx ctx = {
11086 bpfptr_t u_core_relo;
11089 nr_core_relo = attr->core_relo_cnt;
11092 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11095 rec_size = attr->core_relo_rec_size;
11096 if (rec_size < MIN_CORE_RELO_SIZE ||
11097 rec_size > MAX_CORE_RELO_SIZE ||
11098 rec_size % sizeof(u32))
11101 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11102 expected_size = sizeof(struct bpf_core_relo);
11103 ncopy = min_t(u32, expected_size, rec_size);
11105 /* Unlike func_info and line_info, copy and apply each CO-RE
11106 * relocation record one at a time.
11108 for (i = 0; i < nr_core_relo; i++) {
11109 /* future proofing when sizeof(bpf_core_relo) changes */
11110 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11112 if (err == -E2BIG) {
11113 verbose(env, "nonzero tailing record in core_relo");
11114 if (copy_to_bpfptr_offset(uattr,
11115 offsetof(union bpf_attr, core_relo_rec_size),
11116 &expected_size, sizeof(expected_size)))
11122 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11127 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11128 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11129 i, core_relo.insn_off, prog->len);
11134 err = bpf_core_apply(&ctx, &core_relo, i,
11135 &prog->insnsi[core_relo.insn_off / 8]);
11138 bpfptr_add(&u_core_relo, rec_size);
11143 static int check_btf_info(struct bpf_verifier_env *env,
11144 const union bpf_attr *attr,
11150 if (!attr->func_info_cnt && !attr->line_info_cnt) {
11151 if (check_abnormal_return(env))
11156 btf = btf_get_by_fd(attr->prog_btf_fd);
11158 return PTR_ERR(btf);
11159 if (btf_is_kernel(btf)) {
11163 env->prog->aux->btf = btf;
11165 err = check_btf_func(env, attr, uattr);
11169 err = check_btf_line(env, attr, uattr);
11173 err = check_core_relo(env, attr, uattr);
11180 /* check %cur's range satisfies %old's */
11181 static bool range_within(struct bpf_reg_state *old,
11182 struct bpf_reg_state *cur)
11184 return old->umin_value <= cur->umin_value &&
11185 old->umax_value >= cur->umax_value &&
11186 old->smin_value <= cur->smin_value &&
11187 old->smax_value >= cur->smax_value &&
11188 old->u32_min_value <= cur->u32_min_value &&
11189 old->u32_max_value >= cur->u32_max_value &&
11190 old->s32_min_value <= cur->s32_min_value &&
11191 old->s32_max_value >= cur->s32_max_value;
11194 /* If in the old state two registers had the same id, then they need to have
11195 * the same id in the new state as well. But that id could be different from
11196 * the old state, so we need to track the mapping from old to new ids.
11197 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11198 * regs with old id 5 must also have new id 9 for the new state to be safe. But
11199 * regs with a different old id could still have new id 9, we don't care about
11201 * So we look through our idmap to see if this old id has been seen before. If
11202 * so, we require the new id to match; otherwise, we add the id pair to the map.
11204 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11208 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11209 if (!idmap[i].old) {
11210 /* Reached an empty slot; haven't seen this id before */
11211 idmap[i].old = old_id;
11212 idmap[i].cur = cur_id;
11215 if (idmap[i].old == old_id)
11216 return idmap[i].cur == cur_id;
11218 /* We ran out of idmap slots, which should be impossible */
11223 static void clean_func_state(struct bpf_verifier_env *env,
11224 struct bpf_func_state *st)
11226 enum bpf_reg_liveness live;
11229 for (i = 0; i < BPF_REG_FP; i++) {
11230 live = st->regs[i].live;
11231 /* liveness must not touch this register anymore */
11232 st->regs[i].live |= REG_LIVE_DONE;
11233 if (!(live & REG_LIVE_READ))
11234 /* since the register is unused, clear its state
11235 * to make further comparison simpler
11237 __mark_reg_not_init(env, &st->regs[i]);
11240 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11241 live = st->stack[i].spilled_ptr.live;
11242 /* liveness must not touch this stack slot anymore */
11243 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11244 if (!(live & REG_LIVE_READ)) {
11245 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11246 for (j = 0; j < BPF_REG_SIZE; j++)
11247 st->stack[i].slot_type[j] = STACK_INVALID;
11252 static void clean_verifier_state(struct bpf_verifier_env *env,
11253 struct bpf_verifier_state *st)
11257 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11258 /* all regs in this state in all frames were already marked */
11261 for (i = 0; i <= st->curframe; i++)
11262 clean_func_state(env, st->frame[i]);
11265 /* the parentage chains form a tree.
11266 * the verifier states are added to state lists at given insn and
11267 * pushed into state stack for future exploration.
11268 * when the verifier reaches bpf_exit insn some of the verifer states
11269 * stored in the state lists have their final liveness state already,
11270 * but a lot of states will get revised from liveness point of view when
11271 * the verifier explores other branches.
11274 * 2: if r1 == 100 goto pc+1
11277 * when the verifier reaches exit insn the register r0 in the state list of
11278 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11279 * of insn 2 and goes exploring further. At the insn 4 it will walk the
11280 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11282 * Since the verifier pushes the branch states as it sees them while exploring
11283 * the program the condition of walking the branch instruction for the second
11284 * time means that all states below this branch were already explored and
11285 * their final liveness marks are already propagated.
11286 * Hence when the verifier completes the search of state list in is_state_visited()
11287 * we can call this clean_live_states() function to mark all liveness states
11288 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11289 * will not be used.
11290 * This function also clears the registers and stack for states that !READ
11291 * to simplify state merging.
11293 * Important note here that walking the same branch instruction in the callee
11294 * doesn't meant that the states are DONE. The verifier has to compare
11297 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11298 struct bpf_verifier_state *cur)
11300 struct bpf_verifier_state_list *sl;
11303 sl = *explored_state(env, insn);
11305 if (sl->state.branches)
11307 if (sl->state.insn_idx != insn ||
11308 sl->state.curframe != cur->curframe)
11310 for (i = 0; i <= cur->curframe; i++)
11311 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11313 clean_verifier_state(env, &sl->state);
11319 /* Returns true if (rold safe implies rcur safe) */
11320 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11321 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11325 if (!(rold->live & REG_LIVE_READ))
11326 /* explored state didn't use this */
11329 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11331 if (rold->type == PTR_TO_STACK)
11332 /* two stack pointers are equal only if they're pointing to
11333 * the same stack frame, since fp-8 in foo != fp-8 in bar
11335 return equal && rold->frameno == rcur->frameno;
11340 if (rold->type == NOT_INIT)
11341 /* explored state can't have used this */
11343 if (rcur->type == NOT_INIT)
11345 switch (base_type(rold->type)) {
11347 if (env->explore_alu_limits)
11349 if (rcur->type == SCALAR_VALUE) {
11350 if (!rold->precise && !rcur->precise)
11352 /* new val must satisfy old val knowledge */
11353 return range_within(rold, rcur) &&
11354 tnum_in(rold->var_off, rcur->var_off);
11356 /* We're trying to use a pointer in place of a scalar.
11357 * Even if the scalar was unbounded, this could lead to
11358 * pointer leaks because scalars are allowed to leak
11359 * while pointers are not. We could make this safe in
11360 * special cases if root is calling us, but it's
11361 * probably not worth the hassle.
11365 case PTR_TO_MAP_KEY:
11366 case PTR_TO_MAP_VALUE:
11367 /* a PTR_TO_MAP_VALUE could be safe to use as a
11368 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11369 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11370 * checked, doing so could have affected others with the same
11371 * id, and we can't check for that because we lost the id when
11372 * we converted to a PTR_TO_MAP_VALUE.
11374 if (type_may_be_null(rold->type)) {
11375 if (!type_may_be_null(rcur->type))
11377 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11379 /* Check our ids match any regs they're supposed to */
11380 return check_ids(rold->id, rcur->id, idmap);
11383 /* If the new min/max/var_off satisfy the old ones and
11384 * everything else matches, we are OK.
11385 * 'id' is not compared, since it's only used for maps with
11386 * bpf_spin_lock inside map element and in such cases if
11387 * the rest of the prog is valid for one map element then
11388 * it's valid for all map elements regardless of the key
11389 * used in bpf_map_lookup()
11391 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11392 range_within(rold, rcur) &&
11393 tnum_in(rold->var_off, rcur->var_off);
11394 case PTR_TO_PACKET_META:
11395 case PTR_TO_PACKET:
11396 if (rcur->type != rold->type)
11398 /* We must have at least as much range as the old ptr
11399 * did, so that any accesses which were safe before are
11400 * still safe. This is true even if old range < old off,
11401 * since someone could have accessed through (ptr - k), or
11402 * even done ptr -= k in a register, to get a safe access.
11404 if (rold->range > rcur->range)
11406 /* If the offsets don't match, we can't trust our alignment;
11407 * nor can we be sure that we won't fall out of range.
11409 if (rold->off != rcur->off)
11411 /* id relations must be preserved */
11412 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11414 /* new val must satisfy old val knowledge */
11415 return range_within(rold, rcur) &&
11416 tnum_in(rold->var_off, rcur->var_off);
11418 case CONST_PTR_TO_MAP:
11419 case PTR_TO_PACKET_END:
11420 case PTR_TO_FLOW_KEYS:
11421 case PTR_TO_SOCKET:
11422 case PTR_TO_SOCK_COMMON:
11423 case PTR_TO_TCP_SOCK:
11424 case PTR_TO_XDP_SOCK:
11425 /* Only valid matches are exact, which memcmp() above
11426 * would have accepted
11429 /* Don't know what's going on, just say it's not safe */
11433 /* Shouldn't get here; if we do, say it's not safe */
11438 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11439 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11443 /* walk slots of the explored stack and ignore any additional
11444 * slots in the current stack, since explored(safe) state
11447 for (i = 0; i < old->allocated_stack; i++) {
11448 spi = i / BPF_REG_SIZE;
11450 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11451 i += BPF_REG_SIZE - 1;
11452 /* explored state didn't use this */
11456 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11459 /* explored stack has more populated slots than current stack
11460 * and these slots were used
11462 if (i >= cur->allocated_stack)
11465 /* if old state was safe with misc data in the stack
11466 * it will be safe with zero-initialized stack.
11467 * The opposite is not true
11469 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11470 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11472 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11473 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11474 /* Ex: old explored (safe) state has STACK_SPILL in
11475 * this stack slot, but current has STACK_MISC ->
11476 * this verifier states are not equivalent,
11477 * return false to continue verification of this path
11480 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11482 if (!is_spilled_reg(&old->stack[spi]))
11484 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11485 &cur->stack[spi].spilled_ptr, idmap))
11486 /* when explored and current stack slot are both storing
11487 * spilled registers, check that stored pointers types
11488 * are the same as well.
11489 * Ex: explored safe path could have stored
11490 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11491 * but current path has stored:
11492 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11493 * such verifier states are not equivalent.
11494 * return false to continue verification of this path
11501 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11503 if (old->acquired_refs != cur->acquired_refs)
11505 return !memcmp(old->refs, cur->refs,
11506 sizeof(*old->refs) * old->acquired_refs);
11509 /* compare two verifier states
11511 * all states stored in state_list are known to be valid, since
11512 * verifier reached 'bpf_exit' instruction through them
11514 * this function is called when verifier exploring different branches of
11515 * execution popped from the state stack. If it sees an old state that has
11516 * more strict register state and more strict stack state then this execution
11517 * branch doesn't need to be explored further, since verifier already
11518 * concluded that more strict state leads to valid finish.
11520 * Therefore two states are equivalent if register state is more conservative
11521 * and explored stack state is more conservative than the current one.
11524 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11525 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11527 * In other words if current stack state (one being explored) has more
11528 * valid slots than old one that already passed validation, it means
11529 * the verifier can stop exploring and conclude that current state is valid too
11531 * Similarly with registers. If explored state has register type as invalid
11532 * whereas register type in current state is meaningful, it means that
11533 * the current state will reach 'bpf_exit' instruction safely
11535 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11536 struct bpf_func_state *cur)
11540 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11541 for (i = 0; i < MAX_BPF_REG; i++)
11542 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11543 env->idmap_scratch))
11546 if (!stacksafe(env, old, cur, env->idmap_scratch))
11549 if (!refsafe(old, cur))
11555 static bool states_equal(struct bpf_verifier_env *env,
11556 struct bpf_verifier_state *old,
11557 struct bpf_verifier_state *cur)
11561 if (old->curframe != cur->curframe)
11564 /* Verification state from speculative execution simulation
11565 * must never prune a non-speculative execution one.
11567 if (old->speculative && !cur->speculative)
11570 if (old->active_spin_lock != cur->active_spin_lock)
11573 /* for states to be equal callsites have to be the same
11574 * and all frame states need to be equivalent
11576 for (i = 0; i <= old->curframe; i++) {
11577 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11579 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11585 /* Return 0 if no propagation happened. Return negative error code if error
11586 * happened. Otherwise, return the propagated bit.
11588 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11589 struct bpf_reg_state *reg,
11590 struct bpf_reg_state *parent_reg)
11592 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11593 u8 flag = reg->live & REG_LIVE_READ;
11596 /* When comes here, read flags of PARENT_REG or REG could be any of
11597 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11598 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11600 if (parent_flag == REG_LIVE_READ64 ||
11601 /* Or if there is no read flag from REG. */
11603 /* Or if the read flag from REG is the same as PARENT_REG. */
11604 parent_flag == flag)
11607 err = mark_reg_read(env, reg, parent_reg, flag);
11614 /* A write screens off any subsequent reads; but write marks come from the
11615 * straight-line code between a state and its parent. When we arrive at an
11616 * equivalent state (jump target or such) we didn't arrive by the straight-line
11617 * code, so read marks in the state must propagate to the parent regardless
11618 * of the state's write marks. That's what 'parent == state->parent' comparison
11619 * in mark_reg_read() is for.
11621 static int propagate_liveness(struct bpf_verifier_env *env,
11622 const struct bpf_verifier_state *vstate,
11623 struct bpf_verifier_state *vparent)
11625 struct bpf_reg_state *state_reg, *parent_reg;
11626 struct bpf_func_state *state, *parent;
11627 int i, frame, err = 0;
11629 if (vparent->curframe != vstate->curframe) {
11630 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11631 vparent->curframe, vstate->curframe);
11634 /* Propagate read liveness of registers... */
11635 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11636 for (frame = 0; frame <= vstate->curframe; frame++) {
11637 parent = vparent->frame[frame];
11638 state = vstate->frame[frame];
11639 parent_reg = parent->regs;
11640 state_reg = state->regs;
11641 /* We don't need to worry about FP liveness, it's read-only */
11642 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11643 err = propagate_liveness_reg(env, &state_reg[i],
11647 if (err == REG_LIVE_READ64)
11648 mark_insn_zext(env, &parent_reg[i]);
11651 /* Propagate stack slots. */
11652 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11653 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11654 parent_reg = &parent->stack[i].spilled_ptr;
11655 state_reg = &state->stack[i].spilled_ptr;
11656 err = propagate_liveness_reg(env, state_reg,
11665 /* find precise scalars in the previous equivalent state and
11666 * propagate them into the current state
11668 static int propagate_precision(struct bpf_verifier_env *env,
11669 const struct bpf_verifier_state *old)
11671 struct bpf_reg_state *state_reg;
11672 struct bpf_func_state *state;
11675 state = old->frame[old->curframe];
11676 state_reg = state->regs;
11677 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11678 if (state_reg->type != SCALAR_VALUE ||
11679 !state_reg->precise)
11681 if (env->log.level & BPF_LOG_LEVEL2)
11682 verbose(env, "propagating r%d\n", i);
11683 err = mark_chain_precision(env, i);
11688 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11689 if (!is_spilled_reg(&state->stack[i]))
11691 state_reg = &state->stack[i].spilled_ptr;
11692 if (state_reg->type != SCALAR_VALUE ||
11693 !state_reg->precise)
11695 if (env->log.level & BPF_LOG_LEVEL2)
11696 verbose(env, "propagating fp%d\n",
11697 (-i - 1) * BPF_REG_SIZE);
11698 err = mark_chain_precision_stack(env, i);
11705 static bool states_maybe_looping(struct bpf_verifier_state *old,
11706 struct bpf_verifier_state *cur)
11708 struct bpf_func_state *fold, *fcur;
11709 int i, fr = cur->curframe;
11711 if (old->curframe != fr)
11714 fold = old->frame[fr];
11715 fcur = cur->frame[fr];
11716 for (i = 0; i < MAX_BPF_REG; i++)
11717 if (memcmp(&fold->regs[i], &fcur->regs[i],
11718 offsetof(struct bpf_reg_state, parent)))
11724 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11726 struct bpf_verifier_state_list *new_sl;
11727 struct bpf_verifier_state_list *sl, **pprev;
11728 struct bpf_verifier_state *cur = env->cur_state, *new;
11729 int i, j, err, states_cnt = 0;
11730 bool add_new_state = env->test_state_freq ? true : false;
11732 cur->last_insn_idx = env->prev_insn_idx;
11733 if (!env->insn_aux_data[insn_idx].prune_point)
11734 /* this 'insn_idx' instruction wasn't marked, so we will not
11735 * be doing state search here
11739 /* bpf progs typically have pruning point every 4 instructions
11740 * http://vger.kernel.org/bpfconf2019.html#session-1
11741 * Do not add new state for future pruning if the verifier hasn't seen
11742 * at least 2 jumps and at least 8 instructions.
11743 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11744 * In tests that amounts to up to 50% reduction into total verifier
11745 * memory consumption and 20% verifier time speedup.
11747 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11748 env->insn_processed - env->prev_insn_processed >= 8)
11749 add_new_state = true;
11751 pprev = explored_state(env, insn_idx);
11754 clean_live_states(env, insn_idx, cur);
11758 if (sl->state.insn_idx != insn_idx)
11761 if (sl->state.branches) {
11762 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11764 if (frame->in_async_callback_fn &&
11765 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11766 /* Different async_entry_cnt means that the verifier is
11767 * processing another entry into async callback.
11768 * Seeing the same state is not an indication of infinite
11769 * loop or infinite recursion.
11770 * But finding the same state doesn't mean that it's safe
11771 * to stop processing the current state. The previous state
11772 * hasn't yet reached bpf_exit, since state.branches > 0.
11773 * Checking in_async_callback_fn alone is not enough either.
11774 * Since the verifier still needs to catch infinite loops
11775 * inside async callbacks.
11777 } else if (states_maybe_looping(&sl->state, cur) &&
11778 states_equal(env, &sl->state, cur)) {
11779 verbose_linfo(env, insn_idx, "; ");
11780 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11783 /* if the verifier is processing a loop, avoid adding new state
11784 * too often, since different loop iterations have distinct
11785 * states and may not help future pruning.
11786 * This threshold shouldn't be too low to make sure that
11787 * a loop with large bound will be rejected quickly.
11788 * The most abusive loop will be:
11790 * if r1 < 1000000 goto pc-2
11791 * 1M insn_procssed limit / 100 == 10k peak states.
11792 * This threshold shouldn't be too high either, since states
11793 * at the end of the loop are likely to be useful in pruning.
11795 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11796 env->insn_processed - env->prev_insn_processed < 100)
11797 add_new_state = false;
11800 if (states_equal(env, &sl->state, cur)) {
11802 /* reached equivalent register/stack state,
11803 * prune the search.
11804 * Registers read by the continuation are read by us.
11805 * If we have any write marks in env->cur_state, they
11806 * will prevent corresponding reads in the continuation
11807 * from reaching our parent (an explored_state). Our
11808 * own state will get the read marks recorded, but
11809 * they'll be immediately forgotten as we're pruning
11810 * this state and will pop a new one.
11812 err = propagate_liveness(env, &sl->state, cur);
11814 /* if previous state reached the exit with precision and
11815 * current state is equivalent to it (except precsion marks)
11816 * the precision needs to be propagated back in
11817 * the current state.
11819 err = err ? : push_jmp_history(env, cur);
11820 err = err ? : propagate_precision(env, &sl->state);
11826 /* when new state is not going to be added do not increase miss count.
11827 * Otherwise several loop iterations will remove the state
11828 * recorded earlier. The goal of these heuristics is to have
11829 * states from some iterations of the loop (some in the beginning
11830 * and some at the end) to help pruning.
11834 /* heuristic to determine whether this state is beneficial
11835 * to keep checking from state equivalence point of view.
11836 * Higher numbers increase max_states_per_insn and verification time,
11837 * but do not meaningfully decrease insn_processed.
11839 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
11840 /* the state is unlikely to be useful. Remove it to
11841 * speed up verification
11844 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
11845 u32 br = sl->state.branches;
11848 "BUG live_done but branches_to_explore %d\n",
11850 free_verifier_state(&sl->state, false);
11852 env->peak_states--;
11854 /* cannot free this state, since parentage chain may
11855 * walk it later. Add it for free_list instead to
11856 * be freed at the end of verification
11858 sl->next = env->free_list;
11859 env->free_list = sl;
11869 if (env->max_states_per_insn < states_cnt)
11870 env->max_states_per_insn = states_cnt;
11872 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
11873 return push_jmp_history(env, cur);
11875 if (!add_new_state)
11876 return push_jmp_history(env, cur);
11878 /* There were no equivalent states, remember the current one.
11879 * Technically the current state is not proven to be safe yet,
11880 * but it will either reach outer most bpf_exit (which means it's safe)
11881 * or it will be rejected. When there are no loops the verifier won't be
11882 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
11883 * again on the way to bpf_exit.
11884 * When looping the sl->state.branches will be > 0 and this state
11885 * will not be considered for equivalence until branches == 0.
11887 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
11890 env->total_states++;
11891 env->peak_states++;
11892 env->prev_jmps_processed = env->jmps_processed;
11893 env->prev_insn_processed = env->insn_processed;
11895 /* add new state to the head of linked list */
11896 new = &new_sl->state;
11897 err = copy_verifier_state(new, cur);
11899 free_verifier_state(new, false);
11903 new->insn_idx = insn_idx;
11904 WARN_ONCE(new->branches != 1,
11905 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
11908 cur->first_insn_idx = insn_idx;
11909 clear_jmp_history(cur);
11910 new_sl->next = *explored_state(env, insn_idx);
11911 *explored_state(env, insn_idx) = new_sl;
11912 /* connect new state to parentage chain. Current frame needs all
11913 * registers connected. Only r6 - r9 of the callers are alive (pushed
11914 * to the stack implicitly by JITs) so in callers' frames connect just
11915 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
11916 * the state of the call instruction (with WRITTEN set), and r0 comes
11917 * from callee with its full parentage chain, anyway.
11919 /* clear write marks in current state: the writes we did are not writes
11920 * our child did, so they don't screen off its reads from us.
11921 * (There are no read marks in current state, because reads always mark
11922 * their parent and current state never has children yet. Only
11923 * explored_states can get read marks.)
11925 for (j = 0; j <= cur->curframe; j++) {
11926 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
11927 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
11928 for (i = 0; i < BPF_REG_FP; i++)
11929 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
11932 /* all stack frames are accessible from callee, clear them all */
11933 for (j = 0; j <= cur->curframe; j++) {
11934 struct bpf_func_state *frame = cur->frame[j];
11935 struct bpf_func_state *newframe = new->frame[j];
11937 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
11938 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
11939 frame->stack[i].spilled_ptr.parent =
11940 &newframe->stack[i].spilled_ptr;
11946 /* Return true if it's OK to have the same insn return a different type. */
11947 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
11949 switch (base_type(type)) {
11951 case PTR_TO_SOCKET:
11952 case PTR_TO_SOCK_COMMON:
11953 case PTR_TO_TCP_SOCK:
11954 case PTR_TO_XDP_SOCK:
11955 case PTR_TO_BTF_ID:
11962 /* If an instruction was previously used with particular pointer types, then we
11963 * need to be careful to avoid cases such as the below, where it may be ok
11964 * for one branch accessing the pointer, but not ok for the other branch:
11969 * R1 = some_other_valid_ptr;
11972 * R2 = *(u32 *)(R1 + 0);
11974 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
11976 return src != prev && (!reg_type_mismatch_ok(src) ||
11977 !reg_type_mismatch_ok(prev));
11980 static int do_check(struct bpf_verifier_env *env)
11982 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11983 struct bpf_verifier_state *state = env->cur_state;
11984 struct bpf_insn *insns = env->prog->insnsi;
11985 struct bpf_reg_state *regs;
11986 int insn_cnt = env->prog->len;
11987 bool do_print_state = false;
11988 int prev_insn_idx = -1;
11991 struct bpf_insn *insn;
11995 env->prev_insn_idx = prev_insn_idx;
11996 if (env->insn_idx >= insn_cnt) {
11997 verbose(env, "invalid insn idx %d insn_cnt %d\n",
11998 env->insn_idx, insn_cnt);
12002 insn = &insns[env->insn_idx];
12003 class = BPF_CLASS(insn->code);
12005 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12007 "BPF program is too large. Processed %d insn\n",
12008 env->insn_processed);
12012 err = is_state_visited(env, env->insn_idx);
12016 /* found equivalent state, can prune the search */
12017 if (env->log.level & BPF_LOG_LEVEL) {
12018 if (do_print_state)
12019 verbose(env, "\nfrom %d to %d%s: safe\n",
12020 env->prev_insn_idx, env->insn_idx,
12021 env->cur_state->speculative ?
12022 " (speculative execution)" : "");
12024 verbose(env, "%d: safe\n", env->insn_idx);
12026 goto process_bpf_exit;
12029 if (signal_pending(current))
12032 if (need_resched())
12035 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12036 verbose(env, "\nfrom %d to %d%s:",
12037 env->prev_insn_idx, env->insn_idx,
12038 env->cur_state->speculative ?
12039 " (speculative execution)" : "");
12040 print_verifier_state(env, state->frame[state->curframe], true);
12041 do_print_state = false;
12044 if (env->log.level & BPF_LOG_LEVEL) {
12045 const struct bpf_insn_cbs cbs = {
12046 .cb_call = disasm_kfunc_name,
12047 .cb_print = verbose,
12048 .private_data = env,
12051 if (verifier_state_scratched(env))
12052 print_insn_state(env, state->frame[state->curframe]);
12054 verbose_linfo(env, env->insn_idx, "; ");
12055 env->prev_log_len = env->log.len_used;
12056 verbose(env, "%d: ", env->insn_idx);
12057 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12058 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12059 env->prev_log_len = env->log.len_used;
12062 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12063 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12064 env->prev_insn_idx);
12069 regs = cur_regs(env);
12070 sanitize_mark_insn_seen(env);
12071 prev_insn_idx = env->insn_idx;
12073 if (class == BPF_ALU || class == BPF_ALU64) {
12074 err = check_alu_op(env, insn);
12078 } else if (class == BPF_LDX) {
12079 enum bpf_reg_type *prev_src_type, src_reg_type;
12081 /* check for reserved fields is already done */
12083 /* check src operand */
12084 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12088 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12092 src_reg_type = regs[insn->src_reg].type;
12094 /* check that memory (src_reg + off) is readable,
12095 * the state of dst_reg will be updated by this func
12097 err = check_mem_access(env, env->insn_idx, insn->src_reg,
12098 insn->off, BPF_SIZE(insn->code),
12099 BPF_READ, insn->dst_reg, false);
12103 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12105 if (*prev_src_type == NOT_INIT) {
12106 /* saw a valid insn
12107 * dst_reg = *(u32 *)(src_reg + off)
12108 * save type to validate intersecting paths
12110 *prev_src_type = src_reg_type;
12112 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12113 /* ABuser program is trying to use the same insn
12114 * dst_reg = *(u32*) (src_reg + off)
12115 * with different pointer types:
12116 * src_reg == ctx in one branch and
12117 * src_reg == stack|map in some other branch.
12120 verbose(env, "same insn cannot be used with different pointers\n");
12124 } else if (class == BPF_STX) {
12125 enum bpf_reg_type *prev_dst_type, dst_reg_type;
12127 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12128 err = check_atomic(env, env->insn_idx, insn);
12135 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12136 verbose(env, "BPF_STX uses reserved fields\n");
12140 /* check src1 operand */
12141 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12144 /* check src2 operand */
12145 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12149 dst_reg_type = regs[insn->dst_reg].type;
12151 /* check that memory (dst_reg + off) is writeable */
12152 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12153 insn->off, BPF_SIZE(insn->code),
12154 BPF_WRITE, insn->src_reg, false);
12158 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12160 if (*prev_dst_type == NOT_INIT) {
12161 *prev_dst_type = dst_reg_type;
12162 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12163 verbose(env, "same insn cannot be used with different pointers\n");
12167 } else if (class == BPF_ST) {
12168 if (BPF_MODE(insn->code) != BPF_MEM ||
12169 insn->src_reg != BPF_REG_0) {
12170 verbose(env, "BPF_ST uses reserved fields\n");
12173 /* check src operand */
12174 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12178 if (is_ctx_reg(env, insn->dst_reg)) {
12179 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12181 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12185 /* check that memory (dst_reg + off) is writeable */
12186 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12187 insn->off, BPF_SIZE(insn->code),
12188 BPF_WRITE, -1, false);
12192 } else if (class == BPF_JMP || class == BPF_JMP32) {
12193 u8 opcode = BPF_OP(insn->code);
12195 env->jmps_processed++;
12196 if (opcode == BPF_CALL) {
12197 if (BPF_SRC(insn->code) != BPF_K ||
12198 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12199 && insn->off != 0) ||
12200 (insn->src_reg != BPF_REG_0 &&
12201 insn->src_reg != BPF_PSEUDO_CALL &&
12202 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12203 insn->dst_reg != BPF_REG_0 ||
12204 class == BPF_JMP32) {
12205 verbose(env, "BPF_CALL uses reserved fields\n");
12209 if (env->cur_state->active_spin_lock &&
12210 (insn->src_reg == BPF_PSEUDO_CALL ||
12211 insn->imm != BPF_FUNC_spin_unlock)) {
12212 verbose(env, "function calls are not allowed while holding a lock\n");
12215 if (insn->src_reg == BPF_PSEUDO_CALL)
12216 err = check_func_call(env, insn, &env->insn_idx);
12217 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12218 err = check_kfunc_call(env, insn, &env->insn_idx);
12220 err = check_helper_call(env, insn, &env->insn_idx);
12223 } else if (opcode == BPF_JA) {
12224 if (BPF_SRC(insn->code) != BPF_K ||
12226 insn->src_reg != BPF_REG_0 ||
12227 insn->dst_reg != BPF_REG_0 ||
12228 class == BPF_JMP32) {
12229 verbose(env, "BPF_JA uses reserved fields\n");
12233 env->insn_idx += insn->off + 1;
12236 } else if (opcode == BPF_EXIT) {
12237 if (BPF_SRC(insn->code) != BPF_K ||
12239 insn->src_reg != BPF_REG_0 ||
12240 insn->dst_reg != BPF_REG_0 ||
12241 class == BPF_JMP32) {
12242 verbose(env, "BPF_EXIT uses reserved fields\n");
12246 if (env->cur_state->active_spin_lock) {
12247 verbose(env, "bpf_spin_unlock is missing\n");
12251 if (state->curframe) {
12252 /* exit from nested function */
12253 err = prepare_func_exit(env, &env->insn_idx);
12256 do_print_state = true;
12260 err = check_reference_leak(env);
12264 err = check_return_code(env);
12268 mark_verifier_state_scratched(env);
12269 update_branch_counts(env, env->cur_state);
12270 err = pop_stack(env, &prev_insn_idx,
12271 &env->insn_idx, pop_log);
12273 if (err != -ENOENT)
12277 do_print_state = true;
12281 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12285 } else if (class == BPF_LD) {
12286 u8 mode = BPF_MODE(insn->code);
12288 if (mode == BPF_ABS || mode == BPF_IND) {
12289 err = check_ld_abs(env, insn);
12293 } else if (mode == BPF_IMM) {
12294 err = check_ld_imm(env, insn);
12299 sanitize_mark_insn_seen(env);
12301 verbose(env, "invalid BPF_LD mode\n");
12305 verbose(env, "unknown insn class %d\n", class);
12315 static int find_btf_percpu_datasec(struct btf *btf)
12317 const struct btf_type *t;
12322 * Both vmlinux and module each have their own ".data..percpu"
12323 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12324 * types to look at only module's own BTF types.
12326 n = btf_nr_types(btf);
12327 if (btf_is_module(btf))
12328 i = btf_nr_types(btf_vmlinux);
12332 for(; i < n; i++) {
12333 t = btf_type_by_id(btf, i);
12334 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12337 tname = btf_name_by_offset(btf, t->name_off);
12338 if (!strcmp(tname, ".data..percpu"))
12345 /* replace pseudo btf_id with kernel symbol address */
12346 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12347 struct bpf_insn *insn,
12348 struct bpf_insn_aux_data *aux)
12350 const struct btf_var_secinfo *vsi;
12351 const struct btf_type *datasec;
12352 struct btf_mod_pair *btf_mod;
12353 const struct btf_type *t;
12354 const char *sym_name;
12355 bool percpu = false;
12356 u32 type, id = insn->imm;
12360 int i, btf_fd, err;
12362 btf_fd = insn[1].imm;
12364 btf = btf_get_by_fd(btf_fd);
12366 verbose(env, "invalid module BTF object FD specified.\n");
12370 if (!btf_vmlinux) {
12371 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12378 t = btf_type_by_id(btf, id);
12380 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12385 if (!btf_type_is_var(t)) {
12386 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12391 sym_name = btf_name_by_offset(btf, t->name_off);
12392 addr = kallsyms_lookup_name(sym_name);
12394 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12400 datasec_id = find_btf_percpu_datasec(btf);
12401 if (datasec_id > 0) {
12402 datasec = btf_type_by_id(btf, datasec_id);
12403 for_each_vsi(i, datasec, vsi) {
12404 if (vsi->type == id) {
12411 insn[0].imm = (u32)addr;
12412 insn[1].imm = addr >> 32;
12415 t = btf_type_skip_modifiers(btf, type, NULL);
12417 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12418 aux->btf_var.btf = btf;
12419 aux->btf_var.btf_id = type;
12420 } else if (!btf_type_is_struct(t)) {
12421 const struct btf_type *ret;
12425 /* resolve the type size of ksym. */
12426 ret = btf_resolve_size(btf, t, &tsize);
12428 tname = btf_name_by_offset(btf, t->name_off);
12429 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12430 tname, PTR_ERR(ret));
12434 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12435 aux->btf_var.mem_size = tsize;
12437 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12438 aux->btf_var.btf = btf;
12439 aux->btf_var.btf_id = type;
12442 /* check whether we recorded this BTF (and maybe module) already */
12443 for (i = 0; i < env->used_btf_cnt; i++) {
12444 if (env->used_btfs[i].btf == btf) {
12450 if (env->used_btf_cnt >= MAX_USED_BTFS) {
12455 btf_mod = &env->used_btfs[env->used_btf_cnt];
12456 btf_mod->btf = btf;
12457 btf_mod->module = NULL;
12459 /* if we reference variables from kernel module, bump its refcount */
12460 if (btf_is_module(btf)) {
12461 btf_mod->module = btf_try_get_module(btf);
12462 if (!btf_mod->module) {
12468 env->used_btf_cnt++;
12476 static int check_map_prealloc(struct bpf_map *map)
12478 return (map->map_type != BPF_MAP_TYPE_HASH &&
12479 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
12480 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
12481 !(map->map_flags & BPF_F_NO_PREALLOC);
12484 static bool is_tracing_prog_type(enum bpf_prog_type type)
12487 case BPF_PROG_TYPE_KPROBE:
12488 case BPF_PROG_TYPE_TRACEPOINT:
12489 case BPF_PROG_TYPE_PERF_EVENT:
12490 case BPF_PROG_TYPE_RAW_TRACEPOINT:
12497 static bool is_preallocated_map(struct bpf_map *map)
12499 if (!check_map_prealloc(map))
12501 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
12506 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12507 struct bpf_map *map,
12508 struct bpf_prog *prog)
12511 enum bpf_prog_type prog_type = resolve_prog_type(prog);
12513 * Validate that trace type programs use preallocated hash maps.
12515 * For programs attached to PERF events this is mandatory as the
12516 * perf NMI can hit any arbitrary code sequence.
12518 * All other trace types using preallocated hash maps are unsafe as
12519 * well because tracepoint or kprobes can be inside locked regions
12520 * of the memory allocator or at a place where a recursion into the
12521 * memory allocator would see inconsistent state.
12523 * On RT enabled kernels run-time allocation of all trace type
12524 * programs is strictly prohibited due to lock type constraints. On
12525 * !RT kernels it is allowed for backwards compatibility reasons for
12526 * now, but warnings are emitted so developers are made aware of
12527 * the unsafety and can fix their programs before this is enforced.
12529 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
12530 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
12531 verbose(env, "perf_event programs can only use preallocated hash map\n");
12534 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
12535 verbose(env, "trace type programs can only use preallocated hash map\n");
12538 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
12539 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
12542 if (map_value_has_spin_lock(map)) {
12543 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12544 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12548 if (is_tracing_prog_type(prog_type)) {
12549 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12553 if (prog->aux->sleepable) {
12554 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12559 if (map_value_has_timer(map)) {
12560 if (is_tracing_prog_type(prog_type)) {
12561 verbose(env, "tracing progs cannot use bpf_timer yet\n");
12566 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12567 !bpf_offload_prog_map_match(prog, map)) {
12568 verbose(env, "offload device mismatch between prog and map\n");
12572 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12573 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12577 if (prog->aux->sleepable)
12578 switch (map->map_type) {
12579 case BPF_MAP_TYPE_HASH:
12580 case BPF_MAP_TYPE_LRU_HASH:
12581 case BPF_MAP_TYPE_ARRAY:
12582 case BPF_MAP_TYPE_PERCPU_HASH:
12583 case BPF_MAP_TYPE_PERCPU_ARRAY:
12584 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12585 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12586 case BPF_MAP_TYPE_HASH_OF_MAPS:
12587 if (!is_preallocated_map(map)) {
12589 "Sleepable programs can only use preallocated maps\n");
12593 case BPF_MAP_TYPE_RINGBUF:
12594 case BPF_MAP_TYPE_INODE_STORAGE:
12595 case BPF_MAP_TYPE_SK_STORAGE:
12596 case BPF_MAP_TYPE_TASK_STORAGE:
12600 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12607 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12609 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12610 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12613 /* find and rewrite pseudo imm in ld_imm64 instructions:
12615 * 1. if it accesses map FD, replace it with actual map pointer.
12616 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12618 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12620 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12622 struct bpf_insn *insn = env->prog->insnsi;
12623 int insn_cnt = env->prog->len;
12626 err = bpf_prog_calc_tag(env->prog);
12630 for (i = 0; i < insn_cnt; i++, insn++) {
12631 if (BPF_CLASS(insn->code) == BPF_LDX &&
12632 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12633 verbose(env, "BPF_LDX uses reserved fields\n");
12637 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12638 struct bpf_insn_aux_data *aux;
12639 struct bpf_map *map;
12644 if (i == insn_cnt - 1 || insn[1].code != 0 ||
12645 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12646 insn[1].off != 0) {
12647 verbose(env, "invalid bpf_ld_imm64 insn\n");
12651 if (insn[0].src_reg == 0)
12652 /* valid generic load 64-bit imm */
12655 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12656 aux = &env->insn_aux_data[i];
12657 err = check_pseudo_btf_id(env, insn, aux);
12663 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12664 aux = &env->insn_aux_data[i];
12665 aux->ptr_type = PTR_TO_FUNC;
12669 /* In final convert_pseudo_ld_imm64() step, this is
12670 * converted into regular 64-bit imm load insn.
12672 switch (insn[0].src_reg) {
12673 case BPF_PSEUDO_MAP_VALUE:
12674 case BPF_PSEUDO_MAP_IDX_VALUE:
12676 case BPF_PSEUDO_MAP_FD:
12677 case BPF_PSEUDO_MAP_IDX:
12678 if (insn[1].imm == 0)
12682 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12686 switch (insn[0].src_reg) {
12687 case BPF_PSEUDO_MAP_IDX_VALUE:
12688 case BPF_PSEUDO_MAP_IDX:
12689 if (bpfptr_is_null(env->fd_array)) {
12690 verbose(env, "fd_idx without fd_array is invalid\n");
12693 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12694 insn[0].imm * sizeof(fd),
12704 map = __bpf_map_get(f);
12706 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12708 return PTR_ERR(map);
12711 err = check_map_prog_compatibility(env, map, env->prog);
12717 aux = &env->insn_aux_data[i];
12718 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12719 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12720 addr = (unsigned long)map;
12722 u32 off = insn[1].imm;
12724 if (off >= BPF_MAX_VAR_OFF) {
12725 verbose(env, "direct value offset of %u is not allowed\n", off);
12730 if (!map->ops->map_direct_value_addr) {
12731 verbose(env, "no direct value access support for this map type\n");
12736 err = map->ops->map_direct_value_addr(map, &addr, off);
12738 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12739 map->value_size, off);
12744 aux->map_off = off;
12748 insn[0].imm = (u32)addr;
12749 insn[1].imm = addr >> 32;
12751 /* check whether we recorded this map already */
12752 for (j = 0; j < env->used_map_cnt; j++) {
12753 if (env->used_maps[j] == map) {
12754 aux->map_index = j;
12760 if (env->used_map_cnt >= MAX_USED_MAPS) {
12765 /* hold the map. If the program is rejected by verifier,
12766 * the map will be released by release_maps() or it
12767 * will be used by the valid program until it's unloaded
12768 * and all maps are released in free_used_maps()
12772 aux->map_index = env->used_map_cnt;
12773 env->used_maps[env->used_map_cnt++] = map;
12775 if (bpf_map_is_cgroup_storage(map) &&
12776 bpf_cgroup_storage_assign(env->prog->aux, map)) {
12777 verbose(env, "only one cgroup storage of each type is allowed\n");
12789 /* Basic sanity check before we invest more work here. */
12790 if (!bpf_opcode_in_insntable(insn->code)) {
12791 verbose(env, "unknown opcode %02x\n", insn->code);
12796 /* now all pseudo BPF_LD_IMM64 instructions load valid
12797 * 'struct bpf_map *' into a register instead of user map_fd.
12798 * These pointers will be used later by verifier to validate map access.
12803 /* drop refcnt of maps used by the rejected program */
12804 static void release_maps(struct bpf_verifier_env *env)
12806 __bpf_free_used_maps(env->prog->aux, env->used_maps,
12807 env->used_map_cnt);
12810 /* drop refcnt of maps used by the rejected program */
12811 static void release_btfs(struct bpf_verifier_env *env)
12813 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12814 env->used_btf_cnt);
12817 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12818 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12820 struct bpf_insn *insn = env->prog->insnsi;
12821 int insn_cnt = env->prog->len;
12824 for (i = 0; i < insn_cnt; i++, insn++) {
12825 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12827 if (insn->src_reg == BPF_PSEUDO_FUNC)
12833 /* single env->prog->insni[off] instruction was replaced with the range
12834 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
12835 * [0, off) and [off, end) to new locations, so the patched range stays zero
12837 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12838 struct bpf_insn_aux_data *new_data,
12839 struct bpf_prog *new_prog, u32 off, u32 cnt)
12841 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
12842 struct bpf_insn *insn = new_prog->insnsi;
12843 u32 old_seen = old_data[off].seen;
12847 /* aux info at OFF always needs adjustment, no matter fast path
12848 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12849 * original insn at old prog.
12851 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12855 prog_len = new_prog->len;
12857 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12858 memcpy(new_data + off + cnt - 1, old_data + off,
12859 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
12860 for (i = off; i < off + cnt - 1; i++) {
12861 /* Expand insni[off]'s seen count to the patched range. */
12862 new_data[i].seen = old_seen;
12863 new_data[i].zext_dst = insn_has_def32(env, insn + i);
12865 env->insn_aux_data = new_data;
12869 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
12875 /* NOTE: fake 'exit' subprog should be updated as well. */
12876 for (i = 0; i <= env->subprog_cnt; i++) {
12877 if (env->subprog_info[i].start <= off)
12879 env->subprog_info[i].start += len - 1;
12883 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
12885 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
12886 int i, sz = prog->aux->size_poke_tab;
12887 struct bpf_jit_poke_descriptor *desc;
12889 for (i = 0; i < sz; i++) {
12891 if (desc->insn_idx <= off)
12893 desc->insn_idx += len - 1;
12897 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
12898 const struct bpf_insn *patch, u32 len)
12900 struct bpf_prog *new_prog;
12901 struct bpf_insn_aux_data *new_data = NULL;
12904 new_data = vzalloc(array_size(env->prog->len + len - 1,
12905 sizeof(struct bpf_insn_aux_data)));
12910 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
12911 if (IS_ERR(new_prog)) {
12912 if (PTR_ERR(new_prog) == -ERANGE)
12914 "insn %d cannot be patched due to 16-bit range\n",
12915 env->insn_aux_data[off].orig_idx);
12919 adjust_insn_aux_data(env, new_data, new_prog, off, len);
12920 adjust_subprog_starts(env, off, len);
12921 adjust_poke_descs(new_prog, off, len);
12925 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
12930 /* find first prog starting at or after off (first to remove) */
12931 for (i = 0; i < env->subprog_cnt; i++)
12932 if (env->subprog_info[i].start >= off)
12934 /* find first prog starting at or after off + cnt (first to stay) */
12935 for (j = i; j < env->subprog_cnt; j++)
12936 if (env->subprog_info[j].start >= off + cnt)
12938 /* if j doesn't start exactly at off + cnt, we are just removing
12939 * the front of previous prog
12941 if (env->subprog_info[j].start != off + cnt)
12945 struct bpf_prog_aux *aux = env->prog->aux;
12948 /* move fake 'exit' subprog as well */
12949 move = env->subprog_cnt + 1 - j;
12951 memmove(env->subprog_info + i,
12952 env->subprog_info + j,
12953 sizeof(*env->subprog_info) * move);
12954 env->subprog_cnt -= j - i;
12956 /* remove func_info */
12957 if (aux->func_info) {
12958 move = aux->func_info_cnt - j;
12960 memmove(aux->func_info + i,
12961 aux->func_info + j,
12962 sizeof(*aux->func_info) * move);
12963 aux->func_info_cnt -= j - i;
12964 /* func_info->insn_off is set after all code rewrites,
12965 * in adjust_btf_func() - no need to adjust
12969 /* convert i from "first prog to remove" to "first to adjust" */
12970 if (env->subprog_info[i].start == off)
12974 /* update fake 'exit' subprog as well */
12975 for (; i <= env->subprog_cnt; i++)
12976 env->subprog_info[i].start -= cnt;
12981 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
12984 struct bpf_prog *prog = env->prog;
12985 u32 i, l_off, l_cnt, nr_linfo;
12986 struct bpf_line_info *linfo;
12988 nr_linfo = prog->aux->nr_linfo;
12992 linfo = prog->aux->linfo;
12994 /* find first line info to remove, count lines to be removed */
12995 for (i = 0; i < nr_linfo; i++)
12996 if (linfo[i].insn_off >= off)
13001 for (; i < nr_linfo; i++)
13002 if (linfo[i].insn_off < off + cnt)
13007 /* First live insn doesn't match first live linfo, it needs to "inherit"
13008 * last removed linfo. prog is already modified, so prog->len == off
13009 * means no live instructions after (tail of the program was removed).
13011 if (prog->len != off && l_cnt &&
13012 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13014 linfo[--i].insn_off = off + cnt;
13017 /* remove the line info which refer to the removed instructions */
13019 memmove(linfo + l_off, linfo + i,
13020 sizeof(*linfo) * (nr_linfo - i));
13022 prog->aux->nr_linfo -= l_cnt;
13023 nr_linfo = prog->aux->nr_linfo;
13026 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13027 for (i = l_off; i < nr_linfo; i++)
13028 linfo[i].insn_off -= cnt;
13030 /* fix up all subprogs (incl. 'exit') which start >= off */
13031 for (i = 0; i <= env->subprog_cnt; i++)
13032 if (env->subprog_info[i].linfo_idx > l_off) {
13033 /* program may have started in the removed region but
13034 * may not be fully removed
13036 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13037 env->subprog_info[i].linfo_idx -= l_cnt;
13039 env->subprog_info[i].linfo_idx = l_off;
13045 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13047 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13048 unsigned int orig_prog_len = env->prog->len;
13051 if (bpf_prog_is_dev_bound(env->prog->aux))
13052 bpf_prog_offload_remove_insns(env, off, cnt);
13054 err = bpf_remove_insns(env->prog, off, cnt);
13058 err = adjust_subprog_starts_after_remove(env, off, cnt);
13062 err = bpf_adj_linfo_after_remove(env, off, cnt);
13066 memmove(aux_data + off, aux_data + off + cnt,
13067 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13072 /* The verifier does more data flow analysis than llvm and will not
13073 * explore branches that are dead at run time. Malicious programs can
13074 * have dead code too. Therefore replace all dead at-run-time code
13077 * Just nops are not optimal, e.g. if they would sit at the end of the
13078 * program and through another bug we would manage to jump there, then
13079 * we'd execute beyond program memory otherwise. Returning exception
13080 * code also wouldn't work since we can have subprogs where the dead
13081 * code could be located.
13083 static void sanitize_dead_code(struct bpf_verifier_env *env)
13085 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13086 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13087 struct bpf_insn *insn = env->prog->insnsi;
13088 const int insn_cnt = env->prog->len;
13091 for (i = 0; i < insn_cnt; i++) {
13092 if (aux_data[i].seen)
13094 memcpy(insn + i, &trap, sizeof(trap));
13095 aux_data[i].zext_dst = false;
13099 static bool insn_is_cond_jump(u8 code)
13103 if (BPF_CLASS(code) == BPF_JMP32)
13106 if (BPF_CLASS(code) != BPF_JMP)
13110 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13113 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13115 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13116 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13117 struct bpf_insn *insn = env->prog->insnsi;
13118 const int insn_cnt = env->prog->len;
13121 for (i = 0; i < insn_cnt; i++, insn++) {
13122 if (!insn_is_cond_jump(insn->code))
13125 if (!aux_data[i + 1].seen)
13126 ja.off = insn->off;
13127 else if (!aux_data[i + 1 + insn->off].seen)
13132 if (bpf_prog_is_dev_bound(env->prog->aux))
13133 bpf_prog_offload_replace_insn(env, i, &ja);
13135 memcpy(insn, &ja, sizeof(ja));
13139 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13141 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13142 int insn_cnt = env->prog->len;
13145 for (i = 0; i < insn_cnt; i++) {
13149 while (i + j < insn_cnt && !aux_data[i + j].seen)
13154 err = verifier_remove_insns(env, i, j);
13157 insn_cnt = env->prog->len;
13163 static int opt_remove_nops(struct bpf_verifier_env *env)
13165 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13166 struct bpf_insn *insn = env->prog->insnsi;
13167 int insn_cnt = env->prog->len;
13170 for (i = 0; i < insn_cnt; i++) {
13171 if (memcmp(&insn[i], &ja, sizeof(ja)))
13174 err = verifier_remove_insns(env, i, 1);
13184 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13185 const union bpf_attr *attr)
13187 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13188 struct bpf_insn_aux_data *aux = env->insn_aux_data;
13189 int i, patch_len, delta = 0, len = env->prog->len;
13190 struct bpf_insn *insns = env->prog->insnsi;
13191 struct bpf_prog *new_prog;
13194 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13195 zext_patch[1] = BPF_ZEXT_REG(0);
13196 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13197 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13198 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13199 for (i = 0; i < len; i++) {
13200 int adj_idx = i + delta;
13201 struct bpf_insn insn;
13204 insn = insns[adj_idx];
13205 load_reg = insn_def_regno(&insn);
13206 if (!aux[adj_idx].zext_dst) {
13214 class = BPF_CLASS(code);
13215 if (load_reg == -1)
13218 /* NOTE: arg "reg" (the fourth one) is only used for
13219 * BPF_STX + SRC_OP, so it is safe to pass NULL
13222 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13223 if (class == BPF_LD &&
13224 BPF_MODE(code) == BPF_IMM)
13229 /* ctx load could be transformed into wider load. */
13230 if (class == BPF_LDX &&
13231 aux[adj_idx].ptr_type == PTR_TO_CTX)
13234 imm_rnd = get_random_int();
13235 rnd_hi32_patch[0] = insn;
13236 rnd_hi32_patch[1].imm = imm_rnd;
13237 rnd_hi32_patch[3].dst_reg = load_reg;
13238 patch = rnd_hi32_patch;
13240 goto apply_patch_buffer;
13243 /* Add in an zero-extend instruction if a) the JIT has requested
13244 * it or b) it's a CMPXCHG.
13246 * The latter is because: BPF_CMPXCHG always loads a value into
13247 * R0, therefore always zero-extends. However some archs'
13248 * equivalent instruction only does this load when the
13249 * comparison is successful. This detail of CMPXCHG is
13250 * orthogonal to the general zero-extension behaviour of the
13251 * CPU, so it's treated independently of bpf_jit_needs_zext.
13253 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13256 if (WARN_ON(load_reg == -1)) {
13257 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13261 zext_patch[0] = insn;
13262 zext_patch[1].dst_reg = load_reg;
13263 zext_patch[1].src_reg = load_reg;
13264 patch = zext_patch;
13266 apply_patch_buffer:
13267 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13270 env->prog = new_prog;
13271 insns = new_prog->insnsi;
13272 aux = env->insn_aux_data;
13273 delta += patch_len - 1;
13279 /* convert load instructions that access fields of a context type into a
13280 * sequence of instructions that access fields of the underlying structure:
13281 * struct __sk_buff -> struct sk_buff
13282 * struct bpf_sock_ops -> struct sock
13284 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13286 const struct bpf_verifier_ops *ops = env->ops;
13287 int i, cnt, size, ctx_field_size, delta = 0;
13288 const int insn_cnt = env->prog->len;
13289 struct bpf_insn insn_buf[16], *insn;
13290 u32 target_size, size_default, off;
13291 struct bpf_prog *new_prog;
13292 enum bpf_access_type type;
13293 bool is_narrower_load;
13295 if (ops->gen_prologue || env->seen_direct_write) {
13296 if (!ops->gen_prologue) {
13297 verbose(env, "bpf verifier is misconfigured\n");
13300 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13302 if (cnt >= ARRAY_SIZE(insn_buf)) {
13303 verbose(env, "bpf verifier is misconfigured\n");
13306 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13310 env->prog = new_prog;
13315 if (bpf_prog_is_dev_bound(env->prog->aux))
13318 insn = env->prog->insnsi + delta;
13320 for (i = 0; i < insn_cnt; i++, insn++) {
13321 bpf_convert_ctx_access_t convert_ctx_access;
13324 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13325 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13326 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13327 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13330 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13331 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13332 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13333 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13334 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13335 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13336 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13337 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13339 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13344 if (type == BPF_WRITE &&
13345 env->insn_aux_data[i + delta].sanitize_stack_spill) {
13346 struct bpf_insn patch[] = {
13351 cnt = ARRAY_SIZE(patch);
13352 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13357 env->prog = new_prog;
13358 insn = new_prog->insnsi + i + delta;
13365 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13367 if (!ops->convert_ctx_access)
13369 convert_ctx_access = ops->convert_ctx_access;
13371 case PTR_TO_SOCKET:
13372 case PTR_TO_SOCK_COMMON:
13373 convert_ctx_access = bpf_sock_convert_ctx_access;
13375 case PTR_TO_TCP_SOCK:
13376 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13378 case PTR_TO_XDP_SOCK:
13379 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13381 case PTR_TO_BTF_ID:
13382 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13383 if (type == BPF_READ) {
13384 insn->code = BPF_LDX | BPF_PROBE_MEM |
13385 BPF_SIZE((insn)->code);
13386 env->prog->aux->num_exentries++;
13387 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
13388 verbose(env, "Writes through BTF pointers are not allowed\n");
13396 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13397 size = BPF_LDST_BYTES(insn);
13399 /* If the read access is a narrower load of the field,
13400 * convert to a 4/8-byte load, to minimum program type specific
13401 * convert_ctx_access changes. If conversion is successful,
13402 * we will apply proper mask to the result.
13404 is_narrower_load = size < ctx_field_size;
13405 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13407 if (is_narrower_load) {
13410 if (type == BPF_WRITE) {
13411 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13416 if (ctx_field_size == 4)
13418 else if (ctx_field_size == 8)
13419 size_code = BPF_DW;
13421 insn->off = off & ~(size_default - 1);
13422 insn->code = BPF_LDX | BPF_MEM | size_code;
13426 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13428 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13429 (ctx_field_size && !target_size)) {
13430 verbose(env, "bpf verifier is misconfigured\n");
13434 if (is_narrower_load && size < target_size) {
13435 u8 shift = bpf_ctx_narrow_access_offset(
13436 off, size, size_default) * 8;
13437 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13438 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13441 if (ctx_field_size <= 4) {
13443 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13446 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13447 (1 << size * 8) - 1);
13450 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13453 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13454 (1ULL << size * 8) - 1);
13458 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13464 /* keep walking new program and skip insns we just inserted */
13465 env->prog = new_prog;
13466 insn = new_prog->insnsi + i + delta;
13472 static int jit_subprogs(struct bpf_verifier_env *env)
13474 struct bpf_prog *prog = env->prog, **func, *tmp;
13475 int i, j, subprog_start, subprog_end = 0, len, subprog;
13476 struct bpf_map *map_ptr;
13477 struct bpf_insn *insn;
13478 void *old_bpf_func;
13479 int err, num_exentries;
13481 if (env->subprog_cnt <= 1)
13484 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13485 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13488 /* Upon error here we cannot fall back to interpreter but
13489 * need a hard reject of the program. Thus -EFAULT is
13490 * propagated in any case.
13492 subprog = find_subprog(env, i + insn->imm + 1);
13494 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13495 i + insn->imm + 1);
13498 /* temporarily remember subprog id inside insn instead of
13499 * aux_data, since next loop will split up all insns into funcs
13501 insn->off = subprog;
13502 /* remember original imm in case JIT fails and fallback
13503 * to interpreter will be needed
13505 env->insn_aux_data[i].call_imm = insn->imm;
13506 /* point imm to __bpf_call_base+1 from JITs point of view */
13508 if (bpf_pseudo_func(insn))
13509 /* jit (e.g. x86_64) may emit fewer instructions
13510 * if it learns a u32 imm is the same as a u64 imm.
13511 * Force a non zero here.
13516 err = bpf_prog_alloc_jited_linfo(prog);
13518 goto out_undo_insn;
13521 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13523 goto out_undo_insn;
13525 for (i = 0; i < env->subprog_cnt; i++) {
13526 subprog_start = subprog_end;
13527 subprog_end = env->subprog_info[i + 1].start;
13529 len = subprog_end - subprog_start;
13530 /* bpf_prog_run() doesn't call subprogs directly,
13531 * hence main prog stats include the runtime of subprogs.
13532 * subprogs don't have IDs and not reachable via prog_get_next_id
13533 * func[i]->stats will never be accessed and stays NULL
13535 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13538 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13539 len * sizeof(struct bpf_insn));
13540 func[i]->type = prog->type;
13541 func[i]->len = len;
13542 if (bpf_prog_calc_tag(func[i]))
13544 func[i]->is_func = 1;
13545 func[i]->aux->func_idx = i;
13546 /* Below members will be freed only at prog->aux */
13547 func[i]->aux->btf = prog->aux->btf;
13548 func[i]->aux->func_info = prog->aux->func_info;
13549 func[i]->aux->poke_tab = prog->aux->poke_tab;
13550 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13552 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13553 struct bpf_jit_poke_descriptor *poke;
13555 poke = &prog->aux->poke_tab[j];
13556 if (poke->insn_idx < subprog_end &&
13557 poke->insn_idx >= subprog_start)
13558 poke->aux = func[i]->aux;
13561 /* Use bpf_prog_F_tag to indicate functions in stack traces.
13562 * Long term would need debug info to populate names
13564 func[i]->aux->name[0] = 'F';
13565 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13566 func[i]->jit_requested = 1;
13567 func[i]->blinding_requested = prog->blinding_requested;
13568 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13569 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13570 func[i]->aux->linfo = prog->aux->linfo;
13571 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13572 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13573 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13575 insn = func[i]->insnsi;
13576 for (j = 0; j < func[i]->len; j++, insn++) {
13577 if (BPF_CLASS(insn->code) == BPF_LDX &&
13578 BPF_MODE(insn->code) == BPF_PROBE_MEM)
13581 func[i]->aux->num_exentries = num_exentries;
13582 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13583 func[i] = bpf_int_jit_compile(func[i]);
13584 if (!func[i]->jited) {
13591 /* at this point all bpf functions were successfully JITed
13592 * now populate all bpf_calls with correct addresses and
13593 * run last pass of JIT
13595 for (i = 0; i < env->subprog_cnt; i++) {
13596 insn = func[i]->insnsi;
13597 for (j = 0; j < func[i]->len; j++, insn++) {
13598 if (bpf_pseudo_func(insn)) {
13599 subprog = insn->off;
13600 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13601 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13604 if (!bpf_pseudo_call(insn))
13606 subprog = insn->off;
13607 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13610 /* we use the aux data to keep a list of the start addresses
13611 * of the JITed images for each function in the program
13613 * for some architectures, such as powerpc64, the imm field
13614 * might not be large enough to hold the offset of the start
13615 * address of the callee's JITed image from __bpf_call_base
13617 * in such cases, we can lookup the start address of a callee
13618 * by using its subprog id, available from the off field of
13619 * the call instruction, as an index for this list
13621 func[i]->aux->func = func;
13622 func[i]->aux->func_cnt = env->subprog_cnt;
13624 for (i = 0; i < env->subprog_cnt; i++) {
13625 old_bpf_func = func[i]->bpf_func;
13626 tmp = bpf_int_jit_compile(func[i]);
13627 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13628 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13635 /* finally lock prog and jit images for all functions and
13636 * populate kallsysm
13638 for (i = 0; i < env->subprog_cnt; i++) {
13639 bpf_prog_lock_ro(func[i]);
13640 bpf_prog_kallsyms_add(func[i]);
13643 /* Last step: make now unused interpreter insns from main
13644 * prog consistent for later dump requests, so they can
13645 * later look the same as if they were interpreted only.
13647 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13648 if (bpf_pseudo_func(insn)) {
13649 insn[0].imm = env->insn_aux_data[i].call_imm;
13650 insn[1].imm = insn->off;
13654 if (!bpf_pseudo_call(insn))
13656 insn->off = env->insn_aux_data[i].call_imm;
13657 subprog = find_subprog(env, i + insn->off + 1);
13658 insn->imm = subprog;
13662 prog->bpf_func = func[0]->bpf_func;
13663 prog->jited_len = func[0]->jited_len;
13664 prog->aux->func = func;
13665 prog->aux->func_cnt = env->subprog_cnt;
13666 bpf_prog_jit_attempt_done(prog);
13669 /* We failed JIT'ing, so at this point we need to unregister poke
13670 * descriptors from subprogs, so that kernel is not attempting to
13671 * patch it anymore as we're freeing the subprog JIT memory.
13673 for (i = 0; i < prog->aux->size_poke_tab; i++) {
13674 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13675 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13677 /* At this point we're guaranteed that poke descriptors are not
13678 * live anymore. We can just unlink its descriptor table as it's
13679 * released with the main prog.
13681 for (i = 0; i < env->subprog_cnt; i++) {
13684 func[i]->aux->poke_tab = NULL;
13685 bpf_jit_free(func[i]);
13689 /* cleanup main prog to be interpreted */
13690 prog->jit_requested = 0;
13691 prog->blinding_requested = 0;
13692 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13693 if (!bpf_pseudo_call(insn))
13696 insn->imm = env->insn_aux_data[i].call_imm;
13698 bpf_prog_jit_attempt_done(prog);
13702 static int fixup_call_args(struct bpf_verifier_env *env)
13704 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13705 struct bpf_prog *prog = env->prog;
13706 struct bpf_insn *insn = prog->insnsi;
13707 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13712 if (env->prog->jit_requested &&
13713 !bpf_prog_is_dev_bound(env->prog->aux)) {
13714 err = jit_subprogs(env);
13717 if (err == -EFAULT)
13720 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13721 if (has_kfunc_call) {
13722 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13725 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13726 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13727 * have to be rejected, since interpreter doesn't support them yet.
13729 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13732 for (i = 0; i < prog->len; i++, insn++) {
13733 if (bpf_pseudo_func(insn)) {
13734 /* When JIT fails the progs with callback calls
13735 * have to be rejected, since interpreter doesn't support them yet.
13737 verbose(env, "callbacks are not allowed in non-JITed programs\n");
13741 if (!bpf_pseudo_call(insn))
13743 depth = get_callee_stack_depth(env, insn, i);
13746 bpf_patch_call_args(insn, depth);
13753 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13754 struct bpf_insn *insn)
13756 const struct bpf_kfunc_desc *desc;
13759 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13763 /* insn->imm has the btf func_id. Replace it with
13764 * an address (relative to __bpf_base_call).
13766 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13768 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13773 insn->imm = desc->imm;
13778 /* Do various post-verification rewrites in a single program pass.
13779 * These rewrites simplify JIT and interpreter implementations.
13781 static int do_misc_fixups(struct bpf_verifier_env *env)
13783 struct bpf_prog *prog = env->prog;
13784 enum bpf_attach_type eatype = prog->expected_attach_type;
13785 enum bpf_prog_type prog_type = resolve_prog_type(prog);
13786 struct bpf_insn *insn = prog->insnsi;
13787 const struct bpf_func_proto *fn;
13788 const int insn_cnt = prog->len;
13789 const struct bpf_map_ops *ops;
13790 struct bpf_insn_aux_data *aux;
13791 struct bpf_insn insn_buf[16];
13792 struct bpf_prog *new_prog;
13793 struct bpf_map *map_ptr;
13794 int i, ret, cnt, delta = 0;
13796 for (i = 0; i < insn_cnt; i++, insn++) {
13797 /* Make divide-by-zero exceptions impossible. */
13798 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13799 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13800 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13801 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13802 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13803 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13804 struct bpf_insn *patchlet;
13805 struct bpf_insn chk_and_div[] = {
13806 /* [R,W]x div 0 -> 0 */
13807 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13808 BPF_JNE | BPF_K, insn->src_reg,
13810 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13811 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13814 struct bpf_insn chk_and_mod[] = {
13815 /* [R,W]x mod 0 -> [R,W]x */
13816 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13817 BPF_JEQ | BPF_K, insn->src_reg,
13818 0, 1 + (is64 ? 0 : 1), 0),
13820 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13821 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13824 patchlet = isdiv ? chk_and_div : chk_and_mod;
13825 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13826 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
13828 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
13833 env->prog = prog = new_prog;
13834 insn = new_prog->insnsi + i + delta;
13838 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
13839 if (BPF_CLASS(insn->code) == BPF_LD &&
13840 (BPF_MODE(insn->code) == BPF_ABS ||
13841 BPF_MODE(insn->code) == BPF_IND)) {
13842 cnt = env->ops->gen_ld_abs(insn, insn_buf);
13843 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13844 verbose(env, "bpf verifier is misconfigured\n");
13848 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13853 env->prog = prog = new_prog;
13854 insn = new_prog->insnsi + i + delta;
13858 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
13859 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13860 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13861 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13862 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
13863 struct bpf_insn *patch = &insn_buf[0];
13864 bool issrc, isneg, isimm;
13867 aux = &env->insn_aux_data[i + delta];
13868 if (!aux->alu_state ||
13869 aux->alu_state == BPF_ALU_NON_POINTER)
13872 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
13873 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
13874 BPF_ALU_SANITIZE_SRC;
13875 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
13877 off_reg = issrc ? insn->src_reg : insn->dst_reg;
13879 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13882 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13883 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13884 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
13885 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
13886 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
13887 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
13888 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
13891 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
13892 insn->src_reg = BPF_REG_AX;
13894 insn->code = insn->code == code_add ?
13895 code_sub : code_add;
13897 if (issrc && isneg && !isimm)
13898 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13899 cnt = patch - insn_buf;
13901 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13906 env->prog = prog = new_prog;
13907 insn = new_prog->insnsi + i + delta;
13911 if (insn->code != (BPF_JMP | BPF_CALL))
13913 if (insn->src_reg == BPF_PSEUDO_CALL)
13915 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
13916 ret = fixup_kfunc_call(env, insn);
13922 if (insn->imm == BPF_FUNC_get_route_realm)
13923 prog->dst_needed = 1;
13924 if (insn->imm == BPF_FUNC_get_prandom_u32)
13925 bpf_user_rnd_init_once();
13926 if (insn->imm == BPF_FUNC_override_return)
13927 prog->kprobe_override = 1;
13928 if (insn->imm == BPF_FUNC_tail_call) {
13929 /* If we tail call into other programs, we
13930 * cannot make any assumptions since they can
13931 * be replaced dynamically during runtime in
13932 * the program array.
13934 prog->cb_access = 1;
13935 if (!allow_tail_call_in_subprogs(env))
13936 prog->aux->stack_depth = MAX_BPF_STACK;
13937 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
13939 /* mark bpf_tail_call as different opcode to avoid
13940 * conditional branch in the interpreter for every normal
13941 * call and to prevent accidental JITing by JIT compiler
13942 * that doesn't support bpf_tail_call yet
13945 insn->code = BPF_JMP | BPF_TAIL_CALL;
13947 aux = &env->insn_aux_data[i + delta];
13948 if (env->bpf_capable && !prog->blinding_requested &&
13949 prog->jit_requested &&
13950 !bpf_map_key_poisoned(aux) &&
13951 !bpf_map_ptr_poisoned(aux) &&
13952 !bpf_map_ptr_unpriv(aux)) {
13953 struct bpf_jit_poke_descriptor desc = {
13954 .reason = BPF_POKE_REASON_TAIL_CALL,
13955 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
13956 .tail_call.key = bpf_map_key_immediate(aux),
13957 .insn_idx = i + delta,
13960 ret = bpf_jit_add_poke_descriptor(prog, &desc);
13962 verbose(env, "adding tail call poke descriptor failed\n");
13966 insn->imm = ret + 1;
13970 if (!bpf_map_ptr_unpriv(aux))
13973 /* instead of changing every JIT dealing with tail_call
13974 * emit two extra insns:
13975 * if (index >= max_entries) goto out;
13976 * index &= array->index_mask;
13977 * to avoid out-of-bounds cpu speculation
13979 if (bpf_map_ptr_poisoned(aux)) {
13980 verbose(env, "tail_call abusing map_ptr\n");
13984 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13985 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
13986 map_ptr->max_entries, 2);
13987 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
13988 container_of(map_ptr,
13991 insn_buf[2] = *insn;
13993 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13998 env->prog = prog = new_prog;
13999 insn = new_prog->insnsi + i + delta;
14003 if (insn->imm == BPF_FUNC_timer_set_callback) {
14004 /* The verifier will process callback_fn as many times as necessary
14005 * with different maps and the register states prepared by
14006 * set_timer_callback_state will be accurate.
14008 * The following use case is valid:
14009 * map1 is shared by prog1, prog2, prog3.
14010 * prog1 calls bpf_timer_init for some map1 elements
14011 * prog2 calls bpf_timer_set_callback for some map1 elements.
14012 * Those that were not bpf_timer_init-ed will return -EINVAL.
14013 * prog3 calls bpf_timer_start for some map1 elements.
14014 * Those that were not both bpf_timer_init-ed and
14015 * bpf_timer_set_callback-ed will return -EINVAL.
14017 struct bpf_insn ld_addrs[2] = {
14018 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14021 insn_buf[0] = ld_addrs[0];
14022 insn_buf[1] = ld_addrs[1];
14023 insn_buf[2] = *insn;
14026 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14031 env->prog = prog = new_prog;
14032 insn = new_prog->insnsi + i + delta;
14033 goto patch_call_imm;
14036 if (insn->imm == BPF_FUNC_task_storage_get ||
14037 insn->imm == BPF_FUNC_sk_storage_get ||
14038 insn->imm == BPF_FUNC_inode_storage_get) {
14039 if (env->prog->aux->sleepable)
14040 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14042 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14043 insn_buf[1] = *insn;
14046 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14051 env->prog = prog = new_prog;
14052 insn = new_prog->insnsi + i + delta;
14053 goto patch_call_imm;
14056 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14057 * and other inlining handlers are currently limited to 64 bit
14060 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14061 (insn->imm == BPF_FUNC_map_lookup_elem ||
14062 insn->imm == BPF_FUNC_map_update_elem ||
14063 insn->imm == BPF_FUNC_map_delete_elem ||
14064 insn->imm == BPF_FUNC_map_push_elem ||
14065 insn->imm == BPF_FUNC_map_pop_elem ||
14066 insn->imm == BPF_FUNC_map_peek_elem ||
14067 insn->imm == BPF_FUNC_redirect_map ||
14068 insn->imm == BPF_FUNC_for_each_map_elem ||
14069 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14070 aux = &env->insn_aux_data[i + delta];
14071 if (bpf_map_ptr_poisoned(aux))
14072 goto patch_call_imm;
14074 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14075 ops = map_ptr->ops;
14076 if (insn->imm == BPF_FUNC_map_lookup_elem &&
14077 ops->map_gen_lookup) {
14078 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14079 if (cnt == -EOPNOTSUPP)
14080 goto patch_map_ops_generic;
14081 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14082 verbose(env, "bpf verifier is misconfigured\n");
14086 new_prog = bpf_patch_insn_data(env, i + delta,
14092 env->prog = prog = new_prog;
14093 insn = new_prog->insnsi + i + delta;
14097 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14098 (void *(*)(struct bpf_map *map, void *key))NULL));
14099 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14100 (int (*)(struct bpf_map *map, void *key))NULL));
14101 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14102 (int (*)(struct bpf_map *map, void *key, void *value,
14104 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14105 (int (*)(struct bpf_map *map, void *value,
14107 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14108 (int (*)(struct bpf_map *map, void *value))NULL));
14109 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14110 (int (*)(struct bpf_map *map, void *value))NULL));
14111 BUILD_BUG_ON(!__same_type(ops->map_redirect,
14112 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14113 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14114 (int (*)(struct bpf_map *map,
14115 bpf_callback_t callback_fn,
14116 void *callback_ctx,
14118 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14119 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14121 patch_map_ops_generic:
14122 switch (insn->imm) {
14123 case BPF_FUNC_map_lookup_elem:
14124 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14126 case BPF_FUNC_map_update_elem:
14127 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14129 case BPF_FUNC_map_delete_elem:
14130 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14132 case BPF_FUNC_map_push_elem:
14133 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14135 case BPF_FUNC_map_pop_elem:
14136 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14138 case BPF_FUNC_map_peek_elem:
14139 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14141 case BPF_FUNC_redirect_map:
14142 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14144 case BPF_FUNC_for_each_map_elem:
14145 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14147 case BPF_FUNC_map_lookup_percpu_elem:
14148 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14152 goto patch_call_imm;
14155 /* Implement bpf_jiffies64 inline. */
14156 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14157 insn->imm == BPF_FUNC_jiffies64) {
14158 struct bpf_insn ld_jiffies_addr[2] = {
14159 BPF_LD_IMM64(BPF_REG_0,
14160 (unsigned long)&jiffies),
14163 insn_buf[0] = ld_jiffies_addr[0];
14164 insn_buf[1] = ld_jiffies_addr[1];
14165 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14169 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14175 env->prog = prog = new_prog;
14176 insn = new_prog->insnsi + i + delta;
14180 /* Implement bpf_get_func_arg inline. */
14181 if (prog_type == BPF_PROG_TYPE_TRACING &&
14182 insn->imm == BPF_FUNC_get_func_arg) {
14183 /* Load nr_args from ctx - 8 */
14184 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14185 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14186 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14187 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14188 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14189 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14190 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14191 insn_buf[7] = BPF_JMP_A(1);
14192 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14195 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14200 env->prog = prog = new_prog;
14201 insn = new_prog->insnsi + i + delta;
14205 /* Implement bpf_get_func_ret inline. */
14206 if (prog_type == BPF_PROG_TYPE_TRACING &&
14207 insn->imm == BPF_FUNC_get_func_ret) {
14208 if (eatype == BPF_TRACE_FEXIT ||
14209 eatype == BPF_MODIFY_RETURN) {
14210 /* Load nr_args from ctx - 8 */
14211 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14212 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14213 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14214 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14215 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14216 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14219 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14223 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14228 env->prog = prog = new_prog;
14229 insn = new_prog->insnsi + i + delta;
14233 /* Implement get_func_arg_cnt inline. */
14234 if (prog_type == BPF_PROG_TYPE_TRACING &&
14235 insn->imm == BPF_FUNC_get_func_arg_cnt) {
14236 /* Load nr_args from ctx - 8 */
14237 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14239 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14243 env->prog = prog = new_prog;
14244 insn = new_prog->insnsi + i + delta;
14248 /* Implement bpf_get_func_ip inline. */
14249 if (prog_type == BPF_PROG_TYPE_TRACING &&
14250 insn->imm == BPF_FUNC_get_func_ip) {
14251 /* Load IP address from ctx - 16 */
14252 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14254 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14258 env->prog = prog = new_prog;
14259 insn = new_prog->insnsi + i + delta;
14264 fn = env->ops->get_func_proto(insn->imm, env->prog);
14265 /* all functions that have prototype and verifier allowed
14266 * programs to call them, must be real in-kernel functions
14270 "kernel subsystem misconfigured func %s#%d\n",
14271 func_id_name(insn->imm), insn->imm);
14274 insn->imm = fn->func - __bpf_call_base;
14277 /* Since poke tab is now finalized, publish aux to tracker. */
14278 for (i = 0; i < prog->aux->size_poke_tab; i++) {
14279 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14280 if (!map_ptr->ops->map_poke_track ||
14281 !map_ptr->ops->map_poke_untrack ||
14282 !map_ptr->ops->map_poke_run) {
14283 verbose(env, "bpf verifier is misconfigured\n");
14287 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14289 verbose(env, "tracking tail call prog failed\n");
14294 sort_kfunc_descs_by_imm(env->prog);
14299 static void free_states(struct bpf_verifier_env *env)
14301 struct bpf_verifier_state_list *sl, *sln;
14304 sl = env->free_list;
14307 free_verifier_state(&sl->state, false);
14311 env->free_list = NULL;
14313 if (!env->explored_states)
14316 for (i = 0; i < state_htab_size(env); i++) {
14317 sl = env->explored_states[i];
14321 free_verifier_state(&sl->state, false);
14325 env->explored_states[i] = NULL;
14329 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14331 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14332 struct bpf_verifier_state *state;
14333 struct bpf_reg_state *regs;
14336 env->prev_linfo = NULL;
14339 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14342 state->curframe = 0;
14343 state->speculative = false;
14344 state->branches = 1;
14345 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14346 if (!state->frame[0]) {
14350 env->cur_state = state;
14351 init_func_state(env, state->frame[0],
14352 BPF_MAIN_FUNC /* callsite */,
14356 regs = state->frame[state->curframe]->regs;
14357 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14358 ret = btf_prepare_func_args(env, subprog, regs);
14361 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14362 if (regs[i].type == PTR_TO_CTX)
14363 mark_reg_known_zero(env, regs, i);
14364 else if (regs[i].type == SCALAR_VALUE)
14365 mark_reg_unknown(env, regs, i);
14366 else if (base_type(regs[i].type) == PTR_TO_MEM) {
14367 const u32 mem_size = regs[i].mem_size;
14369 mark_reg_known_zero(env, regs, i);
14370 regs[i].mem_size = mem_size;
14371 regs[i].id = ++env->id_gen;
14375 /* 1st arg to a function */
14376 regs[BPF_REG_1].type = PTR_TO_CTX;
14377 mark_reg_known_zero(env, regs, BPF_REG_1);
14378 ret = btf_check_subprog_arg_match(env, subprog, regs);
14379 if (ret == -EFAULT)
14380 /* unlikely verifier bug. abort.
14381 * ret == 0 and ret < 0 are sadly acceptable for
14382 * main() function due to backward compatibility.
14383 * Like socket filter program may be written as:
14384 * int bpf_prog(struct pt_regs *ctx)
14385 * and never dereference that ctx in the program.
14386 * 'struct pt_regs' is a type mismatch for socket
14387 * filter that should be using 'struct __sk_buff'.
14392 ret = do_check(env);
14394 /* check for NULL is necessary, since cur_state can be freed inside
14395 * do_check() under memory pressure.
14397 if (env->cur_state) {
14398 free_verifier_state(env->cur_state, true);
14399 env->cur_state = NULL;
14401 while (!pop_stack(env, NULL, NULL, false));
14402 if (!ret && pop_log)
14403 bpf_vlog_reset(&env->log, 0);
14408 /* Verify all global functions in a BPF program one by one based on their BTF.
14409 * All global functions must pass verification. Otherwise the whole program is rejected.
14420 * foo() will be verified first for R1=any_scalar_value. During verification it
14421 * will be assumed that bar() already verified successfully and call to bar()
14422 * from foo() will be checked for type match only. Later bar() will be verified
14423 * independently to check that it's safe for R1=any_scalar_value.
14425 static int do_check_subprogs(struct bpf_verifier_env *env)
14427 struct bpf_prog_aux *aux = env->prog->aux;
14430 if (!aux->func_info)
14433 for (i = 1; i < env->subprog_cnt; i++) {
14434 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14436 env->insn_idx = env->subprog_info[i].start;
14437 WARN_ON_ONCE(env->insn_idx == 0);
14438 ret = do_check_common(env, i);
14441 } else if (env->log.level & BPF_LOG_LEVEL) {
14443 "Func#%d is safe for any args that match its prototype\n",
14450 static int do_check_main(struct bpf_verifier_env *env)
14455 ret = do_check_common(env, 0);
14457 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14462 static void print_verification_stats(struct bpf_verifier_env *env)
14466 if (env->log.level & BPF_LOG_STATS) {
14467 verbose(env, "verification time %lld usec\n",
14468 div_u64(env->verification_time, 1000));
14469 verbose(env, "stack depth ");
14470 for (i = 0; i < env->subprog_cnt; i++) {
14471 u32 depth = env->subprog_info[i].stack_depth;
14473 verbose(env, "%d", depth);
14474 if (i + 1 < env->subprog_cnt)
14477 verbose(env, "\n");
14479 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14480 "total_states %d peak_states %d mark_read %d\n",
14481 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14482 env->max_states_per_insn, env->total_states,
14483 env->peak_states, env->longest_mark_read_walk);
14486 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14488 const struct btf_type *t, *func_proto;
14489 const struct bpf_struct_ops *st_ops;
14490 const struct btf_member *member;
14491 struct bpf_prog *prog = env->prog;
14492 u32 btf_id, member_idx;
14495 if (!prog->gpl_compatible) {
14496 verbose(env, "struct ops programs must have a GPL compatible license\n");
14500 btf_id = prog->aux->attach_btf_id;
14501 st_ops = bpf_struct_ops_find(btf_id);
14503 verbose(env, "attach_btf_id %u is not a supported struct\n",
14509 member_idx = prog->expected_attach_type;
14510 if (member_idx >= btf_type_vlen(t)) {
14511 verbose(env, "attach to invalid member idx %u of struct %s\n",
14512 member_idx, st_ops->name);
14516 member = &btf_type_member(t)[member_idx];
14517 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14518 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14521 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14522 mname, member_idx, st_ops->name);
14526 if (st_ops->check_member) {
14527 int err = st_ops->check_member(t, member);
14530 verbose(env, "attach to unsupported member %s of struct %s\n",
14531 mname, st_ops->name);
14536 prog->aux->attach_func_proto = func_proto;
14537 prog->aux->attach_func_name = mname;
14538 env->ops = st_ops->verifier_ops;
14542 #define SECURITY_PREFIX "security_"
14544 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14546 if (within_error_injection_list(addr) ||
14547 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14553 /* list of non-sleepable functions that are otherwise on
14554 * ALLOW_ERROR_INJECTION list
14556 BTF_SET_START(btf_non_sleepable_error_inject)
14557 /* Three functions below can be called from sleepable and non-sleepable context.
14558 * Assume non-sleepable from bpf safety point of view.
14560 BTF_ID(func, __filemap_add_folio)
14561 BTF_ID(func, should_fail_alloc_page)
14562 BTF_ID(func, should_failslab)
14563 BTF_SET_END(btf_non_sleepable_error_inject)
14565 static int check_non_sleepable_error_inject(u32 btf_id)
14567 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14570 int bpf_check_attach_target(struct bpf_verifier_log *log,
14571 const struct bpf_prog *prog,
14572 const struct bpf_prog *tgt_prog,
14574 struct bpf_attach_target_info *tgt_info)
14576 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14577 const char prefix[] = "btf_trace_";
14578 int ret = 0, subprog = -1, i;
14579 const struct btf_type *t;
14580 bool conservative = true;
14586 bpf_log(log, "Tracing programs must provide btf_id\n");
14589 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14592 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14595 t = btf_type_by_id(btf, btf_id);
14597 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14600 tname = btf_name_by_offset(btf, t->name_off);
14602 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14606 struct bpf_prog_aux *aux = tgt_prog->aux;
14608 for (i = 0; i < aux->func_info_cnt; i++)
14609 if (aux->func_info[i].type_id == btf_id) {
14613 if (subprog == -1) {
14614 bpf_log(log, "Subprog %s doesn't exist\n", tname);
14617 conservative = aux->func_info_aux[subprog].unreliable;
14618 if (prog_extension) {
14619 if (conservative) {
14621 "Cannot replace static functions\n");
14624 if (!prog->jit_requested) {
14626 "Extension programs should be JITed\n");
14630 if (!tgt_prog->jited) {
14631 bpf_log(log, "Can attach to only JITed progs\n");
14634 if (tgt_prog->type == prog->type) {
14635 /* Cannot fentry/fexit another fentry/fexit program.
14636 * Cannot attach program extension to another extension.
14637 * It's ok to attach fentry/fexit to extension program.
14639 bpf_log(log, "Cannot recursively attach\n");
14642 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14644 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14645 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14646 /* Program extensions can extend all program types
14647 * except fentry/fexit. The reason is the following.
14648 * The fentry/fexit programs are used for performance
14649 * analysis, stats and can be attached to any program
14650 * type except themselves. When extension program is
14651 * replacing XDP function it is necessary to allow
14652 * performance analysis of all functions. Both original
14653 * XDP program and its program extension. Hence
14654 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14655 * allowed. If extending of fentry/fexit was allowed it
14656 * would be possible to create long call chain
14657 * fentry->extension->fentry->extension beyond
14658 * reasonable stack size. Hence extending fentry is not
14661 bpf_log(log, "Cannot extend fentry/fexit\n");
14665 if (prog_extension) {
14666 bpf_log(log, "Cannot replace kernel functions\n");
14671 switch (prog->expected_attach_type) {
14672 case BPF_TRACE_RAW_TP:
14675 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14678 if (!btf_type_is_typedef(t)) {
14679 bpf_log(log, "attach_btf_id %u is not a typedef\n",
14683 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
14684 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
14688 tname += sizeof(prefix) - 1;
14689 t = btf_type_by_id(btf, t->type);
14690 if (!btf_type_is_ptr(t))
14691 /* should never happen in valid vmlinux build */
14693 t = btf_type_by_id(btf, t->type);
14694 if (!btf_type_is_func_proto(t))
14695 /* should never happen in valid vmlinux build */
14699 case BPF_TRACE_ITER:
14700 if (!btf_type_is_func(t)) {
14701 bpf_log(log, "attach_btf_id %u is not a function\n",
14705 t = btf_type_by_id(btf, t->type);
14706 if (!btf_type_is_func_proto(t))
14708 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14713 if (!prog_extension)
14716 case BPF_MODIFY_RETURN:
14718 case BPF_TRACE_FENTRY:
14719 case BPF_TRACE_FEXIT:
14720 if (!btf_type_is_func(t)) {
14721 bpf_log(log, "attach_btf_id %u is not a function\n",
14725 if (prog_extension &&
14726 btf_check_type_match(log, prog, btf, t))
14728 t = btf_type_by_id(btf, t->type);
14729 if (!btf_type_is_func_proto(t))
14732 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
14733 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
14734 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
14737 if (tgt_prog && conservative)
14740 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14746 addr = (long) tgt_prog->bpf_func;
14748 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
14750 addr = kallsyms_lookup_name(tname);
14753 "The address of function %s cannot be found\n",
14759 if (prog->aux->sleepable) {
14761 switch (prog->type) {
14762 case BPF_PROG_TYPE_TRACING:
14763 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
14764 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
14766 if (!check_non_sleepable_error_inject(btf_id) &&
14767 within_error_injection_list(addr))
14770 case BPF_PROG_TYPE_LSM:
14771 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
14772 * Only some of them are sleepable.
14774 if (bpf_lsm_is_sleepable_hook(btf_id))
14781 bpf_log(log, "%s is not sleepable\n", tname);
14784 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
14786 bpf_log(log, "can't modify return codes of BPF programs\n");
14789 ret = check_attach_modify_return(addr, tname);
14791 bpf_log(log, "%s() is not modifiable\n", tname);
14798 tgt_info->tgt_addr = addr;
14799 tgt_info->tgt_name = tname;
14800 tgt_info->tgt_type = t;
14804 BTF_SET_START(btf_id_deny)
14807 BTF_ID(func, migrate_disable)
14808 BTF_ID(func, migrate_enable)
14810 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
14811 BTF_ID(func, rcu_read_unlock_strict)
14813 BTF_SET_END(btf_id_deny)
14815 static int check_attach_btf_id(struct bpf_verifier_env *env)
14817 struct bpf_prog *prog = env->prog;
14818 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
14819 struct bpf_attach_target_info tgt_info = {};
14820 u32 btf_id = prog->aux->attach_btf_id;
14821 struct bpf_trampoline *tr;
14825 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
14826 if (prog->aux->sleepable)
14827 /* attach_btf_id checked to be zero already */
14829 verbose(env, "Syscall programs can only be sleepable\n");
14833 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
14834 prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
14835 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
14839 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
14840 return check_struct_ops_btf_id(env);
14842 if (prog->type != BPF_PROG_TYPE_TRACING &&
14843 prog->type != BPF_PROG_TYPE_LSM &&
14844 prog->type != BPF_PROG_TYPE_EXT)
14847 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
14851 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
14852 /* to make freplace equivalent to their targets, they need to
14853 * inherit env->ops and expected_attach_type for the rest of the
14856 env->ops = bpf_verifier_ops[tgt_prog->type];
14857 prog->expected_attach_type = tgt_prog->expected_attach_type;
14860 /* store info about the attachment target that will be used later */
14861 prog->aux->attach_func_proto = tgt_info.tgt_type;
14862 prog->aux->attach_func_name = tgt_info.tgt_name;
14865 prog->aux->saved_dst_prog_type = tgt_prog->type;
14866 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
14869 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
14870 prog->aux->attach_btf_trace = true;
14872 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
14873 if (!bpf_iter_prog_supported(prog))
14878 if (prog->type == BPF_PROG_TYPE_LSM) {
14879 ret = bpf_lsm_verify_prog(&env->log, prog);
14882 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
14883 btf_id_set_contains(&btf_id_deny, btf_id)) {
14887 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
14888 tr = bpf_trampoline_get(key, &tgt_info);
14892 prog->aux->dst_trampoline = tr;
14896 struct btf *bpf_get_btf_vmlinux(void)
14898 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
14899 mutex_lock(&bpf_verifier_lock);
14901 btf_vmlinux = btf_parse_vmlinux();
14902 mutex_unlock(&bpf_verifier_lock);
14904 return btf_vmlinux;
14907 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
14909 u64 start_time = ktime_get_ns();
14910 struct bpf_verifier_env *env;
14911 struct bpf_verifier_log *log;
14912 int i, len, ret = -EINVAL;
14915 /* no program is valid */
14916 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
14919 /* 'struct bpf_verifier_env' can be global, but since it's not small,
14920 * allocate/free it every time bpf_check() is called
14922 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
14927 len = (*prog)->len;
14928 env->insn_aux_data =
14929 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
14931 if (!env->insn_aux_data)
14933 for (i = 0; i < len; i++)
14934 env->insn_aux_data[i].orig_idx = i;
14936 env->ops = bpf_verifier_ops[env->prog->type];
14937 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
14938 is_priv = bpf_capable();
14940 bpf_get_btf_vmlinux();
14942 /* grab the mutex to protect few globals used by verifier */
14944 mutex_lock(&bpf_verifier_lock);
14946 if (attr->log_level || attr->log_buf || attr->log_size) {
14947 /* user requested verbose verifier output
14948 * and supplied buffer to store the verification trace
14950 log->level = attr->log_level;
14951 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
14952 log->len_total = attr->log_size;
14954 /* log attributes have to be sane */
14955 if (!bpf_verifier_log_attr_valid(log)) {
14961 mark_verifier_state_clean(env);
14963 if (IS_ERR(btf_vmlinux)) {
14964 /* Either gcc or pahole or kernel are broken. */
14965 verbose(env, "in-kernel BTF is malformed\n");
14966 ret = PTR_ERR(btf_vmlinux);
14967 goto skip_full_check;
14970 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
14971 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
14972 env->strict_alignment = true;
14973 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
14974 env->strict_alignment = false;
14976 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
14977 env->allow_uninit_stack = bpf_allow_uninit_stack();
14978 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
14979 env->bypass_spec_v1 = bpf_bypass_spec_v1();
14980 env->bypass_spec_v4 = bpf_bypass_spec_v4();
14981 env->bpf_capable = bpf_capable();
14984 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
14986 env->explored_states = kvcalloc(state_htab_size(env),
14987 sizeof(struct bpf_verifier_state_list *),
14990 if (!env->explored_states)
14991 goto skip_full_check;
14993 ret = add_subprog_and_kfunc(env);
14995 goto skip_full_check;
14997 ret = check_subprogs(env);
14999 goto skip_full_check;
15001 ret = check_btf_info(env, attr, uattr);
15003 goto skip_full_check;
15005 ret = check_attach_btf_id(env);
15007 goto skip_full_check;
15009 ret = resolve_pseudo_ldimm64(env);
15011 goto skip_full_check;
15013 if (bpf_prog_is_dev_bound(env->prog->aux)) {
15014 ret = bpf_prog_offload_verifier_prep(env->prog);
15016 goto skip_full_check;
15019 ret = check_cfg(env);
15021 goto skip_full_check;
15023 ret = do_check_subprogs(env);
15024 ret = ret ?: do_check_main(env);
15026 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15027 ret = bpf_prog_offload_finalize(env);
15030 kvfree(env->explored_states);
15033 ret = check_max_stack_depth(env);
15035 /* instruction rewrites happen after this point */
15038 opt_hard_wire_dead_code_branches(env);
15040 ret = opt_remove_dead_code(env);
15042 ret = opt_remove_nops(env);
15045 sanitize_dead_code(env);
15049 /* program is valid, convert *(u32*)(ctx + off) accesses */
15050 ret = convert_ctx_accesses(env);
15053 ret = do_misc_fixups(env);
15055 /* do 32-bit optimization after insn patching has done so those patched
15056 * insns could be handled correctly.
15058 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15059 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15060 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15065 ret = fixup_call_args(env);
15067 env->verification_time = ktime_get_ns() - start_time;
15068 print_verification_stats(env);
15069 env->prog->aux->verified_insns = env->insn_processed;
15071 if (log->level && bpf_verifier_log_full(log))
15073 if (log->level && !log->ubuf) {
15075 goto err_release_maps;
15079 goto err_release_maps;
15081 if (env->used_map_cnt) {
15082 /* if program passed verifier, update used_maps in bpf_prog_info */
15083 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15084 sizeof(env->used_maps[0]),
15087 if (!env->prog->aux->used_maps) {
15089 goto err_release_maps;
15092 memcpy(env->prog->aux->used_maps, env->used_maps,
15093 sizeof(env->used_maps[0]) * env->used_map_cnt);
15094 env->prog->aux->used_map_cnt = env->used_map_cnt;
15096 if (env->used_btf_cnt) {
15097 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15098 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15099 sizeof(env->used_btfs[0]),
15101 if (!env->prog->aux->used_btfs) {
15103 goto err_release_maps;
15106 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15107 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15108 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15110 if (env->used_map_cnt || env->used_btf_cnt) {
15111 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15112 * bpf_ld_imm64 instructions
15114 convert_pseudo_ld_imm64(env);
15117 adjust_btf_func(env);
15120 if (!env->prog->aux->used_maps)
15121 /* if we didn't copy map pointers into bpf_prog_info, release
15122 * them now. Otherwise free_used_maps() will release them.
15125 if (!env->prog->aux->used_btfs)
15128 /* extension progs temporarily inherit the attach_type of their targets
15129 for verification purposes, so set it back to zero before returning
15131 if (env->prog->type == BPF_PROG_TYPE_EXT)
15132 env->prog->expected_attach_type = 0;
15137 mutex_unlock(&bpf_verifier_lock);
15138 vfree(env->insn_aux_data);