1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3 * Copyright (c) 2016 Facebook
4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32 [_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
41 /* bpf_check() is a static code analyzer that walks eBPF program
42 * instruction by instruction and updates register/stack state.
43 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
45 * The first pass is depth-first-search to check that the program is a DAG.
46 * It rejects the following programs:
47 * - larger than BPF_MAXINSNS insns
48 * - if loop is present (detected via back-edge)
49 * - unreachable insns exist (shouldn't be a forest. program = one function)
50 * - out of bounds or malformed jumps
51 * The second pass is all possible path descent from the 1st insn.
52 * Since it's analyzing all paths through the program, the length of the
53 * analysis is limited to 64k insn, which may be hit even if total number of
54 * insn is less then 4K, but there are too many branches that change stack/regs.
55 * Number of 'branches to be analyzed' is limited to 1k
57 * On entry to each instruction, each register has a type, and the instruction
58 * changes the types of the registers depending on instruction semantics.
59 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
62 * All registers are 64-bit.
63 * R0 - return register
64 * R1-R5 argument passing registers
65 * R6-R9 callee saved registers
66 * R10 - frame pointer read-only
68 * At the start of BPF program the register R1 contains a pointer to bpf_context
69 * and has type PTR_TO_CTX.
71 * Verifier tracks arithmetic operations on pointers in case:
72 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74 * 1st insn copies R10 (which has FRAME_PTR) type into R1
75 * and 2nd arithmetic instruction is pattern matched to recognize
76 * that it wants to construct a pointer to some element within stack.
77 * So after 2nd insn, the register R1 has type PTR_TO_STACK
78 * (and -20 constant is saved for further stack bounds checking).
79 * Meaning that this reg is a pointer to stack plus known immediate constant.
81 * Most of the time the registers have SCALAR_VALUE type, which
82 * means the register has some value, but it's not a valid pointer.
83 * (like pointer plus pointer becomes SCALAR_VALUE type)
85 * When verifier sees load or store instructions the type of base register
86 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87 * four pointer types recognized by check_mem_access() function.
89 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90 * and the range of [ptr, ptr + map's value_size) is accessible.
92 * registers used to pass values to function calls are checked against
93 * function argument constraints.
95 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96 * It means that the register type passed to this function must be
97 * PTR_TO_STACK and it will be used inside the function as
98 * 'pointer to map element key'
100 * For example the argument constraints for bpf_map_lookup_elem():
101 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102 * .arg1_type = ARG_CONST_MAP_PTR,
103 * .arg2_type = ARG_PTR_TO_MAP_KEY,
105 * ret_type says that this function returns 'pointer to map elem value or null'
106 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107 * 2nd argument should be a pointer to stack, which will be used inside
108 * the helper function as a pointer to map element key.
110 * On the kernel side the helper function looks like:
111 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
113 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114 * void *key = (void *) (unsigned long) r2;
117 * here kernel can access 'key' and 'map' pointers safely, knowing that
118 * [key, key + map->key_size) bytes are valid and were initialized on
119 * the stack of eBPF program.
122 * Corresponding eBPF program may look like:
123 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
124 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
126 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127 * here verifier looks at prototype of map_lookup_elem() and sees:
128 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
131 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133 * and were initialized prior to this call.
134 * If it's ok, then verifier allows this BPF_CALL insn and looks at
135 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137 * returns either pointer to map value or NULL.
139 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140 * insn, the register holding that pointer in the true branch changes state to
141 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142 * branch. See check_cond_jmp_op().
144 * After the call R0 is set to return type of the function and registers R1-R5
145 * are set to NOT_INIT to indicate that they are no longer readable.
147 * The following reference types represent a potential reference to a kernel
148 * resource which, after first being allocated, must be checked and freed by
150 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
152 * When the verifier sees a helper call return a reference type, it allocates a
153 * pointer id for the reference and stores it in the current function state.
154 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156 * passes through a NULL-check conditional. For the branch wherein the state is
157 * changed to CONST_IMM, the verifier releases the reference.
159 * For each helper function that allocates a reference, such as
160 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161 * bpf_sk_release(). When a reference type passes into the release function,
162 * the verifier also releases the reference. If any unchecked or unreleased
163 * reference remains at the end of the program, the verifier rejects it.
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168 /* verifer state is 'st'
169 * before processing instruction 'insn_idx'
170 * and after processing instruction 'prev_insn_idx'
172 struct bpf_verifier_state st;
175 struct bpf_verifier_stack_elem *next;
176 /* length of verifier log at the time this state was pushed on stack */
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
181 #define BPF_COMPLEXITY_LIMIT_STATES 64
183 #define BPF_MAP_KEY_POISON (1ULL << 63)
184 #define BPF_MAP_KEY_SEEN (1ULL << 62)
186 #define BPF_MAP_PTR_UNPRIV 1UL
187 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
188 POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
196 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
201 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205 const struct bpf_map *map, bool unpriv)
207 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208 unpriv |= bpf_map_ptr_unpriv(aux);
209 aux->map_ptr_state = (unsigned long)map |
210 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
215 return aux->map_key_state & BPF_MAP_KEY_POISON;
218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
220 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
225 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
230 bool poisoned = bpf_map_key_poisoned(aux);
232 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
236 static bool bpf_pseudo_call(const struct bpf_insn *insn)
238 return insn->code == (BPF_JMP | BPF_CALL) &&
239 insn->src_reg == BPF_PSEUDO_CALL;
242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
244 return insn->code == (BPF_JMP | BPF_CALL) &&
245 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
248 struct bpf_call_arg_meta {
249 struct bpf_map *map_ptr;
265 struct bpf_map_value_off_desc *kptr_off_desc;
266 u8 uninit_dynptr_regno;
269 struct btf *btf_vmlinux;
271 static DEFINE_MUTEX(bpf_verifier_lock);
273 static const struct bpf_line_info *
274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
276 const struct bpf_line_info *linfo;
277 const struct bpf_prog *prog;
281 nr_linfo = prog->aux->nr_linfo;
283 if (!nr_linfo || insn_off >= prog->len)
286 linfo = prog->aux->linfo;
287 for (i = 1; i < nr_linfo; i++)
288 if (insn_off < linfo[i].insn_off)
291 return &linfo[i - 1];
294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
299 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
301 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302 "verifier log line truncated - local buffer too short\n");
304 if (log->level == BPF_LOG_KERNEL) {
305 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
307 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
311 n = min(log->len_total - log->len_used - 1, n);
313 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
323 if (!bpf_verifier_log_needed(log))
326 log->len_used = new_pos;
327 if (put_user(zero, log->ubuf + new_pos))
331 /* log_level controls verbosity level of eBPF verifier.
332 * bpf_verifier_log_write() is used to dump the verification trace to the log,
333 * so the user can figure out what's wrong with the program
335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336 const char *fmt, ...)
340 if (!bpf_verifier_log_needed(&env->log))
344 bpf_verifier_vlog(&env->log, fmt, args);
347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
351 struct bpf_verifier_env *env = private_data;
354 if (!bpf_verifier_log_needed(&env->log))
358 bpf_verifier_vlog(&env->log, fmt, args);
362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363 const char *fmt, ...)
367 if (!bpf_verifier_log_needed(log))
371 bpf_verifier_vlog(log, fmt, args);
374 EXPORT_SYMBOL_GPL(bpf_log);
376 static const char *ltrim(const char *s)
384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
386 const char *prefix_fmt, ...)
388 const struct bpf_line_info *linfo;
390 if (!bpf_verifier_log_needed(&env->log))
393 linfo = find_linfo(env, insn_off);
394 if (!linfo || linfo == env->prev_linfo)
400 va_start(args, prefix_fmt);
401 bpf_verifier_vlog(&env->log, prefix_fmt, args);
406 ltrim(btf_name_by_offset(env->prog->aux->btf,
409 env->prev_linfo = linfo;
412 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413 struct bpf_reg_state *reg,
414 struct tnum *range, const char *ctx,
415 const char *reg_name)
419 verbose(env, "At %s the register %s ", ctx, reg_name);
420 if (!tnum_is_unknown(reg->var_off)) {
421 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422 verbose(env, "has value %s", tn_buf);
424 verbose(env, "has unknown scalar value");
426 tnum_strn(tn_buf, sizeof(tn_buf), *range);
427 verbose(env, " should have been in %s\n", tn_buf);
430 static bool type_is_pkt_pointer(enum bpf_reg_type type)
432 type = base_type(type);
433 return type == PTR_TO_PACKET ||
434 type == PTR_TO_PACKET_META;
437 static bool type_is_sk_pointer(enum bpf_reg_type type)
439 return type == PTR_TO_SOCKET ||
440 type == PTR_TO_SOCK_COMMON ||
441 type == PTR_TO_TCP_SOCK ||
442 type == PTR_TO_XDP_SOCK;
445 static bool reg_type_not_null(enum bpf_reg_type type)
447 return type == PTR_TO_SOCKET ||
448 type == PTR_TO_TCP_SOCK ||
449 type == PTR_TO_MAP_VALUE ||
450 type == PTR_TO_MAP_KEY ||
451 type == PTR_TO_SOCK_COMMON;
454 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
456 return reg->type == PTR_TO_MAP_VALUE &&
457 map_value_has_spin_lock(reg->map_ptr);
460 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
462 type = base_type(type);
463 return type == PTR_TO_SOCKET || type == PTR_TO_TCP_SOCK ||
464 type == PTR_TO_MEM || type == PTR_TO_BTF_ID;
467 static bool type_is_rdonly_mem(u32 type)
469 return type & MEM_RDONLY;
472 static bool type_may_be_null(u32 type)
474 return type & PTR_MAYBE_NULL;
477 static bool is_acquire_function(enum bpf_func_id func_id,
478 const struct bpf_map *map)
480 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
482 if (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_ringbuf_reserve ||
486 func_id == BPF_FUNC_kptr_xchg)
489 if (func_id == BPF_FUNC_map_lookup_elem &&
490 (map_type == BPF_MAP_TYPE_SOCKMAP ||
491 map_type == BPF_MAP_TYPE_SOCKHASH))
497 static bool is_ptr_cast_function(enum bpf_func_id func_id)
499 return func_id == BPF_FUNC_tcp_sock ||
500 func_id == BPF_FUNC_sk_fullsock ||
501 func_id == BPF_FUNC_skc_to_tcp_sock ||
502 func_id == BPF_FUNC_skc_to_tcp6_sock ||
503 func_id == BPF_FUNC_skc_to_udp6_sock ||
504 func_id == BPF_FUNC_skc_to_mptcp_sock ||
505 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
506 func_id == BPF_FUNC_skc_to_tcp_request_sock;
509 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
511 return func_id == BPF_FUNC_dynptr_data;
514 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
515 const struct bpf_map *map)
517 int ref_obj_uses = 0;
519 if (is_ptr_cast_function(func_id))
521 if (is_acquire_function(func_id, map))
523 if (is_dynptr_ref_function(func_id))
526 return ref_obj_uses > 1;
529 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
531 return BPF_CLASS(insn->code) == BPF_STX &&
532 BPF_MODE(insn->code) == BPF_ATOMIC &&
533 insn->imm == BPF_CMPXCHG;
536 /* string representation of 'enum bpf_reg_type'
538 * Note that reg_type_str() can not appear more than once in a single verbose()
541 static const char *reg_type_str(struct bpf_verifier_env *env,
542 enum bpf_reg_type type)
544 char postfix[16] = {0}, prefix[32] = {0};
545 static const char * const str[] = {
547 [SCALAR_VALUE] = "scalar",
548 [PTR_TO_CTX] = "ctx",
549 [CONST_PTR_TO_MAP] = "map_ptr",
550 [PTR_TO_MAP_VALUE] = "map_value",
551 [PTR_TO_STACK] = "fp",
552 [PTR_TO_PACKET] = "pkt",
553 [PTR_TO_PACKET_META] = "pkt_meta",
554 [PTR_TO_PACKET_END] = "pkt_end",
555 [PTR_TO_FLOW_KEYS] = "flow_keys",
556 [PTR_TO_SOCKET] = "sock",
557 [PTR_TO_SOCK_COMMON] = "sock_common",
558 [PTR_TO_TCP_SOCK] = "tcp_sock",
559 [PTR_TO_TP_BUFFER] = "tp_buffer",
560 [PTR_TO_XDP_SOCK] = "xdp_sock",
561 [PTR_TO_BTF_ID] = "ptr_",
562 [PTR_TO_MEM] = "mem",
563 [PTR_TO_BUF] = "buf",
564 [PTR_TO_FUNC] = "func",
565 [PTR_TO_MAP_KEY] = "map_key",
566 [PTR_TO_DYNPTR] = "dynptr_ptr",
569 if (type & PTR_MAYBE_NULL) {
570 if (base_type(type) == PTR_TO_BTF_ID)
571 strncpy(postfix, "or_null_", 16);
573 strncpy(postfix, "_or_null", 16);
576 if (type & MEM_RDONLY)
577 strncpy(prefix, "rdonly_", 32);
578 if (type & MEM_ALLOC)
579 strncpy(prefix, "alloc_", 32);
581 strncpy(prefix, "user_", 32);
582 if (type & MEM_PERCPU)
583 strncpy(prefix, "percpu_", 32);
584 if (type & PTR_UNTRUSTED)
585 strncpy(prefix, "untrusted_", 32);
587 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
588 prefix, str[base_type(type)], postfix);
589 return env->type_str_buf;
592 static char slot_type_char[] = {
593 [STACK_INVALID] = '?',
597 [STACK_DYNPTR] = 'd',
600 static void print_liveness(struct bpf_verifier_env *env,
601 enum bpf_reg_liveness live)
603 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
605 if (live & REG_LIVE_READ)
607 if (live & REG_LIVE_WRITTEN)
609 if (live & REG_LIVE_DONE)
613 static int get_spi(s32 off)
615 return (-off - 1) / BPF_REG_SIZE;
618 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
620 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
622 /* We need to check that slots between [spi - nr_slots + 1, spi] are
623 * within [0, allocated_stack).
625 * Please note that the spi grows downwards. For example, a dynptr
626 * takes the size of two stack slots; the first slot will be at
627 * spi and the second slot will be at spi - 1.
629 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
632 static struct bpf_func_state *func(struct bpf_verifier_env *env,
633 const struct bpf_reg_state *reg)
635 struct bpf_verifier_state *cur = env->cur_state;
637 return cur->frame[reg->frameno];
640 static const char *kernel_type_name(const struct btf* btf, u32 id)
642 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
645 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
647 env->scratched_regs |= 1U << regno;
650 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
652 env->scratched_stack_slots |= 1ULL << spi;
655 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
657 return (env->scratched_regs >> regno) & 1;
660 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
662 return (env->scratched_stack_slots >> regno) & 1;
665 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
667 return env->scratched_regs || env->scratched_stack_slots;
670 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
672 env->scratched_regs = 0U;
673 env->scratched_stack_slots = 0ULL;
676 /* Used for printing the entire verifier state. */
677 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
679 env->scratched_regs = ~0U;
680 env->scratched_stack_slots = ~0ULL;
683 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
685 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
686 case DYNPTR_TYPE_LOCAL:
687 return BPF_DYNPTR_TYPE_LOCAL;
688 case DYNPTR_TYPE_RINGBUF:
689 return BPF_DYNPTR_TYPE_RINGBUF;
691 return BPF_DYNPTR_TYPE_INVALID;
695 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
697 return type == BPF_DYNPTR_TYPE_RINGBUF;
700 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
701 enum bpf_arg_type arg_type, int insn_idx)
703 struct bpf_func_state *state = func(env, reg);
704 enum bpf_dynptr_type type;
707 spi = get_spi(reg->off);
709 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
712 for (i = 0; i < BPF_REG_SIZE; i++) {
713 state->stack[spi].slot_type[i] = STACK_DYNPTR;
714 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
717 type = arg_to_dynptr_type(arg_type);
718 if (type == BPF_DYNPTR_TYPE_INVALID)
721 state->stack[spi].spilled_ptr.dynptr.first_slot = true;
722 state->stack[spi].spilled_ptr.dynptr.type = type;
723 state->stack[spi - 1].spilled_ptr.dynptr.type = type;
725 if (dynptr_type_refcounted(type)) {
726 /* The id is used to track proper releasing */
727 id = acquire_reference_state(env, insn_idx);
731 state->stack[spi].spilled_ptr.id = id;
732 state->stack[spi - 1].spilled_ptr.id = id;
738 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
740 struct bpf_func_state *state = func(env, reg);
743 spi = get_spi(reg->off);
745 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
748 for (i = 0; i < BPF_REG_SIZE; i++) {
749 state->stack[spi].slot_type[i] = STACK_INVALID;
750 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
753 /* Invalidate any slices associated with this dynptr */
754 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
755 release_reference(env, state->stack[spi].spilled_ptr.id);
756 state->stack[spi].spilled_ptr.id = 0;
757 state->stack[spi - 1].spilled_ptr.id = 0;
760 state->stack[spi].spilled_ptr.dynptr.first_slot = false;
761 state->stack[spi].spilled_ptr.dynptr.type = 0;
762 state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
767 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
769 struct bpf_func_state *state = func(env, reg);
770 int spi = get_spi(reg->off);
773 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
776 for (i = 0; i < BPF_REG_SIZE; i++) {
777 if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
778 state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
785 bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
786 struct bpf_reg_state *reg)
788 struct bpf_func_state *state = func(env, reg);
789 int spi = get_spi(reg->off);
792 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
793 !state->stack[spi].spilled_ptr.dynptr.first_slot)
796 for (i = 0; i < BPF_REG_SIZE; i++) {
797 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
798 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
805 bool is_dynptr_type_expected(struct bpf_verifier_env *env,
806 struct bpf_reg_state *reg,
807 enum bpf_arg_type arg_type)
809 struct bpf_func_state *state = func(env, reg);
810 enum bpf_dynptr_type dynptr_type;
811 int spi = get_spi(reg->off);
813 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
814 if (arg_type == ARG_PTR_TO_DYNPTR)
817 dynptr_type = arg_to_dynptr_type(arg_type);
819 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
822 /* The reg state of a pointer or a bounded scalar was saved when
823 * it was spilled to the stack.
825 static bool is_spilled_reg(const struct bpf_stack_state *stack)
827 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
830 static void scrub_spilled_slot(u8 *stype)
832 if (*stype != STACK_INVALID)
836 static void print_verifier_state(struct bpf_verifier_env *env,
837 const struct bpf_func_state *state,
840 const struct bpf_reg_state *reg;
845 verbose(env, " frame%d:", state->frameno);
846 for (i = 0; i < MAX_BPF_REG; i++) {
847 reg = &state->regs[i];
851 if (!print_all && !reg_scratched(env, i))
853 verbose(env, " R%d", i);
854 print_liveness(env, reg->live);
856 if (t == SCALAR_VALUE && reg->precise)
858 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
859 tnum_is_const(reg->var_off)) {
860 /* reg->off should be 0 for SCALAR_VALUE */
861 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
862 verbose(env, "%lld", reg->var_off.value + reg->off);
864 const char *sep = "";
866 verbose(env, "%s", reg_type_str(env, t));
867 if (base_type(t) == PTR_TO_BTF_ID)
868 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
871 * _a stands for append, was shortened to avoid multiline statements below.
872 * This macro is used to output a comma separated list of attributes.
874 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
877 verbose_a("id=%d", reg->id);
878 if (reg_type_may_be_refcounted_or_null(t) && reg->ref_obj_id)
879 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
880 if (t != SCALAR_VALUE)
881 verbose_a("off=%d", reg->off);
882 if (type_is_pkt_pointer(t))
883 verbose_a("r=%d", reg->range);
884 else if (base_type(t) == CONST_PTR_TO_MAP ||
885 base_type(t) == PTR_TO_MAP_KEY ||
886 base_type(t) == PTR_TO_MAP_VALUE)
887 verbose_a("ks=%d,vs=%d",
888 reg->map_ptr->key_size,
889 reg->map_ptr->value_size);
890 if (tnum_is_const(reg->var_off)) {
891 /* Typically an immediate SCALAR_VALUE, but
892 * could be a pointer whose offset is too big
895 verbose_a("imm=%llx", reg->var_off.value);
897 if (reg->smin_value != reg->umin_value &&
898 reg->smin_value != S64_MIN)
899 verbose_a("smin=%lld", (long long)reg->smin_value);
900 if (reg->smax_value != reg->umax_value &&
901 reg->smax_value != S64_MAX)
902 verbose_a("smax=%lld", (long long)reg->smax_value);
903 if (reg->umin_value != 0)
904 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
905 if (reg->umax_value != U64_MAX)
906 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
907 if (!tnum_is_unknown(reg->var_off)) {
910 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
911 verbose_a("var_off=%s", tn_buf);
913 if (reg->s32_min_value != reg->smin_value &&
914 reg->s32_min_value != S32_MIN)
915 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
916 if (reg->s32_max_value != reg->smax_value &&
917 reg->s32_max_value != S32_MAX)
918 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
919 if (reg->u32_min_value != reg->umin_value &&
920 reg->u32_min_value != U32_MIN)
921 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
922 if (reg->u32_max_value != reg->umax_value &&
923 reg->u32_max_value != U32_MAX)
924 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
931 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
932 char types_buf[BPF_REG_SIZE + 1];
936 for (j = 0; j < BPF_REG_SIZE; j++) {
937 if (state->stack[i].slot_type[j] != STACK_INVALID)
939 types_buf[j] = slot_type_char[
940 state->stack[i].slot_type[j]];
942 types_buf[BPF_REG_SIZE] = 0;
945 if (!print_all && !stack_slot_scratched(env, i))
947 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
948 print_liveness(env, state->stack[i].spilled_ptr.live);
949 if (is_spilled_reg(&state->stack[i])) {
950 reg = &state->stack[i].spilled_ptr;
952 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
953 if (t == SCALAR_VALUE && reg->precise)
955 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
956 verbose(env, "%lld", reg->var_off.value + reg->off);
958 verbose(env, "=%s", types_buf);
961 if (state->acquired_refs && state->refs[0].id) {
962 verbose(env, " refs=%d", state->refs[0].id);
963 for (i = 1; i < state->acquired_refs; i++)
964 if (state->refs[i].id)
965 verbose(env, ",%d", state->refs[i].id);
967 if (state->in_callback_fn)
969 if (state->in_async_callback_fn)
970 verbose(env, " async_cb");
972 mark_verifier_state_clean(env);
975 static inline u32 vlog_alignment(u32 pos)
977 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
978 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
981 static void print_insn_state(struct bpf_verifier_env *env,
982 const struct bpf_func_state *state)
984 if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
985 /* remove new line character */
986 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
987 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
989 verbose(env, "%d:", env->insn_idx);
991 print_verifier_state(env, state, false);
994 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
995 * small to hold src. This is different from krealloc since we don't want to preserve
996 * the contents of dst.
998 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1001 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1007 if (ZERO_OR_NULL_PTR(src))
1010 if (unlikely(check_mul_overflow(n, size, &bytes)))
1013 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1014 dst = krealloc(orig, alloc_bytes, flags);
1020 memcpy(dst, src, bytes);
1022 return dst ? dst : ZERO_SIZE_PTR;
1025 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1026 * small to hold new_n items. new items are zeroed out if the array grows.
1028 * Contrary to krealloc_array, does not free arr if new_n is zero.
1030 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1035 if (!new_n || old_n == new_n)
1038 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1039 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1047 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1050 return arr ? arr : ZERO_SIZE_PTR;
1053 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1055 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1056 sizeof(struct bpf_reference_state), GFP_KERNEL);
1060 dst->acquired_refs = src->acquired_refs;
1064 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1066 size_t n = src->allocated_stack / BPF_REG_SIZE;
1068 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1073 dst->allocated_stack = src->allocated_stack;
1077 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1079 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1080 sizeof(struct bpf_reference_state));
1084 state->acquired_refs = n;
1088 static int grow_stack_state(struct bpf_func_state *state, int size)
1090 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1095 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1099 state->allocated_stack = size;
1103 /* Acquire a pointer id from the env and update the state->refs to include
1104 * this new pointer reference.
1105 * On success, returns a valid pointer id to associate with the register
1106 * On failure, returns a negative errno.
1108 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1110 struct bpf_func_state *state = cur_func(env);
1111 int new_ofs = state->acquired_refs;
1114 err = resize_reference_state(state, state->acquired_refs + 1);
1118 state->refs[new_ofs].id = id;
1119 state->refs[new_ofs].insn_idx = insn_idx;
1120 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1125 /* release function corresponding to acquire_reference_state(). Idempotent. */
1126 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1130 last_idx = state->acquired_refs - 1;
1131 for (i = 0; i < state->acquired_refs; i++) {
1132 if (state->refs[i].id == ptr_id) {
1133 /* Cannot release caller references in callbacks */
1134 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1136 if (last_idx && i != last_idx)
1137 memcpy(&state->refs[i], &state->refs[last_idx],
1138 sizeof(*state->refs));
1139 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1140 state->acquired_refs--;
1147 static void free_func_state(struct bpf_func_state *state)
1152 kfree(state->stack);
1156 static void clear_jmp_history(struct bpf_verifier_state *state)
1158 kfree(state->jmp_history);
1159 state->jmp_history = NULL;
1160 state->jmp_history_cnt = 0;
1163 static void free_verifier_state(struct bpf_verifier_state *state,
1168 for (i = 0; i <= state->curframe; i++) {
1169 free_func_state(state->frame[i]);
1170 state->frame[i] = NULL;
1172 clear_jmp_history(state);
1177 /* copy verifier state from src to dst growing dst stack space
1178 * when necessary to accommodate larger src stack
1180 static int copy_func_state(struct bpf_func_state *dst,
1181 const struct bpf_func_state *src)
1185 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1186 err = copy_reference_state(dst, src);
1189 return copy_stack_state(dst, src);
1192 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1193 const struct bpf_verifier_state *src)
1195 struct bpf_func_state *dst;
1198 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1199 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1201 if (!dst_state->jmp_history)
1203 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1205 /* if dst has more stack frames then src frame, free them */
1206 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1207 free_func_state(dst_state->frame[i]);
1208 dst_state->frame[i] = NULL;
1210 dst_state->speculative = src->speculative;
1211 dst_state->curframe = src->curframe;
1212 dst_state->active_spin_lock = src->active_spin_lock;
1213 dst_state->branches = src->branches;
1214 dst_state->parent = src->parent;
1215 dst_state->first_insn_idx = src->first_insn_idx;
1216 dst_state->last_insn_idx = src->last_insn_idx;
1217 for (i = 0; i <= src->curframe; i++) {
1218 dst = dst_state->frame[i];
1220 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1223 dst_state->frame[i] = dst;
1225 err = copy_func_state(dst, src->frame[i]);
1232 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1235 u32 br = --st->branches;
1237 /* WARN_ON(br > 1) technically makes sense here,
1238 * but see comment in push_stack(), hence:
1240 WARN_ONCE((int)br < 0,
1241 "BUG update_branch_counts:branches_to_explore=%d\n",
1249 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1250 int *insn_idx, bool pop_log)
1252 struct bpf_verifier_state *cur = env->cur_state;
1253 struct bpf_verifier_stack_elem *elem, *head = env->head;
1256 if (env->head == NULL)
1260 err = copy_verifier_state(cur, &head->st);
1265 bpf_vlog_reset(&env->log, head->log_pos);
1267 *insn_idx = head->insn_idx;
1269 *prev_insn_idx = head->prev_insn_idx;
1271 free_verifier_state(&head->st, false);
1278 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1279 int insn_idx, int prev_insn_idx,
1282 struct bpf_verifier_state *cur = env->cur_state;
1283 struct bpf_verifier_stack_elem *elem;
1286 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1290 elem->insn_idx = insn_idx;
1291 elem->prev_insn_idx = prev_insn_idx;
1292 elem->next = env->head;
1293 elem->log_pos = env->log.len_used;
1296 err = copy_verifier_state(&elem->st, cur);
1299 elem->st.speculative |= speculative;
1300 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1301 verbose(env, "The sequence of %d jumps is too complex.\n",
1305 if (elem->st.parent) {
1306 ++elem->st.parent->branches;
1307 /* WARN_ON(branches > 2) technically makes sense here,
1309 * 1. speculative states will bump 'branches' for non-branch
1311 * 2. is_state_visited() heuristics may decide not to create
1312 * a new state for a sequence of branches and all such current
1313 * and cloned states will be pointing to a single parent state
1314 * which might have large 'branches' count.
1319 free_verifier_state(env->cur_state, true);
1320 env->cur_state = NULL;
1321 /* pop all elements and return */
1322 while (!pop_stack(env, NULL, NULL, false));
1326 #define CALLER_SAVED_REGS 6
1327 static const int caller_saved[CALLER_SAVED_REGS] = {
1328 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1331 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1332 struct bpf_reg_state *reg);
1334 /* This helper doesn't clear reg->id */
1335 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1337 reg->var_off = tnum_const(imm);
1338 reg->smin_value = (s64)imm;
1339 reg->smax_value = (s64)imm;
1340 reg->umin_value = imm;
1341 reg->umax_value = imm;
1343 reg->s32_min_value = (s32)imm;
1344 reg->s32_max_value = (s32)imm;
1345 reg->u32_min_value = (u32)imm;
1346 reg->u32_max_value = (u32)imm;
1349 /* Mark the unknown part of a register (variable offset or scalar value) as
1350 * known to have the value @imm.
1352 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1354 /* Clear id, off, and union(map_ptr, range) */
1355 memset(((u8 *)reg) + sizeof(reg->type), 0,
1356 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1357 ___mark_reg_known(reg, imm);
1360 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1362 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1363 reg->s32_min_value = (s32)imm;
1364 reg->s32_max_value = (s32)imm;
1365 reg->u32_min_value = (u32)imm;
1366 reg->u32_max_value = (u32)imm;
1369 /* Mark the 'variable offset' part of a register as zero. This should be
1370 * used only on registers holding a pointer type.
1372 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1374 __mark_reg_known(reg, 0);
1377 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1379 __mark_reg_known(reg, 0);
1380 reg->type = SCALAR_VALUE;
1383 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1384 struct bpf_reg_state *regs, u32 regno)
1386 if (WARN_ON(regno >= MAX_BPF_REG)) {
1387 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1388 /* Something bad happened, let's kill all regs */
1389 for (regno = 0; regno < MAX_BPF_REG; regno++)
1390 __mark_reg_not_init(env, regs + regno);
1393 __mark_reg_known_zero(regs + regno);
1396 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1398 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1399 const struct bpf_map *map = reg->map_ptr;
1401 if (map->inner_map_meta) {
1402 reg->type = CONST_PTR_TO_MAP;
1403 reg->map_ptr = map->inner_map_meta;
1404 /* transfer reg's id which is unique for every map_lookup_elem
1405 * as UID of the inner map.
1407 if (map_value_has_timer(map->inner_map_meta))
1408 reg->map_uid = reg->id;
1409 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1410 reg->type = PTR_TO_XDP_SOCK;
1411 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1412 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1413 reg->type = PTR_TO_SOCKET;
1415 reg->type = PTR_TO_MAP_VALUE;
1420 reg->type &= ~PTR_MAYBE_NULL;
1423 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1425 return type_is_pkt_pointer(reg->type);
1428 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1430 return reg_is_pkt_pointer(reg) ||
1431 reg->type == PTR_TO_PACKET_END;
1434 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1435 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1436 enum bpf_reg_type which)
1438 /* The register can already have a range from prior markings.
1439 * This is fine as long as it hasn't been advanced from its
1442 return reg->type == which &&
1445 tnum_equals_const(reg->var_off, 0);
1448 /* Reset the min/max bounds of a register */
1449 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1451 reg->smin_value = S64_MIN;
1452 reg->smax_value = S64_MAX;
1453 reg->umin_value = 0;
1454 reg->umax_value = U64_MAX;
1456 reg->s32_min_value = S32_MIN;
1457 reg->s32_max_value = S32_MAX;
1458 reg->u32_min_value = 0;
1459 reg->u32_max_value = U32_MAX;
1462 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1464 reg->smin_value = S64_MIN;
1465 reg->smax_value = S64_MAX;
1466 reg->umin_value = 0;
1467 reg->umax_value = U64_MAX;
1470 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1472 reg->s32_min_value = S32_MIN;
1473 reg->s32_max_value = S32_MAX;
1474 reg->u32_min_value = 0;
1475 reg->u32_max_value = U32_MAX;
1478 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1480 struct tnum var32_off = tnum_subreg(reg->var_off);
1482 /* min signed is max(sign bit) | min(other bits) */
1483 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1484 var32_off.value | (var32_off.mask & S32_MIN));
1485 /* max signed is min(sign bit) | max(other bits) */
1486 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1487 var32_off.value | (var32_off.mask & S32_MAX));
1488 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1489 reg->u32_max_value = min(reg->u32_max_value,
1490 (u32)(var32_off.value | var32_off.mask));
1493 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1495 /* min signed is max(sign bit) | min(other bits) */
1496 reg->smin_value = max_t(s64, reg->smin_value,
1497 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1498 /* max signed is min(sign bit) | max(other bits) */
1499 reg->smax_value = min_t(s64, reg->smax_value,
1500 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1501 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1502 reg->umax_value = min(reg->umax_value,
1503 reg->var_off.value | reg->var_off.mask);
1506 static void __update_reg_bounds(struct bpf_reg_state *reg)
1508 __update_reg32_bounds(reg);
1509 __update_reg64_bounds(reg);
1512 /* Uses signed min/max values to inform unsigned, and vice-versa */
1513 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1515 /* Learn sign from signed bounds.
1516 * If we cannot cross the sign boundary, then signed and unsigned bounds
1517 * are the same, so combine. This works even in the negative case, e.g.
1518 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1520 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1521 reg->s32_min_value = reg->u32_min_value =
1522 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1523 reg->s32_max_value = reg->u32_max_value =
1524 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1527 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1528 * boundary, so we must be careful.
1530 if ((s32)reg->u32_max_value >= 0) {
1531 /* Positive. We can't learn anything from the smin, but smax
1532 * is positive, hence safe.
1534 reg->s32_min_value = reg->u32_min_value;
1535 reg->s32_max_value = reg->u32_max_value =
1536 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1537 } else if ((s32)reg->u32_min_value < 0) {
1538 /* Negative. We can't learn anything from the smax, but smin
1539 * is negative, hence safe.
1541 reg->s32_min_value = reg->u32_min_value =
1542 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1543 reg->s32_max_value = reg->u32_max_value;
1547 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1549 /* Learn sign from signed bounds.
1550 * If we cannot cross the sign boundary, then signed and unsigned bounds
1551 * are the same, so combine. This works even in the negative case, e.g.
1552 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1554 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1555 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1557 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1561 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1562 * boundary, so we must be careful.
1564 if ((s64)reg->umax_value >= 0) {
1565 /* Positive. We can't learn anything from the smin, but smax
1566 * is positive, hence safe.
1568 reg->smin_value = reg->umin_value;
1569 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1571 } else if ((s64)reg->umin_value < 0) {
1572 /* Negative. We can't learn anything from the smax, but smin
1573 * is negative, hence safe.
1575 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1577 reg->smax_value = reg->umax_value;
1581 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1583 __reg32_deduce_bounds(reg);
1584 __reg64_deduce_bounds(reg);
1587 /* Attempts to improve var_off based on unsigned min/max information */
1588 static void __reg_bound_offset(struct bpf_reg_state *reg)
1590 struct tnum var64_off = tnum_intersect(reg->var_off,
1591 tnum_range(reg->umin_value,
1593 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
1594 tnum_range(reg->u32_min_value,
1595 reg->u32_max_value));
1597 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1600 static void reg_bounds_sync(struct bpf_reg_state *reg)
1602 /* We might have learned new bounds from the var_off. */
1603 __update_reg_bounds(reg);
1604 /* We might have learned something about the sign bit. */
1605 __reg_deduce_bounds(reg);
1606 /* We might have learned some bits from the bounds. */
1607 __reg_bound_offset(reg);
1608 /* Intersecting with the old var_off might have improved our bounds
1609 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1610 * then new var_off is (0; 0x7f...fc) which improves our umax.
1612 __update_reg_bounds(reg);
1615 static bool __reg32_bound_s64(s32 a)
1617 return a >= 0 && a <= S32_MAX;
1620 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1622 reg->umin_value = reg->u32_min_value;
1623 reg->umax_value = reg->u32_max_value;
1625 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1626 * be positive otherwise set to worse case bounds and refine later
1629 if (__reg32_bound_s64(reg->s32_min_value) &&
1630 __reg32_bound_s64(reg->s32_max_value)) {
1631 reg->smin_value = reg->s32_min_value;
1632 reg->smax_value = reg->s32_max_value;
1634 reg->smin_value = 0;
1635 reg->smax_value = U32_MAX;
1639 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1641 /* special case when 64-bit register has upper 32-bit register
1642 * zeroed. Typically happens after zext or <<32, >>32 sequence
1643 * allowing us to use 32-bit bounds directly,
1645 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1646 __reg_assign_32_into_64(reg);
1648 /* Otherwise the best we can do is push lower 32bit known and
1649 * unknown bits into register (var_off set from jmp logic)
1650 * then learn as much as possible from the 64-bit tnum
1651 * known and unknown bits. The previous smin/smax bounds are
1652 * invalid here because of jmp32 compare so mark them unknown
1653 * so they do not impact tnum bounds calculation.
1655 __mark_reg64_unbounded(reg);
1657 reg_bounds_sync(reg);
1660 static bool __reg64_bound_s32(s64 a)
1662 return a >= S32_MIN && a <= S32_MAX;
1665 static bool __reg64_bound_u32(u64 a)
1667 return a >= U32_MIN && a <= U32_MAX;
1670 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1672 __mark_reg32_unbounded(reg);
1673 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1674 reg->s32_min_value = (s32)reg->smin_value;
1675 reg->s32_max_value = (s32)reg->smax_value;
1677 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1678 reg->u32_min_value = (u32)reg->umin_value;
1679 reg->u32_max_value = (u32)reg->umax_value;
1681 reg_bounds_sync(reg);
1684 /* Mark a register as having a completely unknown (scalar) value. */
1685 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1686 struct bpf_reg_state *reg)
1689 * Clear type, id, off, and union(map_ptr, range) and
1690 * padding between 'type' and union
1692 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1693 reg->type = SCALAR_VALUE;
1694 reg->var_off = tnum_unknown;
1696 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1697 __mark_reg_unbounded(reg);
1700 static void mark_reg_unknown(struct bpf_verifier_env *env,
1701 struct bpf_reg_state *regs, u32 regno)
1703 if (WARN_ON(regno >= MAX_BPF_REG)) {
1704 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1705 /* Something bad happened, let's kill all regs except FP */
1706 for (regno = 0; regno < BPF_REG_FP; regno++)
1707 __mark_reg_not_init(env, regs + regno);
1710 __mark_reg_unknown(env, regs + regno);
1713 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1714 struct bpf_reg_state *reg)
1716 __mark_reg_unknown(env, reg);
1717 reg->type = NOT_INIT;
1720 static void mark_reg_not_init(struct bpf_verifier_env *env,
1721 struct bpf_reg_state *regs, u32 regno)
1723 if (WARN_ON(regno >= MAX_BPF_REG)) {
1724 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1725 /* Something bad happened, let's kill all regs except FP */
1726 for (regno = 0; regno < BPF_REG_FP; regno++)
1727 __mark_reg_not_init(env, regs + regno);
1730 __mark_reg_not_init(env, regs + regno);
1733 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1734 struct bpf_reg_state *regs, u32 regno,
1735 enum bpf_reg_type reg_type,
1736 struct btf *btf, u32 btf_id,
1737 enum bpf_type_flag flag)
1739 if (reg_type == SCALAR_VALUE) {
1740 mark_reg_unknown(env, regs, regno);
1743 mark_reg_known_zero(env, regs, regno);
1744 regs[regno].type = PTR_TO_BTF_ID | flag;
1745 regs[regno].btf = btf;
1746 regs[regno].btf_id = btf_id;
1749 #define DEF_NOT_SUBREG (0)
1750 static void init_reg_state(struct bpf_verifier_env *env,
1751 struct bpf_func_state *state)
1753 struct bpf_reg_state *regs = state->regs;
1756 for (i = 0; i < MAX_BPF_REG; i++) {
1757 mark_reg_not_init(env, regs, i);
1758 regs[i].live = REG_LIVE_NONE;
1759 regs[i].parent = NULL;
1760 regs[i].subreg_def = DEF_NOT_SUBREG;
1764 regs[BPF_REG_FP].type = PTR_TO_STACK;
1765 mark_reg_known_zero(env, regs, BPF_REG_FP);
1766 regs[BPF_REG_FP].frameno = state->frameno;
1769 #define BPF_MAIN_FUNC (-1)
1770 static void init_func_state(struct bpf_verifier_env *env,
1771 struct bpf_func_state *state,
1772 int callsite, int frameno, int subprogno)
1774 state->callsite = callsite;
1775 state->frameno = frameno;
1776 state->subprogno = subprogno;
1777 state->callback_ret_range = tnum_range(0, 0);
1778 init_reg_state(env, state);
1779 mark_verifier_state_scratched(env);
1782 /* Similar to push_stack(), but for async callbacks */
1783 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1784 int insn_idx, int prev_insn_idx,
1787 struct bpf_verifier_stack_elem *elem;
1788 struct bpf_func_state *frame;
1790 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1794 elem->insn_idx = insn_idx;
1795 elem->prev_insn_idx = prev_insn_idx;
1796 elem->next = env->head;
1797 elem->log_pos = env->log.len_used;
1800 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1802 "The sequence of %d jumps is too complex for async cb.\n",
1806 /* Unlike push_stack() do not copy_verifier_state().
1807 * The caller state doesn't matter.
1808 * This is async callback. It starts in a fresh stack.
1809 * Initialize it similar to do_check_common().
1811 elem->st.branches = 1;
1812 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1815 init_func_state(env, frame,
1816 BPF_MAIN_FUNC /* callsite */,
1817 0 /* frameno within this callchain */,
1818 subprog /* subprog number within this prog */);
1819 elem->st.frame[0] = frame;
1822 free_verifier_state(env->cur_state, true);
1823 env->cur_state = NULL;
1824 /* pop all elements and return */
1825 while (!pop_stack(env, NULL, NULL, false));
1831 SRC_OP, /* register is used as source operand */
1832 DST_OP, /* register is used as destination operand */
1833 DST_OP_NO_MARK /* same as above, check only, don't mark */
1836 static int cmp_subprogs(const void *a, const void *b)
1838 return ((struct bpf_subprog_info *)a)->start -
1839 ((struct bpf_subprog_info *)b)->start;
1842 static int find_subprog(struct bpf_verifier_env *env, int off)
1844 struct bpf_subprog_info *p;
1846 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1847 sizeof(env->subprog_info[0]), cmp_subprogs);
1850 return p - env->subprog_info;
1854 static int add_subprog(struct bpf_verifier_env *env, int off)
1856 int insn_cnt = env->prog->len;
1859 if (off >= insn_cnt || off < 0) {
1860 verbose(env, "call to invalid destination\n");
1863 ret = find_subprog(env, off);
1866 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1867 verbose(env, "too many subprograms\n");
1870 /* determine subprog starts. The end is one before the next starts */
1871 env->subprog_info[env->subprog_cnt++].start = off;
1872 sort(env->subprog_info, env->subprog_cnt,
1873 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1874 return env->subprog_cnt - 1;
1877 #define MAX_KFUNC_DESCS 256
1878 #define MAX_KFUNC_BTFS 256
1880 struct bpf_kfunc_desc {
1881 struct btf_func_model func_model;
1887 struct bpf_kfunc_btf {
1889 struct module *module;
1893 struct bpf_kfunc_desc_tab {
1894 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1898 struct bpf_kfunc_btf_tab {
1899 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1903 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1905 const struct bpf_kfunc_desc *d0 = a;
1906 const struct bpf_kfunc_desc *d1 = b;
1908 /* func_id is not greater than BTF_MAX_TYPE */
1909 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1912 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1914 const struct bpf_kfunc_btf *d0 = a;
1915 const struct bpf_kfunc_btf *d1 = b;
1917 return d0->offset - d1->offset;
1920 static const struct bpf_kfunc_desc *
1921 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1923 struct bpf_kfunc_desc desc = {
1927 struct bpf_kfunc_desc_tab *tab;
1929 tab = prog->aux->kfunc_tab;
1930 return bsearch(&desc, tab->descs, tab->nr_descs,
1931 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1934 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1937 struct bpf_kfunc_btf kf_btf = { .offset = offset };
1938 struct bpf_kfunc_btf_tab *tab;
1939 struct bpf_kfunc_btf *b;
1944 tab = env->prog->aux->kfunc_btf_tab;
1945 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1946 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1948 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1949 verbose(env, "too many different module BTFs\n");
1950 return ERR_PTR(-E2BIG);
1953 if (bpfptr_is_null(env->fd_array)) {
1954 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1955 return ERR_PTR(-EPROTO);
1958 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1959 offset * sizeof(btf_fd),
1961 return ERR_PTR(-EFAULT);
1963 btf = btf_get_by_fd(btf_fd);
1965 verbose(env, "invalid module BTF fd specified\n");
1969 if (!btf_is_module(btf)) {
1970 verbose(env, "BTF fd for kfunc is not a module BTF\n");
1972 return ERR_PTR(-EINVAL);
1975 mod = btf_try_get_module(btf);
1978 return ERR_PTR(-ENXIO);
1981 b = &tab->descs[tab->nr_descs++];
1986 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1987 kfunc_btf_cmp_by_off, NULL);
1992 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1997 while (tab->nr_descs--) {
1998 module_put(tab->descs[tab->nr_descs].module);
1999 btf_put(tab->descs[tab->nr_descs].btf);
2004 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2008 /* In the future, this can be allowed to increase limit
2009 * of fd index into fd_array, interpreted as u16.
2011 verbose(env, "negative offset disallowed for kernel module function call\n");
2012 return ERR_PTR(-EINVAL);
2015 return __find_kfunc_desc_btf(env, offset);
2017 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2020 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2022 const struct btf_type *func, *func_proto;
2023 struct bpf_kfunc_btf_tab *btf_tab;
2024 struct bpf_kfunc_desc_tab *tab;
2025 struct bpf_prog_aux *prog_aux;
2026 struct bpf_kfunc_desc *desc;
2027 const char *func_name;
2028 struct btf *desc_btf;
2029 unsigned long call_imm;
2033 prog_aux = env->prog->aux;
2034 tab = prog_aux->kfunc_tab;
2035 btf_tab = prog_aux->kfunc_btf_tab;
2038 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2042 if (!env->prog->jit_requested) {
2043 verbose(env, "JIT is required for calling kernel function\n");
2047 if (!bpf_jit_supports_kfunc_call()) {
2048 verbose(env, "JIT does not support calling kernel function\n");
2052 if (!env->prog->gpl_compatible) {
2053 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2057 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2060 prog_aux->kfunc_tab = tab;
2063 /* func_id == 0 is always invalid, but instead of returning an error, be
2064 * conservative and wait until the code elimination pass before returning
2065 * error, so that invalid calls that get pruned out can be in BPF programs
2066 * loaded from userspace. It is also required that offset be untouched
2069 if (!func_id && !offset)
2072 if (!btf_tab && offset) {
2073 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2076 prog_aux->kfunc_btf_tab = btf_tab;
2079 desc_btf = find_kfunc_desc_btf(env, offset);
2080 if (IS_ERR(desc_btf)) {
2081 verbose(env, "failed to find BTF for kernel function\n");
2082 return PTR_ERR(desc_btf);
2085 if (find_kfunc_desc(env->prog, func_id, offset))
2088 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2089 verbose(env, "too many different kernel function calls\n");
2093 func = btf_type_by_id(desc_btf, func_id);
2094 if (!func || !btf_type_is_func(func)) {
2095 verbose(env, "kernel btf_id %u is not a function\n",
2099 func_proto = btf_type_by_id(desc_btf, func->type);
2100 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2101 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2106 func_name = btf_name_by_offset(desc_btf, func->name_off);
2107 addr = kallsyms_lookup_name(func_name);
2109 verbose(env, "cannot find address for kernel function %s\n",
2114 call_imm = BPF_CALL_IMM(addr);
2115 /* Check whether or not the relative offset overflows desc->imm */
2116 if ((unsigned long)(s32)call_imm != call_imm) {
2117 verbose(env, "address of kernel function %s is out of range\n",
2122 desc = &tab->descs[tab->nr_descs++];
2123 desc->func_id = func_id;
2124 desc->imm = call_imm;
2125 desc->offset = offset;
2126 err = btf_distill_func_proto(&env->log, desc_btf,
2127 func_proto, func_name,
2130 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2131 kfunc_desc_cmp_by_id_off, NULL);
2135 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2137 const struct bpf_kfunc_desc *d0 = a;
2138 const struct bpf_kfunc_desc *d1 = b;
2140 if (d0->imm > d1->imm)
2142 else if (d0->imm < d1->imm)
2147 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2149 struct bpf_kfunc_desc_tab *tab;
2151 tab = prog->aux->kfunc_tab;
2155 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2156 kfunc_desc_cmp_by_imm, NULL);
2159 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2161 return !!prog->aux->kfunc_tab;
2164 const struct btf_func_model *
2165 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2166 const struct bpf_insn *insn)
2168 const struct bpf_kfunc_desc desc = {
2171 const struct bpf_kfunc_desc *res;
2172 struct bpf_kfunc_desc_tab *tab;
2174 tab = prog->aux->kfunc_tab;
2175 res = bsearch(&desc, tab->descs, tab->nr_descs,
2176 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2178 return res ? &res->func_model : NULL;
2181 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2183 struct bpf_subprog_info *subprog = env->subprog_info;
2184 struct bpf_insn *insn = env->prog->insnsi;
2185 int i, ret, insn_cnt = env->prog->len;
2187 /* Add entry function. */
2188 ret = add_subprog(env, 0);
2192 for (i = 0; i < insn_cnt; i++, insn++) {
2193 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2194 !bpf_pseudo_kfunc_call(insn))
2197 if (!env->bpf_capable) {
2198 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2202 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2203 ret = add_subprog(env, i + insn->imm + 1);
2205 ret = add_kfunc_call(env, insn->imm, insn->off);
2211 /* Add a fake 'exit' subprog which could simplify subprog iteration
2212 * logic. 'subprog_cnt' should not be increased.
2214 subprog[env->subprog_cnt].start = insn_cnt;
2216 if (env->log.level & BPF_LOG_LEVEL2)
2217 for (i = 0; i < env->subprog_cnt; i++)
2218 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2223 static int check_subprogs(struct bpf_verifier_env *env)
2225 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2226 struct bpf_subprog_info *subprog = env->subprog_info;
2227 struct bpf_insn *insn = env->prog->insnsi;
2228 int insn_cnt = env->prog->len;
2230 /* now check that all jumps are within the same subprog */
2231 subprog_start = subprog[cur_subprog].start;
2232 subprog_end = subprog[cur_subprog + 1].start;
2233 for (i = 0; i < insn_cnt; i++) {
2234 u8 code = insn[i].code;
2236 if (code == (BPF_JMP | BPF_CALL) &&
2237 insn[i].imm == BPF_FUNC_tail_call &&
2238 insn[i].src_reg != BPF_PSEUDO_CALL)
2239 subprog[cur_subprog].has_tail_call = true;
2240 if (BPF_CLASS(code) == BPF_LD &&
2241 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2242 subprog[cur_subprog].has_ld_abs = true;
2243 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2245 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2247 off = i + insn[i].off + 1;
2248 if (off < subprog_start || off >= subprog_end) {
2249 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2253 if (i == subprog_end - 1) {
2254 /* to avoid fall-through from one subprog into another
2255 * the last insn of the subprog should be either exit
2256 * or unconditional jump back
2258 if (code != (BPF_JMP | BPF_EXIT) &&
2259 code != (BPF_JMP | BPF_JA)) {
2260 verbose(env, "last insn is not an exit or jmp\n");
2263 subprog_start = subprog_end;
2265 if (cur_subprog < env->subprog_cnt)
2266 subprog_end = subprog[cur_subprog + 1].start;
2272 /* Parentage chain of this register (or stack slot) should take care of all
2273 * issues like callee-saved registers, stack slot allocation time, etc.
2275 static int mark_reg_read(struct bpf_verifier_env *env,
2276 const struct bpf_reg_state *state,
2277 struct bpf_reg_state *parent, u8 flag)
2279 bool writes = parent == state->parent; /* Observe write marks */
2283 /* if read wasn't screened by an earlier write ... */
2284 if (writes && state->live & REG_LIVE_WRITTEN)
2286 if (parent->live & REG_LIVE_DONE) {
2287 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2288 reg_type_str(env, parent->type),
2289 parent->var_off.value, parent->off);
2292 /* The first condition is more likely to be true than the
2293 * second, checked it first.
2295 if ((parent->live & REG_LIVE_READ) == flag ||
2296 parent->live & REG_LIVE_READ64)
2297 /* The parentage chain never changes and
2298 * this parent was already marked as LIVE_READ.
2299 * There is no need to keep walking the chain again and
2300 * keep re-marking all parents as LIVE_READ.
2301 * This case happens when the same register is read
2302 * multiple times without writes into it in-between.
2303 * Also, if parent has the stronger REG_LIVE_READ64 set,
2304 * then no need to set the weak REG_LIVE_READ32.
2307 /* ... then we depend on parent's value */
2308 parent->live |= flag;
2309 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2310 if (flag == REG_LIVE_READ64)
2311 parent->live &= ~REG_LIVE_READ32;
2313 parent = state->parent;
2318 if (env->longest_mark_read_walk < cnt)
2319 env->longest_mark_read_walk = cnt;
2323 /* This function is supposed to be used by the following 32-bit optimization
2324 * code only. It returns TRUE if the source or destination register operates
2325 * on 64-bit, otherwise return FALSE.
2327 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2328 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2333 class = BPF_CLASS(code);
2335 if (class == BPF_JMP) {
2336 /* BPF_EXIT for "main" will reach here. Return TRUE
2341 if (op == BPF_CALL) {
2342 /* BPF to BPF call will reach here because of marking
2343 * caller saved clobber with DST_OP_NO_MARK for which we
2344 * don't care the register def because they are anyway
2345 * marked as NOT_INIT already.
2347 if (insn->src_reg == BPF_PSEUDO_CALL)
2349 /* Helper call will reach here because of arg type
2350 * check, conservatively return TRUE.
2359 if (class == BPF_ALU64 || class == BPF_JMP ||
2360 /* BPF_END always use BPF_ALU class. */
2361 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2364 if (class == BPF_ALU || class == BPF_JMP32)
2367 if (class == BPF_LDX) {
2369 return BPF_SIZE(code) == BPF_DW;
2370 /* LDX source must be ptr. */
2374 if (class == BPF_STX) {
2375 /* BPF_STX (including atomic variants) has multiple source
2376 * operands, one of which is a ptr. Check whether the caller is
2379 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2381 return BPF_SIZE(code) == BPF_DW;
2384 if (class == BPF_LD) {
2385 u8 mode = BPF_MODE(code);
2388 if (mode == BPF_IMM)
2391 /* Both LD_IND and LD_ABS return 32-bit data. */
2395 /* Implicit ctx ptr. */
2396 if (regno == BPF_REG_6)
2399 /* Explicit source could be any width. */
2403 if (class == BPF_ST)
2404 /* The only source register for BPF_ST is a ptr. */
2407 /* Conservatively return true at default. */
2411 /* Return the regno defined by the insn, or -1. */
2412 static int insn_def_regno(const struct bpf_insn *insn)
2414 switch (BPF_CLASS(insn->code)) {
2420 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2421 (insn->imm & BPF_FETCH)) {
2422 if (insn->imm == BPF_CMPXCHG)
2425 return insn->src_reg;
2430 return insn->dst_reg;
2434 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2435 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2437 int dst_reg = insn_def_regno(insn);
2442 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2445 static void mark_insn_zext(struct bpf_verifier_env *env,
2446 struct bpf_reg_state *reg)
2448 s32 def_idx = reg->subreg_def;
2450 if (def_idx == DEF_NOT_SUBREG)
2453 env->insn_aux_data[def_idx - 1].zext_dst = true;
2454 /* The dst will be zero extended, so won't be sub-register anymore. */
2455 reg->subreg_def = DEF_NOT_SUBREG;
2458 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2459 enum reg_arg_type t)
2461 struct bpf_verifier_state *vstate = env->cur_state;
2462 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2463 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2464 struct bpf_reg_state *reg, *regs = state->regs;
2467 if (regno >= MAX_BPF_REG) {
2468 verbose(env, "R%d is invalid\n", regno);
2472 mark_reg_scratched(env, regno);
2475 rw64 = is_reg64(env, insn, regno, reg, t);
2477 /* check whether register used as source operand can be read */
2478 if (reg->type == NOT_INIT) {
2479 verbose(env, "R%d !read_ok\n", regno);
2482 /* We don't need to worry about FP liveness because it's read-only */
2483 if (regno == BPF_REG_FP)
2487 mark_insn_zext(env, reg);
2489 return mark_reg_read(env, reg, reg->parent,
2490 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2492 /* check whether register used as dest operand can be written to */
2493 if (regno == BPF_REG_FP) {
2494 verbose(env, "frame pointer is read only\n");
2497 reg->live |= REG_LIVE_WRITTEN;
2498 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2500 mark_reg_unknown(env, regs, regno);
2505 /* for any branch, call, exit record the history of jmps in the given state */
2506 static int push_jmp_history(struct bpf_verifier_env *env,
2507 struct bpf_verifier_state *cur)
2509 u32 cnt = cur->jmp_history_cnt;
2510 struct bpf_idx_pair *p;
2514 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2515 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2518 p[cnt - 1].idx = env->insn_idx;
2519 p[cnt - 1].prev_idx = env->prev_insn_idx;
2520 cur->jmp_history = p;
2521 cur->jmp_history_cnt = cnt;
2525 /* Backtrack one insn at a time. If idx is not at the top of recorded
2526 * history then previous instruction came from straight line execution.
2528 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2533 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2534 i = st->jmp_history[cnt - 1].prev_idx;
2542 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2544 const struct btf_type *func;
2545 struct btf *desc_btf;
2547 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2550 desc_btf = find_kfunc_desc_btf(data, insn->off);
2551 if (IS_ERR(desc_btf))
2554 func = btf_type_by_id(desc_btf, insn->imm);
2555 return btf_name_by_offset(desc_btf, func->name_off);
2558 /* For given verifier state backtrack_insn() is called from the last insn to
2559 * the first insn. Its purpose is to compute a bitmask of registers and
2560 * stack slots that needs precision in the parent verifier state.
2562 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2563 u32 *reg_mask, u64 *stack_mask)
2565 const struct bpf_insn_cbs cbs = {
2566 .cb_call = disasm_kfunc_name,
2567 .cb_print = verbose,
2568 .private_data = env,
2570 struct bpf_insn *insn = env->prog->insnsi + idx;
2571 u8 class = BPF_CLASS(insn->code);
2572 u8 opcode = BPF_OP(insn->code);
2573 u8 mode = BPF_MODE(insn->code);
2574 u32 dreg = 1u << insn->dst_reg;
2575 u32 sreg = 1u << insn->src_reg;
2578 if (insn->code == 0)
2580 if (env->log.level & BPF_LOG_LEVEL2) {
2581 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2582 verbose(env, "%d: ", idx);
2583 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2586 if (class == BPF_ALU || class == BPF_ALU64) {
2587 if (!(*reg_mask & dreg))
2589 if (opcode == BPF_MOV) {
2590 if (BPF_SRC(insn->code) == BPF_X) {
2592 * dreg needs precision after this insn
2593 * sreg needs precision before this insn
2599 * dreg needs precision after this insn.
2600 * Corresponding register is already marked
2601 * as precise=true in this verifier state.
2602 * No further markings in parent are necessary
2607 if (BPF_SRC(insn->code) == BPF_X) {
2609 * both dreg and sreg need precision
2614 * dreg still needs precision before this insn
2617 } else if (class == BPF_LDX) {
2618 if (!(*reg_mask & dreg))
2622 /* scalars can only be spilled into stack w/o losing precision.
2623 * Load from any other memory can be zero extended.
2624 * The desire to keep that precision is already indicated
2625 * by 'precise' mark in corresponding register of this state.
2626 * No further tracking necessary.
2628 if (insn->src_reg != BPF_REG_FP)
2631 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2632 * that [fp - off] slot contains scalar that needs to be
2633 * tracked with precision
2635 spi = (-insn->off - 1) / BPF_REG_SIZE;
2637 verbose(env, "BUG spi %d\n", spi);
2638 WARN_ONCE(1, "verifier backtracking bug");
2641 *stack_mask |= 1ull << spi;
2642 } else if (class == BPF_STX || class == BPF_ST) {
2643 if (*reg_mask & dreg)
2644 /* stx & st shouldn't be using _scalar_ dst_reg
2645 * to access memory. It means backtracking
2646 * encountered a case of pointer subtraction.
2649 /* scalars can only be spilled into stack */
2650 if (insn->dst_reg != BPF_REG_FP)
2652 spi = (-insn->off - 1) / BPF_REG_SIZE;
2654 verbose(env, "BUG spi %d\n", spi);
2655 WARN_ONCE(1, "verifier backtracking bug");
2658 if (!(*stack_mask & (1ull << spi)))
2660 *stack_mask &= ~(1ull << spi);
2661 if (class == BPF_STX)
2663 } else if (class == BPF_JMP || class == BPF_JMP32) {
2664 if (opcode == BPF_CALL) {
2665 if (insn->src_reg == BPF_PSEUDO_CALL)
2667 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
2668 * catch this error later. Make backtracking conservative
2671 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
2673 /* regular helper call sets R0 */
2675 if (*reg_mask & 0x3f) {
2676 /* if backtracing was looking for registers R1-R5
2677 * they should have been found already.
2679 verbose(env, "BUG regs %x\n", *reg_mask);
2680 WARN_ONCE(1, "verifier backtracking bug");
2683 } else if (opcode == BPF_EXIT) {
2685 } else if (BPF_SRC(insn->code) == BPF_X) {
2686 if (!(*reg_mask & (dreg | sreg)))
2689 * Both dreg and sreg need precision before
2690 * this insn. If only sreg was marked precise
2691 * before it would be equally necessary to
2692 * propagate it to dreg.
2694 *reg_mask |= (sreg | dreg);
2695 /* else dreg <cond> K
2696 * Only dreg still needs precision before
2697 * this insn, so for the K-based conditional
2698 * there is nothing new to be marked.
2701 } else if (class == BPF_LD) {
2702 if (!(*reg_mask & dreg))
2705 /* It's ld_imm64 or ld_abs or ld_ind.
2706 * For ld_imm64 no further tracking of precision
2707 * into parent is necessary
2709 if (mode == BPF_IND || mode == BPF_ABS)
2710 /* to be analyzed */
2716 /* the scalar precision tracking algorithm:
2717 * . at the start all registers have precise=false.
2718 * . scalar ranges are tracked as normal through alu and jmp insns.
2719 * . once precise value of the scalar register is used in:
2720 * . ptr + scalar alu
2721 * . if (scalar cond K|scalar)
2722 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2723 * backtrack through the verifier states and mark all registers and
2724 * stack slots with spilled constants that these scalar regisers
2725 * should be precise.
2726 * . during state pruning two registers (or spilled stack slots)
2727 * are equivalent if both are not precise.
2729 * Note the verifier cannot simply walk register parentage chain,
2730 * since many different registers and stack slots could have been
2731 * used to compute single precise scalar.
2733 * The approach of starting with precise=true for all registers and then
2734 * backtrack to mark a register as not precise when the verifier detects
2735 * that program doesn't care about specific value (e.g., when helper
2736 * takes register as ARG_ANYTHING parameter) is not safe.
2738 * It's ok to walk single parentage chain of the verifier states.
2739 * It's possible that this backtracking will go all the way till 1st insn.
2740 * All other branches will be explored for needing precision later.
2742 * The backtracking needs to deal with cases like:
2743 * 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)
2746 * if r5 > 0x79f goto pc+7
2747 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2750 * call bpf_perf_event_output#25
2751 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2755 * call foo // uses callee's r6 inside to compute r0
2759 * to track above reg_mask/stack_mask needs to be independent for each frame.
2761 * Also if parent's curframe > frame where backtracking started,
2762 * the verifier need to mark registers in both frames, otherwise callees
2763 * may incorrectly prune callers. This is similar to
2764 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2766 * For now backtracking falls back into conservative marking.
2768 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2769 struct bpf_verifier_state *st)
2771 struct bpf_func_state *func;
2772 struct bpf_reg_state *reg;
2775 /* big hammer: mark all scalars precise in this path.
2776 * pop_stack may still get !precise scalars.
2778 for (; st; st = st->parent)
2779 for (i = 0; i <= st->curframe; i++) {
2780 func = st->frame[i];
2781 for (j = 0; j < BPF_REG_FP; j++) {
2782 reg = &func->regs[j];
2783 if (reg->type != SCALAR_VALUE)
2785 reg->precise = true;
2787 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2788 if (!is_spilled_reg(&func->stack[j]))
2790 reg = &func->stack[j].spilled_ptr;
2791 if (reg->type != SCALAR_VALUE)
2793 reg->precise = true;
2798 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2801 struct bpf_verifier_state *st = env->cur_state;
2802 int first_idx = st->first_insn_idx;
2803 int last_idx = env->insn_idx;
2804 struct bpf_func_state *func;
2805 struct bpf_reg_state *reg;
2806 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2807 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2808 bool skip_first = true;
2809 bool new_marks = false;
2812 if (!env->bpf_capable)
2815 func = st->frame[frame];
2817 reg = &func->regs[regno];
2818 if (reg->type != SCALAR_VALUE) {
2819 WARN_ONCE(1, "backtracing misuse");
2826 reg->precise = true;
2830 if (!is_spilled_reg(&func->stack[spi])) {
2834 reg = &func->stack[spi].spilled_ptr;
2835 if (reg->type != SCALAR_VALUE) {
2843 reg->precise = true;
2849 if (!reg_mask && !stack_mask)
2852 DECLARE_BITMAP(mask, 64);
2853 u32 history = st->jmp_history_cnt;
2855 if (env->log.level & BPF_LOG_LEVEL2)
2856 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2857 for (i = last_idx;;) {
2862 err = backtrack_insn(env, i, ®_mask, &stack_mask);
2864 if (err == -ENOTSUPP) {
2865 mark_all_scalars_precise(env, st);
2870 if (!reg_mask && !stack_mask)
2871 /* Found assignment(s) into tracked register in this state.
2872 * Since this state is already marked, just return.
2873 * Nothing to be tracked further in the parent state.
2878 i = get_prev_insn_idx(st, i, &history);
2879 if (i >= env->prog->len) {
2880 /* This can happen if backtracking reached insn 0
2881 * and there are still reg_mask or stack_mask
2883 * It means the backtracking missed the spot where
2884 * particular register was initialized with a constant.
2886 verbose(env, "BUG backtracking idx %d\n", i);
2887 WARN_ONCE(1, "verifier backtracking bug");
2896 func = st->frame[frame];
2897 bitmap_from_u64(mask, reg_mask);
2898 for_each_set_bit(i, mask, 32) {
2899 reg = &func->regs[i];
2900 if (reg->type != SCALAR_VALUE) {
2901 reg_mask &= ~(1u << i);
2906 reg->precise = true;
2909 bitmap_from_u64(mask, stack_mask);
2910 for_each_set_bit(i, mask, 64) {
2911 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2912 /* the sequence of instructions:
2914 * 3: (7b) *(u64 *)(r3 -8) = r0
2915 * 4: (79) r4 = *(u64 *)(r10 -8)
2916 * doesn't contain jmps. It's backtracked
2917 * as a single block.
2918 * During backtracking insn 3 is not recognized as
2919 * stack access, so at the end of backtracking
2920 * stack slot fp-8 is still marked in stack_mask.
2921 * However the parent state may not have accessed
2922 * fp-8 and it's "unallocated" stack space.
2923 * In such case fallback to conservative.
2925 mark_all_scalars_precise(env, st);
2929 if (!is_spilled_reg(&func->stack[i])) {
2930 stack_mask &= ~(1ull << i);
2933 reg = &func->stack[i].spilled_ptr;
2934 if (reg->type != SCALAR_VALUE) {
2935 stack_mask &= ~(1ull << i);
2940 reg->precise = true;
2942 if (env->log.level & BPF_LOG_LEVEL2) {
2943 verbose(env, "parent %s regs=%x stack=%llx marks:",
2944 new_marks ? "didn't have" : "already had",
2945 reg_mask, stack_mask);
2946 print_verifier_state(env, func, true);
2949 if (!reg_mask && !stack_mask)
2954 last_idx = st->last_insn_idx;
2955 first_idx = st->first_insn_idx;
2960 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2962 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2965 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2967 return __mark_chain_precision(env, frame, regno, -1);
2970 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2972 return __mark_chain_precision(env, frame, -1, spi);
2975 static bool is_spillable_regtype(enum bpf_reg_type type)
2977 switch (base_type(type)) {
2978 case PTR_TO_MAP_VALUE:
2982 case PTR_TO_PACKET_META:
2983 case PTR_TO_PACKET_END:
2984 case PTR_TO_FLOW_KEYS:
2985 case CONST_PTR_TO_MAP:
2987 case PTR_TO_SOCK_COMMON:
2988 case PTR_TO_TCP_SOCK:
2989 case PTR_TO_XDP_SOCK:
2994 case PTR_TO_MAP_KEY:
3001 /* Does this register contain a constant zero? */
3002 static bool register_is_null(struct bpf_reg_state *reg)
3004 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3007 static bool register_is_const(struct bpf_reg_state *reg)
3009 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3012 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3014 return tnum_is_unknown(reg->var_off) &&
3015 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3016 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3017 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3018 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3021 static bool register_is_bounded(struct bpf_reg_state *reg)
3023 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3026 static bool __is_pointer_value(bool allow_ptr_leaks,
3027 const struct bpf_reg_state *reg)
3029 if (allow_ptr_leaks)
3032 return reg->type != SCALAR_VALUE;
3035 /* Copy src state preserving dst->parent and dst->live fields */
3036 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3038 struct bpf_reg_state *parent = dst->parent;
3039 enum bpf_reg_liveness live = dst->live;
3042 dst->parent = parent;
3046 static void save_register_state(struct bpf_func_state *state,
3047 int spi, struct bpf_reg_state *reg,
3052 copy_register_state(&state->stack[spi].spilled_ptr, reg);
3053 if (size == BPF_REG_SIZE)
3054 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3056 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3057 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3059 /* size < 8 bytes spill */
3061 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3064 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3065 * stack boundary and alignment are checked in check_mem_access()
3067 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3068 /* stack frame we're writing to */
3069 struct bpf_func_state *state,
3070 int off, int size, int value_regno,
3073 struct bpf_func_state *cur; /* state of the current function */
3074 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3075 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3076 struct bpf_reg_state *reg = NULL;
3078 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3081 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3082 * so it's aligned access and [off, off + size) are within stack limits
3084 if (!env->allow_ptr_leaks &&
3085 state->stack[spi].slot_type[0] == STACK_SPILL &&
3086 size != BPF_REG_SIZE) {
3087 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3091 cur = env->cur_state->frame[env->cur_state->curframe];
3092 if (value_regno >= 0)
3093 reg = &cur->regs[value_regno];
3094 if (!env->bypass_spec_v4) {
3095 bool sanitize = reg && is_spillable_regtype(reg->type);
3097 for (i = 0; i < size; i++) {
3098 u8 type = state->stack[spi].slot_type[i];
3100 if (type != STACK_MISC && type != STACK_ZERO) {
3107 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3110 mark_stack_slot_scratched(env, spi);
3111 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3112 !register_is_null(reg) && env->bpf_capable) {
3113 if (dst_reg != BPF_REG_FP) {
3114 /* The backtracking logic can only recognize explicit
3115 * stack slot address like [fp - 8]. Other spill of
3116 * scalar via different register has to be conservative.
3117 * Backtrack from here and mark all registers as precise
3118 * that contributed into 'reg' being a constant.
3120 err = mark_chain_precision(env, value_regno);
3124 save_register_state(state, spi, reg, size);
3125 } else if (reg && is_spillable_regtype(reg->type)) {
3126 /* register containing pointer is being spilled into stack */
3127 if (size != BPF_REG_SIZE) {
3128 verbose_linfo(env, insn_idx, "; ");
3129 verbose(env, "invalid size of register spill\n");
3132 if (state != cur && reg->type == PTR_TO_STACK) {
3133 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3136 save_register_state(state, spi, reg, size);
3138 u8 type = STACK_MISC;
3140 /* regular write of data into stack destroys any spilled ptr */
3141 state->stack[spi].spilled_ptr.type = NOT_INIT;
3142 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3143 if (is_spilled_reg(&state->stack[spi]))
3144 for (i = 0; i < BPF_REG_SIZE; i++)
3145 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3147 /* only mark the slot as written if all 8 bytes were written
3148 * otherwise read propagation may incorrectly stop too soon
3149 * when stack slots are partially written.
3150 * This heuristic means that read propagation will be
3151 * conservative, since it will add reg_live_read marks
3152 * to stack slots all the way to first state when programs
3153 * writes+reads less than 8 bytes
3155 if (size == BPF_REG_SIZE)
3156 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3158 /* when we zero initialize stack slots mark them as such */
3159 if (reg && register_is_null(reg)) {
3160 /* backtracking doesn't work for STACK_ZERO yet. */
3161 err = mark_chain_precision(env, value_regno);
3167 /* Mark slots affected by this stack write. */
3168 for (i = 0; i < size; i++)
3169 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3175 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3176 * known to contain a variable offset.
3177 * This function checks whether the write is permitted and conservatively
3178 * tracks the effects of the write, considering that each stack slot in the
3179 * dynamic range is potentially written to.
3181 * 'off' includes 'regno->off'.
3182 * 'value_regno' can be -1, meaning that an unknown value is being written to
3185 * Spilled pointers in range are not marked as written because we don't know
3186 * what's going to be actually written. This means that read propagation for
3187 * future reads cannot be terminated by this write.
3189 * For privileged programs, uninitialized stack slots are considered
3190 * initialized by this write (even though we don't know exactly what offsets
3191 * are going to be written to). The idea is that we don't want the verifier to
3192 * reject future reads that access slots written to through variable offsets.
3194 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3195 /* func where register points to */
3196 struct bpf_func_state *state,
3197 int ptr_regno, int off, int size,
3198 int value_regno, int insn_idx)
3200 struct bpf_func_state *cur; /* state of the current function */
3201 int min_off, max_off;
3203 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3204 bool writing_zero = false;
3205 /* set if the fact that we're writing a zero is used to let any
3206 * stack slots remain STACK_ZERO
3208 bool zero_used = false;
3210 cur = env->cur_state->frame[env->cur_state->curframe];
3211 ptr_reg = &cur->regs[ptr_regno];
3212 min_off = ptr_reg->smin_value + off;
3213 max_off = ptr_reg->smax_value + off + size;
3214 if (value_regno >= 0)
3215 value_reg = &cur->regs[value_regno];
3216 if (value_reg && register_is_null(value_reg))
3217 writing_zero = true;
3219 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3224 /* Variable offset writes destroy any spilled pointers in range. */
3225 for (i = min_off; i < max_off; i++) {
3226 u8 new_type, *stype;
3230 spi = slot / BPF_REG_SIZE;
3231 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3232 mark_stack_slot_scratched(env, spi);
3234 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3235 /* Reject the write if range we may write to has not
3236 * been initialized beforehand. If we didn't reject
3237 * here, the ptr status would be erased below (even
3238 * though not all slots are actually overwritten),
3239 * possibly opening the door to leaks.
3241 * We do however catch STACK_INVALID case below, and
3242 * only allow reading possibly uninitialized memory
3243 * later for CAP_PERFMON, as the write may not happen to
3246 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3251 /* Erase all spilled pointers. */
3252 state->stack[spi].spilled_ptr.type = NOT_INIT;
3254 /* Update the slot type. */
3255 new_type = STACK_MISC;
3256 if (writing_zero && *stype == STACK_ZERO) {
3257 new_type = STACK_ZERO;
3260 /* If the slot is STACK_INVALID, we check whether it's OK to
3261 * pretend that it will be initialized by this write. The slot
3262 * might not actually be written to, and so if we mark it as
3263 * initialized future reads might leak uninitialized memory.
3264 * For privileged programs, we will accept such reads to slots
3265 * that may or may not be written because, if we're reject
3266 * them, the error would be too confusing.
3268 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3269 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3276 /* backtracking doesn't work for STACK_ZERO yet. */
3277 err = mark_chain_precision(env, value_regno);
3284 /* When register 'dst_regno' is assigned some values from stack[min_off,
3285 * max_off), we set the register's type according to the types of the
3286 * respective stack slots. If all the stack values are known to be zeros, then
3287 * so is the destination reg. Otherwise, the register is considered to be
3288 * SCALAR. This function does not deal with register filling; the caller must
3289 * ensure that all spilled registers in the stack range have been marked as
3292 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3293 /* func where src register points to */
3294 struct bpf_func_state *ptr_state,
3295 int min_off, int max_off, int dst_regno)
3297 struct bpf_verifier_state *vstate = env->cur_state;
3298 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3303 for (i = min_off; i < max_off; i++) {
3305 spi = slot / BPF_REG_SIZE;
3306 stype = ptr_state->stack[spi].slot_type;
3307 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3311 if (zeros == max_off - min_off) {
3312 /* any access_size read into register is zero extended,
3313 * so the whole register == const_zero
3315 __mark_reg_const_zero(&state->regs[dst_regno]);
3316 /* backtracking doesn't support STACK_ZERO yet,
3317 * so mark it precise here, so that later
3318 * backtracking can stop here.
3319 * Backtracking may not need this if this register
3320 * doesn't participate in pointer adjustment.
3321 * Forward propagation of precise flag is not
3322 * necessary either. This mark is only to stop
3323 * backtracking. Any register that contributed
3324 * to const 0 was marked precise before spill.
3326 state->regs[dst_regno].precise = true;
3328 /* have read misc data from the stack */
3329 mark_reg_unknown(env, state->regs, dst_regno);
3331 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3334 /* Read the stack at 'off' and put the results into the register indicated by
3335 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3338 * 'dst_regno' can be -1, meaning that the read value is not going to a
3341 * The access is assumed to be within the current stack bounds.
3343 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3344 /* func where src register points to */
3345 struct bpf_func_state *reg_state,
3346 int off, int size, int dst_regno)
3348 struct bpf_verifier_state *vstate = env->cur_state;
3349 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3350 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3351 struct bpf_reg_state *reg;
3354 stype = reg_state->stack[spi].slot_type;
3355 reg = ®_state->stack[spi].spilled_ptr;
3357 if (is_spilled_reg(®_state->stack[spi])) {
3360 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3363 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3364 if (reg->type != SCALAR_VALUE) {
3365 verbose_linfo(env, env->insn_idx, "; ");
3366 verbose(env, "invalid size of register fill\n");
3370 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3374 if (!(off % BPF_REG_SIZE) && size == spill_size) {
3375 /* The earlier check_reg_arg() has decided the
3376 * subreg_def for this insn. Save it first.
3378 s32 subreg_def = state->regs[dst_regno].subreg_def;
3380 copy_register_state(&state->regs[dst_regno], reg);
3381 state->regs[dst_regno].subreg_def = subreg_def;
3383 for (i = 0; i < size; i++) {
3384 type = stype[(slot - i) % BPF_REG_SIZE];
3385 if (type == STACK_SPILL)
3387 if (type == STACK_MISC)
3389 verbose(env, "invalid read from stack off %d+%d size %d\n",
3393 mark_reg_unknown(env, state->regs, dst_regno);
3395 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3399 if (dst_regno >= 0) {
3400 /* restore register state from stack */
3401 copy_register_state(&state->regs[dst_regno], reg);
3402 /* mark reg as written since spilled pointer state likely
3403 * has its liveness marks cleared by is_state_visited()
3404 * which resets stack/reg liveness for state transitions
3406 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3407 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3408 /* If dst_regno==-1, the caller is asking us whether
3409 * it is acceptable to use this value as a SCALAR_VALUE
3411 * We must not allow unprivileged callers to do that
3412 * with spilled pointers.
3414 verbose(env, "leaking pointer from stack off %d\n",
3418 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3420 for (i = 0; i < size; i++) {
3421 type = stype[(slot - i) % BPF_REG_SIZE];
3422 if (type == STACK_MISC)
3424 if (type == STACK_ZERO)
3426 verbose(env, "invalid read from stack off %d+%d size %d\n",
3430 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3432 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3437 enum bpf_access_src {
3438 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
3439 ACCESS_HELPER = 2, /* the access is performed by a helper */
3442 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3443 int regno, int off, int access_size,
3444 bool zero_size_allowed,
3445 enum bpf_access_src type,
3446 struct bpf_call_arg_meta *meta);
3448 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3450 return cur_regs(env) + regno;
3453 /* Read the stack at 'ptr_regno + off' and put the result into the register
3455 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3456 * but not its variable offset.
3457 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3459 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3460 * filling registers (i.e. reads of spilled register cannot be detected when
3461 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3462 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3463 * offset; for a fixed offset check_stack_read_fixed_off should be used
3466 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3467 int ptr_regno, int off, int size, int dst_regno)
3469 /* The state of the source register. */
3470 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3471 struct bpf_func_state *ptr_state = func(env, reg);
3473 int min_off, max_off;
3475 /* Note that we pass a NULL meta, so raw access will not be permitted.
3477 err = check_stack_range_initialized(env, ptr_regno, off, size,
3478 false, ACCESS_DIRECT, NULL);
3482 min_off = reg->smin_value + off;
3483 max_off = reg->smax_value + off;
3484 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3488 /* check_stack_read dispatches to check_stack_read_fixed_off or
3489 * check_stack_read_var_off.
3491 * The caller must ensure that the offset falls within the allocated stack
3494 * 'dst_regno' is a register which will receive the value from the stack. It
3495 * can be -1, meaning that the read value is not going to a register.
3497 static int check_stack_read(struct bpf_verifier_env *env,
3498 int ptr_regno, int off, int size,
3501 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3502 struct bpf_func_state *state = func(env, reg);
3504 /* Some accesses are only permitted with a static offset. */
3505 bool var_off = !tnum_is_const(reg->var_off);
3507 /* The offset is required to be static when reads don't go to a
3508 * register, in order to not leak pointers (see
3509 * check_stack_read_fixed_off).
3511 if (dst_regno < 0 && var_off) {
3514 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3515 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3519 /* Variable offset is prohibited for unprivileged mode for simplicity
3520 * since it requires corresponding support in Spectre masking for stack
3521 * ALU. See also retrieve_ptr_limit(). The check in
3522 * check_stack_access_for_ptr_arithmetic() called by
3523 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
3524 * with variable offsets, therefore no check is required here. Further,
3525 * just checking it here would be insufficient as speculative stack
3526 * writes could still lead to unsafe speculative behaviour.
3529 off += reg->var_off.value;
3530 err = check_stack_read_fixed_off(env, state, off, size,
3533 /* Variable offset stack reads need more conservative handling
3534 * than fixed offset ones. Note that dst_regno >= 0 on this
3537 err = check_stack_read_var_off(env, ptr_regno, off, size,
3544 /* check_stack_write dispatches to check_stack_write_fixed_off or
3545 * check_stack_write_var_off.
3547 * 'ptr_regno' is the register used as a pointer into the stack.
3548 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3549 * 'value_regno' is the register whose value we're writing to the stack. It can
3550 * be -1, meaning that we're not writing from a register.
3552 * The caller must ensure that the offset falls within the maximum stack size.
3554 static int check_stack_write(struct bpf_verifier_env *env,
3555 int ptr_regno, int off, int size,
3556 int value_regno, int insn_idx)
3558 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3559 struct bpf_func_state *state = func(env, reg);
3562 if (tnum_is_const(reg->var_off)) {
3563 off += reg->var_off.value;
3564 err = check_stack_write_fixed_off(env, state, off, size,
3565 value_regno, insn_idx);
3567 /* Variable offset stack reads need more conservative handling
3568 * than fixed offset ones.
3570 err = check_stack_write_var_off(env, state,
3571 ptr_regno, off, size,
3572 value_regno, insn_idx);
3577 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3578 int off, int size, enum bpf_access_type type)
3580 struct bpf_reg_state *regs = cur_regs(env);
3581 struct bpf_map *map = regs[regno].map_ptr;
3582 u32 cap = bpf_map_flags_to_cap(map);
3584 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3585 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3586 map->value_size, off, size);
3590 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3591 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3592 map->value_size, off, size);
3599 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3600 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3601 int off, int size, u32 mem_size,
3602 bool zero_size_allowed)
3604 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3605 struct bpf_reg_state *reg;
3607 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3610 reg = &cur_regs(env)[regno];
3611 switch (reg->type) {
3612 case PTR_TO_MAP_KEY:
3613 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3614 mem_size, off, size);
3616 case PTR_TO_MAP_VALUE:
3617 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3618 mem_size, off, size);
3621 case PTR_TO_PACKET_META:
3622 case PTR_TO_PACKET_END:
3623 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3624 off, size, regno, reg->id, off, mem_size);
3628 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3629 mem_size, off, size);
3635 /* check read/write into a memory region with possible variable offset */
3636 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3637 int off, int size, u32 mem_size,
3638 bool zero_size_allowed)
3640 struct bpf_verifier_state *vstate = env->cur_state;
3641 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3642 struct bpf_reg_state *reg = &state->regs[regno];
3645 /* We may have adjusted the register pointing to memory region, so we
3646 * need to try adding each of min_value and max_value to off
3647 * to make sure our theoretical access will be safe.
3649 * The minimum value is only important with signed
3650 * comparisons where we can't assume the floor of a
3651 * value is 0. If we are using signed variables for our
3652 * index'es we need to make sure that whatever we use
3653 * will have a set floor within our range.
3655 if (reg->smin_value < 0 &&
3656 (reg->smin_value == S64_MIN ||
3657 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3658 reg->smin_value + off < 0)) {
3659 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3663 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3664 mem_size, zero_size_allowed);
3666 verbose(env, "R%d min value is outside of the allowed memory range\n",
3671 /* If we haven't set a max value then we need to bail since we can't be
3672 * sure we won't do bad things.
3673 * If reg->umax_value + off could overflow, treat that as unbounded too.
3675 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3676 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3680 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3681 mem_size, zero_size_allowed);
3683 verbose(env, "R%d max value is outside of the allowed memory range\n",
3691 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3692 const struct bpf_reg_state *reg, int regno,
3695 /* Access to this pointer-typed register or passing it to a helper
3696 * is only allowed in its original, unmodified form.
3700 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3701 reg_type_str(env, reg->type), regno, reg->off);
3705 if (!fixed_off_ok && reg->off) {
3706 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3707 reg_type_str(env, reg->type), regno, reg->off);
3711 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3714 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3715 verbose(env, "variable %s access var_off=%s disallowed\n",
3716 reg_type_str(env, reg->type), tn_buf);
3723 int check_ptr_off_reg(struct bpf_verifier_env *env,
3724 const struct bpf_reg_state *reg, int regno)
3726 return __check_ptr_off_reg(env, reg, regno, false);
3729 static int map_kptr_match_type(struct bpf_verifier_env *env,
3730 struct bpf_map_value_off_desc *off_desc,
3731 struct bpf_reg_state *reg, u32 regno)
3733 const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3734 int perm_flags = PTR_MAYBE_NULL;
3735 const char *reg_name = "";
3737 /* Only unreferenced case accepts untrusted pointers */
3738 if (off_desc->type == BPF_KPTR_UNREF)
3739 perm_flags |= PTR_UNTRUSTED;
3741 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3744 if (!btf_is_kernel(reg->btf)) {
3745 verbose(env, "R%d must point to kernel BTF\n", regno);
3748 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3749 reg_name = kernel_type_name(reg->btf, reg->btf_id);
3751 /* For ref_ptr case, release function check should ensure we get one
3752 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3753 * normal store of unreferenced kptr, we must ensure var_off is zero.
3754 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3755 * reg->off and reg->ref_obj_id are not needed here.
3757 if (__check_ptr_off_reg(env, reg, regno, true))
3760 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3761 * we also need to take into account the reg->off.
3763 * We want to support cases like:
3771 * v = func(); // PTR_TO_BTF_ID
3772 * val->foo = v; // reg->off is zero, btf and btf_id match type
3773 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3774 * // first member type of struct after comparison fails
3775 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3778 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3779 * is zero. We must also ensure that btf_struct_ids_match does not walk
3780 * the struct to match type against first member of struct, i.e. reject
3781 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3782 * strict mode to true for type match.
3784 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3785 off_desc->kptr.btf, off_desc->kptr.btf_id,
3786 off_desc->type == BPF_KPTR_REF))
3790 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3791 reg_type_str(env, reg->type), reg_name);
3792 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3793 if (off_desc->type == BPF_KPTR_UNREF)
3794 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3801 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3802 int value_regno, int insn_idx,
3803 struct bpf_map_value_off_desc *off_desc)
3805 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3806 int class = BPF_CLASS(insn->code);
3807 struct bpf_reg_state *val_reg;
3809 /* Things we already checked for in check_map_access and caller:
3810 * - Reject cases where variable offset may touch kptr
3811 * - size of access (must be BPF_DW)
3812 * - tnum_is_const(reg->var_off)
3813 * - off_desc->offset == off + reg->var_off.value
3815 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3816 if (BPF_MODE(insn->code) != BPF_MEM) {
3817 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3821 /* We only allow loading referenced kptr, since it will be marked as
3822 * untrusted, similar to unreferenced kptr.
3824 if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3825 verbose(env, "store to referenced kptr disallowed\n");
3829 if (class == BPF_LDX) {
3830 val_reg = reg_state(env, value_regno);
3831 /* We can simply mark the value_regno receiving the pointer
3832 * value from map as PTR_TO_BTF_ID, with the correct type.
3834 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3835 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3836 /* For mark_ptr_or_null_reg */
3837 val_reg->id = ++env->id_gen;
3838 } else if (class == BPF_STX) {
3839 val_reg = reg_state(env, value_regno);
3840 if (!register_is_null(val_reg) &&
3841 map_kptr_match_type(env, off_desc, val_reg, value_regno))
3843 } else if (class == BPF_ST) {
3845 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3850 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3856 /* check read/write into a map element with possible variable offset */
3857 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3858 int off, int size, bool zero_size_allowed,
3859 enum bpf_access_src src)
3861 struct bpf_verifier_state *vstate = env->cur_state;
3862 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3863 struct bpf_reg_state *reg = &state->regs[regno];
3864 struct bpf_map *map = reg->map_ptr;
3867 err = check_mem_region_access(env, regno, off, size, map->value_size,
3872 if (map_value_has_spin_lock(map)) {
3873 u32 lock = map->spin_lock_off;
3875 /* if any part of struct bpf_spin_lock can be touched by
3876 * load/store reject this program.
3877 * To check that [x1, x2) overlaps with [y1, y2)
3878 * it is sufficient to check x1 < y2 && y1 < x2.
3880 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3881 lock < reg->umax_value + off + size) {
3882 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3886 if (map_value_has_timer(map)) {
3887 u32 t = map->timer_off;
3889 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3890 t < reg->umax_value + off + size) {
3891 verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3895 if (map_value_has_kptrs(map)) {
3896 struct bpf_map_value_off *tab = map->kptr_off_tab;
3899 for (i = 0; i < tab->nr_off; i++) {
3900 u32 p = tab->off[i].offset;
3902 if (reg->smin_value + off < p + sizeof(u64) &&
3903 p < reg->umax_value + off + size) {
3904 if (src != ACCESS_DIRECT) {
3905 verbose(env, "kptr cannot be accessed indirectly by helper\n");
3908 if (!tnum_is_const(reg->var_off)) {
3909 verbose(env, "kptr access cannot have variable offset\n");
3912 if (p != off + reg->var_off.value) {
3913 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3914 p, off + reg->var_off.value);
3917 if (size != bpf_size_to_bytes(BPF_DW)) {
3918 verbose(env, "kptr access size must be BPF_DW\n");
3928 #define MAX_PACKET_OFF 0xffff
3930 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3931 const struct bpf_call_arg_meta *meta,
3932 enum bpf_access_type t)
3934 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3936 switch (prog_type) {
3937 /* Program types only with direct read access go here! */
3938 case BPF_PROG_TYPE_LWT_IN:
3939 case BPF_PROG_TYPE_LWT_OUT:
3940 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3941 case BPF_PROG_TYPE_SK_REUSEPORT:
3942 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3943 case BPF_PROG_TYPE_CGROUP_SKB:
3948 /* Program types with direct read + write access go here! */
3949 case BPF_PROG_TYPE_SCHED_CLS:
3950 case BPF_PROG_TYPE_SCHED_ACT:
3951 case BPF_PROG_TYPE_XDP:
3952 case BPF_PROG_TYPE_LWT_XMIT:
3953 case BPF_PROG_TYPE_SK_SKB:
3954 case BPF_PROG_TYPE_SK_MSG:
3956 return meta->pkt_access;
3958 env->seen_direct_write = true;
3961 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3963 env->seen_direct_write = true;
3972 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3973 int size, bool zero_size_allowed)
3975 struct bpf_reg_state *regs = cur_regs(env);
3976 struct bpf_reg_state *reg = ®s[regno];
3979 /* We may have added a variable offset to the packet pointer; but any
3980 * reg->range we have comes after that. We are only checking the fixed
3984 /* We don't allow negative numbers, because we aren't tracking enough
3985 * detail to prove they're safe.
3987 if (reg->smin_value < 0) {
3988 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3993 err = reg->range < 0 ? -EINVAL :
3994 __check_mem_access(env, regno, off, size, reg->range,
3997 verbose(env, "R%d offset is outside of the packet\n", regno);
4001 /* __check_mem_access has made sure "off + size - 1" is within u16.
4002 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4003 * otherwise find_good_pkt_pointers would have refused to set range info
4004 * that __check_mem_access would have rejected this pkt access.
4005 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4007 env->prog->aux->max_pkt_offset =
4008 max_t(u32, env->prog->aux->max_pkt_offset,
4009 off + reg->umax_value + size - 1);
4014 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
4015 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4016 enum bpf_access_type t, enum bpf_reg_type *reg_type,
4017 struct btf **btf, u32 *btf_id)
4019 struct bpf_insn_access_aux info = {
4020 .reg_type = *reg_type,
4024 if (env->ops->is_valid_access &&
4025 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4026 /* A non zero info.ctx_field_size indicates that this field is a
4027 * candidate for later verifier transformation to load the whole
4028 * field and then apply a mask when accessed with a narrower
4029 * access than actual ctx access size. A zero info.ctx_field_size
4030 * will only allow for whole field access and rejects any other
4031 * type of narrower access.
4033 *reg_type = info.reg_type;
4035 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4037 *btf_id = info.btf_id;
4039 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4041 /* remember the offset of last byte accessed in ctx */
4042 if (env->prog->aux->max_ctx_offset < off + size)
4043 env->prog->aux->max_ctx_offset = off + size;
4047 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4051 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4054 if (size < 0 || off < 0 ||
4055 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4056 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4063 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4064 u32 regno, int off, int size,
4065 enum bpf_access_type t)
4067 struct bpf_reg_state *regs = cur_regs(env);
4068 struct bpf_reg_state *reg = ®s[regno];
4069 struct bpf_insn_access_aux info = {};
4072 if (reg->smin_value < 0) {
4073 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4078 switch (reg->type) {
4079 case PTR_TO_SOCK_COMMON:
4080 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4083 valid = bpf_sock_is_valid_access(off, size, t, &info);
4085 case PTR_TO_TCP_SOCK:
4086 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4088 case PTR_TO_XDP_SOCK:
4089 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4097 env->insn_aux_data[insn_idx].ctx_field_size =
4098 info.ctx_field_size;
4102 verbose(env, "R%d invalid %s access off=%d size=%d\n",
4103 regno, reg_type_str(env, reg->type), off, size);
4108 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4110 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4113 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4115 const struct bpf_reg_state *reg = reg_state(env, regno);
4117 return reg->type == PTR_TO_CTX;
4120 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4122 const struct bpf_reg_state *reg = reg_state(env, regno);
4124 return type_is_sk_pointer(reg->type);
4127 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4129 const struct bpf_reg_state *reg = reg_state(env, regno);
4131 return type_is_pkt_pointer(reg->type);
4134 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4136 const struct bpf_reg_state *reg = reg_state(env, regno);
4138 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4139 return reg->type == PTR_TO_FLOW_KEYS;
4142 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4143 const struct bpf_reg_state *reg,
4144 int off, int size, bool strict)
4146 struct tnum reg_off;
4149 /* Byte size accesses are always allowed. */
4150 if (!strict || size == 1)
4153 /* For platforms that do not have a Kconfig enabling
4154 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4155 * NET_IP_ALIGN is universally set to '2'. And on platforms
4156 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4157 * to this code only in strict mode where we want to emulate
4158 * the NET_IP_ALIGN==2 checking. Therefore use an
4159 * unconditional IP align value of '2'.
4163 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4164 if (!tnum_is_aligned(reg_off, size)) {
4167 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4169 "misaligned packet access off %d+%s+%d+%d size %d\n",
4170 ip_align, tn_buf, reg->off, off, size);
4177 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4178 const struct bpf_reg_state *reg,
4179 const char *pointer_desc,
4180 int off, int size, bool strict)
4182 struct tnum reg_off;
4184 /* Byte size accesses are always allowed. */
4185 if (!strict || size == 1)
4188 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4189 if (!tnum_is_aligned(reg_off, size)) {
4192 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4193 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4194 pointer_desc, tn_buf, reg->off, off, size);
4201 static int check_ptr_alignment(struct bpf_verifier_env *env,
4202 const struct bpf_reg_state *reg, int off,
4203 int size, bool strict_alignment_once)
4205 bool strict = env->strict_alignment || strict_alignment_once;
4206 const char *pointer_desc = "";
4208 switch (reg->type) {
4210 case PTR_TO_PACKET_META:
4211 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4212 * right in front, treat it the very same way.
4214 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4215 case PTR_TO_FLOW_KEYS:
4216 pointer_desc = "flow keys ";
4218 case PTR_TO_MAP_KEY:
4219 pointer_desc = "key ";
4221 case PTR_TO_MAP_VALUE:
4222 pointer_desc = "value ";
4225 pointer_desc = "context ";
4228 pointer_desc = "stack ";
4229 /* The stack spill tracking logic in check_stack_write_fixed_off()
4230 * and check_stack_read_fixed_off() relies on stack accesses being
4236 pointer_desc = "sock ";
4238 case PTR_TO_SOCK_COMMON:
4239 pointer_desc = "sock_common ";
4241 case PTR_TO_TCP_SOCK:
4242 pointer_desc = "tcp_sock ";
4244 case PTR_TO_XDP_SOCK:
4245 pointer_desc = "xdp_sock ";
4250 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4254 static int update_stack_depth(struct bpf_verifier_env *env,
4255 const struct bpf_func_state *func,
4258 u16 stack = env->subprog_info[func->subprogno].stack_depth;
4263 /* update known max for given subprogram */
4264 env->subprog_info[func->subprogno].stack_depth = -off;
4268 /* starting from main bpf function walk all instructions of the function
4269 * and recursively walk all callees that given function can call.
4270 * Ignore jump and exit insns.
4271 * Since recursion is prevented by check_cfg() this algorithm
4272 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4274 static int check_max_stack_depth(struct bpf_verifier_env *env)
4276 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4277 struct bpf_subprog_info *subprog = env->subprog_info;
4278 struct bpf_insn *insn = env->prog->insnsi;
4279 bool tail_call_reachable = false;
4280 int ret_insn[MAX_CALL_FRAMES];
4281 int ret_prog[MAX_CALL_FRAMES];
4285 /* protect against potential stack overflow that might happen when
4286 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4287 * depth for such case down to 256 so that the worst case scenario
4288 * would result in 8k stack size (32 which is tailcall limit * 256 =
4291 * To get the idea what might happen, see an example:
4292 * func1 -> sub rsp, 128
4293 * subfunc1 -> sub rsp, 256
4294 * tailcall1 -> add rsp, 256
4295 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4296 * subfunc2 -> sub rsp, 64
4297 * subfunc22 -> sub rsp, 128
4298 * tailcall2 -> add rsp, 128
4299 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4301 * tailcall will unwind the current stack frame but it will not get rid
4302 * of caller's stack as shown on the example above.
4304 if (idx && subprog[idx].has_tail_call && depth >= 256) {
4306 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4310 /* round up to 32-bytes, since this is granularity
4311 * of interpreter stack size
4313 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4314 if (depth > MAX_BPF_STACK) {
4315 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4320 subprog_end = subprog[idx + 1].start;
4321 for (; i < subprog_end; i++) {
4324 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4326 /* remember insn and function to return to */
4327 ret_insn[frame] = i + 1;
4328 ret_prog[frame] = idx;
4330 /* find the callee */
4331 next_insn = i + insn[i].imm + 1;
4332 idx = find_subprog(env, next_insn);
4334 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4338 if (subprog[idx].is_async_cb) {
4339 if (subprog[idx].has_tail_call) {
4340 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4343 /* async callbacks don't increase bpf prog stack size */
4348 if (subprog[idx].has_tail_call)
4349 tail_call_reachable = true;
4352 if (frame >= MAX_CALL_FRAMES) {
4353 verbose(env, "the call stack of %d frames is too deep !\n",
4359 /* if tail call got detected across bpf2bpf calls then mark each of the
4360 * currently present subprog frames as tail call reachable subprogs;
4361 * this info will be utilized by JIT so that we will be preserving the
4362 * tail call counter throughout bpf2bpf calls combined with tailcalls
4364 if (tail_call_reachable)
4365 for (j = 0; j < frame; j++)
4366 subprog[ret_prog[j]].tail_call_reachable = true;
4367 if (subprog[0].tail_call_reachable)
4368 env->prog->aux->tail_call_reachable = true;
4370 /* end of for() loop means the last insn of the 'subprog'
4371 * was reached. Doesn't matter whether it was JA or EXIT
4375 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4377 i = ret_insn[frame];
4378 idx = ret_prog[frame];
4382 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4383 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4384 const struct bpf_insn *insn, int idx)
4386 int start = idx + insn->imm + 1, subprog;
4388 subprog = find_subprog(env, start);
4390 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4394 return env->subprog_info[subprog].stack_depth;
4398 static int __check_buffer_access(struct bpf_verifier_env *env,
4399 const char *buf_info,
4400 const struct bpf_reg_state *reg,
4401 int regno, int off, int size)
4405 "R%d invalid %s buffer access: off=%d, size=%d\n",
4406 regno, buf_info, off, size);
4409 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4412 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4414 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4415 regno, off, tn_buf);
4422 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4423 const struct bpf_reg_state *reg,
4424 int regno, int off, int size)
4428 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4432 if (off + size > env->prog->aux->max_tp_access)
4433 env->prog->aux->max_tp_access = off + size;
4438 static int check_buffer_access(struct bpf_verifier_env *env,
4439 const struct bpf_reg_state *reg,
4440 int regno, int off, int size,
4441 bool zero_size_allowed,
4444 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4447 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4451 if (off + size > *max_access)
4452 *max_access = off + size;
4457 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4458 static void zext_32_to_64(struct bpf_reg_state *reg)
4460 reg->var_off = tnum_subreg(reg->var_off);
4461 __reg_assign_32_into_64(reg);
4464 /* truncate register to smaller size (in bytes)
4465 * must be called with size < BPF_REG_SIZE
4467 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4471 /* clear high bits in bit representation */
4472 reg->var_off = tnum_cast(reg->var_off, size);
4474 /* fix arithmetic bounds */
4475 mask = ((u64)1 << (size * 8)) - 1;
4476 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4477 reg->umin_value &= mask;
4478 reg->umax_value &= mask;
4480 reg->umin_value = 0;
4481 reg->umax_value = mask;
4483 reg->smin_value = reg->umin_value;
4484 reg->smax_value = reg->umax_value;
4486 /* If size is smaller than 32bit register the 32bit register
4487 * values are also truncated so we push 64-bit bounds into
4488 * 32-bit bounds. Above were truncated < 32-bits already.
4492 __reg_combine_64_into_32(reg);
4495 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4497 /* A map is considered read-only if the following condition are true:
4499 * 1) BPF program side cannot change any of the map content. The
4500 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4501 * and was set at map creation time.
4502 * 2) The map value(s) have been initialized from user space by a
4503 * loader and then "frozen", such that no new map update/delete
4504 * operations from syscall side are possible for the rest of
4505 * the map's lifetime from that point onwards.
4506 * 3) Any parallel/pending map update/delete operations from syscall
4507 * side have been completed. Only after that point, it's safe to
4508 * assume that map value(s) are immutable.
4510 return (map->map_flags & BPF_F_RDONLY_PROG) &&
4511 READ_ONCE(map->frozen) &&
4512 !bpf_map_write_active(map);
4515 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4521 err = map->ops->map_direct_value_addr(map, &addr, off);
4524 ptr = (void *)(long)addr + off;
4528 *val = (u64)*(u8 *)ptr;
4531 *val = (u64)*(u16 *)ptr;
4534 *val = (u64)*(u32 *)ptr;
4545 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4546 struct bpf_reg_state *regs,
4547 int regno, int off, int size,
4548 enum bpf_access_type atype,
4551 struct bpf_reg_state *reg = regs + regno;
4552 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4553 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4554 enum bpf_type_flag flag = 0;
4560 "R%d is ptr_%s invalid negative access: off=%d\n",
4564 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4567 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4569 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4570 regno, tname, off, tn_buf);
4574 if (reg->type & MEM_USER) {
4576 "R%d is ptr_%s access user memory: off=%d\n",
4581 if (reg->type & MEM_PERCPU) {
4583 "R%d is ptr_%s access percpu memory: off=%d\n",
4588 if (env->ops->btf_struct_access) {
4589 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4590 off, size, atype, &btf_id, &flag);
4592 if (atype != BPF_READ) {
4593 verbose(env, "only read is supported\n");
4597 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4598 atype, &btf_id, &flag);
4604 /* If this is an untrusted pointer, all pointers formed by walking it
4605 * also inherit the untrusted flag.
4607 if (type_flag(reg->type) & PTR_UNTRUSTED)
4608 flag |= PTR_UNTRUSTED;
4610 if (atype == BPF_READ && value_regno >= 0)
4611 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4616 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4617 struct bpf_reg_state *regs,
4618 int regno, int off, int size,
4619 enum bpf_access_type atype,
4622 struct bpf_reg_state *reg = regs + regno;
4623 struct bpf_map *map = reg->map_ptr;
4624 enum bpf_type_flag flag = 0;
4625 const struct btf_type *t;
4631 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4635 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4636 verbose(env, "map_ptr access not supported for map type %d\n",
4641 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4642 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4644 if (!env->allow_ptr_to_map_access) {
4646 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4652 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4657 if (atype != BPF_READ) {
4658 verbose(env, "only read from %s is supported\n", tname);
4662 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4666 if (value_regno >= 0)
4667 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4672 /* Check that the stack access at the given offset is within bounds. The
4673 * maximum valid offset is -1.
4675 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4676 * -state->allocated_stack for reads.
4678 static int check_stack_slot_within_bounds(int off,
4679 struct bpf_func_state *state,
4680 enum bpf_access_type t)
4685 min_valid_off = -MAX_BPF_STACK;
4687 min_valid_off = -state->allocated_stack;
4689 if (off < min_valid_off || off > -1)
4694 /* Check that the stack access at 'regno + off' falls within the maximum stack
4697 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4699 static int check_stack_access_within_bounds(
4700 struct bpf_verifier_env *env,
4701 int regno, int off, int access_size,
4702 enum bpf_access_src src, enum bpf_access_type type)
4704 struct bpf_reg_state *regs = cur_regs(env);
4705 struct bpf_reg_state *reg = regs + regno;
4706 struct bpf_func_state *state = func(env, reg);
4707 int min_off, max_off;
4711 if (src == ACCESS_HELPER)
4712 /* We don't know if helpers are reading or writing (or both). */
4713 err_extra = " indirect access to";
4714 else if (type == BPF_READ)
4715 err_extra = " read from";
4717 err_extra = " write to";
4719 if (tnum_is_const(reg->var_off)) {
4720 min_off = reg->var_off.value + off;
4721 if (access_size > 0)
4722 max_off = min_off + access_size - 1;
4726 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4727 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4728 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4732 min_off = reg->smin_value + off;
4733 if (access_size > 0)
4734 max_off = reg->smax_value + off + access_size - 1;
4739 err = check_stack_slot_within_bounds(min_off, state, type);
4741 err = check_stack_slot_within_bounds(max_off, state, type);
4744 if (tnum_is_const(reg->var_off)) {
4745 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4746 err_extra, regno, off, access_size);
4750 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4751 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4752 err_extra, regno, tn_buf, access_size);
4758 /* check whether memory at (regno + off) is accessible for t = (read | write)
4759 * if t==write, value_regno is a register which value is stored into memory
4760 * if t==read, value_regno is a register which will receive the value from memory
4761 * if t==write && value_regno==-1, some unknown value is stored into memory
4762 * if t==read && value_regno==-1, don't care what we read from memory
4764 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4765 int off, int bpf_size, enum bpf_access_type t,
4766 int value_regno, bool strict_alignment_once)
4768 struct bpf_reg_state *regs = cur_regs(env);
4769 struct bpf_reg_state *reg = regs + regno;
4770 struct bpf_func_state *state;
4773 size = bpf_size_to_bytes(bpf_size);
4777 /* alignment checks will add in reg->off themselves */
4778 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4782 /* for access checks, reg->off is just part of off */
4785 if (reg->type == PTR_TO_MAP_KEY) {
4786 if (t == BPF_WRITE) {
4787 verbose(env, "write to change key R%d not allowed\n", regno);
4791 err = check_mem_region_access(env, regno, off, size,
4792 reg->map_ptr->key_size, false);
4795 if (value_regno >= 0)
4796 mark_reg_unknown(env, regs, value_regno);
4797 } else if (reg->type == PTR_TO_MAP_VALUE) {
4798 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4800 if (t == BPF_WRITE && value_regno >= 0 &&
4801 is_pointer_value(env, value_regno)) {
4802 verbose(env, "R%d leaks addr into map\n", value_regno);
4805 err = check_map_access_type(env, regno, off, size, t);
4808 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4811 if (tnum_is_const(reg->var_off))
4812 kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4813 off + reg->var_off.value);
4814 if (kptr_off_desc) {
4815 err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4817 } else if (t == BPF_READ && value_regno >= 0) {
4818 struct bpf_map *map = reg->map_ptr;
4820 /* if map is read-only, track its contents as scalars */
4821 if (tnum_is_const(reg->var_off) &&
4822 bpf_map_is_rdonly(map) &&
4823 map->ops->map_direct_value_addr) {
4824 int map_off = off + reg->var_off.value;
4827 err = bpf_map_direct_read(map, map_off, size,
4832 regs[value_regno].type = SCALAR_VALUE;
4833 __mark_reg_known(®s[value_regno], val);
4835 mark_reg_unknown(env, regs, value_regno);
4838 } else if (base_type(reg->type) == PTR_TO_MEM) {
4839 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4841 if (type_may_be_null(reg->type)) {
4842 verbose(env, "R%d invalid mem access '%s'\n", regno,
4843 reg_type_str(env, reg->type));
4847 if (t == BPF_WRITE && rdonly_mem) {
4848 verbose(env, "R%d cannot write into %s\n",
4849 regno, reg_type_str(env, reg->type));
4853 if (t == BPF_WRITE && value_regno >= 0 &&
4854 is_pointer_value(env, value_regno)) {
4855 verbose(env, "R%d leaks addr into mem\n", value_regno);
4859 err = check_mem_region_access(env, regno, off, size,
4860 reg->mem_size, false);
4861 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4862 mark_reg_unknown(env, regs, value_regno);
4863 } else if (reg->type == PTR_TO_CTX) {
4864 enum bpf_reg_type reg_type = SCALAR_VALUE;
4865 struct btf *btf = NULL;
4868 if (t == BPF_WRITE && value_regno >= 0 &&
4869 is_pointer_value(env, value_regno)) {
4870 verbose(env, "R%d leaks addr into ctx\n", value_regno);
4874 err = check_ptr_off_reg(env, reg, regno);
4878 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
4881 verbose_linfo(env, insn_idx, "; ");
4882 if (!err && t == BPF_READ && value_regno >= 0) {
4883 /* ctx access returns either a scalar, or a
4884 * PTR_TO_PACKET[_META,_END]. In the latter
4885 * case, we know the offset is zero.
4887 if (reg_type == SCALAR_VALUE) {
4888 mark_reg_unknown(env, regs, value_regno);
4890 mark_reg_known_zero(env, regs,
4892 if (type_may_be_null(reg_type))
4893 regs[value_regno].id = ++env->id_gen;
4894 /* A load of ctx field could have different
4895 * actual load size with the one encoded in the
4896 * insn. When the dst is PTR, it is for sure not
4899 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4900 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4901 regs[value_regno].btf = btf;
4902 regs[value_regno].btf_id = btf_id;
4905 regs[value_regno].type = reg_type;
4908 } else if (reg->type == PTR_TO_STACK) {
4909 /* Basic bounds checks. */
4910 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4914 state = func(env, reg);
4915 err = update_stack_depth(env, state, off);
4920 err = check_stack_read(env, regno, off, size,
4923 err = check_stack_write(env, regno, off, size,
4924 value_regno, insn_idx);
4925 } else if (reg_is_pkt_pointer(reg)) {
4926 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4927 verbose(env, "cannot write into packet\n");
4930 if (t == BPF_WRITE && value_regno >= 0 &&
4931 is_pointer_value(env, value_regno)) {
4932 verbose(env, "R%d leaks addr into packet\n",
4936 err = check_packet_access(env, regno, off, size, false);
4937 if (!err && t == BPF_READ && value_regno >= 0)
4938 mark_reg_unknown(env, regs, value_regno);
4939 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4940 if (t == BPF_WRITE && value_regno >= 0 &&
4941 is_pointer_value(env, value_regno)) {
4942 verbose(env, "R%d leaks addr into flow keys\n",
4947 err = check_flow_keys_access(env, off, size);
4948 if (!err && t == BPF_READ && value_regno >= 0)
4949 mark_reg_unknown(env, regs, value_regno);
4950 } else if (type_is_sk_pointer(reg->type)) {
4951 if (t == BPF_WRITE) {
4952 verbose(env, "R%d cannot write into %s\n",
4953 regno, reg_type_str(env, reg->type));
4956 err = check_sock_access(env, insn_idx, regno, off, size, t);
4957 if (!err && value_regno >= 0)
4958 mark_reg_unknown(env, regs, value_regno);
4959 } else if (reg->type == PTR_TO_TP_BUFFER) {
4960 err = check_tp_buffer_access(env, reg, regno, off, size);
4961 if (!err && t == BPF_READ && value_regno >= 0)
4962 mark_reg_unknown(env, regs, value_regno);
4963 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4964 !type_may_be_null(reg->type)) {
4965 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4967 } else if (reg->type == CONST_PTR_TO_MAP) {
4968 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4970 } else if (base_type(reg->type) == PTR_TO_BUF) {
4971 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4975 if (t == BPF_WRITE) {
4976 verbose(env, "R%d cannot write into %s\n",
4977 regno, reg_type_str(env, reg->type));
4980 max_access = &env->prog->aux->max_rdonly_access;
4982 max_access = &env->prog->aux->max_rdwr_access;
4985 err = check_buffer_access(env, reg, regno, off, size, false,
4988 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4989 mark_reg_unknown(env, regs, value_regno);
4991 verbose(env, "R%d invalid mem access '%s'\n", regno,
4992 reg_type_str(env, reg->type));
4996 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4997 regs[value_regno].type == SCALAR_VALUE) {
4998 /* b/h/w load zero-extends, mark upper bits as known 0 */
4999 coerce_reg_to_size(®s[value_regno], size);
5004 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5009 switch (insn->imm) {
5011 case BPF_ADD | BPF_FETCH:
5013 case BPF_AND | BPF_FETCH:
5015 case BPF_OR | BPF_FETCH:
5017 case BPF_XOR | BPF_FETCH:
5022 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5026 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5027 verbose(env, "invalid atomic operand size\n");
5031 /* check src1 operand */
5032 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5036 /* check src2 operand */
5037 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5041 if (insn->imm == BPF_CMPXCHG) {
5042 /* Check comparison of R0 with memory location */
5043 const u32 aux_reg = BPF_REG_0;
5045 err = check_reg_arg(env, aux_reg, SRC_OP);
5049 if (is_pointer_value(env, aux_reg)) {
5050 verbose(env, "R%d leaks addr into mem\n", aux_reg);
5055 if (is_pointer_value(env, insn->src_reg)) {
5056 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5060 if (is_ctx_reg(env, insn->dst_reg) ||
5061 is_pkt_reg(env, insn->dst_reg) ||
5062 is_flow_key_reg(env, insn->dst_reg) ||
5063 is_sk_reg(env, insn->dst_reg)) {
5064 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5066 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5070 if (insn->imm & BPF_FETCH) {
5071 if (insn->imm == BPF_CMPXCHG)
5072 load_reg = BPF_REG_0;
5074 load_reg = insn->src_reg;
5076 /* check and record load of old value */
5077 err = check_reg_arg(env, load_reg, DST_OP);
5081 /* This instruction accesses a memory location but doesn't
5082 * actually load it into a register.
5087 /* Check whether we can read the memory, with second call for fetch
5088 * case to simulate the register fill.
5090 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5091 BPF_SIZE(insn->code), BPF_READ, -1, true);
5092 if (!err && load_reg >= 0)
5093 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5094 BPF_SIZE(insn->code), BPF_READ, load_reg,
5099 /* Check whether we can write into the same memory. */
5100 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5101 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5108 /* When register 'regno' is used to read the stack (either directly or through
5109 * a helper function) make sure that it's within stack boundary and, depending
5110 * on the access type, that all elements of the stack are initialized.
5112 * 'off' includes 'regno->off', but not its dynamic part (if any).
5114 * All registers that have been spilled on the stack in the slots within the
5115 * read offsets are marked as read.
5117 static int check_stack_range_initialized(
5118 struct bpf_verifier_env *env, int regno, int off,
5119 int access_size, bool zero_size_allowed,
5120 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5122 struct bpf_reg_state *reg = reg_state(env, regno);
5123 struct bpf_func_state *state = func(env, reg);
5124 int err, min_off, max_off, i, j, slot, spi;
5125 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5126 enum bpf_access_type bounds_check_type;
5127 /* Some accesses can write anything into the stack, others are
5130 bool clobber = false;
5132 if (access_size == 0 && !zero_size_allowed) {
5133 verbose(env, "invalid zero-sized read\n");
5137 if (type == ACCESS_HELPER) {
5138 /* The bounds checks for writes are more permissive than for
5139 * reads. However, if raw_mode is not set, we'll do extra
5142 bounds_check_type = BPF_WRITE;
5145 bounds_check_type = BPF_READ;
5147 err = check_stack_access_within_bounds(env, regno, off, access_size,
5148 type, bounds_check_type);
5153 if (tnum_is_const(reg->var_off)) {
5154 min_off = max_off = reg->var_off.value + off;
5156 /* Variable offset is prohibited for unprivileged mode for
5157 * simplicity since it requires corresponding support in
5158 * Spectre masking for stack ALU.
5159 * See also retrieve_ptr_limit().
5161 if (!env->bypass_spec_v1) {
5164 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5165 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5166 regno, err_extra, tn_buf);
5169 /* Only initialized buffer on stack is allowed to be accessed
5170 * with variable offset. With uninitialized buffer it's hard to
5171 * guarantee that whole memory is marked as initialized on
5172 * helper return since specific bounds are unknown what may
5173 * cause uninitialized stack leaking.
5175 if (meta && meta->raw_mode)
5178 min_off = reg->smin_value + off;
5179 max_off = reg->smax_value + off;
5182 if (meta && meta->raw_mode) {
5183 meta->access_size = access_size;
5184 meta->regno = regno;
5188 for (i = min_off; i < max_off + access_size; i++) {
5192 spi = slot / BPF_REG_SIZE;
5193 if (state->allocated_stack <= slot)
5195 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5196 if (*stype == STACK_MISC)
5198 if (*stype == STACK_ZERO) {
5200 /* helper can write anything into the stack */
5201 *stype = STACK_MISC;
5206 if (is_spilled_reg(&state->stack[spi]) &&
5207 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5208 env->allow_ptr_leaks)) {
5210 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5211 for (j = 0; j < BPF_REG_SIZE; j++)
5212 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5218 if (tnum_is_const(reg->var_off)) {
5219 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5220 err_extra, regno, min_off, i - min_off, access_size);
5224 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5225 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5226 err_extra, regno, tn_buf, i - min_off, access_size);
5230 /* reading any byte out of 8-byte 'spill_slot' will cause
5231 * the whole slot to be marked as 'read'
5233 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5234 state->stack[spi].spilled_ptr.parent,
5236 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5237 * be sure that whether stack slot is written to or not. Hence,
5238 * we must still conservatively propagate reads upwards even if
5239 * helper may write to the entire memory range.
5242 return update_stack_depth(env, state, min_off);
5245 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5246 int access_size, bool zero_size_allowed,
5247 struct bpf_call_arg_meta *meta)
5249 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5252 switch (base_type(reg->type)) {
5254 case PTR_TO_PACKET_META:
5255 return check_packet_access(env, regno, reg->off, access_size,
5257 case PTR_TO_MAP_KEY:
5258 if (meta && meta->raw_mode) {
5259 verbose(env, "R%d cannot write into %s\n", regno,
5260 reg_type_str(env, reg->type));
5263 return check_mem_region_access(env, regno, reg->off, access_size,
5264 reg->map_ptr->key_size, false);
5265 case PTR_TO_MAP_VALUE:
5266 if (check_map_access_type(env, regno, reg->off, access_size,
5267 meta && meta->raw_mode ? BPF_WRITE :
5270 return check_map_access(env, regno, reg->off, access_size,
5271 zero_size_allowed, ACCESS_HELPER);
5273 if (type_is_rdonly_mem(reg->type)) {
5274 if (meta && meta->raw_mode) {
5275 verbose(env, "R%d cannot write into %s\n", regno,
5276 reg_type_str(env, reg->type));
5280 return check_mem_region_access(env, regno, reg->off,
5281 access_size, reg->mem_size,
5284 if (type_is_rdonly_mem(reg->type)) {
5285 if (meta && meta->raw_mode) {
5286 verbose(env, "R%d cannot write into %s\n", regno,
5287 reg_type_str(env, reg->type));
5291 max_access = &env->prog->aux->max_rdonly_access;
5293 max_access = &env->prog->aux->max_rdwr_access;
5295 return check_buffer_access(env, reg, regno, reg->off,
5296 access_size, zero_size_allowed,
5299 return check_stack_range_initialized(
5301 regno, reg->off, access_size,
5302 zero_size_allowed, ACCESS_HELPER, meta);
5304 /* in case the function doesn't know how to access the context,
5305 * (because we are in a program of type SYSCALL for example), we
5306 * can not statically check its size.
5307 * Dynamically check it now.
5309 if (!env->ops->convert_ctx_access) {
5310 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5311 int offset = access_size - 1;
5313 /* Allow zero-byte read from PTR_TO_CTX */
5314 if (access_size == 0)
5315 return zero_size_allowed ? 0 : -EACCES;
5317 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5322 default: /* scalar_value or invalid ptr */
5323 /* Allow zero-byte read from NULL, regardless of pointer type */
5324 if (zero_size_allowed && access_size == 0 &&
5325 register_is_null(reg))
5328 verbose(env, "R%d type=%s ", regno,
5329 reg_type_str(env, reg->type));
5330 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5335 static int check_mem_size_reg(struct bpf_verifier_env *env,
5336 struct bpf_reg_state *reg, u32 regno,
5337 bool zero_size_allowed,
5338 struct bpf_call_arg_meta *meta)
5342 /* This is used to refine r0 return value bounds for helpers
5343 * that enforce this value as an upper bound on return values.
5344 * See do_refine_retval_range() for helpers that can refine
5345 * the return value. C type of helper is u32 so we pull register
5346 * bound from umax_value however, if negative verifier errors
5347 * out. Only upper bounds can be learned because retval is an
5348 * int type and negative retvals are allowed.
5350 meta->msize_max_value = reg->umax_value;
5352 /* The register is SCALAR_VALUE; the access check
5353 * happens using its boundaries.
5355 if (!tnum_is_const(reg->var_off))
5356 /* For unprivileged variable accesses, disable raw
5357 * mode so that the program is required to
5358 * initialize all the memory that the helper could
5359 * just partially fill up.
5363 if (reg->smin_value < 0) {
5364 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5369 if (reg->umin_value == 0) {
5370 err = check_helper_mem_access(env, regno - 1, 0,
5377 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5378 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5382 err = check_helper_mem_access(env, regno - 1,
5384 zero_size_allowed, meta);
5386 err = mark_chain_precision(env, regno);
5390 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5391 u32 regno, u32 mem_size)
5393 bool may_be_null = type_may_be_null(reg->type);
5394 struct bpf_reg_state saved_reg;
5395 struct bpf_call_arg_meta meta;
5398 if (register_is_null(reg))
5401 memset(&meta, 0, sizeof(meta));
5402 /* Assuming that the register contains a value check if the memory
5403 * access is safe. Temporarily save and restore the register's state as
5404 * the conversion shouldn't be visible to a caller.
5408 mark_ptr_not_null_reg(reg);
5411 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5412 /* Check access for BPF_WRITE */
5413 meta.raw_mode = true;
5414 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5422 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5425 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5426 bool may_be_null = type_may_be_null(mem_reg->type);
5427 struct bpf_reg_state saved_reg;
5428 struct bpf_call_arg_meta meta;
5431 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5433 memset(&meta, 0, sizeof(meta));
5436 saved_reg = *mem_reg;
5437 mark_ptr_not_null_reg(mem_reg);
5440 err = check_mem_size_reg(env, reg, regno, true, &meta);
5441 /* Check access for BPF_WRITE */
5442 meta.raw_mode = true;
5443 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5446 *mem_reg = saved_reg;
5450 /* Implementation details:
5451 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5452 * Two bpf_map_lookups (even with the same key) will have different reg->id.
5453 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5454 * value_or_null->value transition, since the verifier only cares about
5455 * the range of access to valid map value pointer and doesn't care about actual
5456 * address of the map element.
5457 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5458 * reg->id > 0 after value_or_null->value transition. By doing so
5459 * two bpf_map_lookups will be considered two different pointers that
5460 * point to different bpf_spin_locks.
5461 * The verifier allows taking only one bpf_spin_lock at a time to avoid
5463 * Since only one bpf_spin_lock is allowed the checks are simpler than
5464 * reg_is_refcounted() logic. The verifier needs to remember only
5465 * one spin_lock instead of array of acquired_refs.
5466 * cur_state->active_spin_lock remembers which map value element got locked
5467 * and clears it after bpf_spin_unlock.
5469 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5472 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5473 struct bpf_verifier_state *cur = env->cur_state;
5474 bool is_const = tnum_is_const(reg->var_off);
5475 struct bpf_map *map = reg->map_ptr;
5476 u64 val = reg->var_off.value;
5480 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5486 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5490 if (!map_value_has_spin_lock(map)) {
5491 if (map->spin_lock_off == -E2BIG)
5493 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5495 else if (map->spin_lock_off == -ENOENT)
5497 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5501 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5505 if (map->spin_lock_off != val + reg->off) {
5506 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5511 if (cur->active_spin_lock) {
5513 "Locking two bpf_spin_locks are not allowed\n");
5516 cur->active_spin_lock = reg->id;
5518 if (!cur->active_spin_lock) {
5519 verbose(env, "bpf_spin_unlock without taking a lock\n");
5522 if (cur->active_spin_lock != reg->id) {
5523 verbose(env, "bpf_spin_unlock of different lock\n");
5526 cur->active_spin_lock = 0;
5531 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5532 struct bpf_call_arg_meta *meta)
5534 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5535 bool is_const = tnum_is_const(reg->var_off);
5536 struct bpf_map *map = reg->map_ptr;
5537 u64 val = reg->var_off.value;
5541 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5546 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5550 if (!map_value_has_timer(map)) {
5551 if (map->timer_off == -E2BIG)
5553 "map '%s' has more than one 'struct bpf_timer'\n",
5555 else if (map->timer_off == -ENOENT)
5557 "map '%s' doesn't have 'struct bpf_timer'\n",
5561 "map '%s' is not a struct type or bpf_timer is mangled\n",
5565 if (map->timer_off != val + reg->off) {
5566 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5567 val + reg->off, map->timer_off);
5570 if (meta->map_ptr) {
5571 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5574 meta->map_uid = reg->map_uid;
5575 meta->map_ptr = map;
5579 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5580 struct bpf_call_arg_meta *meta)
5582 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5583 struct bpf_map_value_off_desc *off_desc;
5584 struct bpf_map *map_ptr = reg->map_ptr;
5588 if (!tnum_is_const(reg->var_off)) {
5590 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5594 if (!map_ptr->btf) {
5595 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5599 if (!map_value_has_kptrs(map_ptr)) {
5600 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5602 verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5603 BPF_MAP_VALUE_OFF_MAX);
5604 else if (ret == -EEXIST)
5605 verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5607 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5611 meta->map_ptr = map_ptr;
5612 kptr_off = reg->off + reg->var_off.value;
5613 off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5615 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5618 if (off_desc->type != BPF_KPTR_REF) {
5619 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5622 meta->kptr_off_desc = off_desc;
5626 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5628 return type == ARG_CONST_SIZE ||
5629 type == ARG_CONST_SIZE_OR_ZERO;
5632 static bool arg_type_is_release(enum bpf_arg_type type)
5634 return type & OBJ_RELEASE;
5637 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5639 return base_type(type) == ARG_PTR_TO_DYNPTR;
5642 static int int_ptr_type_to_size(enum bpf_arg_type type)
5644 if (type == ARG_PTR_TO_INT)
5646 else if (type == ARG_PTR_TO_LONG)
5652 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5653 const struct bpf_call_arg_meta *meta,
5654 enum bpf_arg_type *arg_type)
5656 if (!meta->map_ptr) {
5657 /* kernel subsystem misconfigured verifier */
5658 verbose(env, "invalid map_ptr to access map->type\n");
5662 switch (meta->map_ptr->map_type) {
5663 case BPF_MAP_TYPE_SOCKMAP:
5664 case BPF_MAP_TYPE_SOCKHASH:
5665 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5666 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5668 verbose(env, "invalid arg_type for sockmap/sockhash\n");
5672 case BPF_MAP_TYPE_BLOOM_FILTER:
5673 if (meta->func_id == BPF_FUNC_map_peek_elem)
5674 *arg_type = ARG_PTR_TO_MAP_VALUE;
5682 struct bpf_reg_types {
5683 const enum bpf_reg_type types[10];
5687 static const struct bpf_reg_types map_key_value_types = {
5697 static const struct bpf_reg_types sock_types = {
5707 static const struct bpf_reg_types btf_id_sock_common_types = {
5715 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5719 static const struct bpf_reg_types mem_types = {
5727 PTR_TO_MEM | MEM_ALLOC,
5732 static const struct bpf_reg_types int_ptr_types = {
5742 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5743 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5744 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5745 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5746 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5747 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5748 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5749 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5750 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5751 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5752 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5753 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5754 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5755 static const struct bpf_reg_types dynptr_types = {
5758 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5762 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5763 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
5764 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
5765 [ARG_CONST_SIZE] = &scalar_types,
5766 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
5767 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
5768 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
5769 [ARG_PTR_TO_CTX] = &context_types,
5770 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
5772 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5774 [ARG_PTR_TO_SOCKET] = &fullsock_types,
5775 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
5776 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
5777 [ARG_PTR_TO_MEM] = &mem_types,
5778 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
5779 [ARG_PTR_TO_INT] = &int_ptr_types,
5780 [ARG_PTR_TO_LONG] = &int_ptr_types,
5781 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
5782 [ARG_PTR_TO_FUNC] = &func_ptr_types,
5783 [ARG_PTR_TO_STACK] = &stack_ptr_types,
5784 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
5785 [ARG_PTR_TO_TIMER] = &timer_types,
5786 [ARG_PTR_TO_KPTR] = &kptr_types,
5787 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
5790 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5791 enum bpf_arg_type arg_type,
5792 const u32 *arg_btf_id,
5793 struct bpf_call_arg_meta *meta)
5795 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5796 enum bpf_reg_type expected, type = reg->type;
5797 const struct bpf_reg_types *compatible;
5800 compatible = compatible_reg_types[base_type(arg_type)];
5802 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5806 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5807 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5809 * Same for MAYBE_NULL:
5811 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5812 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5814 * Therefore we fold these flags depending on the arg_type before comparison.
5816 if (arg_type & MEM_RDONLY)
5817 type &= ~MEM_RDONLY;
5818 if (arg_type & PTR_MAYBE_NULL)
5819 type &= ~PTR_MAYBE_NULL;
5821 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5822 expected = compatible->types[i];
5823 if (expected == NOT_INIT)
5826 if (type == expected)
5830 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5831 for (j = 0; j + 1 < i; j++)
5832 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5833 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5837 if (reg->type == PTR_TO_BTF_ID) {
5838 /* For bpf_sk_release, it needs to match against first member
5839 * 'struct sock_common', hence make an exception for it. This
5840 * allows bpf_sk_release to work for multiple socket types.
5842 bool strict_type_match = arg_type_is_release(arg_type) &&
5843 meta->func_id != BPF_FUNC_sk_release;
5846 if (!compatible->btf_id) {
5847 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5850 arg_btf_id = compatible->btf_id;
5853 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5854 if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5857 if (arg_btf_id == BPF_PTR_POISON) {
5858 verbose(env, "verifier internal error:");
5859 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5864 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5865 btf_vmlinux, *arg_btf_id,
5866 strict_type_match)) {
5867 verbose(env, "R%d is of type %s but %s is expected\n",
5868 regno, kernel_type_name(reg->btf, reg->btf_id),
5869 kernel_type_name(btf_vmlinux, *arg_btf_id));
5878 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5879 const struct bpf_reg_state *reg, int regno,
5880 enum bpf_arg_type arg_type)
5882 enum bpf_reg_type type = reg->type;
5883 bool fixed_off_ok = false;
5885 switch ((u32)type) {
5886 /* Pointer types where reg offset is explicitly allowed: */
5888 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5889 verbose(env, "cannot pass in dynptr at an offset\n");
5894 case PTR_TO_PACKET_META:
5895 case PTR_TO_MAP_KEY:
5896 case PTR_TO_MAP_VALUE:
5898 case PTR_TO_MEM | MEM_RDONLY:
5899 case PTR_TO_MEM | MEM_ALLOC:
5901 case PTR_TO_BUF | MEM_RDONLY:
5903 /* Some of the argument types nevertheless require a
5904 * zero register offset.
5906 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5909 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5913 /* When referenced PTR_TO_BTF_ID is passed to release function,
5914 * it's fixed offset must be 0. In the other cases, fixed offset
5917 if (arg_type_is_release(arg_type) && reg->off) {
5918 verbose(env, "R%d must have zero offset when passed to release func\n",
5922 /* For arg is release pointer, fixed_off_ok must be false, but
5923 * we already checked and rejected reg->off != 0 above, so set
5924 * to true to allow fixed offset for all other cases.
5926 fixed_off_ok = true;
5931 return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5934 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5936 struct bpf_func_state *state = func(env, reg);
5937 int spi = get_spi(reg->off);
5939 return state->stack[spi].spilled_ptr.id;
5942 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5943 struct bpf_call_arg_meta *meta,
5944 const struct bpf_func_proto *fn)
5946 u32 regno = BPF_REG_1 + arg;
5947 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5948 enum bpf_arg_type arg_type = fn->arg_type[arg];
5949 enum bpf_reg_type type = reg->type;
5950 u32 *arg_btf_id = NULL;
5953 if (arg_type == ARG_DONTCARE)
5956 err = check_reg_arg(env, regno, SRC_OP);
5960 if (arg_type == ARG_ANYTHING) {
5961 if (is_pointer_value(env, regno)) {
5962 verbose(env, "R%d leaks addr into helper function\n",
5969 if (type_is_pkt_pointer(type) &&
5970 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5971 verbose(env, "helper access to the packet is not allowed\n");
5975 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5976 err = resolve_map_arg_type(env, meta, &arg_type);
5981 if (register_is_null(reg) && type_may_be_null(arg_type))
5982 /* A NULL register has a SCALAR_VALUE type, so skip
5985 goto skip_type_check;
5987 /* arg_btf_id and arg_size are in a union. */
5988 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5989 arg_btf_id = fn->arg_btf_id[arg];
5991 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5995 err = check_func_arg_reg_off(env, reg, regno, arg_type);
6000 if (arg_type_is_release(arg_type)) {
6001 if (arg_type_is_dynptr(arg_type)) {
6002 struct bpf_func_state *state = func(env, reg);
6003 int spi = get_spi(reg->off);
6005 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6006 !state->stack[spi].spilled_ptr.id) {
6007 verbose(env, "arg %d is an unacquired reference\n", regno);
6010 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
6011 verbose(env, "R%d must be referenced when passed to release function\n",
6015 if (meta->release_regno) {
6016 verbose(env, "verifier internal error: more than one release argument\n");
6019 meta->release_regno = regno;
6022 if (reg->ref_obj_id) {
6023 if (meta->ref_obj_id) {
6024 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6025 regno, reg->ref_obj_id,
6029 meta->ref_obj_id = reg->ref_obj_id;
6032 switch (base_type(arg_type)) {
6033 case ARG_CONST_MAP_PTR:
6034 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6035 if (meta->map_ptr) {
6036 /* Use map_uid (which is unique id of inner map) to reject:
6037 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6038 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6039 * if (inner_map1 && inner_map2) {
6040 * timer = bpf_map_lookup_elem(inner_map1);
6042 * // mismatch would have been allowed
6043 * bpf_timer_init(timer, inner_map2);
6046 * Comparing map_ptr is enough to distinguish normal and outer maps.
6048 if (meta->map_ptr != reg->map_ptr ||
6049 meta->map_uid != reg->map_uid) {
6051 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6052 meta->map_uid, reg->map_uid);
6056 meta->map_ptr = reg->map_ptr;
6057 meta->map_uid = reg->map_uid;
6059 case ARG_PTR_TO_MAP_KEY:
6060 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6061 * check that [key, key + map->key_size) are within
6062 * stack limits and initialized
6064 if (!meta->map_ptr) {
6065 /* in function declaration map_ptr must come before
6066 * map_key, so that it's verified and known before
6067 * we have to check map_key here. Otherwise it means
6068 * that kernel subsystem misconfigured verifier
6070 verbose(env, "invalid map_ptr to access map->key\n");
6073 err = check_helper_mem_access(env, regno,
6074 meta->map_ptr->key_size, false,
6077 case ARG_PTR_TO_MAP_VALUE:
6078 if (type_may_be_null(arg_type) && register_is_null(reg))
6081 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6082 * check [value, value + map->value_size) validity
6084 if (!meta->map_ptr) {
6085 /* kernel subsystem misconfigured verifier */
6086 verbose(env, "invalid map_ptr to access map->value\n");
6089 meta->raw_mode = arg_type & MEM_UNINIT;
6090 err = check_helper_mem_access(env, regno,
6091 meta->map_ptr->value_size, false,
6094 case ARG_PTR_TO_PERCPU_BTF_ID:
6096 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6099 meta->ret_btf = reg->btf;
6100 meta->ret_btf_id = reg->btf_id;
6102 case ARG_PTR_TO_SPIN_LOCK:
6103 if (meta->func_id == BPF_FUNC_spin_lock) {
6104 if (process_spin_lock(env, regno, true))
6106 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6107 if (process_spin_lock(env, regno, false))
6110 verbose(env, "verifier internal error\n");
6114 case ARG_PTR_TO_TIMER:
6115 if (process_timer_func(env, regno, meta))
6118 case ARG_PTR_TO_FUNC:
6119 meta->subprogno = reg->subprogno;
6121 case ARG_PTR_TO_MEM:
6122 /* The access to this pointer is only checked when we hit the
6123 * next is_mem_size argument below.
6125 meta->raw_mode = arg_type & MEM_UNINIT;
6126 if (arg_type & MEM_FIXED_SIZE) {
6127 err = check_helper_mem_access(env, regno,
6128 fn->arg_size[arg], false,
6132 case ARG_CONST_SIZE:
6133 err = check_mem_size_reg(env, reg, regno, false, meta);
6135 case ARG_CONST_SIZE_OR_ZERO:
6136 err = check_mem_size_reg(env, reg, regno, true, meta);
6138 case ARG_PTR_TO_DYNPTR:
6139 /* We only need to check for initialized / uninitialized helper
6140 * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6141 * assumption is that if it is, that a helper function
6142 * initialized the dynptr on behalf of the BPF program.
6144 if (base_type(reg->type) == PTR_TO_DYNPTR)
6146 if (arg_type & MEM_UNINIT) {
6147 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6148 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6152 /* We only support one dynptr being uninitialized at the moment,
6153 * which is sufficient for the helper functions we have right now.
6155 if (meta->uninit_dynptr_regno) {
6156 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6160 meta->uninit_dynptr_regno = regno;
6161 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6163 "Expected an initialized dynptr as arg #%d\n",
6166 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6167 const char *err_extra = "";
6169 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6170 case DYNPTR_TYPE_LOCAL:
6171 err_extra = "local";
6173 case DYNPTR_TYPE_RINGBUF:
6174 err_extra = "ringbuf";
6177 err_extra = "<unknown>";
6181 "Expected a dynptr of type %s as arg #%d\n",
6182 err_extra, arg + 1);
6186 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6187 if (!tnum_is_const(reg->var_off)) {
6188 verbose(env, "R%d is not a known constant'\n",
6192 meta->mem_size = reg->var_off.value;
6193 err = mark_chain_precision(env, regno);
6197 case ARG_PTR_TO_INT:
6198 case ARG_PTR_TO_LONG:
6200 int size = int_ptr_type_to_size(arg_type);
6202 err = check_helper_mem_access(env, regno, size, false, meta);
6205 err = check_ptr_alignment(env, reg, 0, size, true);
6208 case ARG_PTR_TO_CONST_STR:
6210 struct bpf_map *map = reg->map_ptr;
6215 if (!bpf_map_is_rdonly(map)) {
6216 verbose(env, "R%d does not point to a readonly map'\n", regno);
6220 if (!tnum_is_const(reg->var_off)) {
6221 verbose(env, "R%d is not a constant address'\n", regno);
6225 if (!map->ops->map_direct_value_addr) {
6226 verbose(env, "no direct value access support for this map type\n");
6230 err = check_map_access(env, regno, reg->off,
6231 map->value_size - reg->off, false,
6236 map_off = reg->off + reg->var_off.value;
6237 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6239 verbose(env, "direct value access on string failed\n");
6243 str_ptr = (char *)(long)(map_addr);
6244 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6245 verbose(env, "string is not zero-terminated\n");
6250 case ARG_PTR_TO_KPTR:
6251 if (process_kptr_func(env, regno, meta))
6259 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6261 enum bpf_attach_type eatype = env->prog->expected_attach_type;
6262 enum bpf_prog_type type = resolve_prog_type(env->prog);
6264 if (func_id != BPF_FUNC_map_update_elem)
6267 /* It's not possible to get access to a locked struct sock in these
6268 * contexts, so updating is safe.
6271 case BPF_PROG_TYPE_TRACING:
6272 if (eatype == BPF_TRACE_ITER)
6275 case BPF_PROG_TYPE_SOCKET_FILTER:
6276 case BPF_PROG_TYPE_SCHED_CLS:
6277 case BPF_PROG_TYPE_SCHED_ACT:
6278 case BPF_PROG_TYPE_XDP:
6279 case BPF_PROG_TYPE_SK_REUSEPORT:
6280 case BPF_PROG_TYPE_FLOW_DISSECTOR:
6281 case BPF_PROG_TYPE_SK_LOOKUP:
6287 verbose(env, "cannot update sockmap in this context\n");
6291 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6293 return env->prog->jit_requested &&
6294 bpf_jit_supports_subprog_tailcalls();
6297 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6298 struct bpf_map *map, int func_id)
6303 /* We need a two way check, first is from map perspective ... */
6304 switch (map->map_type) {
6305 case BPF_MAP_TYPE_PROG_ARRAY:
6306 if (func_id != BPF_FUNC_tail_call)
6309 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6310 if (func_id != BPF_FUNC_perf_event_read &&
6311 func_id != BPF_FUNC_perf_event_output &&
6312 func_id != BPF_FUNC_skb_output &&
6313 func_id != BPF_FUNC_perf_event_read_value &&
6314 func_id != BPF_FUNC_xdp_output)
6317 case BPF_MAP_TYPE_RINGBUF:
6318 if (func_id != BPF_FUNC_ringbuf_output &&
6319 func_id != BPF_FUNC_ringbuf_reserve &&
6320 func_id != BPF_FUNC_ringbuf_query &&
6321 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6322 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6323 func_id != BPF_FUNC_ringbuf_discard_dynptr)
6326 case BPF_MAP_TYPE_USER_RINGBUF:
6327 if (func_id != BPF_FUNC_user_ringbuf_drain)
6330 case BPF_MAP_TYPE_STACK_TRACE:
6331 if (func_id != BPF_FUNC_get_stackid)
6334 case BPF_MAP_TYPE_CGROUP_ARRAY:
6335 if (func_id != BPF_FUNC_skb_under_cgroup &&
6336 func_id != BPF_FUNC_current_task_under_cgroup)
6339 case BPF_MAP_TYPE_CGROUP_STORAGE:
6340 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6341 if (func_id != BPF_FUNC_get_local_storage)
6344 case BPF_MAP_TYPE_DEVMAP:
6345 case BPF_MAP_TYPE_DEVMAP_HASH:
6346 if (func_id != BPF_FUNC_redirect_map &&
6347 func_id != BPF_FUNC_map_lookup_elem)
6350 /* Restrict bpf side of cpumap and xskmap, open when use-cases
6353 case BPF_MAP_TYPE_CPUMAP:
6354 if (func_id != BPF_FUNC_redirect_map)
6357 case BPF_MAP_TYPE_XSKMAP:
6358 if (func_id != BPF_FUNC_redirect_map &&
6359 func_id != BPF_FUNC_map_lookup_elem)
6362 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6363 case BPF_MAP_TYPE_HASH_OF_MAPS:
6364 if (func_id != BPF_FUNC_map_lookup_elem)
6367 case BPF_MAP_TYPE_SOCKMAP:
6368 if (func_id != BPF_FUNC_sk_redirect_map &&
6369 func_id != BPF_FUNC_sock_map_update &&
6370 func_id != BPF_FUNC_map_delete_elem &&
6371 func_id != BPF_FUNC_msg_redirect_map &&
6372 func_id != BPF_FUNC_sk_select_reuseport &&
6373 func_id != BPF_FUNC_map_lookup_elem &&
6374 !may_update_sockmap(env, func_id))
6377 case BPF_MAP_TYPE_SOCKHASH:
6378 if (func_id != BPF_FUNC_sk_redirect_hash &&
6379 func_id != BPF_FUNC_sock_hash_update &&
6380 func_id != BPF_FUNC_map_delete_elem &&
6381 func_id != BPF_FUNC_msg_redirect_hash &&
6382 func_id != BPF_FUNC_sk_select_reuseport &&
6383 func_id != BPF_FUNC_map_lookup_elem &&
6384 !may_update_sockmap(env, func_id))
6387 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6388 if (func_id != BPF_FUNC_sk_select_reuseport)
6391 case BPF_MAP_TYPE_QUEUE:
6392 case BPF_MAP_TYPE_STACK:
6393 if (func_id != BPF_FUNC_map_peek_elem &&
6394 func_id != BPF_FUNC_map_pop_elem &&
6395 func_id != BPF_FUNC_map_push_elem)
6398 case BPF_MAP_TYPE_SK_STORAGE:
6399 if (func_id != BPF_FUNC_sk_storage_get &&
6400 func_id != BPF_FUNC_sk_storage_delete)
6403 case BPF_MAP_TYPE_INODE_STORAGE:
6404 if (func_id != BPF_FUNC_inode_storage_get &&
6405 func_id != BPF_FUNC_inode_storage_delete)
6408 case BPF_MAP_TYPE_TASK_STORAGE:
6409 if (func_id != BPF_FUNC_task_storage_get &&
6410 func_id != BPF_FUNC_task_storage_delete)
6413 case BPF_MAP_TYPE_BLOOM_FILTER:
6414 if (func_id != BPF_FUNC_map_peek_elem &&
6415 func_id != BPF_FUNC_map_push_elem)
6422 /* ... and second from the function itself. */
6424 case BPF_FUNC_tail_call:
6425 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6427 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6428 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6432 case BPF_FUNC_perf_event_read:
6433 case BPF_FUNC_perf_event_output:
6434 case BPF_FUNC_perf_event_read_value:
6435 case BPF_FUNC_skb_output:
6436 case BPF_FUNC_xdp_output:
6437 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6440 case BPF_FUNC_ringbuf_output:
6441 case BPF_FUNC_ringbuf_reserve:
6442 case BPF_FUNC_ringbuf_query:
6443 case BPF_FUNC_ringbuf_reserve_dynptr:
6444 case BPF_FUNC_ringbuf_submit_dynptr:
6445 case BPF_FUNC_ringbuf_discard_dynptr:
6446 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6449 case BPF_FUNC_user_ringbuf_drain:
6450 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6453 case BPF_FUNC_get_stackid:
6454 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6457 case BPF_FUNC_current_task_under_cgroup:
6458 case BPF_FUNC_skb_under_cgroup:
6459 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6462 case BPF_FUNC_redirect_map:
6463 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6464 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6465 map->map_type != BPF_MAP_TYPE_CPUMAP &&
6466 map->map_type != BPF_MAP_TYPE_XSKMAP)
6469 case BPF_FUNC_sk_redirect_map:
6470 case BPF_FUNC_msg_redirect_map:
6471 case BPF_FUNC_sock_map_update:
6472 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6475 case BPF_FUNC_sk_redirect_hash:
6476 case BPF_FUNC_msg_redirect_hash:
6477 case BPF_FUNC_sock_hash_update:
6478 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6481 case BPF_FUNC_get_local_storage:
6482 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6483 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6486 case BPF_FUNC_sk_select_reuseport:
6487 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6488 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6489 map->map_type != BPF_MAP_TYPE_SOCKHASH)
6492 case BPF_FUNC_map_pop_elem:
6493 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6494 map->map_type != BPF_MAP_TYPE_STACK)
6497 case BPF_FUNC_map_peek_elem:
6498 case BPF_FUNC_map_push_elem:
6499 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6500 map->map_type != BPF_MAP_TYPE_STACK &&
6501 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6504 case BPF_FUNC_map_lookup_percpu_elem:
6505 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6506 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6507 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6510 case BPF_FUNC_sk_storage_get:
6511 case BPF_FUNC_sk_storage_delete:
6512 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6515 case BPF_FUNC_inode_storage_get:
6516 case BPF_FUNC_inode_storage_delete:
6517 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6520 case BPF_FUNC_task_storage_get:
6521 case BPF_FUNC_task_storage_delete:
6522 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6531 verbose(env, "cannot pass map_type %d into func %s#%d\n",
6532 map->map_type, func_id_name(func_id), func_id);
6536 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6540 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6542 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6544 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6546 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6548 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6551 /* We only support one arg being in raw mode at the moment,
6552 * which is sufficient for the helper functions we have
6558 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6560 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6561 bool has_size = fn->arg_size[arg] != 0;
6562 bool is_next_size = false;
6564 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6565 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6567 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6568 return is_next_size;
6570 return has_size == is_next_size || is_next_size == is_fixed;
6573 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6575 /* bpf_xxx(..., buf, len) call will access 'len'
6576 * bytes from memory 'buf'. Both arg types need
6577 * to be paired, so make sure there's no buggy
6578 * helper function specification.
6580 if (arg_type_is_mem_size(fn->arg1_type) ||
6581 check_args_pair_invalid(fn, 0) ||
6582 check_args_pair_invalid(fn, 1) ||
6583 check_args_pair_invalid(fn, 2) ||
6584 check_args_pair_invalid(fn, 3) ||
6585 check_args_pair_invalid(fn, 4))
6591 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6595 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6596 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6599 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6600 /* arg_btf_id and arg_size are in a union. */
6601 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6602 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6609 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6611 return check_raw_mode_ok(fn) &&
6612 check_arg_pair_ok(fn) &&
6613 check_btf_id_ok(fn) ? 0 : -EINVAL;
6616 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6617 * are now invalid, so turn them into unknown SCALAR_VALUE.
6619 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6621 struct bpf_func_state *state;
6622 struct bpf_reg_state *reg;
6624 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6625 if (reg_is_pkt_pointer_any(reg))
6626 __mark_reg_unknown(env, reg);
6632 BEYOND_PKT_END = -2,
6635 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6637 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6638 struct bpf_reg_state *reg = &state->regs[regn];
6640 if (reg->type != PTR_TO_PACKET)
6641 /* PTR_TO_PACKET_META is not supported yet */
6644 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6645 * How far beyond pkt_end it goes is unknown.
6646 * if (!range_open) it's the case of pkt >= pkt_end
6647 * if (range_open) it's the case of pkt > pkt_end
6648 * hence this pointer is at least 1 byte bigger than pkt_end
6651 reg->range = BEYOND_PKT_END;
6653 reg->range = AT_PKT_END;
6656 /* The pointer with the specified id has released its reference to kernel
6657 * resources. Identify all copies of the same pointer and clear the reference.
6659 static int release_reference(struct bpf_verifier_env *env,
6662 struct bpf_func_state *state;
6663 struct bpf_reg_state *reg;
6666 err = release_reference_state(cur_func(env), ref_obj_id);
6670 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6671 if (reg->ref_obj_id == ref_obj_id) {
6672 if (!env->allow_ptr_leaks)
6673 __mark_reg_not_init(env, reg);
6675 __mark_reg_unknown(env, reg);
6682 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6683 struct bpf_reg_state *regs)
6687 /* after the call registers r0 - r5 were scratched */
6688 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6689 mark_reg_not_init(env, regs, caller_saved[i]);
6690 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6694 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6695 struct bpf_func_state *caller,
6696 struct bpf_func_state *callee,
6699 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6700 int *insn_idx, int subprog,
6701 set_callee_state_fn set_callee_state_cb)
6703 struct bpf_verifier_state *state = env->cur_state;
6704 struct bpf_func_info_aux *func_info_aux;
6705 struct bpf_func_state *caller, *callee;
6707 bool is_global = false;
6709 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6710 verbose(env, "the call stack of %d frames is too deep\n",
6711 state->curframe + 2);
6715 caller = state->frame[state->curframe];
6716 if (state->frame[state->curframe + 1]) {
6717 verbose(env, "verifier bug. Frame %d already allocated\n",
6718 state->curframe + 1);
6722 func_info_aux = env->prog->aux->func_info_aux;
6724 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6725 err = btf_check_subprog_call(env, subprog, caller->regs);
6730 verbose(env, "Caller passes invalid args into func#%d\n",
6734 if (env->log.level & BPF_LOG_LEVEL)
6736 "Func#%d is global and valid. Skipping.\n",
6738 clear_caller_saved_regs(env, caller->regs);
6740 /* All global functions return a 64-bit SCALAR_VALUE */
6741 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6742 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6744 /* continue with next insn after call */
6749 if (insn->code == (BPF_JMP | BPF_CALL) &&
6750 insn->src_reg == 0 &&
6751 insn->imm == BPF_FUNC_timer_set_callback) {
6752 struct bpf_verifier_state *async_cb;
6754 /* there is no real recursion here. timer callbacks are async */
6755 env->subprog_info[subprog].is_async_cb = true;
6756 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6757 *insn_idx, subprog);
6760 callee = async_cb->frame[0];
6761 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6763 /* Convert bpf_timer_set_callback() args into timer callback args */
6764 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6768 clear_caller_saved_regs(env, caller->regs);
6769 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6770 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6771 /* continue with next insn after call */
6775 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6778 state->frame[state->curframe + 1] = callee;
6780 /* callee cannot access r0, r6 - r9 for reading and has to write
6781 * into its own stack before reading from it.
6782 * callee can read/write into caller's stack
6784 init_func_state(env, callee,
6785 /* remember the callsite, it will be used by bpf_exit */
6786 *insn_idx /* callsite */,
6787 state->curframe + 1 /* frameno within this callchain */,
6788 subprog /* subprog number within this prog */);
6790 /* Transfer references to the callee */
6791 err = copy_reference_state(callee, caller);
6795 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6799 clear_caller_saved_regs(env, caller->regs);
6801 /* only increment it after check_reg_arg() finished */
6804 /* and go analyze first insn of the callee */
6805 *insn_idx = env->subprog_info[subprog].start - 1;
6807 if (env->log.level & BPF_LOG_LEVEL) {
6808 verbose(env, "caller:\n");
6809 print_verifier_state(env, caller, true);
6810 verbose(env, "callee:\n");
6811 print_verifier_state(env, callee, true);
6816 free_func_state(callee);
6817 state->frame[state->curframe + 1] = NULL;
6821 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6822 struct bpf_func_state *caller,
6823 struct bpf_func_state *callee)
6825 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6826 * void *callback_ctx, u64 flags);
6827 * callback_fn(struct bpf_map *map, void *key, void *value,
6828 * void *callback_ctx);
6830 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6832 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6833 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6834 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6836 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6837 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6838 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6840 /* pointer to stack or null */
6841 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6844 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6848 static int set_callee_state(struct bpf_verifier_env *env,
6849 struct bpf_func_state *caller,
6850 struct bpf_func_state *callee, int insn_idx)
6854 /* copy r1 - r5 args that callee can access. The copy includes parent
6855 * pointers, which connects us up to the liveness chain
6857 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6858 callee->regs[i] = caller->regs[i];
6862 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6865 int subprog, target_insn;
6867 target_insn = *insn_idx + insn->imm + 1;
6868 subprog = find_subprog(env, target_insn);
6870 verbose(env, "verifier bug. No program starts at insn %d\n",
6875 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6878 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6879 struct bpf_func_state *caller,
6880 struct bpf_func_state *callee,
6883 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6884 struct bpf_map *map;
6887 if (bpf_map_ptr_poisoned(insn_aux)) {
6888 verbose(env, "tail_call abusing map_ptr\n");
6892 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6893 if (!map->ops->map_set_for_each_callback_args ||
6894 !map->ops->map_for_each_callback) {
6895 verbose(env, "callback function not allowed for map\n");
6899 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6903 callee->in_callback_fn = true;
6904 callee->callback_ret_range = tnum_range(0, 1);
6908 static int set_loop_callback_state(struct bpf_verifier_env *env,
6909 struct bpf_func_state *caller,
6910 struct bpf_func_state *callee,
6913 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6915 * callback_fn(u32 index, void *callback_ctx);
6917 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6918 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6921 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6922 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6923 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6925 callee->in_callback_fn = true;
6926 callee->callback_ret_range = tnum_range(0, 1);
6930 static int set_timer_callback_state(struct bpf_verifier_env *env,
6931 struct bpf_func_state *caller,
6932 struct bpf_func_state *callee,
6935 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6937 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6938 * callback_fn(struct bpf_map *map, void *key, void *value);
6940 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6941 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6942 callee->regs[BPF_REG_1].map_ptr = map_ptr;
6944 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6945 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6946 callee->regs[BPF_REG_2].map_ptr = map_ptr;
6948 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6949 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6950 callee->regs[BPF_REG_3].map_ptr = map_ptr;
6953 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6954 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6955 callee->in_async_callback_fn = true;
6956 callee->callback_ret_range = tnum_range(0, 1);
6960 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6961 struct bpf_func_state *caller,
6962 struct bpf_func_state *callee,
6965 /* bpf_find_vma(struct task_struct *task, u64 addr,
6966 * void *callback_fn, void *callback_ctx, u64 flags)
6967 * (callback_fn)(struct task_struct *task,
6968 * struct vm_area_struct *vma, void *callback_ctx);
6970 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6972 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6973 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6974 callee->regs[BPF_REG_2].btf = btf_vmlinux;
6975 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6977 /* pointer to stack or null */
6978 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6981 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6982 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6983 callee->in_callback_fn = true;
6984 callee->callback_ret_range = tnum_range(0, 1);
6988 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
6989 struct bpf_func_state *caller,
6990 struct bpf_func_state *callee,
6993 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
6994 * callback_ctx, u64 flags);
6995 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
6997 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
6998 callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
6999 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7000 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7003 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7004 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7005 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7007 callee->in_callback_fn = true;
7008 callee->callback_ret_range = tnum_range(0, 1);
7012 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7014 struct bpf_verifier_state *state = env->cur_state;
7015 struct bpf_func_state *caller, *callee;
7016 struct bpf_reg_state *r0;
7019 callee = state->frame[state->curframe];
7020 r0 = &callee->regs[BPF_REG_0];
7021 if (r0->type == PTR_TO_STACK) {
7022 /* technically it's ok to return caller's stack pointer
7023 * (or caller's caller's pointer) back to the caller,
7024 * since these pointers are valid. Only current stack
7025 * pointer will be invalid as soon as function exits,
7026 * but let's be conservative
7028 verbose(env, "cannot return stack pointer to the caller\n");
7032 caller = state->frame[state->curframe - 1];
7033 if (callee->in_callback_fn) {
7034 /* enforce R0 return value range [0, 1]. */
7035 struct tnum range = callee->callback_ret_range;
7037 if (r0->type != SCALAR_VALUE) {
7038 verbose(env, "R0 not a scalar value\n");
7041 if (!tnum_in(range, r0->var_off)) {
7042 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7046 /* return to the caller whatever r0 had in the callee */
7047 caller->regs[BPF_REG_0] = *r0;
7050 /* callback_fn frame should have released its own additions to parent's
7051 * reference state at this point, or check_reference_leak would
7052 * complain, hence it must be the same as the caller. There is no need
7055 if (!callee->in_callback_fn) {
7056 /* Transfer references to the caller */
7057 err = copy_reference_state(caller, callee);
7062 *insn_idx = callee->callsite + 1;
7063 if (env->log.level & BPF_LOG_LEVEL) {
7064 verbose(env, "returning from callee:\n");
7065 print_verifier_state(env, callee, true);
7066 verbose(env, "to caller at %d:\n", *insn_idx);
7067 print_verifier_state(env, caller, true);
7069 /* clear everything in the callee */
7070 free_func_state(callee);
7071 state->frame[state->curframe--] = NULL;
7075 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7077 struct bpf_call_arg_meta *meta)
7079 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
7081 if (ret_type != RET_INTEGER ||
7082 (func_id != BPF_FUNC_get_stack &&
7083 func_id != BPF_FUNC_get_task_stack &&
7084 func_id != BPF_FUNC_probe_read_str &&
7085 func_id != BPF_FUNC_probe_read_kernel_str &&
7086 func_id != BPF_FUNC_probe_read_user_str))
7089 ret_reg->smax_value = meta->msize_max_value;
7090 ret_reg->s32_max_value = meta->msize_max_value;
7091 ret_reg->smin_value = -MAX_ERRNO;
7092 ret_reg->s32_min_value = -MAX_ERRNO;
7093 reg_bounds_sync(ret_reg);
7097 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7098 int func_id, int insn_idx)
7100 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7101 struct bpf_map *map = meta->map_ptr;
7103 if (func_id != BPF_FUNC_tail_call &&
7104 func_id != BPF_FUNC_map_lookup_elem &&
7105 func_id != BPF_FUNC_map_update_elem &&
7106 func_id != BPF_FUNC_map_delete_elem &&
7107 func_id != BPF_FUNC_map_push_elem &&
7108 func_id != BPF_FUNC_map_pop_elem &&
7109 func_id != BPF_FUNC_map_peek_elem &&
7110 func_id != BPF_FUNC_for_each_map_elem &&
7111 func_id != BPF_FUNC_redirect_map &&
7112 func_id != BPF_FUNC_map_lookup_percpu_elem)
7116 verbose(env, "kernel subsystem misconfigured verifier\n");
7120 /* In case of read-only, some additional restrictions
7121 * need to be applied in order to prevent altering the
7122 * state of the map from program side.
7124 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7125 (func_id == BPF_FUNC_map_delete_elem ||
7126 func_id == BPF_FUNC_map_update_elem ||
7127 func_id == BPF_FUNC_map_push_elem ||
7128 func_id == BPF_FUNC_map_pop_elem)) {
7129 verbose(env, "write into map forbidden\n");
7133 if (!BPF_MAP_PTR(aux->map_ptr_state))
7134 bpf_map_ptr_store(aux, meta->map_ptr,
7135 !meta->map_ptr->bypass_spec_v1);
7136 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7137 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7138 !meta->map_ptr->bypass_spec_v1);
7143 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7144 int func_id, int insn_idx)
7146 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7147 struct bpf_reg_state *regs = cur_regs(env), *reg;
7148 struct bpf_map *map = meta->map_ptr;
7152 if (func_id != BPF_FUNC_tail_call)
7154 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7155 verbose(env, "kernel subsystem misconfigured verifier\n");
7159 reg = ®s[BPF_REG_3];
7160 val = reg->var_off.value;
7161 max = map->max_entries;
7163 if (!(register_is_const(reg) && val < max)) {
7164 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7168 err = mark_chain_precision(env, BPF_REG_3);
7171 if (bpf_map_key_unseen(aux))
7172 bpf_map_key_store(aux, val);
7173 else if (!bpf_map_key_poisoned(aux) &&
7174 bpf_map_key_immediate(aux) != val)
7175 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7179 static int check_reference_leak(struct bpf_verifier_env *env)
7181 struct bpf_func_state *state = cur_func(env);
7182 bool refs_lingering = false;
7185 if (state->frameno && !state->in_callback_fn)
7188 for (i = 0; i < state->acquired_refs; i++) {
7189 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7191 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7192 state->refs[i].id, state->refs[i].insn_idx);
7193 refs_lingering = true;
7195 return refs_lingering ? -EINVAL : 0;
7198 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7199 struct bpf_reg_state *regs)
7201 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
7202 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
7203 struct bpf_map *fmt_map = fmt_reg->map_ptr;
7204 int err, fmt_map_off, num_args;
7208 /* data must be an array of u64 */
7209 if (data_len_reg->var_off.value % 8)
7211 num_args = data_len_reg->var_off.value / 8;
7213 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7214 * and map_direct_value_addr is set.
7216 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7217 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7220 verbose(env, "verifier bug\n");
7223 fmt = (char *)(long)fmt_addr + fmt_map_off;
7225 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7226 * can focus on validating the format specifiers.
7228 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7230 verbose(env, "Invalid format string\n");
7235 static int check_get_func_ip(struct bpf_verifier_env *env)
7237 enum bpf_prog_type type = resolve_prog_type(env->prog);
7238 int func_id = BPF_FUNC_get_func_ip;
7240 if (type == BPF_PROG_TYPE_TRACING) {
7241 if (!bpf_prog_has_trampoline(env->prog)) {
7242 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7243 func_id_name(func_id), func_id);
7247 } else if (type == BPF_PROG_TYPE_KPROBE) {
7251 verbose(env, "func %s#%d not supported for program type %d\n",
7252 func_id_name(func_id), func_id, type);
7256 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7258 return &env->insn_aux_data[env->insn_idx];
7261 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7263 struct bpf_reg_state *regs = cur_regs(env);
7264 struct bpf_reg_state *reg = ®s[BPF_REG_4];
7265 bool reg_is_null = register_is_null(reg);
7268 mark_chain_precision(env, BPF_REG_4);
7273 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7275 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7277 if (!state->initialized) {
7278 state->initialized = 1;
7279 state->fit_for_inline = loop_flag_is_zero(env);
7280 state->callback_subprogno = subprogno;
7284 if (!state->fit_for_inline)
7287 state->fit_for_inline = (loop_flag_is_zero(env) &&
7288 state->callback_subprogno == subprogno);
7291 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7294 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7295 const struct bpf_func_proto *fn = NULL;
7296 enum bpf_return_type ret_type;
7297 enum bpf_type_flag ret_flag;
7298 struct bpf_reg_state *regs;
7299 struct bpf_call_arg_meta meta;
7300 int insn_idx = *insn_idx_p;
7302 int i, err, func_id;
7304 /* find function prototype */
7305 func_id = insn->imm;
7306 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7307 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7312 if (env->ops->get_func_proto)
7313 fn = env->ops->get_func_proto(func_id, env->prog);
7315 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7320 /* eBPF programs must be GPL compatible to use GPL-ed functions */
7321 if (!env->prog->gpl_compatible && fn->gpl_only) {
7322 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7326 if (fn->allowed && !fn->allowed(env->prog)) {
7327 verbose(env, "helper call is not allowed in probe\n");
7331 /* With LD_ABS/IND some JITs save/restore skb from r1. */
7332 changes_data = bpf_helper_changes_pkt_data(fn->func);
7333 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7334 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7335 func_id_name(func_id), func_id);
7339 memset(&meta, 0, sizeof(meta));
7340 meta.pkt_access = fn->pkt_access;
7342 err = check_func_proto(fn, func_id);
7344 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7345 func_id_name(func_id), func_id);
7349 meta.func_id = func_id;
7351 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7352 err = check_func_arg(env, i, &meta, fn);
7357 err = record_func_map(env, &meta, func_id, insn_idx);
7361 err = record_func_key(env, &meta, func_id, insn_idx);
7365 /* Mark slots with STACK_MISC in case of raw mode, stack offset
7366 * is inferred from register state.
7368 for (i = 0; i < meta.access_size; i++) {
7369 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7370 BPF_WRITE, -1, false);
7375 regs = cur_regs(env);
7377 if (meta.uninit_dynptr_regno) {
7378 /* we write BPF_DW bits (8 bytes) at a time */
7379 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7380 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7381 i, BPF_DW, BPF_WRITE, -1, false);
7386 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno],
7387 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7393 if (meta.release_regno) {
7395 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7396 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
7397 else if (meta.ref_obj_id)
7398 err = release_reference(env, meta.ref_obj_id);
7399 /* meta.ref_obj_id can only be 0 if register that is meant to be
7400 * released is NULL, which must be > R0.
7402 else if (register_is_null(®s[meta.release_regno]))
7405 verbose(env, "func %s#%d reference has not been acquired before\n",
7406 func_id_name(func_id), func_id);
7412 case BPF_FUNC_tail_call:
7413 err = check_reference_leak(env);
7415 verbose(env, "tail_call would lead to reference leak\n");
7419 case BPF_FUNC_get_local_storage:
7420 /* check that flags argument in get_local_storage(map, flags) is 0,
7421 * this is required because get_local_storage() can't return an error.
7423 if (!register_is_null(®s[BPF_REG_2])) {
7424 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7428 case BPF_FUNC_for_each_map_elem:
7429 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7430 set_map_elem_callback_state);
7432 case BPF_FUNC_timer_set_callback:
7433 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7434 set_timer_callback_state);
7436 case BPF_FUNC_find_vma:
7437 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7438 set_find_vma_callback_state);
7440 case BPF_FUNC_snprintf:
7441 err = check_bpf_snprintf_call(env, regs);
7444 update_loop_inline_state(env, meta.subprogno);
7445 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7446 set_loop_callback_state);
7448 case BPF_FUNC_dynptr_from_mem:
7449 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7450 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7451 reg_type_str(env, regs[BPF_REG_1].type));
7455 case BPF_FUNC_set_retval:
7456 if (prog_type == BPF_PROG_TYPE_LSM &&
7457 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7458 if (!env->prog->aux->attach_func_proto->type) {
7459 /* Make sure programs that attach to void
7460 * hooks don't try to modify return value.
7462 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7467 case BPF_FUNC_dynptr_data:
7468 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7469 if (arg_type_is_dynptr(fn->arg_type[i])) {
7470 struct bpf_reg_state *reg = ®s[BPF_REG_1 + i];
7472 if (meta.ref_obj_id) {
7473 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7477 if (base_type(reg->type) != PTR_TO_DYNPTR)
7478 /* Find the id of the dynptr we're
7479 * tracking the reference of
7481 meta.ref_obj_id = stack_slot_get_id(env, reg);
7485 if (i == MAX_BPF_FUNC_REG_ARGS) {
7486 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7490 case BPF_FUNC_user_ringbuf_drain:
7491 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7492 set_user_ringbuf_callback_state);
7499 /* reset caller saved regs */
7500 for (i = 0; i < CALLER_SAVED_REGS; i++) {
7501 mark_reg_not_init(env, regs, caller_saved[i]);
7502 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7505 /* helper call returns 64-bit value. */
7506 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7508 /* update return register (already marked as written above) */
7509 ret_type = fn->ret_type;
7510 ret_flag = type_flag(ret_type);
7512 switch (base_type(ret_type)) {
7514 /* sets type to SCALAR_VALUE */
7515 mark_reg_unknown(env, regs, BPF_REG_0);
7518 regs[BPF_REG_0].type = NOT_INIT;
7520 case RET_PTR_TO_MAP_VALUE:
7521 /* There is no offset yet applied, variable or fixed */
7522 mark_reg_known_zero(env, regs, BPF_REG_0);
7523 /* remember map_ptr, so that check_map_access()
7524 * can check 'value_size' boundary of memory access
7525 * to map element returned from bpf_map_lookup_elem()
7527 if (meta.map_ptr == NULL) {
7529 "kernel subsystem misconfigured verifier\n");
7532 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7533 regs[BPF_REG_0].map_uid = meta.map_uid;
7534 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7535 if (!type_may_be_null(ret_type) &&
7536 map_value_has_spin_lock(meta.map_ptr)) {
7537 regs[BPF_REG_0].id = ++env->id_gen;
7540 case RET_PTR_TO_SOCKET:
7541 mark_reg_known_zero(env, regs, BPF_REG_0);
7542 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7544 case RET_PTR_TO_SOCK_COMMON:
7545 mark_reg_known_zero(env, regs, BPF_REG_0);
7546 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7548 case RET_PTR_TO_TCP_SOCK:
7549 mark_reg_known_zero(env, regs, BPF_REG_0);
7550 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7552 case RET_PTR_TO_ALLOC_MEM:
7553 mark_reg_known_zero(env, regs, BPF_REG_0);
7554 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7555 regs[BPF_REG_0].mem_size = meta.mem_size;
7557 case RET_PTR_TO_MEM_OR_BTF_ID:
7559 const struct btf_type *t;
7561 mark_reg_known_zero(env, regs, BPF_REG_0);
7562 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7563 if (!btf_type_is_struct(t)) {
7565 const struct btf_type *ret;
7568 /* resolve the type size of ksym. */
7569 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7571 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7572 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7573 tname, PTR_ERR(ret));
7576 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7577 regs[BPF_REG_0].mem_size = tsize;
7579 /* MEM_RDONLY may be carried from ret_flag, but it
7580 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7581 * it will confuse the check of PTR_TO_BTF_ID in
7582 * check_mem_access().
7584 ret_flag &= ~MEM_RDONLY;
7586 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7587 regs[BPF_REG_0].btf = meta.ret_btf;
7588 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7592 case RET_PTR_TO_BTF_ID:
7594 struct btf *ret_btf;
7597 mark_reg_known_zero(env, regs, BPF_REG_0);
7598 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7599 if (func_id == BPF_FUNC_kptr_xchg) {
7600 ret_btf = meta.kptr_off_desc->kptr.btf;
7601 ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7603 if (fn->ret_btf_id == BPF_PTR_POISON) {
7604 verbose(env, "verifier internal error:");
7605 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7606 func_id_name(func_id));
7609 ret_btf = btf_vmlinux;
7610 ret_btf_id = *fn->ret_btf_id;
7612 if (ret_btf_id == 0) {
7613 verbose(env, "invalid return type %u of func %s#%d\n",
7614 base_type(ret_type), func_id_name(func_id),
7618 regs[BPF_REG_0].btf = ret_btf;
7619 regs[BPF_REG_0].btf_id = ret_btf_id;
7623 verbose(env, "unknown return type %u of func %s#%d\n",
7624 base_type(ret_type), func_id_name(func_id), func_id);
7628 if (type_may_be_null(regs[BPF_REG_0].type))
7629 regs[BPF_REG_0].id = ++env->id_gen;
7631 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7632 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7633 func_id_name(func_id), func_id);
7637 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7638 /* For release_reference() */
7639 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7640 } else if (is_acquire_function(func_id, meta.map_ptr)) {
7641 int id = acquire_reference_state(env, insn_idx);
7645 /* For mark_ptr_or_null_reg() */
7646 regs[BPF_REG_0].id = id;
7647 /* For release_reference() */
7648 regs[BPF_REG_0].ref_obj_id = id;
7651 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7653 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7657 if ((func_id == BPF_FUNC_get_stack ||
7658 func_id == BPF_FUNC_get_task_stack) &&
7659 !env->prog->has_callchain_buf) {
7660 const char *err_str;
7662 #ifdef CONFIG_PERF_EVENTS
7663 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7664 err_str = "cannot get callchain buffer for func %s#%d\n";
7667 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7670 verbose(env, err_str, func_id_name(func_id), func_id);
7674 env->prog->has_callchain_buf = true;
7677 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7678 env->prog->call_get_stack = true;
7680 if (func_id == BPF_FUNC_get_func_ip) {
7681 if (check_get_func_ip(env))
7683 env->prog->call_get_func_ip = true;
7687 clear_all_pkt_pointers(env);
7691 /* mark_btf_func_reg_size() is used when the reg size is determined by
7692 * the BTF func_proto's return value size and argument.
7694 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7697 struct bpf_reg_state *reg = &cur_regs(env)[regno];
7699 if (regno == BPF_REG_0) {
7700 /* Function return value */
7701 reg->live |= REG_LIVE_WRITTEN;
7702 reg->subreg_def = reg_size == sizeof(u64) ?
7703 DEF_NOT_SUBREG : env->insn_idx + 1;
7705 /* Function argument */
7706 if (reg_size == sizeof(u64)) {
7707 mark_insn_zext(env, reg);
7708 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7710 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7715 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7718 const struct btf_type *t, *func, *func_proto, *ptr_type;
7719 struct bpf_reg_state *regs = cur_regs(env);
7720 struct bpf_kfunc_arg_meta meta = { 0 };
7721 const char *func_name, *ptr_type_name;
7722 u32 i, nargs, func_id, ptr_type_id;
7723 int err, insn_idx = *insn_idx_p;
7724 const struct btf_param *args;
7725 struct btf *desc_btf;
7729 /* skip for now, but return error when we find this in fixup_kfunc_call */
7733 desc_btf = find_kfunc_desc_btf(env, insn->off);
7734 if (IS_ERR(desc_btf))
7735 return PTR_ERR(desc_btf);
7737 func_id = insn->imm;
7738 func = btf_type_by_id(desc_btf, func_id);
7739 func_name = btf_name_by_offset(desc_btf, func->name_off);
7740 func_proto = btf_type_by_id(desc_btf, func->type);
7742 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7744 verbose(env, "calling kernel function %s is not allowed\n",
7748 if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7749 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7753 acq = *kfunc_flags & KF_ACQUIRE;
7755 meta.flags = *kfunc_flags;
7757 /* Check the arguments */
7758 err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7761 /* In case of release function, we get register number of refcounted
7762 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7765 err = release_reference(env, regs[err].ref_obj_id);
7767 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7768 func_name, func_id);
7773 for (i = 0; i < CALLER_SAVED_REGS; i++)
7774 mark_reg_not_init(env, regs, caller_saved[i]);
7776 /* Check return type */
7777 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7779 if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7780 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7784 if (btf_type_is_scalar(t)) {
7785 mark_reg_unknown(env, regs, BPF_REG_0);
7786 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7787 } else if (btf_type_is_ptr(t)) {
7788 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7790 if (!btf_type_is_struct(ptr_type)) {
7791 if (!meta.r0_size) {
7792 ptr_type_name = btf_name_by_offset(desc_btf,
7793 ptr_type->name_off);
7795 "kernel function %s returns pointer type %s %s is not supported\n",
7797 btf_type_str(ptr_type),
7802 mark_reg_known_zero(env, regs, BPF_REG_0);
7803 regs[BPF_REG_0].type = PTR_TO_MEM;
7804 regs[BPF_REG_0].mem_size = meta.r0_size;
7807 regs[BPF_REG_0].type |= MEM_RDONLY;
7809 /* Ensures we don't access the memory after a release_reference() */
7810 if (meta.ref_obj_id)
7811 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7813 mark_reg_known_zero(env, regs, BPF_REG_0);
7814 regs[BPF_REG_0].btf = desc_btf;
7815 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7816 regs[BPF_REG_0].btf_id = ptr_type_id;
7818 if (*kfunc_flags & KF_RET_NULL) {
7819 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7820 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7821 regs[BPF_REG_0].id = ++env->id_gen;
7823 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7825 int id = acquire_reference_state(env, insn_idx);
7829 regs[BPF_REG_0].id = id;
7830 regs[BPF_REG_0].ref_obj_id = id;
7832 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7834 nargs = btf_type_vlen(func_proto);
7835 args = (const struct btf_param *)(func_proto + 1);
7836 for (i = 0; i < nargs; i++) {
7839 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7840 if (btf_type_is_ptr(t))
7841 mark_btf_func_reg_size(env, regno, sizeof(void *));
7843 /* scalar. ensured by btf_check_kfunc_arg_match() */
7844 mark_btf_func_reg_size(env, regno, t->size);
7850 static bool signed_add_overflows(s64 a, s64 b)
7852 /* Do the add in u64, where overflow is well-defined */
7853 s64 res = (s64)((u64)a + (u64)b);
7860 static bool signed_add32_overflows(s32 a, s32 b)
7862 /* Do the add in u32, where overflow is well-defined */
7863 s32 res = (s32)((u32)a + (u32)b);
7870 static bool signed_sub_overflows(s64 a, s64 b)
7872 /* Do the sub in u64, where overflow is well-defined */
7873 s64 res = (s64)((u64)a - (u64)b);
7880 static bool signed_sub32_overflows(s32 a, s32 b)
7882 /* Do the sub in u32, where overflow is well-defined */
7883 s32 res = (s32)((u32)a - (u32)b);
7890 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7891 const struct bpf_reg_state *reg,
7892 enum bpf_reg_type type)
7894 bool known = tnum_is_const(reg->var_off);
7895 s64 val = reg->var_off.value;
7896 s64 smin = reg->smin_value;
7898 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7899 verbose(env, "math between %s pointer and %lld is not allowed\n",
7900 reg_type_str(env, type), val);
7904 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7905 verbose(env, "%s pointer offset %d is not allowed\n",
7906 reg_type_str(env, type), reg->off);
7910 if (smin == S64_MIN) {
7911 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7912 reg_type_str(env, type));
7916 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7917 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7918 smin, reg_type_str(env, type));
7933 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7934 u32 *alu_limit, bool mask_to_left)
7936 u32 max = 0, ptr_limit = 0;
7938 switch (ptr_reg->type) {
7940 /* Offset 0 is out-of-bounds, but acceptable start for the
7941 * left direction, see BPF_REG_FP. Also, unknown scalar
7942 * offset where we would need to deal with min/max bounds is
7943 * currently prohibited for unprivileged.
7945 max = MAX_BPF_STACK + mask_to_left;
7946 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7948 case PTR_TO_MAP_VALUE:
7949 max = ptr_reg->map_ptr->value_size;
7950 ptr_limit = (mask_to_left ?
7951 ptr_reg->smin_value :
7952 ptr_reg->umax_value) + ptr_reg->off;
7958 if (ptr_limit >= max)
7959 return REASON_LIMIT;
7960 *alu_limit = ptr_limit;
7964 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7965 const struct bpf_insn *insn)
7967 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7970 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7971 u32 alu_state, u32 alu_limit)
7973 /* If we arrived here from different branches with different
7974 * state or limits to sanitize, then this won't work.
7976 if (aux->alu_state &&
7977 (aux->alu_state != alu_state ||
7978 aux->alu_limit != alu_limit))
7979 return REASON_PATHS;
7981 /* Corresponding fixup done in do_misc_fixups(). */
7982 aux->alu_state = alu_state;
7983 aux->alu_limit = alu_limit;
7987 static int sanitize_val_alu(struct bpf_verifier_env *env,
7988 struct bpf_insn *insn)
7990 struct bpf_insn_aux_data *aux = cur_aux(env);
7992 if (can_skip_alu_sanitation(env, insn))
7995 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7998 static bool sanitize_needed(u8 opcode)
8000 return opcode == BPF_ADD || opcode == BPF_SUB;
8003 struct bpf_sanitize_info {
8004 struct bpf_insn_aux_data aux;
8008 static struct bpf_verifier_state *
8009 sanitize_speculative_path(struct bpf_verifier_env *env,
8010 const struct bpf_insn *insn,
8011 u32 next_idx, u32 curr_idx)
8013 struct bpf_verifier_state *branch;
8014 struct bpf_reg_state *regs;
8016 branch = push_stack(env, next_idx, curr_idx, true);
8017 if (branch && insn) {
8018 regs = branch->frame[branch->curframe]->regs;
8019 if (BPF_SRC(insn->code) == BPF_K) {
8020 mark_reg_unknown(env, regs, insn->dst_reg);
8021 } else if (BPF_SRC(insn->code) == BPF_X) {
8022 mark_reg_unknown(env, regs, insn->dst_reg);
8023 mark_reg_unknown(env, regs, insn->src_reg);
8029 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
8030 struct bpf_insn *insn,
8031 const struct bpf_reg_state *ptr_reg,
8032 const struct bpf_reg_state *off_reg,
8033 struct bpf_reg_state *dst_reg,
8034 struct bpf_sanitize_info *info,
8035 const bool commit_window)
8037 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
8038 struct bpf_verifier_state *vstate = env->cur_state;
8039 bool off_is_imm = tnum_is_const(off_reg->var_off);
8040 bool off_is_neg = off_reg->smin_value < 0;
8041 bool ptr_is_dst_reg = ptr_reg == dst_reg;
8042 u8 opcode = BPF_OP(insn->code);
8043 u32 alu_state, alu_limit;
8044 struct bpf_reg_state tmp;
8048 if (can_skip_alu_sanitation(env, insn))
8051 /* We already marked aux for masking from non-speculative
8052 * paths, thus we got here in the first place. We only care
8053 * to explore bad access from here.
8055 if (vstate->speculative)
8058 if (!commit_window) {
8059 if (!tnum_is_const(off_reg->var_off) &&
8060 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8061 return REASON_BOUNDS;
8063 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
8064 (opcode == BPF_SUB && !off_is_neg);
8067 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8071 if (commit_window) {
8072 /* In commit phase we narrow the masking window based on
8073 * the observed pointer move after the simulated operation.
8075 alu_state = info->aux.alu_state;
8076 alu_limit = abs(info->aux.alu_limit - alu_limit);
8078 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8079 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8080 alu_state |= ptr_is_dst_reg ?
8081 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8083 /* Limit pruning on unknown scalars to enable deep search for
8084 * potential masking differences from other program paths.
8087 env->explore_alu_limits = true;
8090 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8094 /* If we're in commit phase, we're done here given we already
8095 * pushed the truncated dst_reg into the speculative verification
8098 * Also, when register is a known constant, we rewrite register-based
8099 * operation to immediate-based, and thus do not need masking (and as
8100 * a consequence, do not need to simulate the zero-truncation either).
8102 if (commit_window || off_is_imm)
8105 /* Simulate and find potential out-of-bounds access under
8106 * speculative execution from truncation as a result of
8107 * masking when off was not within expected range. If off
8108 * sits in dst, then we temporarily need to move ptr there
8109 * to simulate dst (== 0) +/-= ptr. Needed, for example,
8110 * for cases where we use K-based arithmetic in one direction
8111 * and truncated reg-based in the other in order to explore
8114 if (!ptr_is_dst_reg) {
8116 copy_register_state(dst_reg, ptr_reg);
8118 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8120 if (!ptr_is_dst_reg && ret)
8122 return !ret ? REASON_STACK : 0;
8125 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8127 struct bpf_verifier_state *vstate = env->cur_state;
8129 /* If we simulate paths under speculation, we don't update the
8130 * insn as 'seen' such that when we verify unreachable paths in
8131 * the non-speculative domain, sanitize_dead_code() can still
8132 * rewrite/sanitize them.
8134 if (!vstate->speculative)
8135 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8138 static int sanitize_err(struct bpf_verifier_env *env,
8139 const struct bpf_insn *insn, int reason,
8140 const struct bpf_reg_state *off_reg,
8141 const struct bpf_reg_state *dst_reg)
8143 static const char *err = "pointer arithmetic with it prohibited for !root";
8144 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8145 u32 dst = insn->dst_reg, src = insn->src_reg;
8149 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8150 off_reg == dst_reg ? dst : src, err);
8153 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8154 off_reg == dst_reg ? src : dst, err);
8157 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8161 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8165 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8169 verbose(env, "verifier internal error: unknown reason (%d)\n",
8177 /* check that stack access falls within stack limits and that 'reg' doesn't
8178 * have a variable offset.
8180 * Variable offset is prohibited for unprivileged mode for simplicity since it
8181 * requires corresponding support in Spectre masking for stack ALU. See also
8182 * retrieve_ptr_limit().
8185 * 'off' includes 'reg->off'.
8187 static int check_stack_access_for_ptr_arithmetic(
8188 struct bpf_verifier_env *env,
8190 const struct bpf_reg_state *reg,
8193 if (!tnum_is_const(reg->var_off)) {
8196 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8197 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8198 regno, tn_buf, off);
8202 if (off >= 0 || off < -MAX_BPF_STACK) {
8203 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8204 "prohibited for !root; off=%d\n", regno, off);
8211 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8212 const struct bpf_insn *insn,
8213 const struct bpf_reg_state *dst_reg)
8215 u32 dst = insn->dst_reg;
8217 /* For unprivileged we require that resulting offset must be in bounds
8218 * in order to be able to sanitize access later on.
8220 if (env->bypass_spec_v1)
8223 switch (dst_reg->type) {
8225 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8226 dst_reg->off + dst_reg->var_off.value))
8229 case PTR_TO_MAP_VALUE:
8230 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8231 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8232 "prohibited for !root\n", dst);
8243 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8244 * Caller should also handle BPF_MOV case separately.
8245 * If we return -EACCES, caller may want to try again treating pointer as a
8246 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
8248 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8249 struct bpf_insn *insn,
8250 const struct bpf_reg_state *ptr_reg,
8251 const struct bpf_reg_state *off_reg)
8253 struct bpf_verifier_state *vstate = env->cur_state;
8254 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8255 struct bpf_reg_state *regs = state->regs, *dst_reg;
8256 bool known = tnum_is_const(off_reg->var_off);
8257 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8258 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8259 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8260 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8261 struct bpf_sanitize_info info = {};
8262 u8 opcode = BPF_OP(insn->code);
8263 u32 dst = insn->dst_reg;
8266 dst_reg = ®s[dst];
8268 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8269 smin_val > smax_val || umin_val > umax_val) {
8270 /* Taint dst register if offset had invalid bounds derived from
8271 * e.g. dead branches.
8273 __mark_reg_unknown(env, dst_reg);
8277 if (BPF_CLASS(insn->code) != BPF_ALU64) {
8278 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8279 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8280 __mark_reg_unknown(env, dst_reg);
8285 "R%d 32-bit pointer arithmetic prohibited\n",
8290 if (ptr_reg->type & PTR_MAYBE_NULL) {
8291 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8292 dst, reg_type_str(env, ptr_reg->type));
8296 switch (base_type(ptr_reg->type)) {
8297 case CONST_PTR_TO_MAP:
8298 /* smin_val represents the known value */
8299 if (known && smin_val == 0 && opcode == BPF_ADD)
8302 case PTR_TO_PACKET_END:
8304 case PTR_TO_SOCK_COMMON:
8305 case PTR_TO_TCP_SOCK:
8306 case PTR_TO_XDP_SOCK:
8307 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8308 dst, reg_type_str(env, ptr_reg->type));
8314 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8315 * The id may be overwritten later if we create a new variable offset.
8317 dst_reg->type = ptr_reg->type;
8318 dst_reg->id = ptr_reg->id;
8320 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8321 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8324 /* pointer types do not carry 32-bit bounds at the moment. */
8325 __mark_reg32_unbounded(dst_reg);
8327 if (sanitize_needed(opcode)) {
8328 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8331 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8336 /* We can take a fixed offset as long as it doesn't overflow
8337 * the s32 'off' field
8339 if (known && (ptr_reg->off + smin_val ==
8340 (s64)(s32)(ptr_reg->off + smin_val))) {
8341 /* pointer += K. Accumulate it into fixed offset */
8342 dst_reg->smin_value = smin_ptr;
8343 dst_reg->smax_value = smax_ptr;
8344 dst_reg->umin_value = umin_ptr;
8345 dst_reg->umax_value = umax_ptr;
8346 dst_reg->var_off = ptr_reg->var_off;
8347 dst_reg->off = ptr_reg->off + smin_val;
8348 dst_reg->raw = ptr_reg->raw;
8351 /* A new variable offset is created. Note that off_reg->off
8352 * == 0, since it's a scalar.
8353 * dst_reg gets the pointer type and since some positive
8354 * integer value was added to the pointer, give it a new 'id'
8355 * if it's a PTR_TO_PACKET.
8356 * this creates a new 'base' pointer, off_reg (variable) gets
8357 * added into the variable offset, and we copy the fixed offset
8360 if (signed_add_overflows(smin_ptr, smin_val) ||
8361 signed_add_overflows(smax_ptr, smax_val)) {
8362 dst_reg->smin_value = S64_MIN;
8363 dst_reg->smax_value = S64_MAX;
8365 dst_reg->smin_value = smin_ptr + smin_val;
8366 dst_reg->smax_value = smax_ptr + smax_val;
8368 if (umin_ptr + umin_val < umin_ptr ||
8369 umax_ptr + umax_val < umax_ptr) {
8370 dst_reg->umin_value = 0;
8371 dst_reg->umax_value = U64_MAX;
8373 dst_reg->umin_value = umin_ptr + umin_val;
8374 dst_reg->umax_value = umax_ptr + umax_val;
8376 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8377 dst_reg->off = ptr_reg->off;
8378 dst_reg->raw = ptr_reg->raw;
8379 if (reg_is_pkt_pointer(ptr_reg)) {
8380 dst_reg->id = ++env->id_gen;
8381 /* something was added to pkt_ptr, set range to zero */
8382 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8386 if (dst_reg == off_reg) {
8387 /* scalar -= pointer. Creates an unknown scalar */
8388 verbose(env, "R%d tried to subtract pointer from scalar\n",
8392 /* We don't allow subtraction from FP, because (according to
8393 * test_verifier.c test "invalid fp arithmetic", JITs might not
8394 * be able to deal with it.
8396 if (ptr_reg->type == PTR_TO_STACK) {
8397 verbose(env, "R%d subtraction from stack pointer prohibited\n",
8401 if (known && (ptr_reg->off - smin_val ==
8402 (s64)(s32)(ptr_reg->off - smin_val))) {
8403 /* pointer -= K. Subtract it from fixed offset */
8404 dst_reg->smin_value = smin_ptr;
8405 dst_reg->smax_value = smax_ptr;
8406 dst_reg->umin_value = umin_ptr;
8407 dst_reg->umax_value = umax_ptr;
8408 dst_reg->var_off = ptr_reg->var_off;
8409 dst_reg->id = ptr_reg->id;
8410 dst_reg->off = ptr_reg->off - smin_val;
8411 dst_reg->raw = ptr_reg->raw;
8414 /* A new variable offset is created. If the subtrahend is known
8415 * nonnegative, then any reg->range we had before is still good.
8417 if (signed_sub_overflows(smin_ptr, smax_val) ||
8418 signed_sub_overflows(smax_ptr, smin_val)) {
8419 /* Overflow possible, we know nothing */
8420 dst_reg->smin_value = S64_MIN;
8421 dst_reg->smax_value = S64_MAX;
8423 dst_reg->smin_value = smin_ptr - smax_val;
8424 dst_reg->smax_value = smax_ptr - smin_val;
8426 if (umin_ptr < umax_val) {
8427 /* Overflow possible, we know nothing */
8428 dst_reg->umin_value = 0;
8429 dst_reg->umax_value = U64_MAX;
8431 /* Cannot overflow (as long as bounds are consistent) */
8432 dst_reg->umin_value = umin_ptr - umax_val;
8433 dst_reg->umax_value = umax_ptr - umin_val;
8435 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8436 dst_reg->off = ptr_reg->off;
8437 dst_reg->raw = ptr_reg->raw;
8438 if (reg_is_pkt_pointer(ptr_reg)) {
8439 dst_reg->id = ++env->id_gen;
8440 /* something was added to pkt_ptr, set range to zero */
8442 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8448 /* bitwise ops on pointers are troublesome, prohibit. */
8449 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8450 dst, bpf_alu_string[opcode >> 4]);
8453 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8454 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8455 dst, bpf_alu_string[opcode >> 4]);
8459 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8461 reg_bounds_sync(dst_reg);
8462 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8464 if (sanitize_needed(opcode)) {
8465 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8468 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8474 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8475 struct bpf_reg_state *src_reg)
8477 s32 smin_val = src_reg->s32_min_value;
8478 s32 smax_val = src_reg->s32_max_value;
8479 u32 umin_val = src_reg->u32_min_value;
8480 u32 umax_val = src_reg->u32_max_value;
8482 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8483 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8484 dst_reg->s32_min_value = S32_MIN;
8485 dst_reg->s32_max_value = S32_MAX;
8487 dst_reg->s32_min_value += smin_val;
8488 dst_reg->s32_max_value += smax_val;
8490 if (dst_reg->u32_min_value + umin_val < umin_val ||
8491 dst_reg->u32_max_value + umax_val < umax_val) {
8492 dst_reg->u32_min_value = 0;
8493 dst_reg->u32_max_value = U32_MAX;
8495 dst_reg->u32_min_value += umin_val;
8496 dst_reg->u32_max_value += umax_val;
8500 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8501 struct bpf_reg_state *src_reg)
8503 s64 smin_val = src_reg->smin_value;
8504 s64 smax_val = src_reg->smax_value;
8505 u64 umin_val = src_reg->umin_value;
8506 u64 umax_val = src_reg->umax_value;
8508 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8509 signed_add_overflows(dst_reg->smax_value, smax_val)) {
8510 dst_reg->smin_value = S64_MIN;
8511 dst_reg->smax_value = S64_MAX;
8513 dst_reg->smin_value += smin_val;
8514 dst_reg->smax_value += smax_val;
8516 if (dst_reg->umin_value + umin_val < umin_val ||
8517 dst_reg->umax_value + umax_val < umax_val) {
8518 dst_reg->umin_value = 0;
8519 dst_reg->umax_value = U64_MAX;
8521 dst_reg->umin_value += umin_val;
8522 dst_reg->umax_value += umax_val;
8526 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8527 struct bpf_reg_state *src_reg)
8529 s32 smin_val = src_reg->s32_min_value;
8530 s32 smax_val = src_reg->s32_max_value;
8531 u32 umin_val = src_reg->u32_min_value;
8532 u32 umax_val = src_reg->u32_max_value;
8534 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8535 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8536 /* Overflow possible, we know nothing */
8537 dst_reg->s32_min_value = S32_MIN;
8538 dst_reg->s32_max_value = S32_MAX;
8540 dst_reg->s32_min_value -= smax_val;
8541 dst_reg->s32_max_value -= smin_val;
8543 if (dst_reg->u32_min_value < umax_val) {
8544 /* Overflow possible, we know nothing */
8545 dst_reg->u32_min_value = 0;
8546 dst_reg->u32_max_value = U32_MAX;
8548 /* Cannot overflow (as long as bounds are consistent) */
8549 dst_reg->u32_min_value -= umax_val;
8550 dst_reg->u32_max_value -= umin_val;
8554 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8555 struct bpf_reg_state *src_reg)
8557 s64 smin_val = src_reg->smin_value;
8558 s64 smax_val = src_reg->smax_value;
8559 u64 umin_val = src_reg->umin_value;
8560 u64 umax_val = src_reg->umax_value;
8562 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8563 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8564 /* Overflow possible, we know nothing */
8565 dst_reg->smin_value = S64_MIN;
8566 dst_reg->smax_value = S64_MAX;
8568 dst_reg->smin_value -= smax_val;
8569 dst_reg->smax_value -= smin_val;
8571 if (dst_reg->umin_value < umax_val) {
8572 /* Overflow possible, we know nothing */
8573 dst_reg->umin_value = 0;
8574 dst_reg->umax_value = U64_MAX;
8576 /* Cannot overflow (as long as bounds are consistent) */
8577 dst_reg->umin_value -= umax_val;
8578 dst_reg->umax_value -= umin_val;
8582 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8583 struct bpf_reg_state *src_reg)
8585 s32 smin_val = src_reg->s32_min_value;
8586 u32 umin_val = src_reg->u32_min_value;
8587 u32 umax_val = src_reg->u32_max_value;
8589 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8590 /* Ain't nobody got time to multiply that sign */
8591 __mark_reg32_unbounded(dst_reg);
8594 /* Both values are positive, so we can work with unsigned and
8595 * copy the result to signed (unless it exceeds S32_MAX).
8597 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8598 /* Potential overflow, we know nothing */
8599 __mark_reg32_unbounded(dst_reg);
8602 dst_reg->u32_min_value *= umin_val;
8603 dst_reg->u32_max_value *= umax_val;
8604 if (dst_reg->u32_max_value > S32_MAX) {
8605 /* Overflow possible, we know nothing */
8606 dst_reg->s32_min_value = S32_MIN;
8607 dst_reg->s32_max_value = S32_MAX;
8609 dst_reg->s32_min_value = dst_reg->u32_min_value;
8610 dst_reg->s32_max_value = dst_reg->u32_max_value;
8614 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8615 struct bpf_reg_state *src_reg)
8617 s64 smin_val = src_reg->smin_value;
8618 u64 umin_val = src_reg->umin_value;
8619 u64 umax_val = src_reg->umax_value;
8621 if (smin_val < 0 || dst_reg->smin_value < 0) {
8622 /* Ain't nobody got time to multiply that sign */
8623 __mark_reg64_unbounded(dst_reg);
8626 /* Both values are positive, so we can work with unsigned and
8627 * copy the result to signed (unless it exceeds S64_MAX).
8629 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8630 /* Potential overflow, we know nothing */
8631 __mark_reg64_unbounded(dst_reg);
8634 dst_reg->umin_value *= umin_val;
8635 dst_reg->umax_value *= umax_val;
8636 if (dst_reg->umax_value > S64_MAX) {
8637 /* Overflow possible, we know nothing */
8638 dst_reg->smin_value = S64_MIN;
8639 dst_reg->smax_value = S64_MAX;
8641 dst_reg->smin_value = dst_reg->umin_value;
8642 dst_reg->smax_value = dst_reg->umax_value;
8646 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8647 struct bpf_reg_state *src_reg)
8649 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8650 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8651 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8652 s32 smin_val = src_reg->s32_min_value;
8653 u32 umax_val = src_reg->u32_max_value;
8655 if (src_known && dst_known) {
8656 __mark_reg32_known(dst_reg, var32_off.value);
8660 /* We get our minimum from the var_off, since that's inherently
8661 * bitwise. Our maximum is the minimum of the operands' maxima.
8663 dst_reg->u32_min_value = var32_off.value;
8664 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8665 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8666 /* Lose signed bounds when ANDing negative numbers,
8667 * ain't nobody got time for that.
8669 dst_reg->s32_min_value = S32_MIN;
8670 dst_reg->s32_max_value = S32_MAX;
8672 /* ANDing two positives gives a positive, so safe to
8673 * cast result into s64.
8675 dst_reg->s32_min_value = dst_reg->u32_min_value;
8676 dst_reg->s32_max_value = dst_reg->u32_max_value;
8680 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8681 struct bpf_reg_state *src_reg)
8683 bool src_known = tnum_is_const(src_reg->var_off);
8684 bool dst_known = tnum_is_const(dst_reg->var_off);
8685 s64 smin_val = src_reg->smin_value;
8686 u64 umax_val = src_reg->umax_value;
8688 if (src_known && dst_known) {
8689 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8693 /* We get our minimum from the var_off, since that's inherently
8694 * bitwise. Our maximum is the minimum of the operands' maxima.
8696 dst_reg->umin_value = dst_reg->var_off.value;
8697 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8698 if (dst_reg->smin_value < 0 || smin_val < 0) {
8699 /* Lose signed bounds when ANDing negative numbers,
8700 * ain't nobody got time for that.
8702 dst_reg->smin_value = S64_MIN;
8703 dst_reg->smax_value = S64_MAX;
8705 /* ANDing two positives gives a positive, so safe to
8706 * cast result into s64.
8708 dst_reg->smin_value = dst_reg->umin_value;
8709 dst_reg->smax_value = dst_reg->umax_value;
8711 /* We may learn something more from the var_off */
8712 __update_reg_bounds(dst_reg);
8715 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8716 struct bpf_reg_state *src_reg)
8718 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8719 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8720 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8721 s32 smin_val = src_reg->s32_min_value;
8722 u32 umin_val = src_reg->u32_min_value;
8724 if (src_known && dst_known) {
8725 __mark_reg32_known(dst_reg, var32_off.value);
8729 /* We get our maximum from the var_off, and our minimum is the
8730 * maximum of the operands' minima
8732 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8733 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8734 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8735 /* Lose signed bounds when ORing negative numbers,
8736 * ain't nobody got time for that.
8738 dst_reg->s32_min_value = S32_MIN;
8739 dst_reg->s32_max_value = S32_MAX;
8741 /* ORing two positives gives a positive, so safe to
8742 * cast result into s64.
8744 dst_reg->s32_min_value = dst_reg->u32_min_value;
8745 dst_reg->s32_max_value = dst_reg->u32_max_value;
8749 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8750 struct bpf_reg_state *src_reg)
8752 bool src_known = tnum_is_const(src_reg->var_off);
8753 bool dst_known = tnum_is_const(dst_reg->var_off);
8754 s64 smin_val = src_reg->smin_value;
8755 u64 umin_val = src_reg->umin_value;
8757 if (src_known && dst_known) {
8758 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8762 /* We get our maximum from the var_off, and our minimum is the
8763 * maximum of the operands' minima
8765 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8766 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8767 if (dst_reg->smin_value < 0 || smin_val < 0) {
8768 /* Lose signed bounds when ORing negative numbers,
8769 * ain't nobody got time for that.
8771 dst_reg->smin_value = S64_MIN;
8772 dst_reg->smax_value = S64_MAX;
8774 /* ORing two positives gives a positive, so safe to
8775 * cast result into s64.
8777 dst_reg->smin_value = dst_reg->umin_value;
8778 dst_reg->smax_value = dst_reg->umax_value;
8780 /* We may learn something more from the var_off */
8781 __update_reg_bounds(dst_reg);
8784 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8785 struct bpf_reg_state *src_reg)
8787 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8788 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8789 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8790 s32 smin_val = src_reg->s32_min_value;
8792 if (src_known && dst_known) {
8793 __mark_reg32_known(dst_reg, var32_off.value);
8797 /* We get both minimum and maximum from the var32_off. */
8798 dst_reg->u32_min_value = var32_off.value;
8799 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8801 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8802 /* XORing two positive sign numbers gives a positive,
8803 * so safe to cast u32 result into s32.
8805 dst_reg->s32_min_value = dst_reg->u32_min_value;
8806 dst_reg->s32_max_value = dst_reg->u32_max_value;
8808 dst_reg->s32_min_value = S32_MIN;
8809 dst_reg->s32_max_value = S32_MAX;
8813 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8814 struct bpf_reg_state *src_reg)
8816 bool src_known = tnum_is_const(src_reg->var_off);
8817 bool dst_known = tnum_is_const(dst_reg->var_off);
8818 s64 smin_val = src_reg->smin_value;
8820 if (src_known && dst_known) {
8821 /* dst_reg->var_off.value has been updated earlier */
8822 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8826 /* We get both minimum and maximum from the var_off. */
8827 dst_reg->umin_value = dst_reg->var_off.value;
8828 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8830 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8831 /* XORing two positive sign numbers gives a positive,
8832 * so safe to cast u64 result into s64.
8834 dst_reg->smin_value = dst_reg->umin_value;
8835 dst_reg->smax_value = dst_reg->umax_value;
8837 dst_reg->smin_value = S64_MIN;
8838 dst_reg->smax_value = S64_MAX;
8841 __update_reg_bounds(dst_reg);
8844 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8845 u64 umin_val, u64 umax_val)
8847 /* We lose all sign bit information (except what we can pick
8850 dst_reg->s32_min_value = S32_MIN;
8851 dst_reg->s32_max_value = S32_MAX;
8852 /* If we might shift our top bit out, then we know nothing */
8853 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8854 dst_reg->u32_min_value = 0;
8855 dst_reg->u32_max_value = U32_MAX;
8857 dst_reg->u32_min_value <<= umin_val;
8858 dst_reg->u32_max_value <<= umax_val;
8862 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8863 struct bpf_reg_state *src_reg)
8865 u32 umax_val = src_reg->u32_max_value;
8866 u32 umin_val = src_reg->u32_min_value;
8867 /* u32 alu operation will zext upper bits */
8868 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8870 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8871 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8872 /* Not required but being careful mark reg64 bounds as unknown so
8873 * that we are forced to pick them up from tnum and zext later and
8874 * if some path skips this step we are still safe.
8876 __mark_reg64_unbounded(dst_reg);
8877 __update_reg32_bounds(dst_reg);
8880 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8881 u64 umin_val, u64 umax_val)
8883 /* Special case <<32 because it is a common compiler pattern to sign
8884 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8885 * positive we know this shift will also be positive so we can track
8886 * bounds correctly. Otherwise we lose all sign bit information except
8887 * what we can pick up from var_off. Perhaps we can generalize this
8888 * later to shifts of any length.
8890 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8891 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8893 dst_reg->smax_value = S64_MAX;
8895 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8896 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8898 dst_reg->smin_value = S64_MIN;
8900 /* If we might shift our top bit out, then we know nothing */
8901 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8902 dst_reg->umin_value = 0;
8903 dst_reg->umax_value = U64_MAX;
8905 dst_reg->umin_value <<= umin_val;
8906 dst_reg->umax_value <<= umax_val;
8910 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8911 struct bpf_reg_state *src_reg)
8913 u64 umax_val = src_reg->umax_value;
8914 u64 umin_val = src_reg->umin_value;
8916 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8917 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8918 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8920 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8921 /* We may learn something more from the var_off */
8922 __update_reg_bounds(dst_reg);
8925 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8926 struct bpf_reg_state *src_reg)
8928 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8929 u32 umax_val = src_reg->u32_max_value;
8930 u32 umin_val = src_reg->u32_min_value;
8932 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8933 * be negative, then either:
8934 * 1) src_reg might be zero, so the sign bit of the result is
8935 * unknown, so we lose our signed bounds
8936 * 2) it's known negative, thus the unsigned bounds capture the
8938 * 3) the signed bounds cross zero, so they tell us nothing
8940 * If the value in dst_reg is known nonnegative, then again the
8941 * unsigned bounds capture the signed bounds.
8942 * Thus, in all cases it suffices to blow away our signed bounds
8943 * and rely on inferring new ones from the unsigned bounds and
8944 * var_off of the result.
8946 dst_reg->s32_min_value = S32_MIN;
8947 dst_reg->s32_max_value = S32_MAX;
8949 dst_reg->var_off = tnum_rshift(subreg, umin_val);
8950 dst_reg->u32_min_value >>= umax_val;
8951 dst_reg->u32_max_value >>= umin_val;
8953 __mark_reg64_unbounded(dst_reg);
8954 __update_reg32_bounds(dst_reg);
8957 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8958 struct bpf_reg_state *src_reg)
8960 u64 umax_val = src_reg->umax_value;
8961 u64 umin_val = src_reg->umin_value;
8963 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8964 * be negative, then either:
8965 * 1) src_reg might be zero, so the sign bit of the result is
8966 * unknown, so we lose our signed bounds
8967 * 2) it's known negative, thus the unsigned bounds capture the
8969 * 3) the signed bounds cross zero, so they tell us nothing
8971 * If the value in dst_reg is known nonnegative, then again the
8972 * unsigned bounds capture the signed bounds.
8973 * Thus, in all cases it suffices to blow away our signed bounds
8974 * and rely on inferring new ones from the unsigned bounds and
8975 * var_off of the result.
8977 dst_reg->smin_value = S64_MIN;
8978 dst_reg->smax_value = S64_MAX;
8979 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8980 dst_reg->umin_value >>= umax_val;
8981 dst_reg->umax_value >>= umin_val;
8983 /* Its not easy to operate on alu32 bounds here because it depends
8984 * on bits being shifted in. Take easy way out and mark unbounded
8985 * so we can recalculate later from tnum.
8987 __mark_reg32_unbounded(dst_reg);
8988 __update_reg_bounds(dst_reg);
8991 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8992 struct bpf_reg_state *src_reg)
8994 u64 umin_val = src_reg->u32_min_value;
8996 /* Upon reaching here, src_known is true and
8997 * umax_val is equal to umin_val.
8999 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
9000 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
9002 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
9004 /* blow away the dst_reg umin_value/umax_value and rely on
9005 * dst_reg var_off to refine the result.
9007 dst_reg->u32_min_value = 0;
9008 dst_reg->u32_max_value = U32_MAX;
9010 __mark_reg64_unbounded(dst_reg);
9011 __update_reg32_bounds(dst_reg);
9014 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
9015 struct bpf_reg_state *src_reg)
9017 u64 umin_val = src_reg->umin_value;
9019 /* Upon reaching here, src_known is true and umax_val is equal
9022 dst_reg->smin_value >>= umin_val;
9023 dst_reg->smax_value >>= umin_val;
9025 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
9027 /* blow away the dst_reg umin_value/umax_value and rely on
9028 * dst_reg var_off to refine the result.
9030 dst_reg->umin_value = 0;
9031 dst_reg->umax_value = U64_MAX;
9033 /* Its not easy to operate on alu32 bounds here because it depends
9034 * on bits being shifted in from upper 32-bits. Take easy way out
9035 * and mark unbounded so we can recalculate later from tnum.
9037 __mark_reg32_unbounded(dst_reg);
9038 __update_reg_bounds(dst_reg);
9041 /* WARNING: This function does calculations on 64-bit values, but the actual
9042 * execution may occur on 32-bit values. Therefore, things like bitshifts
9043 * need extra checks in the 32-bit case.
9045 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9046 struct bpf_insn *insn,
9047 struct bpf_reg_state *dst_reg,
9048 struct bpf_reg_state src_reg)
9050 struct bpf_reg_state *regs = cur_regs(env);
9051 u8 opcode = BPF_OP(insn->code);
9053 s64 smin_val, smax_val;
9054 u64 umin_val, umax_val;
9055 s32 s32_min_val, s32_max_val;
9056 u32 u32_min_val, u32_max_val;
9057 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9058 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9061 smin_val = src_reg.smin_value;
9062 smax_val = src_reg.smax_value;
9063 umin_val = src_reg.umin_value;
9064 umax_val = src_reg.umax_value;
9066 s32_min_val = src_reg.s32_min_value;
9067 s32_max_val = src_reg.s32_max_value;
9068 u32_min_val = src_reg.u32_min_value;
9069 u32_max_val = src_reg.u32_max_value;
9072 src_known = tnum_subreg_is_const(src_reg.var_off);
9074 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9075 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9076 /* Taint dst register if offset had invalid bounds
9077 * derived from e.g. dead branches.
9079 __mark_reg_unknown(env, dst_reg);
9083 src_known = tnum_is_const(src_reg.var_off);
9085 (smin_val != smax_val || umin_val != umax_val)) ||
9086 smin_val > smax_val || umin_val > umax_val) {
9087 /* Taint dst register if offset had invalid bounds
9088 * derived from e.g. dead branches.
9090 __mark_reg_unknown(env, dst_reg);
9096 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9097 __mark_reg_unknown(env, dst_reg);
9101 if (sanitize_needed(opcode)) {
9102 ret = sanitize_val_alu(env, insn);
9104 return sanitize_err(env, insn, ret, NULL, NULL);
9107 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9108 * There are two classes of instructions: The first class we track both
9109 * alu32 and alu64 sign/unsigned bounds independently this provides the
9110 * greatest amount of precision when alu operations are mixed with jmp32
9111 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9112 * and BPF_OR. This is possible because these ops have fairly easy to
9113 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9114 * See alu32 verifier tests for examples. The second class of
9115 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9116 * with regards to tracking sign/unsigned bounds because the bits may
9117 * cross subreg boundaries in the alu64 case. When this happens we mark
9118 * the reg unbounded in the subreg bound space and use the resulting
9119 * tnum to calculate an approximation of the sign/unsigned bounds.
9123 scalar32_min_max_add(dst_reg, &src_reg);
9124 scalar_min_max_add(dst_reg, &src_reg);
9125 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9128 scalar32_min_max_sub(dst_reg, &src_reg);
9129 scalar_min_max_sub(dst_reg, &src_reg);
9130 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9133 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9134 scalar32_min_max_mul(dst_reg, &src_reg);
9135 scalar_min_max_mul(dst_reg, &src_reg);
9138 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9139 scalar32_min_max_and(dst_reg, &src_reg);
9140 scalar_min_max_and(dst_reg, &src_reg);
9143 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9144 scalar32_min_max_or(dst_reg, &src_reg);
9145 scalar_min_max_or(dst_reg, &src_reg);
9148 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9149 scalar32_min_max_xor(dst_reg, &src_reg);
9150 scalar_min_max_xor(dst_reg, &src_reg);
9153 if (umax_val >= insn_bitness) {
9154 /* Shifts greater than 31 or 63 are undefined.
9155 * This includes shifts by a negative number.
9157 mark_reg_unknown(env, regs, insn->dst_reg);
9161 scalar32_min_max_lsh(dst_reg, &src_reg);
9163 scalar_min_max_lsh(dst_reg, &src_reg);
9166 if (umax_val >= insn_bitness) {
9167 /* Shifts greater than 31 or 63 are undefined.
9168 * This includes shifts by a negative number.
9170 mark_reg_unknown(env, regs, insn->dst_reg);
9174 scalar32_min_max_rsh(dst_reg, &src_reg);
9176 scalar_min_max_rsh(dst_reg, &src_reg);
9179 if (umax_val >= insn_bitness) {
9180 /* Shifts greater than 31 or 63 are undefined.
9181 * This includes shifts by a negative number.
9183 mark_reg_unknown(env, regs, insn->dst_reg);
9187 scalar32_min_max_arsh(dst_reg, &src_reg);
9189 scalar_min_max_arsh(dst_reg, &src_reg);
9192 mark_reg_unknown(env, regs, insn->dst_reg);
9196 /* ALU32 ops are zero extended into 64bit register */
9198 zext_32_to_64(dst_reg);
9199 reg_bounds_sync(dst_reg);
9203 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9206 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9207 struct bpf_insn *insn)
9209 struct bpf_verifier_state *vstate = env->cur_state;
9210 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9211 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9212 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9213 u8 opcode = BPF_OP(insn->code);
9216 dst_reg = ®s[insn->dst_reg];
9218 if (dst_reg->type != SCALAR_VALUE)
9221 /* Make sure ID is cleared otherwise dst_reg min/max could be
9222 * incorrectly propagated into other registers by find_equal_scalars()
9225 if (BPF_SRC(insn->code) == BPF_X) {
9226 src_reg = ®s[insn->src_reg];
9227 if (src_reg->type != SCALAR_VALUE) {
9228 if (dst_reg->type != SCALAR_VALUE) {
9229 /* Combining two pointers by any ALU op yields
9230 * an arbitrary scalar. Disallow all math except
9231 * pointer subtraction
9233 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9234 mark_reg_unknown(env, regs, insn->dst_reg);
9237 verbose(env, "R%d pointer %s pointer prohibited\n",
9239 bpf_alu_string[opcode >> 4]);
9242 /* scalar += pointer
9243 * This is legal, but we have to reverse our
9244 * src/dest handling in computing the range
9246 err = mark_chain_precision(env, insn->dst_reg);
9249 return adjust_ptr_min_max_vals(env, insn,
9252 } else if (ptr_reg) {
9253 /* pointer += scalar */
9254 err = mark_chain_precision(env, insn->src_reg);
9257 return adjust_ptr_min_max_vals(env, insn,
9259 } else if (dst_reg->precise) {
9260 /* if dst_reg is precise, src_reg should be precise as well */
9261 err = mark_chain_precision(env, insn->src_reg);
9266 /* Pretend the src is a reg with a known value, since we only
9267 * need to be able to read from this state.
9269 off_reg.type = SCALAR_VALUE;
9270 __mark_reg_known(&off_reg, insn->imm);
9272 if (ptr_reg) /* pointer += K */
9273 return adjust_ptr_min_max_vals(env, insn,
9277 /* Got here implies adding two SCALAR_VALUEs */
9278 if (WARN_ON_ONCE(ptr_reg)) {
9279 print_verifier_state(env, state, true);
9280 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9283 if (WARN_ON(!src_reg)) {
9284 print_verifier_state(env, state, true);
9285 verbose(env, "verifier internal error: no src_reg\n");
9288 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9291 /* check validity of 32-bit and 64-bit arithmetic operations */
9292 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9294 struct bpf_reg_state *regs = cur_regs(env);
9295 u8 opcode = BPF_OP(insn->code);
9298 if (opcode == BPF_END || opcode == BPF_NEG) {
9299 if (opcode == BPF_NEG) {
9300 if (BPF_SRC(insn->code) != BPF_K ||
9301 insn->src_reg != BPF_REG_0 ||
9302 insn->off != 0 || insn->imm != 0) {
9303 verbose(env, "BPF_NEG uses reserved fields\n");
9307 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9308 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9309 BPF_CLASS(insn->code) == BPF_ALU64) {
9310 verbose(env, "BPF_END uses reserved fields\n");
9315 /* check src operand */
9316 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9320 if (is_pointer_value(env, insn->dst_reg)) {
9321 verbose(env, "R%d pointer arithmetic prohibited\n",
9326 /* check dest operand */
9327 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9331 } else if (opcode == BPF_MOV) {
9333 if (BPF_SRC(insn->code) == BPF_X) {
9334 if (insn->imm != 0 || insn->off != 0) {
9335 verbose(env, "BPF_MOV uses reserved fields\n");
9339 /* check src operand */
9340 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9344 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9345 verbose(env, "BPF_MOV uses reserved fields\n");
9350 /* check dest operand, mark as required later */
9351 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9355 if (BPF_SRC(insn->code) == BPF_X) {
9356 struct bpf_reg_state *src_reg = regs + insn->src_reg;
9357 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9359 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9361 * copy register state to dest reg
9363 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9364 /* Assign src and dst registers the same ID
9365 * that will be used by find_equal_scalars()
9366 * to propagate min/max range.
9368 src_reg->id = ++env->id_gen;
9369 copy_register_state(dst_reg, src_reg);
9370 dst_reg->live |= REG_LIVE_WRITTEN;
9371 dst_reg->subreg_def = DEF_NOT_SUBREG;
9374 if (is_pointer_value(env, insn->src_reg)) {
9376 "R%d partial copy of pointer\n",
9379 } else if (src_reg->type == SCALAR_VALUE) {
9380 copy_register_state(dst_reg, src_reg);
9381 /* Make sure ID is cleared otherwise
9382 * dst_reg min/max could be incorrectly
9383 * propagated into src_reg by find_equal_scalars()
9386 dst_reg->live |= REG_LIVE_WRITTEN;
9387 dst_reg->subreg_def = env->insn_idx + 1;
9389 mark_reg_unknown(env, regs,
9392 zext_32_to_64(dst_reg);
9393 reg_bounds_sync(dst_reg);
9397 * remember the value we stored into this reg
9399 /* clear any state __mark_reg_known doesn't set */
9400 mark_reg_unknown(env, regs, insn->dst_reg);
9401 regs[insn->dst_reg].type = SCALAR_VALUE;
9402 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9403 __mark_reg_known(regs + insn->dst_reg,
9406 __mark_reg_known(regs + insn->dst_reg,
9411 } else if (opcode > BPF_END) {
9412 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9415 } else { /* all other ALU ops: and, sub, xor, add, ... */
9417 if (BPF_SRC(insn->code) == BPF_X) {
9418 if (insn->imm != 0 || insn->off != 0) {
9419 verbose(env, "BPF_ALU uses reserved fields\n");
9422 /* check src1 operand */
9423 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9427 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9428 verbose(env, "BPF_ALU uses reserved fields\n");
9433 /* check src2 operand */
9434 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9438 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9439 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9440 verbose(env, "div by zero\n");
9444 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9445 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9446 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9448 if (insn->imm < 0 || insn->imm >= size) {
9449 verbose(env, "invalid shift %d\n", insn->imm);
9454 /* check dest operand */
9455 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9459 return adjust_reg_min_max_vals(env, insn);
9465 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9466 struct bpf_reg_state *dst_reg,
9467 enum bpf_reg_type type,
9468 bool range_right_open)
9470 struct bpf_func_state *state;
9471 struct bpf_reg_state *reg;
9474 if (dst_reg->off < 0 ||
9475 (dst_reg->off == 0 && range_right_open))
9476 /* This doesn't give us any range */
9479 if (dst_reg->umax_value > MAX_PACKET_OFF ||
9480 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9481 /* Risk of overflow. For instance, ptr + (1<<63) may be less
9482 * than pkt_end, but that's because it's also less than pkt.
9486 new_range = dst_reg->off;
9487 if (range_right_open)
9490 /* Examples for register markings:
9492 * pkt_data in dst register:
9496 * if (r2 > pkt_end) goto <handle exception>
9501 * if (r2 < pkt_end) goto <access okay>
9502 * <handle exception>
9505 * r2 == dst_reg, pkt_end == src_reg
9506 * r2=pkt(id=n,off=8,r=0)
9507 * r3=pkt(id=n,off=0,r=0)
9509 * pkt_data in src register:
9513 * if (pkt_end >= r2) goto <access okay>
9514 * <handle exception>
9518 * if (pkt_end <= r2) goto <handle exception>
9522 * pkt_end == dst_reg, r2 == src_reg
9523 * r2=pkt(id=n,off=8,r=0)
9524 * r3=pkt(id=n,off=0,r=0)
9526 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9527 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9528 * and [r3, r3 + 8-1) respectively is safe to access depending on
9532 /* If our ids match, then we must have the same max_value. And we
9533 * don't care about the other reg's fixed offset, since if it's too big
9534 * the range won't allow anything.
9535 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9537 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9538 if (reg->type == type && reg->id == dst_reg->id)
9539 /* keep the maximum range already checked */
9540 reg->range = max(reg->range, new_range);
9544 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9546 struct tnum subreg = tnum_subreg(reg->var_off);
9547 s32 sval = (s32)val;
9551 if (tnum_is_const(subreg))
9552 return !!tnum_equals_const(subreg, val);
9555 if (tnum_is_const(subreg))
9556 return !tnum_equals_const(subreg, val);
9559 if ((~subreg.mask & subreg.value) & val)
9561 if (!((subreg.mask | subreg.value) & val))
9565 if (reg->u32_min_value > val)
9567 else if (reg->u32_max_value <= val)
9571 if (reg->s32_min_value > sval)
9573 else if (reg->s32_max_value <= sval)
9577 if (reg->u32_max_value < val)
9579 else if (reg->u32_min_value >= val)
9583 if (reg->s32_max_value < sval)
9585 else if (reg->s32_min_value >= sval)
9589 if (reg->u32_min_value >= val)
9591 else if (reg->u32_max_value < val)
9595 if (reg->s32_min_value >= sval)
9597 else if (reg->s32_max_value < sval)
9601 if (reg->u32_max_value <= val)
9603 else if (reg->u32_min_value > val)
9607 if (reg->s32_max_value <= sval)
9609 else if (reg->s32_min_value > sval)
9618 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9620 s64 sval = (s64)val;
9624 if (tnum_is_const(reg->var_off))
9625 return !!tnum_equals_const(reg->var_off, val);
9628 if (tnum_is_const(reg->var_off))
9629 return !tnum_equals_const(reg->var_off, val);
9632 if ((~reg->var_off.mask & reg->var_off.value) & val)
9634 if (!((reg->var_off.mask | reg->var_off.value) & val))
9638 if (reg->umin_value > val)
9640 else if (reg->umax_value <= val)
9644 if (reg->smin_value > sval)
9646 else if (reg->smax_value <= sval)
9650 if (reg->umax_value < val)
9652 else if (reg->umin_value >= val)
9656 if (reg->smax_value < sval)
9658 else if (reg->smin_value >= sval)
9662 if (reg->umin_value >= val)
9664 else if (reg->umax_value < val)
9668 if (reg->smin_value >= sval)
9670 else if (reg->smax_value < sval)
9674 if (reg->umax_value <= val)
9676 else if (reg->umin_value > val)
9680 if (reg->smax_value <= sval)
9682 else if (reg->smin_value > sval)
9690 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9692 * 1 - branch will be taken and "goto target" will be executed
9693 * 0 - branch will not be taken and fall-through to next insn
9694 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9697 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9700 if (__is_pointer_value(false, reg)) {
9701 if (!reg_type_not_null(reg->type))
9704 /* If pointer is valid tests against zero will fail so we can
9705 * use this to direct branch taken.
9721 return is_branch32_taken(reg, val, opcode);
9722 return is_branch64_taken(reg, val, opcode);
9725 static int flip_opcode(u32 opcode)
9727 /* How can we transform "a <op> b" into "b <op> a"? */
9728 static const u8 opcode_flip[16] = {
9729 /* these stay the same */
9730 [BPF_JEQ >> 4] = BPF_JEQ,
9731 [BPF_JNE >> 4] = BPF_JNE,
9732 [BPF_JSET >> 4] = BPF_JSET,
9733 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9734 [BPF_JGE >> 4] = BPF_JLE,
9735 [BPF_JGT >> 4] = BPF_JLT,
9736 [BPF_JLE >> 4] = BPF_JGE,
9737 [BPF_JLT >> 4] = BPF_JGT,
9738 [BPF_JSGE >> 4] = BPF_JSLE,
9739 [BPF_JSGT >> 4] = BPF_JSLT,
9740 [BPF_JSLE >> 4] = BPF_JSGE,
9741 [BPF_JSLT >> 4] = BPF_JSGT
9743 return opcode_flip[opcode >> 4];
9746 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9747 struct bpf_reg_state *src_reg,
9750 struct bpf_reg_state *pkt;
9752 if (src_reg->type == PTR_TO_PACKET_END) {
9754 } else if (dst_reg->type == PTR_TO_PACKET_END) {
9756 opcode = flip_opcode(opcode);
9761 if (pkt->range >= 0)
9766 /* pkt <= pkt_end */
9770 if (pkt->range == BEYOND_PKT_END)
9771 /* pkt has at last one extra byte beyond pkt_end */
9772 return opcode == BPF_JGT;
9778 /* pkt >= pkt_end */
9779 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9780 return opcode == BPF_JGE;
9786 /* Adjusts the register min/max values in the case that the dst_reg is the
9787 * variable register that we are working on, and src_reg is a constant or we're
9788 * simply doing a BPF_K check.
9789 * In JEQ/JNE cases we also adjust the var_off values.
9791 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9792 struct bpf_reg_state *false_reg,
9794 u8 opcode, bool is_jmp32)
9796 struct tnum false_32off = tnum_subreg(false_reg->var_off);
9797 struct tnum false_64off = false_reg->var_off;
9798 struct tnum true_32off = tnum_subreg(true_reg->var_off);
9799 struct tnum true_64off = true_reg->var_off;
9800 s64 sval = (s64)val;
9801 s32 sval32 = (s32)val32;
9803 /* If the dst_reg is a pointer, we can't learn anything about its
9804 * variable offset from the compare (unless src_reg were a pointer into
9805 * the same object, but we don't bother with that.
9806 * Since false_reg and true_reg have the same type by construction, we
9807 * only need to check one of them for pointerness.
9809 if (__is_pointer_value(false, false_reg))
9813 /* JEQ/JNE comparison doesn't change the register equivalence.
9816 * if (r1 == 42) goto label;
9818 * label: // here both r1 and r2 are known to be 42.
9820 * Hence when marking register as known preserve it's ID.
9824 __mark_reg32_known(true_reg, val32);
9825 true_32off = tnum_subreg(true_reg->var_off);
9827 ___mark_reg_known(true_reg, val);
9828 true_64off = true_reg->var_off;
9833 __mark_reg32_known(false_reg, val32);
9834 false_32off = tnum_subreg(false_reg->var_off);
9836 ___mark_reg_known(false_reg, val);
9837 false_64off = false_reg->var_off;
9842 false_32off = tnum_and(false_32off, tnum_const(~val32));
9843 if (is_power_of_2(val32))
9844 true_32off = tnum_or(true_32off,
9847 false_64off = tnum_and(false_64off, tnum_const(~val));
9848 if (is_power_of_2(val))
9849 true_64off = tnum_or(true_64off,
9857 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
9858 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9860 false_reg->u32_max_value = min(false_reg->u32_max_value,
9862 true_reg->u32_min_value = max(true_reg->u32_min_value,
9865 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
9866 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9868 false_reg->umax_value = min(false_reg->umax_value, false_umax);
9869 true_reg->umin_value = max(true_reg->umin_value, true_umin);
9877 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
9878 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9880 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9881 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9883 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
9884 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9886 false_reg->smax_value = min(false_reg->smax_value, false_smax);
9887 true_reg->smin_value = max(true_reg->smin_value, true_smin);
9895 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
9896 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9898 false_reg->u32_min_value = max(false_reg->u32_min_value,
9900 true_reg->u32_max_value = min(true_reg->u32_max_value,
9903 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
9904 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9906 false_reg->umin_value = max(false_reg->umin_value, false_umin);
9907 true_reg->umax_value = min(true_reg->umax_value, true_umax);
9915 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
9916 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9918 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9919 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9921 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
9922 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9924 false_reg->smin_value = max(false_reg->smin_value, false_smin);
9925 true_reg->smax_value = min(true_reg->smax_value, true_smax);
9934 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9935 tnum_subreg(false_32off));
9936 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9937 tnum_subreg(true_32off));
9938 __reg_combine_32_into_64(false_reg);
9939 __reg_combine_32_into_64(true_reg);
9941 false_reg->var_off = false_64off;
9942 true_reg->var_off = true_64off;
9943 __reg_combine_64_into_32(false_reg);
9944 __reg_combine_64_into_32(true_reg);
9948 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9951 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9952 struct bpf_reg_state *false_reg,
9954 u8 opcode, bool is_jmp32)
9956 opcode = flip_opcode(opcode);
9957 /* This uses zero as "not present in table"; luckily the zero opcode,
9958 * BPF_JA, can't get here.
9961 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9964 /* Regs are known to be equal, so intersect their min/max/var_off */
9965 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9966 struct bpf_reg_state *dst_reg)
9968 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9969 dst_reg->umin_value);
9970 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9971 dst_reg->umax_value);
9972 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9973 dst_reg->smin_value);
9974 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9975 dst_reg->smax_value);
9976 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9978 reg_bounds_sync(src_reg);
9979 reg_bounds_sync(dst_reg);
9982 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9983 struct bpf_reg_state *true_dst,
9984 struct bpf_reg_state *false_src,
9985 struct bpf_reg_state *false_dst,
9990 __reg_combine_min_max(true_src, true_dst);
9993 __reg_combine_min_max(false_src, false_dst);
9998 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9999 struct bpf_reg_state *reg, u32 id,
10002 if (type_may_be_null(reg->type) && reg->id == id &&
10003 !WARN_ON_ONCE(!reg->id)) {
10004 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
10005 !tnum_equals_const(reg->var_off, 0) ||
10007 /* Old offset (both fixed and variable parts) should
10008 * have been known-zero, because we don't allow pointer
10009 * arithmetic on pointers that might be NULL. If we
10010 * see this happening, don't convert the register.
10015 reg->type = SCALAR_VALUE;
10016 /* We don't need id and ref_obj_id from this point
10017 * onwards anymore, thus we should better reset it,
10018 * so that state pruning has chances to take effect.
10021 reg->ref_obj_id = 0;
10026 mark_ptr_not_null_reg(reg);
10028 if (!reg_may_point_to_spin_lock(reg)) {
10029 /* For not-NULL ptr, reg->ref_obj_id will be reset
10030 * in release_reference().
10032 * reg->id is still used by spin_lock ptr. Other
10033 * than spin_lock ptr type, reg->id can be reset.
10040 /* The logic is similar to find_good_pkt_pointers(), both could eventually
10041 * be folded together at some point.
10043 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
10046 struct bpf_func_state *state = vstate->frame[vstate->curframe];
10047 struct bpf_reg_state *regs = state->regs, *reg;
10048 u32 ref_obj_id = regs[regno].ref_obj_id;
10049 u32 id = regs[regno].id;
10051 if (ref_obj_id && ref_obj_id == id && is_null)
10052 /* regs[regno] is in the " == NULL" branch.
10053 * No one could have freed the reference state before
10054 * doing the NULL check.
10056 WARN_ON_ONCE(release_reference_state(state, id));
10058 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10059 mark_ptr_or_null_reg(state, reg, id, is_null);
10063 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10064 struct bpf_reg_state *dst_reg,
10065 struct bpf_reg_state *src_reg,
10066 struct bpf_verifier_state *this_branch,
10067 struct bpf_verifier_state *other_branch)
10069 if (BPF_SRC(insn->code) != BPF_X)
10072 /* Pointers are always 64-bit. */
10073 if (BPF_CLASS(insn->code) == BPF_JMP32)
10076 switch (BPF_OP(insn->code)) {
10078 if ((dst_reg->type == PTR_TO_PACKET &&
10079 src_reg->type == PTR_TO_PACKET_END) ||
10080 (dst_reg->type == PTR_TO_PACKET_META &&
10081 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10082 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10083 find_good_pkt_pointers(this_branch, dst_reg,
10084 dst_reg->type, false);
10085 mark_pkt_end(other_branch, insn->dst_reg, true);
10086 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10087 src_reg->type == PTR_TO_PACKET) ||
10088 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10089 src_reg->type == PTR_TO_PACKET_META)) {
10090 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
10091 find_good_pkt_pointers(other_branch, src_reg,
10092 src_reg->type, true);
10093 mark_pkt_end(this_branch, insn->src_reg, false);
10099 if ((dst_reg->type == PTR_TO_PACKET &&
10100 src_reg->type == PTR_TO_PACKET_END) ||
10101 (dst_reg->type == PTR_TO_PACKET_META &&
10102 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10103 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10104 find_good_pkt_pointers(other_branch, dst_reg,
10105 dst_reg->type, true);
10106 mark_pkt_end(this_branch, insn->dst_reg, false);
10107 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10108 src_reg->type == PTR_TO_PACKET) ||
10109 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10110 src_reg->type == PTR_TO_PACKET_META)) {
10111 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
10112 find_good_pkt_pointers(this_branch, src_reg,
10113 src_reg->type, false);
10114 mark_pkt_end(other_branch, insn->src_reg, true);
10120 if ((dst_reg->type == PTR_TO_PACKET &&
10121 src_reg->type == PTR_TO_PACKET_END) ||
10122 (dst_reg->type == PTR_TO_PACKET_META &&
10123 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10124 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10125 find_good_pkt_pointers(this_branch, dst_reg,
10126 dst_reg->type, true);
10127 mark_pkt_end(other_branch, insn->dst_reg, false);
10128 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10129 src_reg->type == PTR_TO_PACKET) ||
10130 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10131 src_reg->type == PTR_TO_PACKET_META)) {
10132 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10133 find_good_pkt_pointers(other_branch, src_reg,
10134 src_reg->type, false);
10135 mark_pkt_end(this_branch, insn->src_reg, true);
10141 if ((dst_reg->type == PTR_TO_PACKET &&
10142 src_reg->type == PTR_TO_PACKET_END) ||
10143 (dst_reg->type == PTR_TO_PACKET_META &&
10144 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10145 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10146 find_good_pkt_pointers(other_branch, dst_reg,
10147 dst_reg->type, false);
10148 mark_pkt_end(this_branch, insn->dst_reg, true);
10149 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10150 src_reg->type == PTR_TO_PACKET) ||
10151 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10152 src_reg->type == PTR_TO_PACKET_META)) {
10153 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10154 find_good_pkt_pointers(this_branch, src_reg,
10155 src_reg->type, true);
10156 mark_pkt_end(other_branch, insn->src_reg, false);
10168 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10169 struct bpf_reg_state *known_reg)
10171 struct bpf_func_state *state;
10172 struct bpf_reg_state *reg;
10174 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10175 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10176 copy_register_state(reg, known_reg);
10180 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10181 struct bpf_insn *insn, int *insn_idx)
10183 struct bpf_verifier_state *this_branch = env->cur_state;
10184 struct bpf_verifier_state *other_branch;
10185 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10186 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10187 u8 opcode = BPF_OP(insn->code);
10192 /* Only conditional jumps are expected to reach here. */
10193 if (opcode == BPF_JA || opcode > BPF_JSLE) {
10194 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10198 if (BPF_SRC(insn->code) == BPF_X) {
10199 if (insn->imm != 0) {
10200 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10204 /* check src1 operand */
10205 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10209 if (is_pointer_value(env, insn->src_reg)) {
10210 verbose(env, "R%d pointer comparison prohibited\n",
10214 src_reg = ®s[insn->src_reg];
10216 if (insn->src_reg != BPF_REG_0) {
10217 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10222 /* check src2 operand */
10223 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10227 dst_reg = ®s[insn->dst_reg];
10228 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10230 if (BPF_SRC(insn->code) == BPF_K) {
10231 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10232 } else if (src_reg->type == SCALAR_VALUE &&
10233 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10234 pred = is_branch_taken(dst_reg,
10235 tnum_subreg(src_reg->var_off).value,
10238 } else if (src_reg->type == SCALAR_VALUE &&
10239 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10240 pred = is_branch_taken(dst_reg,
10241 src_reg->var_off.value,
10244 } else if (reg_is_pkt_pointer_any(dst_reg) &&
10245 reg_is_pkt_pointer_any(src_reg) &&
10247 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10251 /* If we get here with a dst_reg pointer type it is because
10252 * above is_branch_taken() special cased the 0 comparison.
10254 if (!__is_pointer_value(false, dst_reg))
10255 err = mark_chain_precision(env, insn->dst_reg);
10256 if (BPF_SRC(insn->code) == BPF_X && !err &&
10257 !__is_pointer_value(false, src_reg))
10258 err = mark_chain_precision(env, insn->src_reg);
10264 /* Only follow the goto, ignore fall-through. If needed, push
10265 * the fall-through branch for simulation under speculative
10268 if (!env->bypass_spec_v1 &&
10269 !sanitize_speculative_path(env, insn, *insn_idx + 1,
10272 *insn_idx += insn->off;
10274 } else if (pred == 0) {
10275 /* Only follow the fall-through branch, since that's where the
10276 * program will go. If needed, push the goto branch for
10277 * simulation under speculative execution.
10279 if (!env->bypass_spec_v1 &&
10280 !sanitize_speculative_path(env, insn,
10281 *insn_idx + insn->off + 1,
10287 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10291 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10293 /* detect if we are comparing against a constant value so we can adjust
10294 * our min/max values for our dst register.
10295 * this is only legit if both are scalars (or pointers to the same
10296 * object, I suppose, but we don't support that right now), because
10297 * otherwise the different base pointers mean the offsets aren't
10300 if (BPF_SRC(insn->code) == BPF_X) {
10301 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
10303 if (dst_reg->type == SCALAR_VALUE &&
10304 src_reg->type == SCALAR_VALUE) {
10305 if (tnum_is_const(src_reg->var_off) ||
10307 tnum_is_const(tnum_subreg(src_reg->var_off))))
10308 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10310 src_reg->var_off.value,
10311 tnum_subreg(src_reg->var_off).value,
10313 else if (tnum_is_const(dst_reg->var_off) ||
10315 tnum_is_const(tnum_subreg(dst_reg->var_off))))
10316 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10318 dst_reg->var_off.value,
10319 tnum_subreg(dst_reg->var_off).value,
10321 else if (!is_jmp32 &&
10322 (opcode == BPF_JEQ || opcode == BPF_JNE))
10323 /* Comparing for equality, we can combine knowledge */
10324 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10325 &other_branch_regs[insn->dst_reg],
10326 src_reg, dst_reg, opcode);
10328 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10329 find_equal_scalars(this_branch, src_reg);
10330 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10334 } else if (dst_reg->type == SCALAR_VALUE) {
10335 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10336 dst_reg, insn->imm, (u32)insn->imm,
10340 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10341 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10342 find_equal_scalars(this_branch, dst_reg);
10343 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10346 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10347 * NOTE: these optimizations below are related with pointer comparison
10348 * which will never be JMP32.
10350 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10351 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10352 type_may_be_null(dst_reg->type)) {
10353 /* Mark all identical registers in each branch as either
10354 * safe or unknown depending R == 0 or R != 0 conditional.
10356 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10357 opcode == BPF_JNE);
10358 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10359 opcode == BPF_JEQ);
10360 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
10361 this_branch, other_branch) &&
10362 is_pointer_value(env, insn->dst_reg)) {
10363 verbose(env, "R%d pointer comparison prohibited\n",
10367 if (env->log.level & BPF_LOG_LEVEL)
10368 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10372 /* verify BPF_LD_IMM64 instruction */
10373 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10375 struct bpf_insn_aux_data *aux = cur_aux(env);
10376 struct bpf_reg_state *regs = cur_regs(env);
10377 struct bpf_reg_state *dst_reg;
10378 struct bpf_map *map;
10381 if (BPF_SIZE(insn->code) != BPF_DW) {
10382 verbose(env, "invalid BPF_LD_IMM insn\n");
10385 if (insn->off != 0) {
10386 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10390 err = check_reg_arg(env, insn->dst_reg, DST_OP);
10394 dst_reg = ®s[insn->dst_reg];
10395 if (insn->src_reg == 0) {
10396 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10398 dst_reg->type = SCALAR_VALUE;
10399 __mark_reg_known(®s[insn->dst_reg], imm);
10403 /* All special src_reg cases are listed below. From this point onwards
10404 * we either succeed and assign a corresponding dst_reg->type after
10405 * zeroing the offset, or fail and reject the program.
10407 mark_reg_known_zero(env, regs, insn->dst_reg);
10409 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10410 dst_reg->type = aux->btf_var.reg_type;
10411 switch (base_type(dst_reg->type)) {
10413 dst_reg->mem_size = aux->btf_var.mem_size;
10415 case PTR_TO_BTF_ID:
10416 dst_reg->btf = aux->btf_var.btf;
10417 dst_reg->btf_id = aux->btf_var.btf_id;
10420 verbose(env, "bpf verifier is misconfigured\n");
10426 if (insn->src_reg == BPF_PSEUDO_FUNC) {
10427 struct bpf_prog_aux *aux = env->prog->aux;
10428 u32 subprogno = find_subprog(env,
10429 env->insn_idx + insn->imm + 1);
10431 if (!aux->func_info) {
10432 verbose(env, "missing btf func_info\n");
10435 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10436 verbose(env, "callback function not static\n");
10440 dst_reg->type = PTR_TO_FUNC;
10441 dst_reg->subprogno = subprogno;
10445 map = env->used_maps[aux->map_index];
10446 dst_reg->map_ptr = map;
10448 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10449 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10450 dst_reg->type = PTR_TO_MAP_VALUE;
10451 dst_reg->off = aux->map_off;
10452 if (map_value_has_spin_lock(map))
10453 dst_reg->id = ++env->id_gen;
10454 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10455 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10456 dst_reg->type = CONST_PTR_TO_MAP;
10458 verbose(env, "bpf verifier is misconfigured\n");
10465 static bool may_access_skb(enum bpf_prog_type type)
10468 case BPF_PROG_TYPE_SOCKET_FILTER:
10469 case BPF_PROG_TYPE_SCHED_CLS:
10470 case BPF_PROG_TYPE_SCHED_ACT:
10477 /* verify safety of LD_ABS|LD_IND instructions:
10478 * - they can only appear in the programs where ctx == skb
10479 * - since they are wrappers of function calls, they scratch R1-R5 registers,
10480 * preserve R6-R9, and store return value into R0
10483 * ctx == skb == R6 == CTX
10486 * SRC == any register
10487 * IMM == 32-bit immediate
10490 * R0 - 8/16/32-bit skb data converted to cpu endianness
10492 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10494 struct bpf_reg_state *regs = cur_regs(env);
10495 static const int ctx_reg = BPF_REG_6;
10496 u8 mode = BPF_MODE(insn->code);
10499 if (!may_access_skb(resolve_prog_type(env->prog))) {
10500 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10504 if (!env->ops->gen_ld_abs) {
10505 verbose(env, "bpf verifier is misconfigured\n");
10509 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10510 BPF_SIZE(insn->code) == BPF_DW ||
10511 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10512 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10516 /* check whether implicit source operand (register R6) is readable */
10517 err = check_reg_arg(env, ctx_reg, SRC_OP);
10521 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10522 * gen_ld_abs() may terminate the program at runtime, leading to
10525 err = check_reference_leak(env);
10527 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10531 if (env->cur_state->active_spin_lock) {
10532 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10536 if (regs[ctx_reg].type != PTR_TO_CTX) {
10538 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10542 if (mode == BPF_IND) {
10543 /* check explicit source operand */
10544 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10549 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
10553 /* reset caller saved regs to unreadable */
10554 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10555 mark_reg_not_init(env, regs, caller_saved[i]);
10556 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10559 /* mark destination R0 register as readable, since it contains
10560 * the value fetched from the packet.
10561 * Already marked as written above.
10563 mark_reg_unknown(env, regs, BPF_REG_0);
10564 /* ld_abs load up to 32-bit skb data. */
10565 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10569 static int check_return_code(struct bpf_verifier_env *env)
10571 struct tnum enforce_attach_type_range = tnum_unknown;
10572 const struct bpf_prog *prog = env->prog;
10573 struct bpf_reg_state *reg;
10574 struct tnum range = tnum_range(0, 1);
10575 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10577 struct bpf_func_state *frame = env->cur_state->frame[0];
10578 const bool is_subprog = frame->subprogno;
10580 /* LSM and struct_ops func-ptr's return type could be "void" */
10582 switch (prog_type) {
10583 case BPF_PROG_TYPE_LSM:
10584 if (prog->expected_attach_type == BPF_LSM_CGROUP)
10585 /* See below, can be 0 or 0-1 depending on hook. */
10588 case BPF_PROG_TYPE_STRUCT_OPS:
10589 if (!prog->aux->attach_func_proto->type)
10597 /* eBPF calling convention is such that R0 is used
10598 * to return the value from eBPF program.
10599 * Make sure that it's readable at this time
10600 * of bpf_exit, which means that program wrote
10601 * something into it earlier
10603 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10607 if (is_pointer_value(env, BPF_REG_0)) {
10608 verbose(env, "R0 leaks addr as return value\n");
10612 reg = cur_regs(env) + BPF_REG_0;
10614 if (frame->in_async_callback_fn) {
10615 /* enforce return zero from async callbacks like timer */
10616 if (reg->type != SCALAR_VALUE) {
10617 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10618 reg_type_str(env, reg->type));
10622 if (!tnum_in(tnum_const(0), reg->var_off)) {
10623 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10630 if (reg->type != SCALAR_VALUE) {
10631 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10632 reg_type_str(env, reg->type));
10638 switch (prog_type) {
10639 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10640 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10641 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10642 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10643 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10644 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10645 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10646 range = tnum_range(1, 1);
10647 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10648 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10649 range = tnum_range(0, 3);
10651 case BPF_PROG_TYPE_CGROUP_SKB:
10652 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10653 range = tnum_range(0, 3);
10654 enforce_attach_type_range = tnum_range(2, 3);
10657 case BPF_PROG_TYPE_CGROUP_SOCK:
10658 case BPF_PROG_TYPE_SOCK_OPS:
10659 case BPF_PROG_TYPE_CGROUP_DEVICE:
10660 case BPF_PROG_TYPE_CGROUP_SYSCTL:
10661 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10663 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10664 if (!env->prog->aux->attach_btf_id)
10666 range = tnum_const(0);
10668 case BPF_PROG_TYPE_TRACING:
10669 switch (env->prog->expected_attach_type) {
10670 case BPF_TRACE_FENTRY:
10671 case BPF_TRACE_FEXIT:
10672 range = tnum_const(0);
10674 case BPF_TRACE_RAW_TP:
10675 case BPF_MODIFY_RETURN:
10677 case BPF_TRACE_ITER:
10683 case BPF_PROG_TYPE_SK_LOOKUP:
10684 range = tnum_range(SK_DROP, SK_PASS);
10687 case BPF_PROG_TYPE_LSM:
10688 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10689 /* Regular BPF_PROG_TYPE_LSM programs can return
10694 if (!env->prog->aux->attach_func_proto->type) {
10695 /* Make sure programs that attach to void
10696 * hooks don't try to modify return value.
10698 range = tnum_range(1, 1);
10702 case BPF_PROG_TYPE_EXT:
10703 /* freplace program can return anything as its return value
10704 * depends on the to-be-replaced kernel func or bpf program.
10710 if (reg->type != SCALAR_VALUE) {
10711 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10712 reg_type_str(env, reg->type));
10716 if (!tnum_in(range, reg->var_off)) {
10717 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10718 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10719 prog_type == BPF_PROG_TYPE_LSM &&
10720 !prog->aux->attach_func_proto->type)
10721 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10725 if (!tnum_is_unknown(enforce_attach_type_range) &&
10726 tnum_in(enforce_attach_type_range, reg->var_off))
10727 env->prog->enforce_expected_attach_type = 1;
10731 /* non-recursive DFS pseudo code
10732 * 1 procedure DFS-iterative(G,v):
10733 * 2 label v as discovered
10734 * 3 let S be a stack
10736 * 5 while S is not empty
10738 * 7 if t is what we're looking for:
10740 * 9 for all edges e in G.adjacentEdges(t) do
10741 * 10 if edge e is already labelled
10742 * 11 continue with the next edge
10743 * 12 w <- G.adjacentVertex(t,e)
10744 * 13 if vertex w is not discovered and not explored
10745 * 14 label e as tree-edge
10746 * 15 label w as discovered
10749 * 18 else if vertex w is discovered
10750 * 19 label e as back-edge
10752 * 21 // vertex w is explored
10753 * 22 label e as forward- or cross-edge
10754 * 23 label t as explored
10758 * 0x10 - discovered
10759 * 0x11 - discovered and fall-through edge labelled
10760 * 0x12 - discovered and fall-through and branch edges labelled
10771 static u32 state_htab_size(struct bpf_verifier_env *env)
10773 return env->prog->len;
10776 static struct bpf_verifier_state_list **explored_state(
10777 struct bpf_verifier_env *env,
10780 struct bpf_verifier_state *cur = env->cur_state;
10781 struct bpf_func_state *state = cur->frame[cur->curframe];
10783 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10786 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10788 env->insn_aux_data[idx].prune_point = true;
10792 DONE_EXPLORING = 0,
10793 KEEP_EXPLORING = 1,
10796 /* t, w, e - match pseudo-code above:
10797 * t - index of current instruction
10798 * w - next instruction
10801 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10804 int *insn_stack = env->cfg.insn_stack;
10805 int *insn_state = env->cfg.insn_state;
10807 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10808 return DONE_EXPLORING;
10810 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10811 return DONE_EXPLORING;
10813 if (w < 0 || w >= env->prog->len) {
10814 verbose_linfo(env, t, "%d: ", t);
10815 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10820 /* mark branch target for state pruning */
10821 init_explored_state(env, w);
10823 if (insn_state[w] == 0) {
10825 insn_state[t] = DISCOVERED | e;
10826 insn_state[w] = DISCOVERED;
10827 if (env->cfg.cur_stack >= env->prog->len)
10829 insn_stack[env->cfg.cur_stack++] = w;
10830 return KEEP_EXPLORING;
10831 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10832 if (loop_ok && env->bpf_capable)
10833 return DONE_EXPLORING;
10834 verbose_linfo(env, t, "%d: ", t);
10835 verbose_linfo(env, w, "%d: ", w);
10836 verbose(env, "back-edge from insn %d to %d\n", t, w);
10838 } else if (insn_state[w] == EXPLORED) {
10839 /* forward- or cross-edge */
10840 insn_state[t] = DISCOVERED | e;
10842 verbose(env, "insn state internal bug\n");
10845 return DONE_EXPLORING;
10848 static int visit_func_call_insn(int t, int insn_cnt,
10849 struct bpf_insn *insns,
10850 struct bpf_verifier_env *env,
10855 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10859 if (t + 1 < insn_cnt)
10860 init_explored_state(env, t + 1);
10861 if (visit_callee) {
10862 init_explored_state(env, t);
10863 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10864 /* It's ok to allow recursion from CFG point of
10865 * view. __check_func_call() will do the actual
10868 bpf_pseudo_func(insns + t));
10873 /* Visits the instruction at index t and returns one of the following:
10874 * < 0 - an error occurred
10875 * DONE_EXPLORING - the instruction was fully explored
10876 * KEEP_EXPLORING - there is still work to be done before it is fully explored
10878 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10880 struct bpf_insn *insns = env->prog->insnsi;
10883 if (bpf_pseudo_func(insns + t))
10884 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10886 /* All non-branch instructions have a single fall-through edge. */
10887 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10888 BPF_CLASS(insns[t].code) != BPF_JMP32)
10889 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10891 switch (BPF_OP(insns[t].code)) {
10893 return DONE_EXPLORING;
10896 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10897 /* Mark this call insn to trigger is_state_visited() check
10898 * before call itself is processed by __check_func_call().
10899 * Otherwise new async state will be pushed for further
10902 init_explored_state(env, t);
10903 return visit_func_call_insn(t, insn_cnt, insns, env,
10904 insns[t].src_reg == BPF_PSEUDO_CALL);
10907 if (BPF_SRC(insns[t].code) != BPF_K)
10910 /* unconditional jump with single edge */
10911 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10916 /* unconditional jmp is not a good pruning point,
10917 * but it's marked, since backtracking needs
10918 * to record jmp history in is_state_visited().
10920 init_explored_state(env, t + insns[t].off + 1);
10921 /* tell verifier to check for equivalent states
10922 * after every call and jump
10924 if (t + 1 < insn_cnt)
10925 init_explored_state(env, t + 1);
10930 /* conditional jump with two edges */
10931 init_explored_state(env, t);
10932 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10936 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10940 /* non-recursive depth-first-search to detect loops in BPF program
10941 * loop == back-edge in directed graph
10943 static int check_cfg(struct bpf_verifier_env *env)
10945 int insn_cnt = env->prog->len;
10946 int *insn_stack, *insn_state;
10950 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10954 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10956 kvfree(insn_state);
10960 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10961 insn_stack[0] = 0; /* 0 is the first instruction */
10962 env->cfg.cur_stack = 1;
10964 while (env->cfg.cur_stack > 0) {
10965 int t = insn_stack[env->cfg.cur_stack - 1];
10967 ret = visit_insn(t, insn_cnt, env);
10969 case DONE_EXPLORING:
10970 insn_state[t] = EXPLORED;
10971 env->cfg.cur_stack--;
10973 case KEEP_EXPLORING:
10977 verbose(env, "visit_insn internal bug\n");
10984 if (env->cfg.cur_stack < 0) {
10985 verbose(env, "pop stack internal bug\n");
10990 for (i = 0; i < insn_cnt; i++) {
10991 if (insn_state[i] != EXPLORED) {
10992 verbose(env, "unreachable insn %d\n", i);
10997 ret = 0; /* cfg looks good */
11000 kvfree(insn_state);
11001 kvfree(insn_stack);
11002 env->cfg.insn_state = env->cfg.insn_stack = NULL;
11006 static int check_abnormal_return(struct bpf_verifier_env *env)
11010 for (i = 1; i < env->subprog_cnt; i++) {
11011 if (env->subprog_info[i].has_ld_abs) {
11012 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
11015 if (env->subprog_info[i].has_tail_call) {
11016 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
11023 /* The minimum supported BTF func info size */
11024 #define MIN_BPF_FUNCINFO_SIZE 8
11025 #define MAX_FUNCINFO_REC_SIZE 252
11027 static int check_btf_func(struct bpf_verifier_env *env,
11028 const union bpf_attr *attr,
11031 const struct btf_type *type, *func_proto, *ret_type;
11032 u32 i, nfuncs, urec_size, min_size;
11033 u32 krec_size = sizeof(struct bpf_func_info);
11034 struct bpf_func_info *krecord;
11035 struct bpf_func_info_aux *info_aux = NULL;
11036 struct bpf_prog *prog;
11037 const struct btf *btf;
11039 u32 prev_offset = 0;
11040 bool scalar_return;
11043 nfuncs = attr->func_info_cnt;
11045 if (check_abnormal_return(env))
11050 if (nfuncs != env->subprog_cnt) {
11051 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11055 urec_size = attr->func_info_rec_size;
11056 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11057 urec_size > MAX_FUNCINFO_REC_SIZE ||
11058 urec_size % sizeof(u32)) {
11059 verbose(env, "invalid func info rec size %u\n", urec_size);
11064 btf = prog->aux->btf;
11066 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11067 min_size = min_t(u32, krec_size, urec_size);
11069 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11072 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11076 for (i = 0; i < nfuncs; i++) {
11077 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11079 if (ret == -E2BIG) {
11080 verbose(env, "nonzero tailing record in func info");
11081 /* set the size kernel expects so loader can zero
11082 * out the rest of the record.
11084 if (copy_to_bpfptr_offset(uattr,
11085 offsetof(union bpf_attr, func_info_rec_size),
11086 &min_size, sizeof(min_size)))
11092 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11097 /* check insn_off */
11100 if (krecord[i].insn_off) {
11102 "nonzero insn_off %u for the first func info record",
11103 krecord[i].insn_off);
11106 } else if (krecord[i].insn_off <= prev_offset) {
11108 "same or smaller insn offset (%u) than previous func info record (%u)",
11109 krecord[i].insn_off, prev_offset);
11113 if (env->subprog_info[i].start != krecord[i].insn_off) {
11114 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11118 /* check type_id */
11119 type = btf_type_by_id(btf, krecord[i].type_id);
11120 if (!type || !btf_type_is_func(type)) {
11121 verbose(env, "invalid type id %d in func info",
11122 krecord[i].type_id);
11125 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11127 func_proto = btf_type_by_id(btf, type->type);
11128 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11129 /* btf_func_check() already verified it during BTF load */
11131 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11133 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11134 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11135 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11138 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11139 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11143 prev_offset = krecord[i].insn_off;
11144 bpfptr_add(&urecord, urec_size);
11147 prog->aux->func_info = krecord;
11148 prog->aux->func_info_cnt = nfuncs;
11149 prog->aux->func_info_aux = info_aux;
11158 static void adjust_btf_func(struct bpf_verifier_env *env)
11160 struct bpf_prog_aux *aux = env->prog->aux;
11163 if (!aux->func_info)
11166 for (i = 0; i < env->subprog_cnt; i++)
11167 aux->func_info[i].insn_off = env->subprog_info[i].start;
11170 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
11171 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
11173 static int check_btf_line(struct bpf_verifier_env *env,
11174 const union bpf_attr *attr,
11177 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11178 struct bpf_subprog_info *sub;
11179 struct bpf_line_info *linfo;
11180 struct bpf_prog *prog;
11181 const struct btf *btf;
11185 nr_linfo = attr->line_info_cnt;
11188 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11191 rec_size = attr->line_info_rec_size;
11192 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11193 rec_size > MAX_LINEINFO_REC_SIZE ||
11194 rec_size & (sizeof(u32) - 1))
11197 /* Need to zero it in case the userspace may
11198 * pass in a smaller bpf_line_info object.
11200 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11201 GFP_KERNEL | __GFP_NOWARN);
11206 btf = prog->aux->btf;
11209 sub = env->subprog_info;
11210 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11211 expected_size = sizeof(struct bpf_line_info);
11212 ncopy = min_t(u32, expected_size, rec_size);
11213 for (i = 0; i < nr_linfo; i++) {
11214 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11216 if (err == -E2BIG) {
11217 verbose(env, "nonzero tailing record in line_info");
11218 if (copy_to_bpfptr_offset(uattr,
11219 offsetof(union bpf_attr, line_info_rec_size),
11220 &expected_size, sizeof(expected_size)))
11226 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11232 * Check insn_off to ensure
11233 * 1) strictly increasing AND
11234 * 2) bounded by prog->len
11236 * The linfo[0].insn_off == 0 check logically falls into
11237 * the later "missing bpf_line_info for func..." case
11238 * because the first linfo[0].insn_off must be the
11239 * first sub also and the first sub must have
11240 * subprog_info[0].start == 0.
11242 if ((i && linfo[i].insn_off <= prev_offset) ||
11243 linfo[i].insn_off >= prog->len) {
11244 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11245 i, linfo[i].insn_off, prev_offset,
11251 if (!prog->insnsi[linfo[i].insn_off].code) {
11253 "Invalid insn code at line_info[%u].insn_off\n",
11259 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11260 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11261 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11266 if (s != env->subprog_cnt) {
11267 if (linfo[i].insn_off == sub[s].start) {
11268 sub[s].linfo_idx = i;
11270 } else if (sub[s].start < linfo[i].insn_off) {
11271 verbose(env, "missing bpf_line_info for func#%u\n", s);
11277 prev_offset = linfo[i].insn_off;
11278 bpfptr_add(&ulinfo, rec_size);
11281 if (s != env->subprog_cnt) {
11282 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11283 env->subprog_cnt - s, s);
11288 prog->aux->linfo = linfo;
11289 prog->aux->nr_linfo = nr_linfo;
11298 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
11299 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
11301 static int check_core_relo(struct bpf_verifier_env *env,
11302 const union bpf_attr *attr,
11305 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11306 struct bpf_core_relo core_relo = {};
11307 struct bpf_prog *prog = env->prog;
11308 const struct btf *btf = prog->aux->btf;
11309 struct bpf_core_ctx ctx = {
11313 bpfptr_t u_core_relo;
11316 nr_core_relo = attr->core_relo_cnt;
11319 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11322 rec_size = attr->core_relo_rec_size;
11323 if (rec_size < MIN_CORE_RELO_SIZE ||
11324 rec_size > MAX_CORE_RELO_SIZE ||
11325 rec_size % sizeof(u32))
11328 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11329 expected_size = sizeof(struct bpf_core_relo);
11330 ncopy = min_t(u32, expected_size, rec_size);
11332 /* Unlike func_info and line_info, copy and apply each CO-RE
11333 * relocation record one at a time.
11335 for (i = 0; i < nr_core_relo; i++) {
11336 /* future proofing when sizeof(bpf_core_relo) changes */
11337 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11339 if (err == -E2BIG) {
11340 verbose(env, "nonzero tailing record in core_relo");
11341 if (copy_to_bpfptr_offset(uattr,
11342 offsetof(union bpf_attr, core_relo_rec_size),
11343 &expected_size, sizeof(expected_size)))
11349 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11354 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11355 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11356 i, core_relo.insn_off, prog->len);
11361 err = bpf_core_apply(&ctx, &core_relo, i,
11362 &prog->insnsi[core_relo.insn_off / 8]);
11365 bpfptr_add(&u_core_relo, rec_size);
11370 static int check_btf_info(struct bpf_verifier_env *env,
11371 const union bpf_attr *attr,
11377 if (!attr->func_info_cnt && !attr->line_info_cnt) {
11378 if (check_abnormal_return(env))
11383 btf = btf_get_by_fd(attr->prog_btf_fd);
11385 return PTR_ERR(btf);
11386 if (btf_is_kernel(btf)) {
11390 env->prog->aux->btf = btf;
11392 err = check_btf_func(env, attr, uattr);
11396 err = check_btf_line(env, attr, uattr);
11400 err = check_core_relo(env, attr, uattr);
11407 /* check %cur's range satisfies %old's */
11408 static bool range_within(struct bpf_reg_state *old,
11409 struct bpf_reg_state *cur)
11411 return old->umin_value <= cur->umin_value &&
11412 old->umax_value >= cur->umax_value &&
11413 old->smin_value <= cur->smin_value &&
11414 old->smax_value >= cur->smax_value &&
11415 old->u32_min_value <= cur->u32_min_value &&
11416 old->u32_max_value >= cur->u32_max_value &&
11417 old->s32_min_value <= cur->s32_min_value &&
11418 old->s32_max_value >= cur->s32_max_value;
11421 /* If in the old state two registers had the same id, then they need to have
11422 * the same id in the new state as well. But that id could be different from
11423 * the old state, so we need to track the mapping from old to new ids.
11424 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11425 * regs with old id 5 must also have new id 9 for the new state to be safe. But
11426 * regs with a different old id could still have new id 9, we don't care about
11428 * So we look through our idmap to see if this old id has been seen before. If
11429 * so, we require the new id to match; otherwise, we add the id pair to the map.
11431 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11435 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11436 if (!idmap[i].old) {
11437 /* Reached an empty slot; haven't seen this id before */
11438 idmap[i].old = old_id;
11439 idmap[i].cur = cur_id;
11442 if (idmap[i].old == old_id)
11443 return idmap[i].cur == cur_id;
11445 /* We ran out of idmap slots, which should be impossible */
11450 static void clean_func_state(struct bpf_verifier_env *env,
11451 struct bpf_func_state *st)
11453 enum bpf_reg_liveness live;
11456 for (i = 0; i < BPF_REG_FP; i++) {
11457 live = st->regs[i].live;
11458 /* liveness must not touch this register anymore */
11459 st->regs[i].live |= REG_LIVE_DONE;
11460 if (!(live & REG_LIVE_READ))
11461 /* since the register is unused, clear its state
11462 * to make further comparison simpler
11464 __mark_reg_not_init(env, &st->regs[i]);
11467 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11468 live = st->stack[i].spilled_ptr.live;
11469 /* liveness must not touch this stack slot anymore */
11470 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11471 if (!(live & REG_LIVE_READ)) {
11472 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11473 for (j = 0; j < BPF_REG_SIZE; j++)
11474 st->stack[i].slot_type[j] = STACK_INVALID;
11479 static void clean_verifier_state(struct bpf_verifier_env *env,
11480 struct bpf_verifier_state *st)
11484 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11485 /* all regs in this state in all frames were already marked */
11488 for (i = 0; i <= st->curframe; i++)
11489 clean_func_state(env, st->frame[i]);
11492 /* the parentage chains form a tree.
11493 * the verifier states are added to state lists at given insn and
11494 * pushed into state stack for future exploration.
11495 * when the verifier reaches bpf_exit insn some of the verifer states
11496 * stored in the state lists have their final liveness state already,
11497 * but a lot of states will get revised from liveness point of view when
11498 * the verifier explores other branches.
11501 * 2: if r1 == 100 goto pc+1
11504 * when the verifier reaches exit insn the register r0 in the state list of
11505 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11506 * of insn 2 and goes exploring further. At the insn 4 it will walk the
11507 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11509 * Since the verifier pushes the branch states as it sees them while exploring
11510 * the program the condition of walking the branch instruction for the second
11511 * time means that all states below this branch were already explored and
11512 * their final liveness marks are already propagated.
11513 * Hence when the verifier completes the search of state list in is_state_visited()
11514 * we can call this clean_live_states() function to mark all liveness states
11515 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11516 * will not be used.
11517 * This function also clears the registers and stack for states that !READ
11518 * to simplify state merging.
11520 * Important note here that walking the same branch instruction in the callee
11521 * doesn't meant that the states are DONE. The verifier has to compare
11524 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11525 struct bpf_verifier_state *cur)
11527 struct bpf_verifier_state_list *sl;
11530 sl = *explored_state(env, insn);
11532 if (sl->state.branches)
11534 if (sl->state.insn_idx != insn ||
11535 sl->state.curframe != cur->curframe)
11537 for (i = 0; i <= cur->curframe; i++)
11538 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11540 clean_verifier_state(env, &sl->state);
11546 /* Returns true if (rold safe implies rcur safe) */
11547 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11548 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11552 if (!(rold->live & REG_LIVE_READ))
11553 /* explored state didn't use this */
11556 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11558 if (rold->type == PTR_TO_STACK)
11559 /* two stack pointers are equal only if they're pointing to
11560 * the same stack frame, since fp-8 in foo != fp-8 in bar
11562 return equal && rold->frameno == rcur->frameno;
11567 if (rold->type == NOT_INIT)
11568 /* explored state can't have used this */
11570 if (rcur->type == NOT_INIT)
11572 switch (base_type(rold->type)) {
11574 if (env->explore_alu_limits)
11576 if (rcur->type == SCALAR_VALUE) {
11577 if (!rold->precise && !rcur->precise)
11579 /* new val must satisfy old val knowledge */
11580 return range_within(rold, rcur) &&
11581 tnum_in(rold->var_off, rcur->var_off);
11583 /* We're trying to use a pointer in place of a scalar.
11584 * Even if the scalar was unbounded, this could lead to
11585 * pointer leaks because scalars are allowed to leak
11586 * while pointers are not. We could make this safe in
11587 * special cases if root is calling us, but it's
11588 * probably not worth the hassle.
11592 case PTR_TO_MAP_KEY:
11593 case PTR_TO_MAP_VALUE:
11594 /* a PTR_TO_MAP_VALUE could be safe to use as a
11595 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11596 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11597 * checked, doing so could have affected others with the same
11598 * id, and we can't check for that because we lost the id when
11599 * we converted to a PTR_TO_MAP_VALUE.
11601 if (type_may_be_null(rold->type)) {
11602 if (!type_may_be_null(rcur->type))
11604 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11606 /* Check our ids match any regs they're supposed to */
11607 return check_ids(rold->id, rcur->id, idmap);
11610 /* If the new min/max/var_off satisfy the old ones and
11611 * everything else matches, we are OK.
11612 * 'id' is not compared, since it's only used for maps with
11613 * bpf_spin_lock inside map element and in such cases if
11614 * the rest of the prog is valid for one map element then
11615 * it's valid for all map elements regardless of the key
11616 * used in bpf_map_lookup()
11618 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11619 range_within(rold, rcur) &&
11620 tnum_in(rold->var_off, rcur->var_off);
11621 case PTR_TO_PACKET_META:
11622 case PTR_TO_PACKET:
11623 if (rcur->type != rold->type)
11625 /* We must have at least as much range as the old ptr
11626 * did, so that any accesses which were safe before are
11627 * still safe. This is true even if old range < old off,
11628 * since someone could have accessed through (ptr - k), or
11629 * even done ptr -= k in a register, to get a safe access.
11631 if (rold->range > rcur->range)
11633 /* If the offsets don't match, we can't trust our alignment;
11634 * nor can we be sure that we won't fall out of range.
11636 if (rold->off != rcur->off)
11638 /* id relations must be preserved */
11639 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11641 /* new val must satisfy old val knowledge */
11642 return range_within(rold, rcur) &&
11643 tnum_in(rold->var_off, rcur->var_off);
11645 case CONST_PTR_TO_MAP:
11646 case PTR_TO_PACKET_END:
11647 case PTR_TO_FLOW_KEYS:
11648 case PTR_TO_SOCKET:
11649 case PTR_TO_SOCK_COMMON:
11650 case PTR_TO_TCP_SOCK:
11651 case PTR_TO_XDP_SOCK:
11652 /* Only valid matches are exact, which memcmp() above
11653 * would have accepted
11656 /* Don't know what's going on, just say it's not safe */
11660 /* Shouldn't get here; if we do, say it's not safe */
11665 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11666 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11670 /* walk slots of the explored stack and ignore any additional
11671 * slots in the current stack, since explored(safe) state
11674 for (i = 0; i < old->allocated_stack; i++) {
11675 spi = i / BPF_REG_SIZE;
11677 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11678 i += BPF_REG_SIZE - 1;
11679 /* explored state didn't use this */
11683 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11686 /* explored stack has more populated slots than current stack
11687 * and these slots were used
11689 if (i >= cur->allocated_stack)
11692 /* if old state was safe with misc data in the stack
11693 * it will be safe with zero-initialized stack.
11694 * The opposite is not true
11696 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11697 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11699 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11700 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11701 /* Ex: old explored (safe) state has STACK_SPILL in
11702 * this stack slot, but current has STACK_MISC ->
11703 * this verifier states are not equivalent,
11704 * return false to continue verification of this path
11707 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11709 if (!is_spilled_reg(&old->stack[spi]))
11711 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11712 &cur->stack[spi].spilled_ptr, idmap))
11713 /* when explored and current stack slot are both storing
11714 * spilled registers, check that stored pointers types
11715 * are the same as well.
11716 * Ex: explored safe path could have stored
11717 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11718 * but current path has stored:
11719 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11720 * such verifier states are not equivalent.
11721 * return false to continue verification of this path
11728 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11730 if (old->acquired_refs != cur->acquired_refs)
11732 return !memcmp(old->refs, cur->refs,
11733 sizeof(*old->refs) * old->acquired_refs);
11736 /* compare two verifier states
11738 * all states stored in state_list are known to be valid, since
11739 * verifier reached 'bpf_exit' instruction through them
11741 * this function is called when verifier exploring different branches of
11742 * execution popped from the state stack. If it sees an old state that has
11743 * more strict register state and more strict stack state then this execution
11744 * branch doesn't need to be explored further, since verifier already
11745 * concluded that more strict state leads to valid finish.
11747 * Therefore two states are equivalent if register state is more conservative
11748 * and explored stack state is more conservative than the current one.
11751 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11752 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11754 * In other words if current stack state (one being explored) has more
11755 * valid slots than old one that already passed validation, it means
11756 * the verifier can stop exploring and conclude that current state is valid too
11758 * Similarly with registers. If explored state has register type as invalid
11759 * whereas register type in current state is meaningful, it means that
11760 * the current state will reach 'bpf_exit' instruction safely
11762 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11763 struct bpf_func_state *cur)
11767 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11768 for (i = 0; i < MAX_BPF_REG; i++)
11769 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11770 env->idmap_scratch))
11773 if (!stacksafe(env, old, cur, env->idmap_scratch))
11776 if (!refsafe(old, cur))
11782 static bool states_equal(struct bpf_verifier_env *env,
11783 struct bpf_verifier_state *old,
11784 struct bpf_verifier_state *cur)
11788 if (old->curframe != cur->curframe)
11791 /* Verification state from speculative execution simulation
11792 * must never prune a non-speculative execution one.
11794 if (old->speculative && !cur->speculative)
11797 if (old->active_spin_lock != cur->active_spin_lock)
11800 /* for states to be equal callsites have to be the same
11801 * and all frame states need to be equivalent
11803 for (i = 0; i <= old->curframe; i++) {
11804 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11806 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11812 /* Return 0 if no propagation happened. Return negative error code if error
11813 * happened. Otherwise, return the propagated bit.
11815 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11816 struct bpf_reg_state *reg,
11817 struct bpf_reg_state *parent_reg)
11819 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11820 u8 flag = reg->live & REG_LIVE_READ;
11823 /* When comes here, read flags of PARENT_REG or REG could be any of
11824 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11825 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11827 if (parent_flag == REG_LIVE_READ64 ||
11828 /* Or if there is no read flag from REG. */
11830 /* Or if the read flag from REG is the same as PARENT_REG. */
11831 parent_flag == flag)
11834 err = mark_reg_read(env, reg, parent_reg, flag);
11841 /* A write screens off any subsequent reads; but write marks come from the
11842 * straight-line code between a state and its parent. When we arrive at an
11843 * equivalent state (jump target or such) we didn't arrive by the straight-line
11844 * code, so read marks in the state must propagate to the parent regardless
11845 * of the state's write marks. That's what 'parent == state->parent' comparison
11846 * in mark_reg_read() is for.
11848 static int propagate_liveness(struct bpf_verifier_env *env,
11849 const struct bpf_verifier_state *vstate,
11850 struct bpf_verifier_state *vparent)
11852 struct bpf_reg_state *state_reg, *parent_reg;
11853 struct bpf_func_state *state, *parent;
11854 int i, frame, err = 0;
11856 if (vparent->curframe != vstate->curframe) {
11857 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11858 vparent->curframe, vstate->curframe);
11861 /* Propagate read liveness of registers... */
11862 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11863 for (frame = 0; frame <= vstate->curframe; frame++) {
11864 parent = vparent->frame[frame];
11865 state = vstate->frame[frame];
11866 parent_reg = parent->regs;
11867 state_reg = state->regs;
11868 /* We don't need to worry about FP liveness, it's read-only */
11869 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11870 err = propagate_liveness_reg(env, &state_reg[i],
11874 if (err == REG_LIVE_READ64)
11875 mark_insn_zext(env, &parent_reg[i]);
11878 /* Propagate stack slots. */
11879 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11880 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11881 parent_reg = &parent->stack[i].spilled_ptr;
11882 state_reg = &state->stack[i].spilled_ptr;
11883 err = propagate_liveness_reg(env, state_reg,
11892 /* find precise scalars in the previous equivalent state and
11893 * propagate them into the current state
11895 static int propagate_precision(struct bpf_verifier_env *env,
11896 const struct bpf_verifier_state *old)
11898 struct bpf_reg_state *state_reg;
11899 struct bpf_func_state *state;
11900 int i, err = 0, fr;
11902 for (fr = old->curframe; fr >= 0; fr--) {
11903 state = old->frame[fr];
11904 state_reg = state->regs;
11905 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11906 if (state_reg->type != SCALAR_VALUE ||
11907 !state_reg->precise ||
11908 !(state_reg->live & REG_LIVE_READ))
11910 if (env->log.level & BPF_LOG_LEVEL2)
11911 verbose(env, "frame %d: propagating r%d\n", fr, i);
11912 err = mark_chain_precision_frame(env, fr, i);
11917 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11918 if (!is_spilled_reg(&state->stack[i]))
11920 state_reg = &state->stack[i].spilled_ptr;
11921 if (state_reg->type != SCALAR_VALUE ||
11922 !state_reg->precise ||
11923 !(state_reg->live & REG_LIVE_READ))
11925 if (env->log.level & BPF_LOG_LEVEL2)
11926 verbose(env, "frame %d: propagating fp%d\n",
11927 fr, (-i - 1) * BPF_REG_SIZE);
11928 err = mark_chain_precision_stack_frame(env, fr, i);
11936 static bool states_maybe_looping(struct bpf_verifier_state *old,
11937 struct bpf_verifier_state *cur)
11939 struct bpf_func_state *fold, *fcur;
11940 int i, fr = cur->curframe;
11942 if (old->curframe != fr)
11945 fold = old->frame[fr];
11946 fcur = cur->frame[fr];
11947 for (i = 0; i < MAX_BPF_REG; i++)
11948 if (memcmp(&fold->regs[i], &fcur->regs[i],
11949 offsetof(struct bpf_reg_state, parent)))
11955 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11957 struct bpf_verifier_state_list *new_sl;
11958 struct bpf_verifier_state_list *sl, **pprev;
11959 struct bpf_verifier_state *cur = env->cur_state, *new;
11960 int i, j, err, states_cnt = 0;
11961 bool add_new_state = env->test_state_freq ? true : false;
11963 cur->last_insn_idx = env->prev_insn_idx;
11964 if (!env->insn_aux_data[insn_idx].prune_point)
11965 /* this 'insn_idx' instruction wasn't marked, so we will not
11966 * be doing state search here
11970 /* bpf progs typically have pruning point every 4 instructions
11971 * http://vger.kernel.org/bpfconf2019.html#session-1
11972 * Do not add new state for future pruning if the verifier hasn't seen
11973 * at least 2 jumps and at least 8 instructions.
11974 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11975 * In tests that amounts to up to 50% reduction into total verifier
11976 * memory consumption and 20% verifier time speedup.
11978 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11979 env->insn_processed - env->prev_insn_processed >= 8)
11980 add_new_state = true;
11982 pprev = explored_state(env, insn_idx);
11985 clean_live_states(env, insn_idx, cur);
11989 if (sl->state.insn_idx != insn_idx)
11992 if (sl->state.branches) {
11993 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11995 if (frame->in_async_callback_fn &&
11996 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11997 /* Different async_entry_cnt means that the verifier is
11998 * processing another entry into async callback.
11999 * Seeing the same state is not an indication of infinite
12000 * loop or infinite recursion.
12001 * But finding the same state doesn't mean that it's safe
12002 * to stop processing the current state. The previous state
12003 * hasn't yet reached bpf_exit, since state.branches > 0.
12004 * Checking in_async_callback_fn alone is not enough either.
12005 * Since the verifier still needs to catch infinite loops
12006 * inside async callbacks.
12008 } else if (states_maybe_looping(&sl->state, cur) &&
12009 states_equal(env, &sl->state, cur)) {
12010 verbose_linfo(env, insn_idx, "; ");
12011 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
12014 /* if the verifier is processing a loop, avoid adding new state
12015 * too often, since different loop iterations have distinct
12016 * states and may not help future pruning.
12017 * This threshold shouldn't be too low to make sure that
12018 * a loop with large bound will be rejected quickly.
12019 * The most abusive loop will be:
12021 * if r1 < 1000000 goto pc-2
12022 * 1M insn_procssed limit / 100 == 10k peak states.
12023 * This threshold shouldn't be too high either, since states
12024 * at the end of the loop are likely to be useful in pruning.
12026 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
12027 env->insn_processed - env->prev_insn_processed < 100)
12028 add_new_state = false;
12031 if (states_equal(env, &sl->state, cur)) {
12033 /* reached equivalent register/stack state,
12034 * prune the search.
12035 * Registers read by the continuation are read by us.
12036 * If we have any write marks in env->cur_state, they
12037 * will prevent corresponding reads in the continuation
12038 * from reaching our parent (an explored_state). Our
12039 * own state will get the read marks recorded, but
12040 * they'll be immediately forgotten as we're pruning
12041 * this state and will pop a new one.
12043 err = propagate_liveness(env, &sl->state, cur);
12045 /* if previous state reached the exit with precision and
12046 * current state is equivalent to it (except precsion marks)
12047 * the precision needs to be propagated back in
12048 * the current state.
12050 err = err ? : push_jmp_history(env, cur);
12051 err = err ? : propagate_precision(env, &sl->state);
12057 /* when new state is not going to be added do not increase miss count.
12058 * Otherwise several loop iterations will remove the state
12059 * recorded earlier. The goal of these heuristics is to have
12060 * states from some iterations of the loop (some in the beginning
12061 * and some at the end) to help pruning.
12065 /* heuristic to determine whether this state is beneficial
12066 * to keep checking from state equivalence point of view.
12067 * Higher numbers increase max_states_per_insn and verification time,
12068 * but do not meaningfully decrease insn_processed.
12070 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12071 /* the state is unlikely to be useful. Remove it to
12072 * speed up verification
12075 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12076 u32 br = sl->state.branches;
12079 "BUG live_done but branches_to_explore %d\n",
12081 free_verifier_state(&sl->state, false);
12083 env->peak_states--;
12085 /* cannot free this state, since parentage chain may
12086 * walk it later. Add it for free_list instead to
12087 * be freed at the end of verification
12089 sl->next = env->free_list;
12090 env->free_list = sl;
12100 if (env->max_states_per_insn < states_cnt)
12101 env->max_states_per_insn = states_cnt;
12103 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12104 return push_jmp_history(env, cur);
12106 if (!add_new_state)
12107 return push_jmp_history(env, cur);
12109 /* There were no equivalent states, remember the current one.
12110 * Technically the current state is not proven to be safe yet,
12111 * but it will either reach outer most bpf_exit (which means it's safe)
12112 * or it will be rejected. When there are no loops the verifier won't be
12113 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12114 * again on the way to bpf_exit.
12115 * When looping the sl->state.branches will be > 0 and this state
12116 * will not be considered for equivalence until branches == 0.
12118 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12121 env->total_states++;
12122 env->peak_states++;
12123 env->prev_jmps_processed = env->jmps_processed;
12124 env->prev_insn_processed = env->insn_processed;
12126 /* add new state to the head of linked list */
12127 new = &new_sl->state;
12128 err = copy_verifier_state(new, cur);
12130 free_verifier_state(new, false);
12134 new->insn_idx = insn_idx;
12135 WARN_ONCE(new->branches != 1,
12136 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12139 cur->first_insn_idx = insn_idx;
12140 clear_jmp_history(cur);
12141 new_sl->next = *explored_state(env, insn_idx);
12142 *explored_state(env, insn_idx) = new_sl;
12143 /* connect new state to parentage chain. Current frame needs all
12144 * registers connected. Only r6 - r9 of the callers are alive (pushed
12145 * to the stack implicitly by JITs) so in callers' frames connect just
12146 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12147 * the state of the call instruction (with WRITTEN set), and r0 comes
12148 * from callee with its full parentage chain, anyway.
12150 /* clear write marks in current state: the writes we did are not writes
12151 * our child did, so they don't screen off its reads from us.
12152 * (There are no read marks in current state, because reads always mark
12153 * their parent and current state never has children yet. Only
12154 * explored_states can get read marks.)
12156 for (j = 0; j <= cur->curframe; j++) {
12157 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12158 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12159 for (i = 0; i < BPF_REG_FP; i++)
12160 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12163 /* all stack frames are accessible from callee, clear them all */
12164 for (j = 0; j <= cur->curframe; j++) {
12165 struct bpf_func_state *frame = cur->frame[j];
12166 struct bpf_func_state *newframe = new->frame[j];
12168 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12169 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12170 frame->stack[i].spilled_ptr.parent =
12171 &newframe->stack[i].spilled_ptr;
12177 /* Return true if it's OK to have the same insn return a different type. */
12178 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12180 switch (base_type(type)) {
12182 case PTR_TO_SOCKET:
12183 case PTR_TO_SOCK_COMMON:
12184 case PTR_TO_TCP_SOCK:
12185 case PTR_TO_XDP_SOCK:
12186 case PTR_TO_BTF_ID:
12193 /* If an instruction was previously used with particular pointer types, then we
12194 * need to be careful to avoid cases such as the below, where it may be ok
12195 * for one branch accessing the pointer, but not ok for the other branch:
12200 * R1 = some_other_valid_ptr;
12203 * R2 = *(u32 *)(R1 + 0);
12205 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12207 return src != prev && (!reg_type_mismatch_ok(src) ||
12208 !reg_type_mismatch_ok(prev));
12211 static int do_check(struct bpf_verifier_env *env)
12213 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12214 struct bpf_verifier_state *state = env->cur_state;
12215 struct bpf_insn *insns = env->prog->insnsi;
12216 struct bpf_reg_state *regs;
12217 int insn_cnt = env->prog->len;
12218 bool do_print_state = false;
12219 int prev_insn_idx = -1;
12222 struct bpf_insn *insn;
12226 env->prev_insn_idx = prev_insn_idx;
12227 if (env->insn_idx >= insn_cnt) {
12228 verbose(env, "invalid insn idx %d insn_cnt %d\n",
12229 env->insn_idx, insn_cnt);
12233 insn = &insns[env->insn_idx];
12234 class = BPF_CLASS(insn->code);
12236 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12238 "BPF program is too large. Processed %d insn\n",
12239 env->insn_processed);
12243 err = is_state_visited(env, env->insn_idx);
12247 /* found equivalent state, can prune the search */
12248 if (env->log.level & BPF_LOG_LEVEL) {
12249 if (do_print_state)
12250 verbose(env, "\nfrom %d to %d%s: safe\n",
12251 env->prev_insn_idx, env->insn_idx,
12252 env->cur_state->speculative ?
12253 " (speculative execution)" : "");
12255 verbose(env, "%d: safe\n", env->insn_idx);
12257 goto process_bpf_exit;
12260 if (signal_pending(current))
12263 if (need_resched())
12266 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12267 verbose(env, "\nfrom %d to %d%s:",
12268 env->prev_insn_idx, env->insn_idx,
12269 env->cur_state->speculative ?
12270 " (speculative execution)" : "");
12271 print_verifier_state(env, state->frame[state->curframe], true);
12272 do_print_state = false;
12275 if (env->log.level & BPF_LOG_LEVEL) {
12276 const struct bpf_insn_cbs cbs = {
12277 .cb_call = disasm_kfunc_name,
12278 .cb_print = verbose,
12279 .private_data = env,
12282 if (verifier_state_scratched(env))
12283 print_insn_state(env, state->frame[state->curframe]);
12285 verbose_linfo(env, env->insn_idx, "; ");
12286 env->prev_log_len = env->log.len_used;
12287 verbose(env, "%d: ", env->insn_idx);
12288 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12289 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12290 env->prev_log_len = env->log.len_used;
12293 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12294 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12295 env->prev_insn_idx);
12300 regs = cur_regs(env);
12301 sanitize_mark_insn_seen(env);
12302 prev_insn_idx = env->insn_idx;
12304 if (class == BPF_ALU || class == BPF_ALU64) {
12305 err = check_alu_op(env, insn);
12309 } else if (class == BPF_LDX) {
12310 enum bpf_reg_type *prev_src_type, src_reg_type;
12312 /* check for reserved fields is already done */
12314 /* check src operand */
12315 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12319 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12323 src_reg_type = regs[insn->src_reg].type;
12325 /* check that memory (src_reg + off) is readable,
12326 * the state of dst_reg will be updated by this func
12328 err = check_mem_access(env, env->insn_idx, insn->src_reg,
12329 insn->off, BPF_SIZE(insn->code),
12330 BPF_READ, insn->dst_reg, false);
12334 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12336 if (*prev_src_type == NOT_INIT) {
12337 /* saw a valid insn
12338 * dst_reg = *(u32 *)(src_reg + off)
12339 * save type to validate intersecting paths
12341 *prev_src_type = src_reg_type;
12343 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12344 /* ABuser program is trying to use the same insn
12345 * dst_reg = *(u32*) (src_reg + off)
12346 * with different pointer types:
12347 * src_reg == ctx in one branch and
12348 * src_reg == stack|map in some other branch.
12351 verbose(env, "same insn cannot be used with different pointers\n");
12355 } else if (class == BPF_STX) {
12356 enum bpf_reg_type *prev_dst_type, dst_reg_type;
12358 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12359 err = check_atomic(env, env->insn_idx, insn);
12366 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12367 verbose(env, "BPF_STX uses reserved fields\n");
12371 /* check src1 operand */
12372 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12375 /* check src2 operand */
12376 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12380 dst_reg_type = regs[insn->dst_reg].type;
12382 /* check that memory (dst_reg + off) is writeable */
12383 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12384 insn->off, BPF_SIZE(insn->code),
12385 BPF_WRITE, insn->src_reg, false);
12389 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12391 if (*prev_dst_type == NOT_INIT) {
12392 *prev_dst_type = dst_reg_type;
12393 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12394 verbose(env, "same insn cannot be used with different pointers\n");
12398 } else if (class == BPF_ST) {
12399 if (BPF_MODE(insn->code) != BPF_MEM ||
12400 insn->src_reg != BPF_REG_0) {
12401 verbose(env, "BPF_ST uses reserved fields\n");
12404 /* check src operand */
12405 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12409 if (is_ctx_reg(env, insn->dst_reg)) {
12410 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12412 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12416 /* check that memory (dst_reg + off) is writeable */
12417 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12418 insn->off, BPF_SIZE(insn->code),
12419 BPF_WRITE, -1, false);
12423 } else if (class == BPF_JMP || class == BPF_JMP32) {
12424 u8 opcode = BPF_OP(insn->code);
12426 env->jmps_processed++;
12427 if (opcode == BPF_CALL) {
12428 if (BPF_SRC(insn->code) != BPF_K ||
12429 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12430 && insn->off != 0) ||
12431 (insn->src_reg != BPF_REG_0 &&
12432 insn->src_reg != BPF_PSEUDO_CALL &&
12433 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12434 insn->dst_reg != BPF_REG_0 ||
12435 class == BPF_JMP32) {
12436 verbose(env, "BPF_CALL uses reserved fields\n");
12440 if (env->cur_state->active_spin_lock &&
12441 (insn->src_reg == BPF_PSEUDO_CALL ||
12442 insn->imm != BPF_FUNC_spin_unlock)) {
12443 verbose(env, "function calls are not allowed while holding a lock\n");
12446 if (insn->src_reg == BPF_PSEUDO_CALL)
12447 err = check_func_call(env, insn, &env->insn_idx);
12448 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12449 err = check_kfunc_call(env, insn, &env->insn_idx);
12451 err = check_helper_call(env, insn, &env->insn_idx);
12454 } else if (opcode == BPF_JA) {
12455 if (BPF_SRC(insn->code) != BPF_K ||
12457 insn->src_reg != BPF_REG_0 ||
12458 insn->dst_reg != BPF_REG_0 ||
12459 class == BPF_JMP32) {
12460 verbose(env, "BPF_JA uses reserved fields\n");
12464 env->insn_idx += insn->off + 1;
12467 } else if (opcode == BPF_EXIT) {
12468 if (BPF_SRC(insn->code) != BPF_K ||
12470 insn->src_reg != BPF_REG_0 ||
12471 insn->dst_reg != BPF_REG_0 ||
12472 class == BPF_JMP32) {
12473 verbose(env, "BPF_EXIT uses reserved fields\n");
12477 if (env->cur_state->active_spin_lock) {
12478 verbose(env, "bpf_spin_unlock is missing\n");
12482 /* We must do check_reference_leak here before
12483 * prepare_func_exit to handle the case when
12484 * state->curframe > 0, it may be a callback
12485 * function, for which reference_state must
12486 * match caller reference state when it exits.
12488 err = check_reference_leak(env);
12492 if (state->curframe) {
12493 /* exit from nested function */
12494 err = prepare_func_exit(env, &env->insn_idx);
12497 do_print_state = true;
12501 err = check_return_code(env);
12505 mark_verifier_state_scratched(env);
12506 update_branch_counts(env, env->cur_state);
12507 err = pop_stack(env, &prev_insn_idx,
12508 &env->insn_idx, pop_log);
12510 if (err != -ENOENT)
12514 do_print_state = true;
12518 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12522 } else if (class == BPF_LD) {
12523 u8 mode = BPF_MODE(insn->code);
12525 if (mode == BPF_ABS || mode == BPF_IND) {
12526 err = check_ld_abs(env, insn);
12530 } else if (mode == BPF_IMM) {
12531 err = check_ld_imm(env, insn);
12536 sanitize_mark_insn_seen(env);
12538 verbose(env, "invalid BPF_LD mode\n");
12542 verbose(env, "unknown insn class %d\n", class);
12552 static int find_btf_percpu_datasec(struct btf *btf)
12554 const struct btf_type *t;
12559 * Both vmlinux and module each have their own ".data..percpu"
12560 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12561 * types to look at only module's own BTF types.
12563 n = btf_nr_types(btf);
12564 if (btf_is_module(btf))
12565 i = btf_nr_types(btf_vmlinux);
12569 for(; i < n; i++) {
12570 t = btf_type_by_id(btf, i);
12571 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12574 tname = btf_name_by_offset(btf, t->name_off);
12575 if (!strcmp(tname, ".data..percpu"))
12582 /* replace pseudo btf_id with kernel symbol address */
12583 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12584 struct bpf_insn *insn,
12585 struct bpf_insn_aux_data *aux)
12587 const struct btf_var_secinfo *vsi;
12588 const struct btf_type *datasec;
12589 struct btf_mod_pair *btf_mod;
12590 const struct btf_type *t;
12591 const char *sym_name;
12592 bool percpu = false;
12593 u32 type, id = insn->imm;
12597 int i, btf_fd, err;
12599 btf_fd = insn[1].imm;
12601 btf = btf_get_by_fd(btf_fd);
12603 verbose(env, "invalid module BTF object FD specified.\n");
12607 if (!btf_vmlinux) {
12608 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12615 t = btf_type_by_id(btf, id);
12617 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12622 if (!btf_type_is_var(t)) {
12623 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12628 sym_name = btf_name_by_offset(btf, t->name_off);
12629 addr = kallsyms_lookup_name(sym_name);
12631 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12637 datasec_id = find_btf_percpu_datasec(btf);
12638 if (datasec_id > 0) {
12639 datasec = btf_type_by_id(btf, datasec_id);
12640 for_each_vsi(i, datasec, vsi) {
12641 if (vsi->type == id) {
12648 insn[0].imm = (u32)addr;
12649 insn[1].imm = addr >> 32;
12652 t = btf_type_skip_modifiers(btf, type, NULL);
12654 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12655 aux->btf_var.btf = btf;
12656 aux->btf_var.btf_id = type;
12657 } else if (!btf_type_is_struct(t)) {
12658 const struct btf_type *ret;
12662 /* resolve the type size of ksym. */
12663 ret = btf_resolve_size(btf, t, &tsize);
12665 tname = btf_name_by_offset(btf, t->name_off);
12666 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12667 tname, PTR_ERR(ret));
12671 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12672 aux->btf_var.mem_size = tsize;
12674 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12675 aux->btf_var.btf = btf;
12676 aux->btf_var.btf_id = type;
12679 /* check whether we recorded this BTF (and maybe module) already */
12680 for (i = 0; i < env->used_btf_cnt; i++) {
12681 if (env->used_btfs[i].btf == btf) {
12687 if (env->used_btf_cnt >= MAX_USED_BTFS) {
12692 btf_mod = &env->used_btfs[env->used_btf_cnt];
12693 btf_mod->btf = btf;
12694 btf_mod->module = NULL;
12696 /* if we reference variables from kernel module, bump its refcount */
12697 if (btf_is_module(btf)) {
12698 btf_mod->module = btf_try_get_module(btf);
12699 if (!btf_mod->module) {
12705 env->used_btf_cnt++;
12713 static bool is_tracing_prog_type(enum bpf_prog_type type)
12716 case BPF_PROG_TYPE_KPROBE:
12717 case BPF_PROG_TYPE_TRACEPOINT:
12718 case BPF_PROG_TYPE_PERF_EVENT:
12719 case BPF_PROG_TYPE_RAW_TRACEPOINT:
12720 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12727 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12728 struct bpf_map *map,
12729 struct bpf_prog *prog)
12732 enum bpf_prog_type prog_type = resolve_prog_type(prog);
12734 if (map_value_has_spin_lock(map)) {
12735 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12736 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12740 if (is_tracing_prog_type(prog_type)) {
12741 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12745 if (prog->aux->sleepable) {
12746 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12751 if (map_value_has_timer(map)) {
12752 if (is_tracing_prog_type(prog_type)) {
12753 verbose(env, "tracing progs cannot use bpf_timer yet\n");
12758 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12759 !bpf_offload_prog_map_match(prog, map)) {
12760 verbose(env, "offload device mismatch between prog and map\n");
12764 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12765 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12769 if (prog->aux->sleepable)
12770 switch (map->map_type) {
12771 case BPF_MAP_TYPE_HASH:
12772 case BPF_MAP_TYPE_LRU_HASH:
12773 case BPF_MAP_TYPE_ARRAY:
12774 case BPF_MAP_TYPE_PERCPU_HASH:
12775 case BPF_MAP_TYPE_PERCPU_ARRAY:
12776 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12777 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12778 case BPF_MAP_TYPE_HASH_OF_MAPS:
12779 case BPF_MAP_TYPE_RINGBUF:
12780 case BPF_MAP_TYPE_USER_RINGBUF:
12781 case BPF_MAP_TYPE_INODE_STORAGE:
12782 case BPF_MAP_TYPE_SK_STORAGE:
12783 case BPF_MAP_TYPE_TASK_STORAGE:
12787 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12794 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12796 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12797 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12800 /* find and rewrite pseudo imm in ld_imm64 instructions:
12802 * 1. if it accesses map FD, replace it with actual map pointer.
12803 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12805 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12807 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12809 struct bpf_insn *insn = env->prog->insnsi;
12810 int insn_cnt = env->prog->len;
12813 err = bpf_prog_calc_tag(env->prog);
12817 for (i = 0; i < insn_cnt; i++, insn++) {
12818 if (BPF_CLASS(insn->code) == BPF_LDX &&
12819 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12820 verbose(env, "BPF_LDX uses reserved fields\n");
12824 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12825 struct bpf_insn_aux_data *aux;
12826 struct bpf_map *map;
12831 if (i == insn_cnt - 1 || insn[1].code != 0 ||
12832 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12833 insn[1].off != 0) {
12834 verbose(env, "invalid bpf_ld_imm64 insn\n");
12838 if (insn[0].src_reg == 0)
12839 /* valid generic load 64-bit imm */
12842 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12843 aux = &env->insn_aux_data[i];
12844 err = check_pseudo_btf_id(env, insn, aux);
12850 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12851 aux = &env->insn_aux_data[i];
12852 aux->ptr_type = PTR_TO_FUNC;
12856 /* In final convert_pseudo_ld_imm64() step, this is
12857 * converted into regular 64-bit imm load insn.
12859 switch (insn[0].src_reg) {
12860 case BPF_PSEUDO_MAP_VALUE:
12861 case BPF_PSEUDO_MAP_IDX_VALUE:
12863 case BPF_PSEUDO_MAP_FD:
12864 case BPF_PSEUDO_MAP_IDX:
12865 if (insn[1].imm == 0)
12869 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12873 switch (insn[0].src_reg) {
12874 case BPF_PSEUDO_MAP_IDX_VALUE:
12875 case BPF_PSEUDO_MAP_IDX:
12876 if (bpfptr_is_null(env->fd_array)) {
12877 verbose(env, "fd_idx without fd_array is invalid\n");
12880 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12881 insn[0].imm * sizeof(fd),
12891 map = __bpf_map_get(f);
12893 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12895 return PTR_ERR(map);
12898 err = check_map_prog_compatibility(env, map, env->prog);
12904 aux = &env->insn_aux_data[i];
12905 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12906 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12907 addr = (unsigned long)map;
12909 u32 off = insn[1].imm;
12911 if (off >= BPF_MAX_VAR_OFF) {
12912 verbose(env, "direct value offset of %u is not allowed\n", off);
12917 if (!map->ops->map_direct_value_addr) {
12918 verbose(env, "no direct value access support for this map type\n");
12923 err = map->ops->map_direct_value_addr(map, &addr, off);
12925 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12926 map->value_size, off);
12931 aux->map_off = off;
12935 insn[0].imm = (u32)addr;
12936 insn[1].imm = addr >> 32;
12938 /* check whether we recorded this map already */
12939 for (j = 0; j < env->used_map_cnt; j++) {
12940 if (env->used_maps[j] == map) {
12941 aux->map_index = j;
12947 if (env->used_map_cnt >= MAX_USED_MAPS) {
12952 /* hold the map. If the program is rejected by verifier,
12953 * the map will be released by release_maps() or it
12954 * will be used by the valid program until it's unloaded
12955 * and all maps are released in free_used_maps()
12959 aux->map_index = env->used_map_cnt;
12960 env->used_maps[env->used_map_cnt++] = map;
12962 if (bpf_map_is_cgroup_storage(map) &&
12963 bpf_cgroup_storage_assign(env->prog->aux, map)) {
12964 verbose(env, "only one cgroup storage of each type is allowed\n");
12976 /* Basic sanity check before we invest more work here. */
12977 if (!bpf_opcode_in_insntable(insn->code)) {
12978 verbose(env, "unknown opcode %02x\n", insn->code);
12983 /* now all pseudo BPF_LD_IMM64 instructions load valid
12984 * 'struct bpf_map *' into a register instead of user map_fd.
12985 * These pointers will be used later by verifier to validate map access.
12990 /* drop refcnt of maps used by the rejected program */
12991 static void release_maps(struct bpf_verifier_env *env)
12993 __bpf_free_used_maps(env->prog->aux, env->used_maps,
12994 env->used_map_cnt);
12997 /* drop refcnt of maps used by the rejected program */
12998 static void release_btfs(struct bpf_verifier_env *env)
13000 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
13001 env->used_btf_cnt);
13004 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
13005 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
13007 struct bpf_insn *insn = env->prog->insnsi;
13008 int insn_cnt = env->prog->len;
13011 for (i = 0; i < insn_cnt; i++, insn++) {
13012 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
13014 if (insn->src_reg == BPF_PSEUDO_FUNC)
13020 /* single env->prog->insni[off] instruction was replaced with the range
13021 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
13022 * [0, off) and [off, end) to new locations, so the patched range stays zero
13024 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
13025 struct bpf_insn_aux_data *new_data,
13026 struct bpf_prog *new_prog, u32 off, u32 cnt)
13028 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
13029 struct bpf_insn *insn = new_prog->insnsi;
13030 u32 old_seen = old_data[off].seen;
13034 /* aux info at OFF always needs adjustment, no matter fast path
13035 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
13036 * original insn at old prog.
13038 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
13042 prog_len = new_prog->len;
13044 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
13045 memcpy(new_data + off + cnt - 1, old_data + off,
13046 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
13047 for (i = off; i < off + cnt - 1; i++) {
13048 /* Expand insni[off]'s seen count to the patched range. */
13049 new_data[i].seen = old_seen;
13050 new_data[i].zext_dst = insn_has_def32(env, insn + i);
13052 env->insn_aux_data = new_data;
13056 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13062 /* NOTE: fake 'exit' subprog should be updated as well. */
13063 for (i = 0; i <= env->subprog_cnt; i++) {
13064 if (env->subprog_info[i].start <= off)
13066 env->subprog_info[i].start += len - 1;
13070 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13072 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13073 int i, sz = prog->aux->size_poke_tab;
13074 struct bpf_jit_poke_descriptor *desc;
13076 for (i = 0; i < sz; i++) {
13078 if (desc->insn_idx <= off)
13080 desc->insn_idx += len - 1;
13084 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13085 const struct bpf_insn *patch, u32 len)
13087 struct bpf_prog *new_prog;
13088 struct bpf_insn_aux_data *new_data = NULL;
13091 new_data = vzalloc(array_size(env->prog->len + len - 1,
13092 sizeof(struct bpf_insn_aux_data)));
13097 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13098 if (IS_ERR(new_prog)) {
13099 if (PTR_ERR(new_prog) == -ERANGE)
13101 "insn %d cannot be patched due to 16-bit range\n",
13102 env->insn_aux_data[off].orig_idx);
13106 adjust_insn_aux_data(env, new_data, new_prog, off, len);
13107 adjust_subprog_starts(env, off, len);
13108 adjust_poke_descs(new_prog, off, len);
13112 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13117 /* find first prog starting at or after off (first to remove) */
13118 for (i = 0; i < env->subprog_cnt; i++)
13119 if (env->subprog_info[i].start >= off)
13121 /* find first prog starting at or after off + cnt (first to stay) */
13122 for (j = i; j < env->subprog_cnt; j++)
13123 if (env->subprog_info[j].start >= off + cnt)
13125 /* if j doesn't start exactly at off + cnt, we are just removing
13126 * the front of previous prog
13128 if (env->subprog_info[j].start != off + cnt)
13132 struct bpf_prog_aux *aux = env->prog->aux;
13135 /* move fake 'exit' subprog as well */
13136 move = env->subprog_cnt + 1 - j;
13138 memmove(env->subprog_info + i,
13139 env->subprog_info + j,
13140 sizeof(*env->subprog_info) * move);
13141 env->subprog_cnt -= j - i;
13143 /* remove func_info */
13144 if (aux->func_info) {
13145 move = aux->func_info_cnt - j;
13147 memmove(aux->func_info + i,
13148 aux->func_info + j,
13149 sizeof(*aux->func_info) * move);
13150 aux->func_info_cnt -= j - i;
13151 /* func_info->insn_off is set after all code rewrites,
13152 * in adjust_btf_func() - no need to adjust
13156 /* convert i from "first prog to remove" to "first to adjust" */
13157 if (env->subprog_info[i].start == off)
13161 /* update fake 'exit' subprog as well */
13162 for (; i <= env->subprog_cnt; i++)
13163 env->subprog_info[i].start -= cnt;
13168 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13171 struct bpf_prog *prog = env->prog;
13172 u32 i, l_off, l_cnt, nr_linfo;
13173 struct bpf_line_info *linfo;
13175 nr_linfo = prog->aux->nr_linfo;
13179 linfo = prog->aux->linfo;
13181 /* find first line info to remove, count lines to be removed */
13182 for (i = 0; i < nr_linfo; i++)
13183 if (linfo[i].insn_off >= off)
13188 for (; i < nr_linfo; i++)
13189 if (linfo[i].insn_off < off + cnt)
13194 /* First live insn doesn't match first live linfo, it needs to "inherit"
13195 * last removed linfo. prog is already modified, so prog->len == off
13196 * means no live instructions after (tail of the program was removed).
13198 if (prog->len != off && l_cnt &&
13199 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13201 linfo[--i].insn_off = off + cnt;
13204 /* remove the line info which refer to the removed instructions */
13206 memmove(linfo + l_off, linfo + i,
13207 sizeof(*linfo) * (nr_linfo - i));
13209 prog->aux->nr_linfo -= l_cnt;
13210 nr_linfo = prog->aux->nr_linfo;
13213 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13214 for (i = l_off; i < nr_linfo; i++)
13215 linfo[i].insn_off -= cnt;
13217 /* fix up all subprogs (incl. 'exit') which start >= off */
13218 for (i = 0; i <= env->subprog_cnt; i++)
13219 if (env->subprog_info[i].linfo_idx > l_off) {
13220 /* program may have started in the removed region but
13221 * may not be fully removed
13223 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13224 env->subprog_info[i].linfo_idx -= l_cnt;
13226 env->subprog_info[i].linfo_idx = l_off;
13232 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13234 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13235 unsigned int orig_prog_len = env->prog->len;
13238 if (bpf_prog_is_dev_bound(env->prog->aux))
13239 bpf_prog_offload_remove_insns(env, off, cnt);
13241 err = bpf_remove_insns(env->prog, off, cnt);
13245 err = adjust_subprog_starts_after_remove(env, off, cnt);
13249 err = bpf_adj_linfo_after_remove(env, off, cnt);
13253 memmove(aux_data + off, aux_data + off + cnt,
13254 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13259 /* The verifier does more data flow analysis than llvm and will not
13260 * explore branches that are dead at run time. Malicious programs can
13261 * have dead code too. Therefore replace all dead at-run-time code
13264 * Just nops are not optimal, e.g. if they would sit at the end of the
13265 * program and through another bug we would manage to jump there, then
13266 * we'd execute beyond program memory otherwise. Returning exception
13267 * code also wouldn't work since we can have subprogs where the dead
13268 * code could be located.
13270 static void sanitize_dead_code(struct bpf_verifier_env *env)
13272 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13273 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13274 struct bpf_insn *insn = env->prog->insnsi;
13275 const int insn_cnt = env->prog->len;
13278 for (i = 0; i < insn_cnt; i++) {
13279 if (aux_data[i].seen)
13281 memcpy(insn + i, &trap, sizeof(trap));
13282 aux_data[i].zext_dst = false;
13286 static bool insn_is_cond_jump(u8 code)
13290 if (BPF_CLASS(code) == BPF_JMP32)
13293 if (BPF_CLASS(code) != BPF_JMP)
13297 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13300 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13302 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13303 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13304 struct bpf_insn *insn = env->prog->insnsi;
13305 const int insn_cnt = env->prog->len;
13308 for (i = 0; i < insn_cnt; i++, insn++) {
13309 if (!insn_is_cond_jump(insn->code))
13312 if (!aux_data[i + 1].seen)
13313 ja.off = insn->off;
13314 else if (!aux_data[i + 1 + insn->off].seen)
13319 if (bpf_prog_is_dev_bound(env->prog->aux))
13320 bpf_prog_offload_replace_insn(env, i, &ja);
13322 memcpy(insn, &ja, sizeof(ja));
13326 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13328 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13329 int insn_cnt = env->prog->len;
13332 for (i = 0; i < insn_cnt; i++) {
13336 while (i + j < insn_cnt && !aux_data[i + j].seen)
13341 err = verifier_remove_insns(env, i, j);
13344 insn_cnt = env->prog->len;
13350 static int opt_remove_nops(struct bpf_verifier_env *env)
13352 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13353 struct bpf_insn *insn = env->prog->insnsi;
13354 int insn_cnt = env->prog->len;
13357 for (i = 0; i < insn_cnt; i++) {
13358 if (memcmp(&insn[i], &ja, sizeof(ja)))
13361 err = verifier_remove_insns(env, i, 1);
13371 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13372 const union bpf_attr *attr)
13374 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13375 struct bpf_insn_aux_data *aux = env->insn_aux_data;
13376 int i, patch_len, delta = 0, len = env->prog->len;
13377 struct bpf_insn *insns = env->prog->insnsi;
13378 struct bpf_prog *new_prog;
13381 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13382 zext_patch[1] = BPF_ZEXT_REG(0);
13383 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13384 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13385 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13386 for (i = 0; i < len; i++) {
13387 int adj_idx = i + delta;
13388 struct bpf_insn insn;
13391 insn = insns[adj_idx];
13392 load_reg = insn_def_regno(&insn);
13393 if (!aux[adj_idx].zext_dst) {
13401 class = BPF_CLASS(code);
13402 if (load_reg == -1)
13405 /* NOTE: arg "reg" (the fourth one) is only used for
13406 * BPF_STX + SRC_OP, so it is safe to pass NULL
13409 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13410 if (class == BPF_LD &&
13411 BPF_MODE(code) == BPF_IMM)
13416 /* ctx load could be transformed into wider load. */
13417 if (class == BPF_LDX &&
13418 aux[adj_idx].ptr_type == PTR_TO_CTX)
13421 imm_rnd = get_random_u32();
13422 rnd_hi32_patch[0] = insn;
13423 rnd_hi32_patch[1].imm = imm_rnd;
13424 rnd_hi32_patch[3].dst_reg = load_reg;
13425 patch = rnd_hi32_patch;
13427 goto apply_patch_buffer;
13430 /* Add in an zero-extend instruction if a) the JIT has requested
13431 * it or b) it's a CMPXCHG.
13433 * The latter is because: BPF_CMPXCHG always loads a value into
13434 * R0, therefore always zero-extends. However some archs'
13435 * equivalent instruction only does this load when the
13436 * comparison is successful. This detail of CMPXCHG is
13437 * orthogonal to the general zero-extension behaviour of the
13438 * CPU, so it's treated independently of bpf_jit_needs_zext.
13440 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13443 /* Zero-extension is done by the caller. */
13444 if (bpf_pseudo_kfunc_call(&insn))
13447 if (WARN_ON(load_reg == -1)) {
13448 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13452 zext_patch[0] = insn;
13453 zext_patch[1].dst_reg = load_reg;
13454 zext_patch[1].src_reg = load_reg;
13455 patch = zext_patch;
13457 apply_patch_buffer:
13458 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13461 env->prog = new_prog;
13462 insns = new_prog->insnsi;
13463 aux = env->insn_aux_data;
13464 delta += patch_len - 1;
13470 /* convert load instructions that access fields of a context type into a
13471 * sequence of instructions that access fields of the underlying structure:
13472 * struct __sk_buff -> struct sk_buff
13473 * struct bpf_sock_ops -> struct sock
13475 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13477 const struct bpf_verifier_ops *ops = env->ops;
13478 int i, cnt, size, ctx_field_size, delta = 0;
13479 const int insn_cnt = env->prog->len;
13480 struct bpf_insn insn_buf[16], *insn;
13481 u32 target_size, size_default, off;
13482 struct bpf_prog *new_prog;
13483 enum bpf_access_type type;
13484 bool is_narrower_load;
13486 if (ops->gen_prologue || env->seen_direct_write) {
13487 if (!ops->gen_prologue) {
13488 verbose(env, "bpf verifier is misconfigured\n");
13491 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13493 if (cnt >= ARRAY_SIZE(insn_buf)) {
13494 verbose(env, "bpf verifier is misconfigured\n");
13497 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13501 env->prog = new_prog;
13506 if (bpf_prog_is_dev_bound(env->prog->aux))
13509 insn = env->prog->insnsi + delta;
13511 for (i = 0; i < insn_cnt; i++, insn++) {
13512 bpf_convert_ctx_access_t convert_ctx_access;
13515 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13516 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13517 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13518 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13521 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13522 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13523 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13524 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13525 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13526 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13527 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13528 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13530 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13535 if (type == BPF_WRITE &&
13536 env->insn_aux_data[i + delta].sanitize_stack_spill) {
13537 struct bpf_insn patch[] = {
13542 cnt = ARRAY_SIZE(patch);
13543 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13548 env->prog = new_prog;
13549 insn = new_prog->insnsi + i + delta;
13556 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13558 if (!ops->convert_ctx_access)
13560 convert_ctx_access = ops->convert_ctx_access;
13562 case PTR_TO_SOCKET:
13563 case PTR_TO_SOCK_COMMON:
13564 convert_ctx_access = bpf_sock_convert_ctx_access;
13566 case PTR_TO_TCP_SOCK:
13567 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13569 case PTR_TO_XDP_SOCK:
13570 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13572 case PTR_TO_BTF_ID:
13573 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13574 if (type == BPF_READ) {
13575 insn->code = BPF_LDX | BPF_PROBE_MEM |
13576 BPF_SIZE((insn)->code);
13577 env->prog->aux->num_exentries++;
13584 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13585 size = BPF_LDST_BYTES(insn);
13587 /* If the read access is a narrower load of the field,
13588 * convert to a 4/8-byte load, to minimum program type specific
13589 * convert_ctx_access changes. If conversion is successful,
13590 * we will apply proper mask to the result.
13592 is_narrower_load = size < ctx_field_size;
13593 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13595 if (is_narrower_load) {
13598 if (type == BPF_WRITE) {
13599 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13604 if (ctx_field_size == 4)
13606 else if (ctx_field_size == 8)
13607 size_code = BPF_DW;
13609 insn->off = off & ~(size_default - 1);
13610 insn->code = BPF_LDX | BPF_MEM | size_code;
13614 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13616 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13617 (ctx_field_size && !target_size)) {
13618 verbose(env, "bpf verifier is misconfigured\n");
13622 if (is_narrower_load && size < target_size) {
13623 u8 shift = bpf_ctx_narrow_access_offset(
13624 off, size, size_default) * 8;
13625 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13626 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13629 if (ctx_field_size <= 4) {
13631 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13634 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13635 (1 << size * 8) - 1);
13638 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13641 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13642 (1ULL << size * 8) - 1);
13646 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13652 /* keep walking new program and skip insns we just inserted */
13653 env->prog = new_prog;
13654 insn = new_prog->insnsi + i + delta;
13660 static int jit_subprogs(struct bpf_verifier_env *env)
13662 struct bpf_prog *prog = env->prog, **func, *tmp;
13663 int i, j, subprog_start, subprog_end = 0, len, subprog;
13664 struct bpf_map *map_ptr;
13665 struct bpf_insn *insn;
13666 void *old_bpf_func;
13667 int err, num_exentries;
13669 if (env->subprog_cnt <= 1)
13672 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13673 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13676 /* Upon error here we cannot fall back to interpreter but
13677 * need a hard reject of the program. Thus -EFAULT is
13678 * propagated in any case.
13680 subprog = find_subprog(env, i + insn->imm + 1);
13682 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13683 i + insn->imm + 1);
13686 /* temporarily remember subprog id inside insn instead of
13687 * aux_data, since next loop will split up all insns into funcs
13689 insn->off = subprog;
13690 /* remember original imm in case JIT fails and fallback
13691 * to interpreter will be needed
13693 env->insn_aux_data[i].call_imm = insn->imm;
13694 /* point imm to __bpf_call_base+1 from JITs point of view */
13696 if (bpf_pseudo_func(insn))
13697 /* jit (e.g. x86_64) may emit fewer instructions
13698 * if it learns a u32 imm is the same as a u64 imm.
13699 * Force a non zero here.
13704 err = bpf_prog_alloc_jited_linfo(prog);
13706 goto out_undo_insn;
13709 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13711 goto out_undo_insn;
13713 for (i = 0; i < env->subprog_cnt; i++) {
13714 subprog_start = subprog_end;
13715 subprog_end = env->subprog_info[i + 1].start;
13717 len = subprog_end - subprog_start;
13718 /* bpf_prog_run() doesn't call subprogs directly,
13719 * hence main prog stats include the runtime of subprogs.
13720 * subprogs don't have IDs and not reachable via prog_get_next_id
13721 * func[i]->stats will never be accessed and stays NULL
13723 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13726 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13727 len * sizeof(struct bpf_insn));
13728 func[i]->type = prog->type;
13729 func[i]->len = len;
13730 if (bpf_prog_calc_tag(func[i]))
13732 func[i]->is_func = 1;
13733 func[i]->aux->func_idx = i;
13734 /* Below members will be freed only at prog->aux */
13735 func[i]->aux->btf = prog->aux->btf;
13736 func[i]->aux->func_info = prog->aux->func_info;
13737 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13738 func[i]->aux->poke_tab = prog->aux->poke_tab;
13739 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13741 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13742 struct bpf_jit_poke_descriptor *poke;
13744 poke = &prog->aux->poke_tab[j];
13745 if (poke->insn_idx < subprog_end &&
13746 poke->insn_idx >= subprog_start)
13747 poke->aux = func[i]->aux;
13750 func[i]->aux->name[0] = 'F';
13751 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13752 func[i]->jit_requested = 1;
13753 func[i]->blinding_requested = prog->blinding_requested;
13754 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13755 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13756 func[i]->aux->linfo = prog->aux->linfo;
13757 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13758 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13759 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13761 insn = func[i]->insnsi;
13762 for (j = 0; j < func[i]->len; j++, insn++) {
13763 if (BPF_CLASS(insn->code) == BPF_LDX &&
13764 BPF_MODE(insn->code) == BPF_PROBE_MEM)
13767 func[i]->aux->num_exentries = num_exentries;
13768 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13769 func[i] = bpf_int_jit_compile(func[i]);
13770 if (!func[i]->jited) {
13777 /* at this point all bpf functions were successfully JITed
13778 * now populate all bpf_calls with correct addresses and
13779 * run last pass of JIT
13781 for (i = 0; i < env->subprog_cnt; i++) {
13782 insn = func[i]->insnsi;
13783 for (j = 0; j < func[i]->len; j++, insn++) {
13784 if (bpf_pseudo_func(insn)) {
13785 subprog = insn->off;
13786 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13787 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13790 if (!bpf_pseudo_call(insn))
13792 subprog = insn->off;
13793 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13796 /* we use the aux data to keep a list of the start addresses
13797 * of the JITed images for each function in the program
13799 * for some architectures, such as powerpc64, the imm field
13800 * might not be large enough to hold the offset of the start
13801 * address of the callee's JITed image from __bpf_call_base
13803 * in such cases, we can lookup the start address of a callee
13804 * by using its subprog id, available from the off field of
13805 * the call instruction, as an index for this list
13807 func[i]->aux->func = func;
13808 func[i]->aux->func_cnt = env->subprog_cnt;
13810 for (i = 0; i < env->subprog_cnt; i++) {
13811 old_bpf_func = func[i]->bpf_func;
13812 tmp = bpf_int_jit_compile(func[i]);
13813 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13814 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13821 /* finally lock prog and jit images for all functions and
13822 * populate kallsysm
13824 for (i = 0; i < env->subprog_cnt; i++) {
13825 bpf_prog_lock_ro(func[i]);
13826 bpf_prog_kallsyms_add(func[i]);
13829 /* Last step: make now unused interpreter insns from main
13830 * prog consistent for later dump requests, so they can
13831 * later look the same as if they were interpreted only.
13833 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13834 if (bpf_pseudo_func(insn)) {
13835 insn[0].imm = env->insn_aux_data[i].call_imm;
13836 insn[1].imm = insn->off;
13840 if (!bpf_pseudo_call(insn))
13842 insn->off = env->insn_aux_data[i].call_imm;
13843 subprog = find_subprog(env, i + insn->off + 1);
13844 insn->imm = subprog;
13848 prog->bpf_func = func[0]->bpf_func;
13849 prog->jited_len = func[0]->jited_len;
13850 prog->aux->func = func;
13851 prog->aux->func_cnt = env->subprog_cnt;
13852 bpf_prog_jit_attempt_done(prog);
13855 /* We failed JIT'ing, so at this point we need to unregister poke
13856 * descriptors from subprogs, so that kernel is not attempting to
13857 * patch it anymore as we're freeing the subprog JIT memory.
13859 for (i = 0; i < prog->aux->size_poke_tab; i++) {
13860 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13861 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13863 /* At this point we're guaranteed that poke descriptors are not
13864 * live anymore. We can just unlink its descriptor table as it's
13865 * released with the main prog.
13867 for (i = 0; i < env->subprog_cnt; i++) {
13870 func[i]->aux->poke_tab = NULL;
13871 bpf_jit_free(func[i]);
13875 /* cleanup main prog to be interpreted */
13876 prog->jit_requested = 0;
13877 prog->blinding_requested = 0;
13878 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13879 if (!bpf_pseudo_call(insn))
13882 insn->imm = env->insn_aux_data[i].call_imm;
13884 bpf_prog_jit_attempt_done(prog);
13888 static int fixup_call_args(struct bpf_verifier_env *env)
13890 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13891 struct bpf_prog *prog = env->prog;
13892 struct bpf_insn *insn = prog->insnsi;
13893 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13898 if (env->prog->jit_requested &&
13899 !bpf_prog_is_dev_bound(env->prog->aux)) {
13900 err = jit_subprogs(env);
13903 if (err == -EFAULT)
13906 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13907 if (has_kfunc_call) {
13908 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13911 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13912 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13913 * have to be rejected, since interpreter doesn't support them yet.
13915 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13918 for (i = 0; i < prog->len; i++, insn++) {
13919 if (bpf_pseudo_func(insn)) {
13920 /* When JIT fails the progs with callback calls
13921 * have to be rejected, since interpreter doesn't support them yet.
13923 verbose(env, "callbacks are not allowed in non-JITed programs\n");
13927 if (!bpf_pseudo_call(insn))
13929 depth = get_callee_stack_depth(env, insn, i);
13932 bpf_patch_call_args(insn, depth);
13939 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13940 struct bpf_insn *insn)
13942 const struct bpf_kfunc_desc *desc;
13945 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13949 /* insn->imm has the btf func_id. Replace it with
13950 * an address (relative to __bpf_base_call).
13952 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13954 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13959 insn->imm = desc->imm;
13964 /* Do various post-verification rewrites in a single program pass.
13965 * These rewrites simplify JIT and interpreter implementations.
13967 static int do_misc_fixups(struct bpf_verifier_env *env)
13969 struct bpf_prog *prog = env->prog;
13970 enum bpf_attach_type eatype = prog->expected_attach_type;
13971 enum bpf_prog_type prog_type = resolve_prog_type(prog);
13972 struct bpf_insn *insn = prog->insnsi;
13973 const struct bpf_func_proto *fn;
13974 const int insn_cnt = prog->len;
13975 const struct bpf_map_ops *ops;
13976 struct bpf_insn_aux_data *aux;
13977 struct bpf_insn insn_buf[16];
13978 struct bpf_prog *new_prog;
13979 struct bpf_map *map_ptr;
13980 int i, ret, cnt, delta = 0;
13982 for (i = 0; i < insn_cnt; i++, insn++) {
13983 /* Make divide-by-zero exceptions impossible. */
13984 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13985 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13986 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13987 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13988 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13989 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13990 struct bpf_insn *patchlet;
13991 struct bpf_insn chk_and_div[] = {
13992 /* [R,W]x div 0 -> 0 */
13993 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13994 BPF_JNE | BPF_K, insn->src_reg,
13996 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13997 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14000 struct bpf_insn chk_and_mod[] = {
14001 /* [R,W]x mod 0 -> [R,W]x */
14002 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14003 BPF_JEQ | BPF_K, insn->src_reg,
14004 0, 1 + (is64 ? 0 : 1), 0),
14006 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14007 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
14010 patchlet = isdiv ? chk_and_div : chk_and_mod;
14011 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
14012 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
14014 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
14019 env->prog = prog = new_prog;
14020 insn = new_prog->insnsi + i + delta;
14024 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
14025 if (BPF_CLASS(insn->code) == BPF_LD &&
14026 (BPF_MODE(insn->code) == BPF_ABS ||
14027 BPF_MODE(insn->code) == BPF_IND)) {
14028 cnt = env->ops->gen_ld_abs(insn, insn_buf);
14029 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14030 verbose(env, "bpf verifier is misconfigured\n");
14034 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14039 env->prog = prog = new_prog;
14040 insn = new_prog->insnsi + i + delta;
14044 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
14045 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
14046 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
14047 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
14048 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
14049 struct bpf_insn *patch = &insn_buf[0];
14050 bool issrc, isneg, isimm;
14053 aux = &env->insn_aux_data[i + delta];
14054 if (!aux->alu_state ||
14055 aux->alu_state == BPF_ALU_NON_POINTER)
14058 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14059 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14060 BPF_ALU_SANITIZE_SRC;
14061 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14063 off_reg = issrc ? insn->src_reg : insn->dst_reg;
14065 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14068 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14069 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14070 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14071 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14072 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14073 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14074 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14077 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14078 insn->src_reg = BPF_REG_AX;
14080 insn->code = insn->code == code_add ?
14081 code_sub : code_add;
14083 if (issrc && isneg && !isimm)
14084 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14085 cnt = patch - insn_buf;
14087 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14092 env->prog = prog = new_prog;
14093 insn = new_prog->insnsi + i + delta;
14097 if (insn->code != (BPF_JMP | BPF_CALL))
14099 if (insn->src_reg == BPF_PSEUDO_CALL)
14101 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14102 ret = fixup_kfunc_call(env, insn);
14108 if (insn->imm == BPF_FUNC_get_route_realm)
14109 prog->dst_needed = 1;
14110 if (insn->imm == BPF_FUNC_get_prandom_u32)
14111 bpf_user_rnd_init_once();
14112 if (insn->imm == BPF_FUNC_override_return)
14113 prog->kprobe_override = 1;
14114 if (insn->imm == BPF_FUNC_tail_call) {
14115 /* If we tail call into other programs, we
14116 * cannot make any assumptions since they can
14117 * be replaced dynamically during runtime in
14118 * the program array.
14120 prog->cb_access = 1;
14121 if (!allow_tail_call_in_subprogs(env))
14122 prog->aux->stack_depth = MAX_BPF_STACK;
14123 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14125 /* mark bpf_tail_call as different opcode to avoid
14126 * conditional branch in the interpreter for every normal
14127 * call and to prevent accidental JITing by JIT compiler
14128 * that doesn't support bpf_tail_call yet
14131 insn->code = BPF_JMP | BPF_TAIL_CALL;
14133 aux = &env->insn_aux_data[i + delta];
14134 if (env->bpf_capable && !prog->blinding_requested &&
14135 prog->jit_requested &&
14136 !bpf_map_key_poisoned(aux) &&
14137 !bpf_map_ptr_poisoned(aux) &&
14138 !bpf_map_ptr_unpriv(aux)) {
14139 struct bpf_jit_poke_descriptor desc = {
14140 .reason = BPF_POKE_REASON_TAIL_CALL,
14141 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14142 .tail_call.key = bpf_map_key_immediate(aux),
14143 .insn_idx = i + delta,
14146 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14148 verbose(env, "adding tail call poke descriptor failed\n");
14152 insn->imm = ret + 1;
14156 if (!bpf_map_ptr_unpriv(aux))
14159 /* instead of changing every JIT dealing with tail_call
14160 * emit two extra insns:
14161 * if (index >= max_entries) goto out;
14162 * index &= array->index_mask;
14163 * to avoid out-of-bounds cpu speculation
14165 if (bpf_map_ptr_poisoned(aux)) {
14166 verbose(env, "tail_call abusing map_ptr\n");
14170 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14171 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14172 map_ptr->max_entries, 2);
14173 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14174 container_of(map_ptr,
14177 insn_buf[2] = *insn;
14179 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14184 env->prog = prog = new_prog;
14185 insn = new_prog->insnsi + i + delta;
14189 if (insn->imm == BPF_FUNC_timer_set_callback) {
14190 /* The verifier will process callback_fn as many times as necessary
14191 * with different maps and the register states prepared by
14192 * set_timer_callback_state will be accurate.
14194 * The following use case is valid:
14195 * map1 is shared by prog1, prog2, prog3.
14196 * prog1 calls bpf_timer_init for some map1 elements
14197 * prog2 calls bpf_timer_set_callback for some map1 elements.
14198 * Those that were not bpf_timer_init-ed will return -EINVAL.
14199 * prog3 calls bpf_timer_start for some map1 elements.
14200 * Those that were not both bpf_timer_init-ed and
14201 * bpf_timer_set_callback-ed will return -EINVAL.
14203 struct bpf_insn ld_addrs[2] = {
14204 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14207 insn_buf[0] = ld_addrs[0];
14208 insn_buf[1] = ld_addrs[1];
14209 insn_buf[2] = *insn;
14212 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14217 env->prog = prog = new_prog;
14218 insn = new_prog->insnsi + i + delta;
14219 goto patch_call_imm;
14222 if (insn->imm == BPF_FUNC_task_storage_get ||
14223 insn->imm == BPF_FUNC_sk_storage_get ||
14224 insn->imm == BPF_FUNC_inode_storage_get) {
14225 if (env->prog->aux->sleepable)
14226 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14228 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14229 insn_buf[1] = *insn;
14232 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14237 env->prog = prog = new_prog;
14238 insn = new_prog->insnsi + i + delta;
14239 goto patch_call_imm;
14242 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14243 * and other inlining handlers are currently limited to 64 bit
14246 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14247 (insn->imm == BPF_FUNC_map_lookup_elem ||
14248 insn->imm == BPF_FUNC_map_update_elem ||
14249 insn->imm == BPF_FUNC_map_delete_elem ||
14250 insn->imm == BPF_FUNC_map_push_elem ||
14251 insn->imm == BPF_FUNC_map_pop_elem ||
14252 insn->imm == BPF_FUNC_map_peek_elem ||
14253 insn->imm == BPF_FUNC_redirect_map ||
14254 insn->imm == BPF_FUNC_for_each_map_elem ||
14255 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14256 aux = &env->insn_aux_data[i + delta];
14257 if (bpf_map_ptr_poisoned(aux))
14258 goto patch_call_imm;
14260 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14261 ops = map_ptr->ops;
14262 if (insn->imm == BPF_FUNC_map_lookup_elem &&
14263 ops->map_gen_lookup) {
14264 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14265 if (cnt == -EOPNOTSUPP)
14266 goto patch_map_ops_generic;
14267 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14268 verbose(env, "bpf verifier is misconfigured\n");
14272 new_prog = bpf_patch_insn_data(env, i + delta,
14278 env->prog = prog = new_prog;
14279 insn = new_prog->insnsi + i + delta;
14283 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14284 (void *(*)(struct bpf_map *map, void *key))NULL));
14285 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14286 (int (*)(struct bpf_map *map, void *key))NULL));
14287 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14288 (int (*)(struct bpf_map *map, void *key, void *value,
14290 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14291 (int (*)(struct bpf_map *map, void *value,
14293 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14294 (int (*)(struct bpf_map *map, void *value))NULL));
14295 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14296 (int (*)(struct bpf_map *map, void *value))NULL));
14297 BUILD_BUG_ON(!__same_type(ops->map_redirect,
14298 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14299 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14300 (int (*)(struct bpf_map *map,
14301 bpf_callback_t callback_fn,
14302 void *callback_ctx,
14304 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14305 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14307 patch_map_ops_generic:
14308 switch (insn->imm) {
14309 case BPF_FUNC_map_lookup_elem:
14310 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14312 case BPF_FUNC_map_update_elem:
14313 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14315 case BPF_FUNC_map_delete_elem:
14316 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14318 case BPF_FUNC_map_push_elem:
14319 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14321 case BPF_FUNC_map_pop_elem:
14322 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14324 case BPF_FUNC_map_peek_elem:
14325 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14327 case BPF_FUNC_redirect_map:
14328 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14330 case BPF_FUNC_for_each_map_elem:
14331 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14333 case BPF_FUNC_map_lookup_percpu_elem:
14334 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14338 goto patch_call_imm;
14341 /* Implement bpf_jiffies64 inline. */
14342 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14343 insn->imm == BPF_FUNC_jiffies64) {
14344 struct bpf_insn ld_jiffies_addr[2] = {
14345 BPF_LD_IMM64(BPF_REG_0,
14346 (unsigned long)&jiffies),
14349 insn_buf[0] = ld_jiffies_addr[0];
14350 insn_buf[1] = ld_jiffies_addr[1];
14351 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14355 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14361 env->prog = prog = new_prog;
14362 insn = new_prog->insnsi + i + delta;
14366 /* Implement bpf_get_func_arg inline. */
14367 if (prog_type == BPF_PROG_TYPE_TRACING &&
14368 insn->imm == BPF_FUNC_get_func_arg) {
14369 /* Load nr_args from ctx - 8 */
14370 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14371 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14372 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14373 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14374 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14375 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14376 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14377 insn_buf[7] = BPF_JMP_A(1);
14378 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14381 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14386 env->prog = prog = new_prog;
14387 insn = new_prog->insnsi + i + delta;
14391 /* Implement bpf_get_func_ret inline. */
14392 if (prog_type == BPF_PROG_TYPE_TRACING &&
14393 insn->imm == BPF_FUNC_get_func_ret) {
14394 if (eatype == BPF_TRACE_FEXIT ||
14395 eatype == BPF_MODIFY_RETURN) {
14396 /* Load nr_args from ctx - 8 */
14397 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14398 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14399 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14400 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14401 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14402 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14405 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14409 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14414 env->prog = prog = new_prog;
14415 insn = new_prog->insnsi + i + delta;
14419 /* Implement get_func_arg_cnt inline. */
14420 if (prog_type == BPF_PROG_TYPE_TRACING &&
14421 insn->imm == BPF_FUNC_get_func_arg_cnt) {
14422 /* Load nr_args from ctx - 8 */
14423 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14425 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14429 env->prog = prog = new_prog;
14430 insn = new_prog->insnsi + i + delta;
14434 /* Implement bpf_get_func_ip inline. */
14435 if (prog_type == BPF_PROG_TYPE_TRACING &&
14436 insn->imm == BPF_FUNC_get_func_ip) {
14437 /* Load IP address from ctx - 16 */
14438 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14440 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14444 env->prog = prog = new_prog;
14445 insn = new_prog->insnsi + i + delta;
14450 fn = env->ops->get_func_proto(insn->imm, env->prog);
14451 /* all functions that have prototype and verifier allowed
14452 * programs to call them, must be real in-kernel functions
14456 "kernel subsystem misconfigured func %s#%d\n",
14457 func_id_name(insn->imm), insn->imm);
14460 insn->imm = fn->func - __bpf_call_base;
14463 /* Since poke tab is now finalized, publish aux to tracker. */
14464 for (i = 0; i < prog->aux->size_poke_tab; i++) {
14465 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14466 if (!map_ptr->ops->map_poke_track ||
14467 !map_ptr->ops->map_poke_untrack ||
14468 !map_ptr->ops->map_poke_run) {
14469 verbose(env, "bpf verifier is misconfigured\n");
14473 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14475 verbose(env, "tracking tail call prog failed\n");
14480 sort_kfunc_descs_by_imm(env->prog);
14485 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14488 u32 callback_subprogno,
14491 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14492 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14493 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14494 int reg_loop_max = BPF_REG_6;
14495 int reg_loop_cnt = BPF_REG_7;
14496 int reg_loop_ctx = BPF_REG_8;
14498 struct bpf_prog *new_prog;
14499 u32 callback_start;
14500 u32 call_insn_offset;
14501 s32 callback_offset;
14503 /* This represents an inlined version of bpf_iter.c:bpf_loop,
14504 * be careful to modify this code in sync.
14506 struct bpf_insn insn_buf[] = {
14507 /* Return error and jump to the end of the patch if
14508 * expected number of iterations is too big.
14510 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14511 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14512 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14513 /* spill R6, R7, R8 to use these as loop vars */
14514 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14515 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14516 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14517 /* initialize loop vars */
14518 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14519 BPF_MOV32_IMM(reg_loop_cnt, 0),
14520 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14522 * if reg_loop_cnt >= reg_loop_max skip the loop body
14524 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14526 * correct callback offset would be set after patching
14528 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14529 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14531 /* increment loop counter */
14532 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14533 /* jump to loop header if callback returned 0 */
14534 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14535 /* return value of bpf_loop,
14536 * set R0 to the number of iterations
14538 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14539 /* restore original values of R6, R7, R8 */
14540 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14541 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14542 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14545 *cnt = ARRAY_SIZE(insn_buf);
14546 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14550 /* callback start is known only after patching */
14551 callback_start = env->subprog_info[callback_subprogno].start;
14552 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14553 call_insn_offset = position + 12;
14554 callback_offset = callback_start - call_insn_offset - 1;
14555 new_prog->insnsi[call_insn_offset].imm = callback_offset;
14560 static bool is_bpf_loop_call(struct bpf_insn *insn)
14562 return insn->code == (BPF_JMP | BPF_CALL) &&
14563 insn->src_reg == 0 &&
14564 insn->imm == BPF_FUNC_loop;
14567 /* For all sub-programs in the program (including main) check
14568 * insn_aux_data to see if there are bpf_loop calls that require
14569 * inlining. If such calls are found the calls are replaced with a
14570 * sequence of instructions produced by `inline_bpf_loop` function and
14571 * subprog stack_depth is increased by the size of 3 registers.
14572 * This stack space is used to spill values of the R6, R7, R8. These
14573 * registers are used to store the loop bound, counter and context
14576 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14578 struct bpf_subprog_info *subprogs = env->subprog_info;
14579 int i, cur_subprog = 0, cnt, delta = 0;
14580 struct bpf_insn *insn = env->prog->insnsi;
14581 int insn_cnt = env->prog->len;
14582 u16 stack_depth = subprogs[cur_subprog].stack_depth;
14583 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14584 u16 stack_depth_extra = 0;
14586 for (i = 0; i < insn_cnt; i++, insn++) {
14587 struct bpf_loop_inline_state *inline_state =
14588 &env->insn_aux_data[i + delta].loop_inline_state;
14590 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14591 struct bpf_prog *new_prog;
14593 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14594 new_prog = inline_bpf_loop(env,
14596 -(stack_depth + stack_depth_extra),
14597 inline_state->callback_subprogno,
14603 env->prog = new_prog;
14604 insn = new_prog->insnsi + i + delta;
14607 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14608 subprogs[cur_subprog].stack_depth += stack_depth_extra;
14610 stack_depth = subprogs[cur_subprog].stack_depth;
14611 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14612 stack_depth_extra = 0;
14616 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14621 static void free_states(struct bpf_verifier_env *env)
14623 struct bpf_verifier_state_list *sl, *sln;
14626 sl = env->free_list;
14629 free_verifier_state(&sl->state, false);
14633 env->free_list = NULL;
14635 if (!env->explored_states)
14638 for (i = 0; i < state_htab_size(env); i++) {
14639 sl = env->explored_states[i];
14643 free_verifier_state(&sl->state, false);
14647 env->explored_states[i] = NULL;
14651 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14653 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14654 struct bpf_verifier_state *state;
14655 struct bpf_reg_state *regs;
14658 env->prev_linfo = NULL;
14661 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14664 state->curframe = 0;
14665 state->speculative = false;
14666 state->branches = 1;
14667 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14668 if (!state->frame[0]) {
14672 env->cur_state = state;
14673 init_func_state(env, state->frame[0],
14674 BPF_MAIN_FUNC /* callsite */,
14678 regs = state->frame[state->curframe]->regs;
14679 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14680 ret = btf_prepare_func_args(env, subprog, regs);
14683 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14684 if (regs[i].type == PTR_TO_CTX)
14685 mark_reg_known_zero(env, regs, i);
14686 else if (regs[i].type == SCALAR_VALUE)
14687 mark_reg_unknown(env, regs, i);
14688 else if (base_type(regs[i].type) == PTR_TO_MEM) {
14689 const u32 mem_size = regs[i].mem_size;
14691 mark_reg_known_zero(env, regs, i);
14692 regs[i].mem_size = mem_size;
14693 regs[i].id = ++env->id_gen;
14697 /* 1st arg to a function */
14698 regs[BPF_REG_1].type = PTR_TO_CTX;
14699 mark_reg_known_zero(env, regs, BPF_REG_1);
14700 ret = btf_check_subprog_arg_match(env, subprog, regs);
14701 if (ret == -EFAULT)
14702 /* unlikely verifier bug. abort.
14703 * ret == 0 and ret < 0 are sadly acceptable for
14704 * main() function due to backward compatibility.
14705 * Like socket filter program may be written as:
14706 * int bpf_prog(struct pt_regs *ctx)
14707 * and never dereference that ctx in the program.
14708 * 'struct pt_regs' is a type mismatch for socket
14709 * filter that should be using 'struct __sk_buff'.
14714 ret = do_check(env);
14716 /* check for NULL is necessary, since cur_state can be freed inside
14717 * do_check() under memory pressure.
14719 if (env->cur_state) {
14720 free_verifier_state(env->cur_state, true);
14721 env->cur_state = NULL;
14723 while (!pop_stack(env, NULL, NULL, false));
14724 if (!ret && pop_log)
14725 bpf_vlog_reset(&env->log, 0);
14730 /* Verify all global functions in a BPF program one by one based on their BTF.
14731 * All global functions must pass verification. Otherwise the whole program is rejected.
14742 * foo() will be verified first for R1=any_scalar_value. During verification it
14743 * will be assumed that bar() already verified successfully and call to bar()
14744 * from foo() will be checked for type match only. Later bar() will be verified
14745 * independently to check that it's safe for R1=any_scalar_value.
14747 static int do_check_subprogs(struct bpf_verifier_env *env)
14749 struct bpf_prog_aux *aux = env->prog->aux;
14752 if (!aux->func_info)
14755 for (i = 1; i < env->subprog_cnt; i++) {
14756 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14758 env->insn_idx = env->subprog_info[i].start;
14759 WARN_ON_ONCE(env->insn_idx == 0);
14760 ret = do_check_common(env, i);
14763 } else if (env->log.level & BPF_LOG_LEVEL) {
14765 "Func#%d is safe for any args that match its prototype\n",
14772 static int do_check_main(struct bpf_verifier_env *env)
14777 ret = do_check_common(env, 0);
14779 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14784 static void print_verification_stats(struct bpf_verifier_env *env)
14788 if (env->log.level & BPF_LOG_STATS) {
14789 verbose(env, "verification time %lld usec\n",
14790 div_u64(env->verification_time, 1000));
14791 verbose(env, "stack depth ");
14792 for (i = 0; i < env->subprog_cnt; i++) {
14793 u32 depth = env->subprog_info[i].stack_depth;
14795 verbose(env, "%d", depth);
14796 if (i + 1 < env->subprog_cnt)
14799 verbose(env, "\n");
14801 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14802 "total_states %d peak_states %d mark_read %d\n",
14803 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14804 env->max_states_per_insn, env->total_states,
14805 env->peak_states, env->longest_mark_read_walk);
14808 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14810 const struct btf_type *t, *func_proto;
14811 const struct bpf_struct_ops *st_ops;
14812 const struct btf_member *member;
14813 struct bpf_prog *prog = env->prog;
14814 u32 btf_id, member_idx;
14817 if (!prog->gpl_compatible) {
14818 verbose(env, "struct ops programs must have a GPL compatible license\n");
14822 btf_id = prog->aux->attach_btf_id;
14823 st_ops = bpf_struct_ops_find(btf_id);
14825 verbose(env, "attach_btf_id %u is not a supported struct\n",
14831 member_idx = prog->expected_attach_type;
14832 if (member_idx >= btf_type_vlen(t)) {
14833 verbose(env, "attach to invalid member idx %u of struct %s\n",
14834 member_idx, st_ops->name);
14838 member = &btf_type_member(t)[member_idx];
14839 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14840 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14843 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14844 mname, member_idx, st_ops->name);
14848 if (st_ops->check_member) {
14849 int err = st_ops->check_member(t, member);
14852 verbose(env, "attach to unsupported member %s of struct %s\n",
14853 mname, st_ops->name);
14858 prog->aux->attach_func_proto = func_proto;
14859 prog->aux->attach_func_name = mname;
14860 env->ops = st_ops->verifier_ops;
14864 #define SECURITY_PREFIX "security_"
14866 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14868 if (within_error_injection_list(addr) ||
14869 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14875 /* list of non-sleepable functions that are otherwise on
14876 * ALLOW_ERROR_INJECTION list
14878 BTF_SET_START(btf_non_sleepable_error_inject)
14879 /* Three functions below can be called from sleepable and non-sleepable context.
14880 * Assume non-sleepable from bpf safety point of view.
14882 BTF_ID(func, __filemap_add_folio)
14883 BTF_ID(func, should_fail_alloc_page)
14884 BTF_ID(func, should_failslab)
14885 BTF_SET_END(btf_non_sleepable_error_inject)
14887 static int check_non_sleepable_error_inject(u32 btf_id)
14889 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14892 int bpf_check_attach_target(struct bpf_verifier_log *log,
14893 const struct bpf_prog *prog,
14894 const struct bpf_prog *tgt_prog,
14896 struct bpf_attach_target_info *tgt_info)
14898 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14899 const char prefix[] = "btf_trace_";
14900 int ret = 0, subprog = -1, i;
14901 const struct btf_type *t;
14902 bool conservative = true;
14908 bpf_log(log, "Tracing programs must provide btf_id\n");
14911 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14914 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14917 t = btf_type_by_id(btf, btf_id);
14919 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14922 tname = btf_name_by_offset(btf, t->name_off);
14924 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14928 struct bpf_prog_aux *aux = tgt_prog->aux;
14930 for (i = 0; i < aux->func_info_cnt; i++)
14931 if (aux->func_info[i].type_id == btf_id) {
14935 if (subprog == -1) {
14936 bpf_log(log, "Subprog %s doesn't exist\n", tname);
14939 conservative = aux->func_info_aux[subprog].unreliable;
14940 if (prog_extension) {
14941 if (conservative) {
14943 "Cannot replace static functions\n");
14946 if (!prog->jit_requested) {
14948 "Extension programs should be JITed\n");
14952 if (!tgt_prog->jited) {
14953 bpf_log(log, "Can attach to only JITed progs\n");
14956 if (tgt_prog->type == prog->type) {
14957 /* Cannot fentry/fexit another fentry/fexit program.
14958 * Cannot attach program extension to another extension.
14959 * It's ok to attach fentry/fexit to extension program.
14961 bpf_log(log, "Cannot recursively attach\n");
14964 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14966 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14967 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14968 /* Program extensions can extend all program types
14969 * except fentry/fexit. The reason is the following.
14970 * The fentry/fexit programs are used for performance
14971 * analysis, stats and can be attached to any program
14972 * type except themselves. When extension program is
14973 * replacing XDP function it is necessary to allow
14974 * performance analysis of all functions. Both original
14975 * XDP program and its program extension. Hence
14976 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14977 * allowed. If extending of fentry/fexit was allowed it
14978 * would be possible to create long call chain
14979 * fentry->extension->fentry->extension beyond
14980 * reasonable stack size. Hence extending fentry is not
14983 bpf_log(log, "Cannot extend fentry/fexit\n");
14987 if (prog_extension) {
14988 bpf_log(log, "Cannot replace kernel functions\n");
14993 switch (prog->expected_attach_type) {
14994 case BPF_TRACE_RAW_TP:
14997 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
15000 if (!btf_type_is_typedef(t)) {
15001 bpf_log(log, "attach_btf_id %u is not a typedef\n",
15005 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
15006 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
15010 tname += sizeof(prefix) - 1;
15011 t = btf_type_by_id(btf, t->type);
15012 if (!btf_type_is_ptr(t))
15013 /* should never happen in valid vmlinux build */
15015 t = btf_type_by_id(btf, t->type);
15016 if (!btf_type_is_func_proto(t))
15017 /* should never happen in valid vmlinux build */
15021 case BPF_TRACE_ITER:
15022 if (!btf_type_is_func(t)) {
15023 bpf_log(log, "attach_btf_id %u is not a function\n",
15027 t = btf_type_by_id(btf, t->type);
15028 if (!btf_type_is_func_proto(t))
15030 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15035 if (!prog_extension)
15038 case BPF_MODIFY_RETURN:
15040 case BPF_LSM_CGROUP:
15041 case BPF_TRACE_FENTRY:
15042 case BPF_TRACE_FEXIT:
15043 if (!btf_type_is_func(t)) {
15044 bpf_log(log, "attach_btf_id %u is not a function\n",
15048 if (prog_extension &&
15049 btf_check_type_match(log, prog, btf, t))
15051 t = btf_type_by_id(btf, t->type);
15052 if (!btf_type_is_func_proto(t))
15055 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15056 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15057 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15060 if (tgt_prog && conservative)
15063 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15069 addr = (long) tgt_prog->bpf_func;
15071 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15073 addr = kallsyms_lookup_name(tname);
15076 "The address of function %s cannot be found\n",
15082 if (prog->aux->sleepable) {
15084 switch (prog->type) {
15085 case BPF_PROG_TYPE_TRACING:
15086 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
15087 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15089 if (!check_non_sleepable_error_inject(btf_id) &&
15090 within_error_injection_list(addr))
15093 case BPF_PROG_TYPE_LSM:
15094 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
15095 * Only some of them are sleepable.
15097 if (bpf_lsm_is_sleepable_hook(btf_id))
15104 bpf_log(log, "%s is not sleepable\n", tname);
15107 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15109 bpf_log(log, "can't modify return codes of BPF programs\n");
15112 ret = check_attach_modify_return(addr, tname);
15114 bpf_log(log, "%s() is not modifiable\n", tname);
15121 tgt_info->tgt_addr = addr;
15122 tgt_info->tgt_name = tname;
15123 tgt_info->tgt_type = t;
15127 BTF_SET_START(btf_id_deny)
15130 BTF_ID(func, migrate_disable)
15131 BTF_ID(func, migrate_enable)
15133 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15134 BTF_ID(func, rcu_read_unlock_strict)
15136 BTF_SET_END(btf_id_deny)
15138 static int check_attach_btf_id(struct bpf_verifier_env *env)
15140 struct bpf_prog *prog = env->prog;
15141 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15142 struct bpf_attach_target_info tgt_info = {};
15143 u32 btf_id = prog->aux->attach_btf_id;
15144 struct bpf_trampoline *tr;
15148 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15149 if (prog->aux->sleepable)
15150 /* attach_btf_id checked to be zero already */
15152 verbose(env, "Syscall programs can only be sleepable\n");
15156 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15157 prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15158 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15162 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15163 return check_struct_ops_btf_id(env);
15165 if (prog->type != BPF_PROG_TYPE_TRACING &&
15166 prog->type != BPF_PROG_TYPE_LSM &&
15167 prog->type != BPF_PROG_TYPE_EXT)
15170 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15174 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15175 /* to make freplace equivalent to their targets, they need to
15176 * inherit env->ops and expected_attach_type for the rest of the
15179 env->ops = bpf_verifier_ops[tgt_prog->type];
15180 prog->expected_attach_type = tgt_prog->expected_attach_type;
15183 /* store info about the attachment target that will be used later */
15184 prog->aux->attach_func_proto = tgt_info.tgt_type;
15185 prog->aux->attach_func_name = tgt_info.tgt_name;
15188 prog->aux->saved_dst_prog_type = tgt_prog->type;
15189 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15192 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15193 prog->aux->attach_btf_trace = true;
15195 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15196 if (!bpf_iter_prog_supported(prog))
15201 if (prog->type == BPF_PROG_TYPE_LSM) {
15202 ret = bpf_lsm_verify_prog(&env->log, prog);
15205 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15206 btf_id_set_contains(&btf_id_deny, btf_id)) {
15210 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15211 tr = bpf_trampoline_get(key, &tgt_info);
15215 prog->aux->dst_trampoline = tr;
15219 struct btf *bpf_get_btf_vmlinux(void)
15221 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15222 mutex_lock(&bpf_verifier_lock);
15224 btf_vmlinux = btf_parse_vmlinux();
15225 mutex_unlock(&bpf_verifier_lock);
15227 return btf_vmlinux;
15230 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15232 u64 start_time = ktime_get_ns();
15233 struct bpf_verifier_env *env;
15234 struct bpf_verifier_log *log;
15235 int i, len, ret = -EINVAL;
15238 /* no program is valid */
15239 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15242 /* 'struct bpf_verifier_env' can be global, but since it's not small,
15243 * allocate/free it every time bpf_check() is called
15245 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15250 len = (*prog)->len;
15251 env->insn_aux_data =
15252 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15254 if (!env->insn_aux_data)
15256 for (i = 0; i < len; i++)
15257 env->insn_aux_data[i].orig_idx = i;
15259 env->ops = bpf_verifier_ops[env->prog->type];
15260 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15261 is_priv = bpf_capable();
15263 bpf_get_btf_vmlinux();
15265 /* grab the mutex to protect few globals used by verifier */
15267 mutex_lock(&bpf_verifier_lock);
15269 if (attr->log_level || attr->log_buf || attr->log_size) {
15270 /* user requested verbose verifier output
15271 * and supplied buffer to store the verification trace
15273 log->level = attr->log_level;
15274 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15275 log->len_total = attr->log_size;
15277 /* log attributes have to be sane */
15278 if (!bpf_verifier_log_attr_valid(log)) {
15284 mark_verifier_state_clean(env);
15286 if (IS_ERR(btf_vmlinux)) {
15287 /* Either gcc or pahole or kernel are broken. */
15288 verbose(env, "in-kernel BTF is malformed\n");
15289 ret = PTR_ERR(btf_vmlinux);
15290 goto skip_full_check;
15293 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15294 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15295 env->strict_alignment = true;
15296 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15297 env->strict_alignment = false;
15299 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15300 env->allow_uninit_stack = bpf_allow_uninit_stack();
15301 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15302 env->bypass_spec_v1 = bpf_bypass_spec_v1();
15303 env->bypass_spec_v4 = bpf_bypass_spec_v4();
15304 env->bpf_capable = bpf_capable();
15307 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15309 env->explored_states = kvcalloc(state_htab_size(env),
15310 sizeof(struct bpf_verifier_state_list *),
15313 if (!env->explored_states)
15314 goto skip_full_check;
15316 ret = add_subprog_and_kfunc(env);
15318 goto skip_full_check;
15320 ret = check_subprogs(env);
15322 goto skip_full_check;
15324 ret = check_btf_info(env, attr, uattr);
15326 goto skip_full_check;
15328 ret = check_attach_btf_id(env);
15330 goto skip_full_check;
15332 ret = resolve_pseudo_ldimm64(env);
15334 goto skip_full_check;
15336 if (bpf_prog_is_dev_bound(env->prog->aux)) {
15337 ret = bpf_prog_offload_verifier_prep(env->prog);
15339 goto skip_full_check;
15342 ret = check_cfg(env);
15344 goto skip_full_check;
15346 ret = do_check_subprogs(env);
15347 ret = ret ?: do_check_main(env);
15349 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15350 ret = bpf_prog_offload_finalize(env);
15353 kvfree(env->explored_states);
15356 ret = check_max_stack_depth(env);
15358 /* instruction rewrites happen after this point */
15360 ret = optimize_bpf_loop(env);
15364 opt_hard_wire_dead_code_branches(env);
15366 ret = opt_remove_dead_code(env);
15368 ret = opt_remove_nops(env);
15371 sanitize_dead_code(env);
15375 /* program is valid, convert *(u32*)(ctx + off) accesses */
15376 ret = convert_ctx_accesses(env);
15379 ret = do_misc_fixups(env);
15381 /* do 32-bit optimization after insn patching has done so those patched
15382 * insns could be handled correctly.
15384 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15385 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15386 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15391 ret = fixup_call_args(env);
15393 env->verification_time = ktime_get_ns() - start_time;
15394 print_verification_stats(env);
15395 env->prog->aux->verified_insns = env->insn_processed;
15397 if (log->level && bpf_verifier_log_full(log))
15399 if (log->level && !log->ubuf) {
15401 goto err_release_maps;
15405 goto err_release_maps;
15407 if (env->used_map_cnt) {
15408 /* if program passed verifier, update used_maps in bpf_prog_info */
15409 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15410 sizeof(env->used_maps[0]),
15413 if (!env->prog->aux->used_maps) {
15415 goto err_release_maps;
15418 memcpy(env->prog->aux->used_maps, env->used_maps,
15419 sizeof(env->used_maps[0]) * env->used_map_cnt);
15420 env->prog->aux->used_map_cnt = env->used_map_cnt;
15422 if (env->used_btf_cnt) {
15423 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15424 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15425 sizeof(env->used_btfs[0]),
15427 if (!env->prog->aux->used_btfs) {
15429 goto err_release_maps;
15432 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15433 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15434 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15436 if (env->used_map_cnt || env->used_btf_cnt) {
15437 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15438 * bpf_ld_imm64 instructions
15440 convert_pseudo_ld_imm64(env);
15443 adjust_btf_func(env);
15446 if (!env->prog->aux->used_maps)
15447 /* if we didn't copy map pointers into bpf_prog_info, release
15448 * them now. Otherwise free_used_maps() will release them.
15451 if (!env->prog->aux->used_btfs)
15454 /* extension progs temporarily inherit the attach_type of their targets
15455 for verification purposes, so set it back to zero before returning
15457 if (env->prog->type == BPF_PROG_TYPE_EXT)
15458 env->prog->expected_attach_type = 0;
15463 mutex_unlock(&bpf_verifier_lock);
15464 vfree(env->insn_aux_data);