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(reg->var_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().
3523 if (!env->bypass_spec_v1 && var_off) {
3526 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3527 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3533 off += reg->var_off.value;
3534 err = check_stack_read_fixed_off(env, state, off, size,
3537 /* Variable offset stack reads need more conservative handling
3538 * than fixed offset ones. Note that dst_regno >= 0 on this
3541 err = check_stack_read_var_off(env, ptr_regno, off, size,
3548 /* check_stack_write dispatches to check_stack_write_fixed_off or
3549 * check_stack_write_var_off.
3551 * 'ptr_regno' is the register used as a pointer into the stack.
3552 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3553 * 'value_regno' is the register whose value we're writing to the stack. It can
3554 * be -1, meaning that we're not writing from a register.
3556 * The caller must ensure that the offset falls within the maximum stack size.
3558 static int check_stack_write(struct bpf_verifier_env *env,
3559 int ptr_regno, int off, int size,
3560 int value_regno, int insn_idx)
3562 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3563 struct bpf_func_state *state = func(env, reg);
3566 if (tnum_is_const(reg->var_off)) {
3567 off += reg->var_off.value;
3568 err = check_stack_write_fixed_off(env, state, off, size,
3569 value_regno, insn_idx);
3571 /* Variable offset stack reads need more conservative handling
3572 * than fixed offset ones.
3574 err = check_stack_write_var_off(env, state,
3575 ptr_regno, off, size,
3576 value_regno, insn_idx);
3581 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3582 int off, int size, enum bpf_access_type type)
3584 struct bpf_reg_state *regs = cur_regs(env);
3585 struct bpf_map *map = regs[regno].map_ptr;
3586 u32 cap = bpf_map_flags_to_cap(map);
3588 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3589 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3590 map->value_size, off, size);
3594 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3595 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3596 map->value_size, off, size);
3603 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3604 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3605 int off, int size, u32 mem_size,
3606 bool zero_size_allowed)
3608 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3609 struct bpf_reg_state *reg;
3611 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3614 reg = &cur_regs(env)[regno];
3615 switch (reg->type) {
3616 case PTR_TO_MAP_KEY:
3617 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3618 mem_size, off, size);
3620 case PTR_TO_MAP_VALUE:
3621 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3622 mem_size, off, size);
3625 case PTR_TO_PACKET_META:
3626 case PTR_TO_PACKET_END:
3627 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3628 off, size, regno, reg->id, off, mem_size);
3632 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3633 mem_size, off, size);
3639 /* check read/write into a memory region with possible variable offset */
3640 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3641 int off, int size, u32 mem_size,
3642 bool zero_size_allowed)
3644 struct bpf_verifier_state *vstate = env->cur_state;
3645 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3646 struct bpf_reg_state *reg = &state->regs[regno];
3649 /* We may have adjusted the register pointing to memory region, so we
3650 * need to try adding each of min_value and max_value to off
3651 * to make sure our theoretical access will be safe.
3653 * The minimum value is only important with signed
3654 * comparisons where we can't assume the floor of a
3655 * value is 0. If we are using signed variables for our
3656 * index'es we need to make sure that whatever we use
3657 * will have a set floor within our range.
3659 if (reg->smin_value < 0 &&
3660 (reg->smin_value == S64_MIN ||
3661 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3662 reg->smin_value + off < 0)) {
3663 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3667 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3668 mem_size, zero_size_allowed);
3670 verbose(env, "R%d min value is outside of the allowed memory range\n",
3675 /* If we haven't set a max value then we need to bail since we can't be
3676 * sure we won't do bad things.
3677 * If reg->umax_value + off could overflow, treat that as unbounded too.
3679 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3680 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3684 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3685 mem_size, zero_size_allowed);
3687 verbose(env, "R%d max value is outside of the allowed memory range\n",
3695 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3696 const struct bpf_reg_state *reg, int regno,
3699 /* Access to this pointer-typed register or passing it to a helper
3700 * is only allowed in its original, unmodified form.
3704 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3705 reg_type_str(env, reg->type), regno, reg->off);
3709 if (!fixed_off_ok && reg->off) {
3710 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3711 reg_type_str(env, reg->type), regno, reg->off);
3715 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3718 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3719 verbose(env, "variable %s access var_off=%s disallowed\n",
3720 reg_type_str(env, reg->type), tn_buf);
3727 int check_ptr_off_reg(struct bpf_verifier_env *env,
3728 const struct bpf_reg_state *reg, int regno)
3730 return __check_ptr_off_reg(env, reg, regno, false);
3733 static int map_kptr_match_type(struct bpf_verifier_env *env,
3734 struct bpf_map_value_off_desc *off_desc,
3735 struct bpf_reg_state *reg, u32 regno)
3737 const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3738 int perm_flags = PTR_MAYBE_NULL;
3739 const char *reg_name = "";
3741 /* Only unreferenced case accepts untrusted pointers */
3742 if (off_desc->type == BPF_KPTR_UNREF)
3743 perm_flags |= PTR_UNTRUSTED;
3745 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3748 if (!btf_is_kernel(reg->btf)) {
3749 verbose(env, "R%d must point to kernel BTF\n", regno);
3752 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3753 reg_name = kernel_type_name(reg->btf, reg->btf_id);
3755 /* For ref_ptr case, release function check should ensure we get one
3756 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3757 * normal store of unreferenced kptr, we must ensure var_off is zero.
3758 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3759 * reg->off and reg->ref_obj_id are not needed here.
3761 if (__check_ptr_off_reg(env, reg, regno, true))
3764 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3765 * we also need to take into account the reg->off.
3767 * We want to support cases like:
3775 * v = func(); // PTR_TO_BTF_ID
3776 * val->foo = v; // reg->off is zero, btf and btf_id match type
3777 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3778 * // first member type of struct after comparison fails
3779 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3782 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3783 * is zero. We must also ensure that btf_struct_ids_match does not walk
3784 * the struct to match type against first member of struct, i.e. reject
3785 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3786 * strict mode to true for type match.
3788 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3789 off_desc->kptr.btf, off_desc->kptr.btf_id,
3790 off_desc->type == BPF_KPTR_REF))
3794 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3795 reg_type_str(env, reg->type), reg_name);
3796 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3797 if (off_desc->type == BPF_KPTR_UNREF)
3798 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3805 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3806 int value_regno, int insn_idx,
3807 struct bpf_map_value_off_desc *off_desc)
3809 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3810 int class = BPF_CLASS(insn->code);
3811 struct bpf_reg_state *val_reg;
3813 /* Things we already checked for in check_map_access and caller:
3814 * - Reject cases where variable offset may touch kptr
3815 * - size of access (must be BPF_DW)
3816 * - tnum_is_const(reg->var_off)
3817 * - off_desc->offset == off + reg->var_off.value
3819 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3820 if (BPF_MODE(insn->code) != BPF_MEM) {
3821 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3825 /* We only allow loading referenced kptr, since it will be marked as
3826 * untrusted, similar to unreferenced kptr.
3828 if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3829 verbose(env, "store to referenced kptr disallowed\n");
3833 if (class == BPF_LDX) {
3834 val_reg = reg_state(env, value_regno);
3835 /* We can simply mark the value_regno receiving the pointer
3836 * value from map as PTR_TO_BTF_ID, with the correct type.
3838 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3839 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3840 /* For mark_ptr_or_null_reg */
3841 val_reg->id = ++env->id_gen;
3842 } else if (class == BPF_STX) {
3843 val_reg = reg_state(env, value_regno);
3844 if (!register_is_null(val_reg) &&
3845 map_kptr_match_type(env, off_desc, val_reg, value_regno))
3847 } else if (class == BPF_ST) {
3849 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3854 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3860 /* check read/write into a map element with possible variable offset */
3861 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3862 int off, int size, bool zero_size_allowed,
3863 enum bpf_access_src src)
3865 struct bpf_verifier_state *vstate = env->cur_state;
3866 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3867 struct bpf_reg_state *reg = &state->regs[regno];
3868 struct bpf_map *map = reg->map_ptr;
3871 err = check_mem_region_access(env, regno, off, size, map->value_size,
3876 if (map_value_has_spin_lock(map)) {
3877 u32 lock = map->spin_lock_off;
3879 /* if any part of struct bpf_spin_lock can be touched by
3880 * load/store reject this program.
3881 * To check that [x1, x2) overlaps with [y1, y2)
3882 * it is sufficient to check x1 < y2 && y1 < x2.
3884 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3885 lock < reg->umax_value + off + size) {
3886 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3890 if (map_value_has_timer(map)) {
3891 u32 t = map->timer_off;
3893 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3894 t < reg->umax_value + off + size) {
3895 verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3899 if (map_value_has_kptrs(map)) {
3900 struct bpf_map_value_off *tab = map->kptr_off_tab;
3903 for (i = 0; i < tab->nr_off; i++) {
3904 u32 p = tab->off[i].offset;
3906 if (reg->smin_value + off < p + sizeof(u64) &&
3907 p < reg->umax_value + off + size) {
3908 if (src != ACCESS_DIRECT) {
3909 verbose(env, "kptr cannot be accessed indirectly by helper\n");
3912 if (!tnum_is_const(reg->var_off)) {
3913 verbose(env, "kptr access cannot have variable offset\n");
3916 if (p != off + reg->var_off.value) {
3917 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3918 p, off + reg->var_off.value);
3921 if (size != bpf_size_to_bytes(BPF_DW)) {
3922 verbose(env, "kptr access size must be BPF_DW\n");
3932 #define MAX_PACKET_OFF 0xffff
3934 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3935 const struct bpf_call_arg_meta *meta,
3936 enum bpf_access_type t)
3938 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3940 switch (prog_type) {
3941 /* Program types only with direct read access go here! */
3942 case BPF_PROG_TYPE_LWT_IN:
3943 case BPF_PROG_TYPE_LWT_OUT:
3944 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3945 case BPF_PROG_TYPE_SK_REUSEPORT:
3946 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3947 case BPF_PROG_TYPE_CGROUP_SKB:
3952 /* Program types with direct read + write access go here! */
3953 case BPF_PROG_TYPE_SCHED_CLS:
3954 case BPF_PROG_TYPE_SCHED_ACT:
3955 case BPF_PROG_TYPE_XDP:
3956 case BPF_PROG_TYPE_LWT_XMIT:
3957 case BPF_PROG_TYPE_SK_SKB:
3958 case BPF_PROG_TYPE_SK_MSG:
3960 return meta->pkt_access;
3962 env->seen_direct_write = true;
3965 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3967 env->seen_direct_write = true;
3976 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3977 int size, bool zero_size_allowed)
3979 struct bpf_reg_state *regs = cur_regs(env);
3980 struct bpf_reg_state *reg = ®s[regno];
3983 /* We may have added a variable offset to the packet pointer; but any
3984 * reg->range we have comes after that. We are only checking the fixed
3988 /* We don't allow negative numbers, because we aren't tracking enough
3989 * detail to prove they're safe.
3991 if (reg->smin_value < 0) {
3992 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3997 err = reg->range < 0 ? -EINVAL :
3998 __check_mem_access(env, regno, off, size, reg->range,
4001 verbose(env, "R%d offset is outside of the packet\n", regno);
4005 /* __check_mem_access has made sure "off + size - 1" is within u16.
4006 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4007 * otherwise find_good_pkt_pointers would have refused to set range info
4008 * that __check_mem_access would have rejected this pkt access.
4009 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4011 env->prog->aux->max_pkt_offset =
4012 max_t(u32, env->prog->aux->max_pkt_offset,
4013 off + reg->umax_value + size - 1);
4018 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
4019 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4020 enum bpf_access_type t, enum bpf_reg_type *reg_type,
4021 struct btf **btf, u32 *btf_id)
4023 struct bpf_insn_access_aux info = {
4024 .reg_type = *reg_type,
4028 if (env->ops->is_valid_access &&
4029 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4030 /* A non zero info.ctx_field_size indicates that this field is a
4031 * candidate for later verifier transformation to load the whole
4032 * field and then apply a mask when accessed with a narrower
4033 * access than actual ctx access size. A zero info.ctx_field_size
4034 * will only allow for whole field access and rejects any other
4035 * type of narrower access.
4037 *reg_type = info.reg_type;
4039 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4041 *btf_id = info.btf_id;
4043 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4045 /* remember the offset of last byte accessed in ctx */
4046 if (env->prog->aux->max_ctx_offset < off + size)
4047 env->prog->aux->max_ctx_offset = off + size;
4051 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4055 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4058 if (size < 0 || off < 0 ||
4059 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4060 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4067 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4068 u32 regno, int off, int size,
4069 enum bpf_access_type t)
4071 struct bpf_reg_state *regs = cur_regs(env);
4072 struct bpf_reg_state *reg = ®s[regno];
4073 struct bpf_insn_access_aux info = {};
4076 if (reg->smin_value < 0) {
4077 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4082 switch (reg->type) {
4083 case PTR_TO_SOCK_COMMON:
4084 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4087 valid = bpf_sock_is_valid_access(off, size, t, &info);
4089 case PTR_TO_TCP_SOCK:
4090 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4092 case PTR_TO_XDP_SOCK:
4093 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4101 env->insn_aux_data[insn_idx].ctx_field_size =
4102 info.ctx_field_size;
4106 verbose(env, "R%d invalid %s access off=%d size=%d\n",
4107 regno, reg_type_str(env, reg->type), off, size);
4112 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4114 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4117 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4119 const struct bpf_reg_state *reg = reg_state(env, regno);
4121 return reg->type == PTR_TO_CTX;
4124 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4126 const struct bpf_reg_state *reg = reg_state(env, regno);
4128 return type_is_sk_pointer(reg->type);
4131 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4133 const struct bpf_reg_state *reg = reg_state(env, regno);
4135 return type_is_pkt_pointer(reg->type);
4138 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4140 const struct bpf_reg_state *reg = reg_state(env, regno);
4142 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4143 return reg->type == PTR_TO_FLOW_KEYS;
4146 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4147 const struct bpf_reg_state *reg,
4148 int off, int size, bool strict)
4150 struct tnum reg_off;
4153 /* Byte size accesses are always allowed. */
4154 if (!strict || size == 1)
4157 /* For platforms that do not have a Kconfig enabling
4158 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4159 * NET_IP_ALIGN is universally set to '2'. And on platforms
4160 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4161 * to this code only in strict mode where we want to emulate
4162 * the NET_IP_ALIGN==2 checking. Therefore use an
4163 * unconditional IP align value of '2'.
4167 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4168 if (!tnum_is_aligned(reg_off, size)) {
4171 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4173 "misaligned packet access off %d+%s+%d+%d size %d\n",
4174 ip_align, tn_buf, reg->off, off, size);
4181 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4182 const struct bpf_reg_state *reg,
4183 const char *pointer_desc,
4184 int off, int size, bool strict)
4186 struct tnum reg_off;
4188 /* Byte size accesses are always allowed. */
4189 if (!strict || size == 1)
4192 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4193 if (!tnum_is_aligned(reg_off, size)) {
4196 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4197 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4198 pointer_desc, tn_buf, reg->off, off, size);
4205 static int check_ptr_alignment(struct bpf_verifier_env *env,
4206 const struct bpf_reg_state *reg, int off,
4207 int size, bool strict_alignment_once)
4209 bool strict = env->strict_alignment || strict_alignment_once;
4210 const char *pointer_desc = "";
4212 switch (reg->type) {
4214 case PTR_TO_PACKET_META:
4215 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4216 * right in front, treat it the very same way.
4218 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4219 case PTR_TO_FLOW_KEYS:
4220 pointer_desc = "flow keys ";
4222 case PTR_TO_MAP_KEY:
4223 pointer_desc = "key ";
4225 case PTR_TO_MAP_VALUE:
4226 pointer_desc = "value ";
4229 pointer_desc = "context ";
4232 pointer_desc = "stack ";
4233 /* The stack spill tracking logic in check_stack_write_fixed_off()
4234 * and check_stack_read_fixed_off() relies on stack accesses being
4240 pointer_desc = "sock ";
4242 case PTR_TO_SOCK_COMMON:
4243 pointer_desc = "sock_common ";
4245 case PTR_TO_TCP_SOCK:
4246 pointer_desc = "tcp_sock ";
4248 case PTR_TO_XDP_SOCK:
4249 pointer_desc = "xdp_sock ";
4254 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4258 static int update_stack_depth(struct bpf_verifier_env *env,
4259 const struct bpf_func_state *func,
4262 u16 stack = env->subprog_info[func->subprogno].stack_depth;
4267 /* update known max for given subprogram */
4268 env->subprog_info[func->subprogno].stack_depth = -off;
4272 /* starting from main bpf function walk all instructions of the function
4273 * and recursively walk all callees that given function can call.
4274 * Ignore jump and exit insns.
4275 * Since recursion is prevented by check_cfg() this algorithm
4276 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4278 static int check_max_stack_depth(struct bpf_verifier_env *env)
4280 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4281 struct bpf_subprog_info *subprog = env->subprog_info;
4282 struct bpf_insn *insn = env->prog->insnsi;
4283 bool tail_call_reachable = false;
4284 int ret_insn[MAX_CALL_FRAMES];
4285 int ret_prog[MAX_CALL_FRAMES];
4289 /* protect against potential stack overflow that might happen when
4290 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4291 * depth for such case down to 256 so that the worst case scenario
4292 * would result in 8k stack size (32 which is tailcall limit * 256 =
4295 * To get the idea what might happen, see an example:
4296 * func1 -> sub rsp, 128
4297 * subfunc1 -> sub rsp, 256
4298 * tailcall1 -> add rsp, 256
4299 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4300 * subfunc2 -> sub rsp, 64
4301 * subfunc22 -> sub rsp, 128
4302 * tailcall2 -> add rsp, 128
4303 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4305 * tailcall will unwind the current stack frame but it will not get rid
4306 * of caller's stack as shown on the example above.
4308 if (idx && subprog[idx].has_tail_call && depth >= 256) {
4310 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4314 /* round up to 32-bytes, since this is granularity
4315 * of interpreter stack size
4317 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4318 if (depth > MAX_BPF_STACK) {
4319 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4324 subprog_end = subprog[idx + 1].start;
4325 for (; i < subprog_end; i++) {
4328 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4330 /* remember insn and function to return to */
4331 ret_insn[frame] = i + 1;
4332 ret_prog[frame] = idx;
4334 /* find the callee */
4335 next_insn = i + insn[i].imm + 1;
4336 idx = find_subprog(env, next_insn);
4338 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4342 if (subprog[idx].is_async_cb) {
4343 if (subprog[idx].has_tail_call) {
4344 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4347 /* async callbacks don't increase bpf prog stack size */
4352 if (subprog[idx].has_tail_call)
4353 tail_call_reachable = true;
4356 if (frame >= MAX_CALL_FRAMES) {
4357 verbose(env, "the call stack of %d frames is too deep !\n",
4363 /* if tail call got detected across bpf2bpf calls then mark each of the
4364 * currently present subprog frames as tail call reachable subprogs;
4365 * this info will be utilized by JIT so that we will be preserving the
4366 * tail call counter throughout bpf2bpf calls combined with tailcalls
4368 if (tail_call_reachable)
4369 for (j = 0; j < frame; j++)
4370 subprog[ret_prog[j]].tail_call_reachable = true;
4371 if (subprog[0].tail_call_reachable)
4372 env->prog->aux->tail_call_reachable = true;
4374 /* end of for() loop means the last insn of the 'subprog'
4375 * was reached. Doesn't matter whether it was JA or EXIT
4379 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4381 i = ret_insn[frame];
4382 idx = ret_prog[frame];
4386 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4387 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4388 const struct bpf_insn *insn, int idx)
4390 int start = idx + insn->imm + 1, subprog;
4392 subprog = find_subprog(env, start);
4394 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4398 return env->subprog_info[subprog].stack_depth;
4402 static int __check_buffer_access(struct bpf_verifier_env *env,
4403 const char *buf_info,
4404 const struct bpf_reg_state *reg,
4405 int regno, int off, int size)
4409 "R%d invalid %s buffer access: off=%d, size=%d\n",
4410 regno, buf_info, off, size);
4413 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4416 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4418 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4419 regno, off, tn_buf);
4426 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4427 const struct bpf_reg_state *reg,
4428 int regno, int off, int size)
4432 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4436 if (off + size > env->prog->aux->max_tp_access)
4437 env->prog->aux->max_tp_access = off + size;
4442 static int check_buffer_access(struct bpf_verifier_env *env,
4443 const struct bpf_reg_state *reg,
4444 int regno, int off, int size,
4445 bool zero_size_allowed,
4448 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4451 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4455 if (off + size > *max_access)
4456 *max_access = off + size;
4461 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4462 static void zext_32_to_64(struct bpf_reg_state *reg)
4464 reg->var_off = tnum_subreg(reg->var_off);
4465 __reg_assign_32_into_64(reg);
4468 /* truncate register to smaller size (in bytes)
4469 * must be called with size < BPF_REG_SIZE
4471 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4475 /* clear high bits in bit representation */
4476 reg->var_off = tnum_cast(reg->var_off, size);
4478 /* fix arithmetic bounds */
4479 mask = ((u64)1 << (size * 8)) - 1;
4480 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4481 reg->umin_value &= mask;
4482 reg->umax_value &= mask;
4484 reg->umin_value = 0;
4485 reg->umax_value = mask;
4487 reg->smin_value = reg->umin_value;
4488 reg->smax_value = reg->umax_value;
4490 /* If size is smaller than 32bit register the 32bit register
4491 * values are also truncated so we push 64-bit bounds into
4492 * 32-bit bounds. Above were truncated < 32-bits already.
4496 __reg_combine_64_into_32(reg);
4499 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4501 /* A map is considered read-only if the following condition are true:
4503 * 1) BPF program side cannot change any of the map content. The
4504 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4505 * and was set at map creation time.
4506 * 2) The map value(s) have been initialized from user space by a
4507 * loader and then "frozen", such that no new map update/delete
4508 * operations from syscall side are possible for the rest of
4509 * the map's lifetime from that point onwards.
4510 * 3) Any parallel/pending map update/delete operations from syscall
4511 * side have been completed. Only after that point, it's safe to
4512 * assume that map value(s) are immutable.
4514 return (map->map_flags & BPF_F_RDONLY_PROG) &&
4515 READ_ONCE(map->frozen) &&
4516 !bpf_map_write_active(map);
4519 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4525 err = map->ops->map_direct_value_addr(map, &addr, off);
4528 ptr = (void *)(long)addr + off;
4532 *val = (u64)*(u8 *)ptr;
4535 *val = (u64)*(u16 *)ptr;
4538 *val = (u64)*(u32 *)ptr;
4549 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4550 struct bpf_reg_state *regs,
4551 int regno, int off, int size,
4552 enum bpf_access_type atype,
4555 struct bpf_reg_state *reg = regs + regno;
4556 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4557 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4558 enum bpf_type_flag flag = 0;
4564 "R%d is ptr_%s invalid negative access: off=%d\n",
4568 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4571 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4573 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4574 regno, tname, off, tn_buf);
4578 if (reg->type & MEM_USER) {
4580 "R%d is ptr_%s access user memory: off=%d\n",
4585 if (reg->type & MEM_PERCPU) {
4587 "R%d is ptr_%s access percpu memory: off=%d\n",
4592 if (env->ops->btf_struct_access) {
4593 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4594 off, size, atype, &btf_id, &flag);
4596 if (atype != BPF_READ) {
4597 verbose(env, "only read is supported\n");
4601 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4602 atype, &btf_id, &flag);
4608 /* If this is an untrusted pointer, all pointers formed by walking it
4609 * also inherit the untrusted flag.
4611 if (type_flag(reg->type) & PTR_UNTRUSTED)
4612 flag |= PTR_UNTRUSTED;
4614 if (atype == BPF_READ && value_regno >= 0)
4615 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4620 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4621 struct bpf_reg_state *regs,
4622 int regno, int off, int size,
4623 enum bpf_access_type atype,
4626 struct bpf_reg_state *reg = regs + regno;
4627 struct bpf_map *map = reg->map_ptr;
4628 enum bpf_type_flag flag = 0;
4629 const struct btf_type *t;
4635 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4639 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4640 verbose(env, "map_ptr access not supported for map type %d\n",
4645 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4646 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4648 if (!env->allow_ptr_to_map_access) {
4650 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4656 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4661 if (atype != BPF_READ) {
4662 verbose(env, "only read from %s is supported\n", tname);
4666 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4670 if (value_regno >= 0)
4671 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4676 /* Check that the stack access at the given offset is within bounds. The
4677 * maximum valid offset is -1.
4679 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4680 * -state->allocated_stack for reads.
4682 static int check_stack_slot_within_bounds(int off,
4683 struct bpf_func_state *state,
4684 enum bpf_access_type t)
4689 min_valid_off = -MAX_BPF_STACK;
4691 min_valid_off = -state->allocated_stack;
4693 if (off < min_valid_off || off > -1)
4698 /* Check that the stack access at 'regno + off' falls within the maximum stack
4701 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4703 static int check_stack_access_within_bounds(
4704 struct bpf_verifier_env *env,
4705 int regno, int off, int access_size,
4706 enum bpf_access_src src, enum bpf_access_type type)
4708 struct bpf_reg_state *regs = cur_regs(env);
4709 struct bpf_reg_state *reg = regs + regno;
4710 struct bpf_func_state *state = func(env, reg);
4711 int min_off, max_off;
4715 if (src == ACCESS_HELPER)
4716 /* We don't know if helpers are reading or writing (or both). */
4717 err_extra = " indirect access to";
4718 else if (type == BPF_READ)
4719 err_extra = " read from";
4721 err_extra = " write to";
4723 if (tnum_is_const(reg->var_off)) {
4724 min_off = reg->var_off.value + off;
4725 if (access_size > 0)
4726 max_off = min_off + access_size - 1;
4730 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4731 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4732 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4736 min_off = reg->smin_value + off;
4737 if (access_size > 0)
4738 max_off = reg->smax_value + off + access_size - 1;
4743 err = check_stack_slot_within_bounds(min_off, state, type);
4745 err = check_stack_slot_within_bounds(max_off, state, type);
4748 if (tnum_is_const(reg->var_off)) {
4749 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4750 err_extra, regno, off, access_size);
4754 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4755 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4756 err_extra, regno, tn_buf, access_size);
4762 /* check whether memory at (regno + off) is accessible for t = (read | write)
4763 * if t==write, value_regno is a register which value is stored into memory
4764 * if t==read, value_regno is a register which will receive the value from memory
4765 * if t==write && value_regno==-1, some unknown value is stored into memory
4766 * if t==read && value_regno==-1, don't care what we read from memory
4768 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4769 int off, int bpf_size, enum bpf_access_type t,
4770 int value_regno, bool strict_alignment_once)
4772 struct bpf_reg_state *regs = cur_regs(env);
4773 struct bpf_reg_state *reg = regs + regno;
4774 struct bpf_func_state *state;
4777 size = bpf_size_to_bytes(bpf_size);
4781 /* alignment checks will add in reg->off themselves */
4782 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4786 /* for access checks, reg->off is just part of off */
4789 if (reg->type == PTR_TO_MAP_KEY) {
4790 if (t == BPF_WRITE) {
4791 verbose(env, "write to change key R%d not allowed\n", regno);
4795 err = check_mem_region_access(env, regno, off, size,
4796 reg->map_ptr->key_size, false);
4799 if (value_regno >= 0)
4800 mark_reg_unknown(env, regs, value_regno);
4801 } else if (reg->type == PTR_TO_MAP_VALUE) {
4802 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4804 if (t == BPF_WRITE && value_regno >= 0 &&
4805 is_pointer_value(env, value_regno)) {
4806 verbose(env, "R%d leaks addr into map\n", value_regno);
4809 err = check_map_access_type(env, regno, off, size, t);
4812 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4815 if (tnum_is_const(reg->var_off))
4816 kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4817 off + reg->var_off.value);
4818 if (kptr_off_desc) {
4819 err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4821 } else if (t == BPF_READ && value_regno >= 0) {
4822 struct bpf_map *map = reg->map_ptr;
4824 /* if map is read-only, track its contents as scalars */
4825 if (tnum_is_const(reg->var_off) &&
4826 bpf_map_is_rdonly(map) &&
4827 map->ops->map_direct_value_addr) {
4828 int map_off = off + reg->var_off.value;
4831 err = bpf_map_direct_read(map, map_off, size,
4836 regs[value_regno].type = SCALAR_VALUE;
4837 __mark_reg_known(®s[value_regno], val);
4839 mark_reg_unknown(env, regs, value_regno);
4842 } else if (base_type(reg->type) == PTR_TO_MEM) {
4843 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4845 if (type_may_be_null(reg->type)) {
4846 verbose(env, "R%d invalid mem access '%s'\n", regno,
4847 reg_type_str(env, reg->type));
4851 if (t == BPF_WRITE && rdonly_mem) {
4852 verbose(env, "R%d cannot write into %s\n",
4853 regno, reg_type_str(env, reg->type));
4857 if (t == BPF_WRITE && value_regno >= 0 &&
4858 is_pointer_value(env, value_regno)) {
4859 verbose(env, "R%d leaks addr into mem\n", value_regno);
4863 err = check_mem_region_access(env, regno, off, size,
4864 reg->mem_size, false);
4865 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4866 mark_reg_unknown(env, regs, value_regno);
4867 } else if (reg->type == PTR_TO_CTX) {
4868 enum bpf_reg_type reg_type = SCALAR_VALUE;
4869 struct btf *btf = NULL;
4872 if (t == BPF_WRITE && value_regno >= 0 &&
4873 is_pointer_value(env, value_regno)) {
4874 verbose(env, "R%d leaks addr into ctx\n", value_regno);
4878 err = check_ptr_off_reg(env, reg, regno);
4882 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
4885 verbose_linfo(env, insn_idx, "; ");
4886 if (!err && t == BPF_READ && value_regno >= 0) {
4887 /* ctx access returns either a scalar, or a
4888 * PTR_TO_PACKET[_META,_END]. In the latter
4889 * case, we know the offset is zero.
4891 if (reg_type == SCALAR_VALUE) {
4892 mark_reg_unknown(env, regs, value_regno);
4894 mark_reg_known_zero(env, regs,
4896 if (type_may_be_null(reg_type))
4897 regs[value_regno].id = ++env->id_gen;
4898 /* A load of ctx field could have different
4899 * actual load size with the one encoded in the
4900 * insn. When the dst is PTR, it is for sure not
4903 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4904 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4905 regs[value_regno].btf = btf;
4906 regs[value_regno].btf_id = btf_id;
4909 regs[value_regno].type = reg_type;
4912 } else if (reg->type == PTR_TO_STACK) {
4913 /* Basic bounds checks. */
4914 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4918 state = func(env, reg);
4919 err = update_stack_depth(env, state, off);
4924 err = check_stack_read(env, regno, off, size,
4927 err = check_stack_write(env, regno, off, size,
4928 value_regno, insn_idx);
4929 } else if (reg_is_pkt_pointer(reg)) {
4930 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4931 verbose(env, "cannot write into packet\n");
4934 if (t == BPF_WRITE && value_regno >= 0 &&
4935 is_pointer_value(env, value_regno)) {
4936 verbose(env, "R%d leaks addr into packet\n",
4940 err = check_packet_access(env, regno, off, size, false);
4941 if (!err && t == BPF_READ && value_regno >= 0)
4942 mark_reg_unknown(env, regs, value_regno);
4943 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4944 if (t == BPF_WRITE && value_regno >= 0 &&
4945 is_pointer_value(env, value_regno)) {
4946 verbose(env, "R%d leaks addr into flow keys\n",
4951 err = check_flow_keys_access(env, off, size);
4952 if (!err && t == BPF_READ && value_regno >= 0)
4953 mark_reg_unknown(env, regs, value_regno);
4954 } else if (type_is_sk_pointer(reg->type)) {
4955 if (t == BPF_WRITE) {
4956 verbose(env, "R%d cannot write into %s\n",
4957 regno, reg_type_str(env, reg->type));
4960 err = check_sock_access(env, insn_idx, regno, off, size, t);
4961 if (!err && value_regno >= 0)
4962 mark_reg_unknown(env, regs, value_regno);
4963 } else if (reg->type == PTR_TO_TP_BUFFER) {
4964 err = check_tp_buffer_access(env, reg, regno, off, size);
4965 if (!err && t == BPF_READ && value_regno >= 0)
4966 mark_reg_unknown(env, regs, value_regno);
4967 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4968 !type_may_be_null(reg->type)) {
4969 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4971 } else if (reg->type == CONST_PTR_TO_MAP) {
4972 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4974 } else if (base_type(reg->type) == PTR_TO_BUF) {
4975 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4979 if (t == BPF_WRITE) {
4980 verbose(env, "R%d cannot write into %s\n",
4981 regno, reg_type_str(env, reg->type));
4984 max_access = &env->prog->aux->max_rdonly_access;
4986 max_access = &env->prog->aux->max_rdwr_access;
4989 err = check_buffer_access(env, reg, regno, off, size, false,
4992 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4993 mark_reg_unknown(env, regs, value_regno);
4995 verbose(env, "R%d invalid mem access '%s'\n", regno,
4996 reg_type_str(env, reg->type));
5000 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5001 regs[value_regno].type == SCALAR_VALUE) {
5002 /* b/h/w load zero-extends, mark upper bits as known 0 */
5003 coerce_reg_to_size(®s[value_regno], size);
5008 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5013 switch (insn->imm) {
5015 case BPF_ADD | BPF_FETCH:
5017 case BPF_AND | BPF_FETCH:
5019 case BPF_OR | BPF_FETCH:
5021 case BPF_XOR | BPF_FETCH:
5026 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5030 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5031 verbose(env, "invalid atomic operand size\n");
5035 /* check src1 operand */
5036 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5040 /* check src2 operand */
5041 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5045 if (insn->imm == BPF_CMPXCHG) {
5046 /* Check comparison of R0 with memory location */
5047 const u32 aux_reg = BPF_REG_0;
5049 err = check_reg_arg(env, aux_reg, SRC_OP);
5053 if (is_pointer_value(env, aux_reg)) {
5054 verbose(env, "R%d leaks addr into mem\n", aux_reg);
5059 if (is_pointer_value(env, insn->src_reg)) {
5060 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5064 if (is_ctx_reg(env, insn->dst_reg) ||
5065 is_pkt_reg(env, insn->dst_reg) ||
5066 is_flow_key_reg(env, insn->dst_reg) ||
5067 is_sk_reg(env, insn->dst_reg)) {
5068 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5070 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5074 if (insn->imm & BPF_FETCH) {
5075 if (insn->imm == BPF_CMPXCHG)
5076 load_reg = BPF_REG_0;
5078 load_reg = insn->src_reg;
5080 /* check and record load of old value */
5081 err = check_reg_arg(env, load_reg, DST_OP);
5085 /* This instruction accesses a memory location but doesn't
5086 * actually load it into a register.
5091 /* Check whether we can read the memory, with second call for fetch
5092 * case to simulate the register fill.
5094 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5095 BPF_SIZE(insn->code), BPF_READ, -1, true);
5096 if (!err && load_reg >= 0)
5097 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5098 BPF_SIZE(insn->code), BPF_READ, load_reg,
5103 /* Check whether we can write into the same memory. */
5104 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5105 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5112 /* When register 'regno' is used to read the stack (either directly or through
5113 * a helper function) make sure that it's within stack boundary and, depending
5114 * on the access type, that all elements of the stack are initialized.
5116 * 'off' includes 'regno->off', but not its dynamic part (if any).
5118 * All registers that have been spilled on the stack in the slots within the
5119 * read offsets are marked as read.
5121 static int check_stack_range_initialized(
5122 struct bpf_verifier_env *env, int regno, int off,
5123 int access_size, bool zero_size_allowed,
5124 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5126 struct bpf_reg_state *reg = reg_state(env, regno);
5127 struct bpf_func_state *state = func(env, reg);
5128 int err, min_off, max_off, i, j, slot, spi;
5129 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5130 enum bpf_access_type bounds_check_type;
5131 /* Some accesses can write anything into the stack, others are
5134 bool clobber = false;
5136 if (access_size == 0 && !zero_size_allowed) {
5137 verbose(env, "invalid zero-sized read\n");
5141 if (type == ACCESS_HELPER) {
5142 /* The bounds checks for writes are more permissive than for
5143 * reads. However, if raw_mode is not set, we'll do extra
5146 bounds_check_type = BPF_WRITE;
5149 bounds_check_type = BPF_READ;
5151 err = check_stack_access_within_bounds(env, regno, off, access_size,
5152 type, bounds_check_type);
5157 if (tnum_is_const(reg->var_off)) {
5158 min_off = max_off = reg->var_off.value + off;
5160 /* Variable offset is prohibited for unprivileged mode for
5161 * simplicity since it requires corresponding support in
5162 * Spectre masking for stack ALU.
5163 * See also retrieve_ptr_limit().
5165 if (!env->bypass_spec_v1) {
5168 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5169 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5170 regno, err_extra, tn_buf);
5173 /* Only initialized buffer on stack is allowed to be accessed
5174 * with variable offset. With uninitialized buffer it's hard to
5175 * guarantee that whole memory is marked as initialized on
5176 * helper return since specific bounds are unknown what may
5177 * cause uninitialized stack leaking.
5179 if (meta && meta->raw_mode)
5182 min_off = reg->smin_value + off;
5183 max_off = reg->smax_value + off;
5186 if (meta && meta->raw_mode) {
5187 meta->access_size = access_size;
5188 meta->regno = regno;
5192 for (i = min_off; i < max_off + access_size; i++) {
5196 spi = slot / BPF_REG_SIZE;
5197 if (state->allocated_stack <= slot)
5199 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5200 if (*stype == STACK_MISC)
5202 if (*stype == STACK_ZERO) {
5204 /* helper can write anything into the stack */
5205 *stype = STACK_MISC;
5210 if (is_spilled_reg(&state->stack[spi]) &&
5211 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5212 env->allow_ptr_leaks)) {
5214 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5215 for (j = 0; j < BPF_REG_SIZE; j++)
5216 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5222 if (tnum_is_const(reg->var_off)) {
5223 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5224 err_extra, regno, min_off, i - min_off, access_size);
5228 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5229 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5230 err_extra, regno, tn_buf, i - min_off, access_size);
5234 /* reading any byte out of 8-byte 'spill_slot' will cause
5235 * the whole slot to be marked as 'read'
5237 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5238 state->stack[spi].spilled_ptr.parent,
5240 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5241 * be sure that whether stack slot is written to or not. Hence,
5242 * we must still conservatively propagate reads upwards even if
5243 * helper may write to the entire memory range.
5246 return update_stack_depth(env, state, min_off);
5249 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5250 int access_size, bool zero_size_allowed,
5251 struct bpf_call_arg_meta *meta)
5253 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5256 switch (base_type(reg->type)) {
5258 case PTR_TO_PACKET_META:
5259 return check_packet_access(env, regno, reg->off, access_size,
5261 case PTR_TO_MAP_KEY:
5262 if (meta && meta->raw_mode) {
5263 verbose(env, "R%d cannot write into %s\n", regno,
5264 reg_type_str(env, reg->type));
5267 return check_mem_region_access(env, regno, reg->off, access_size,
5268 reg->map_ptr->key_size, false);
5269 case PTR_TO_MAP_VALUE:
5270 if (check_map_access_type(env, regno, reg->off, access_size,
5271 meta && meta->raw_mode ? BPF_WRITE :
5274 return check_map_access(env, regno, reg->off, access_size,
5275 zero_size_allowed, ACCESS_HELPER);
5277 if (type_is_rdonly_mem(reg->type)) {
5278 if (meta && meta->raw_mode) {
5279 verbose(env, "R%d cannot write into %s\n", regno,
5280 reg_type_str(env, reg->type));
5284 return check_mem_region_access(env, regno, reg->off,
5285 access_size, reg->mem_size,
5288 if (type_is_rdonly_mem(reg->type)) {
5289 if (meta && meta->raw_mode) {
5290 verbose(env, "R%d cannot write into %s\n", regno,
5291 reg_type_str(env, reg->type));
5295 max_access = &env->prog->aux->max_rdonly_access;
5297 max_access = &env->prog->aux->max_rdwr_access;
5299 return check_buffer_access(env, reg, regno, reg->off,
5300 access_size, zero_size_allowed,
5303 return check_stack_range_initialized(
5305 regno, reg->off, access_size,
5306 zero_size_allowed, ACCESS_HELPER, meta);
5308 /* in case the function doesn't know how to access the context,
5309 * (because we are in a program of type SYSCALL for example), we
5310 * can not statically check its size.
5311 * Dynamically check it now.
5313 if (!env->ops->convert_ctx_access) {
5314 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5315 int offset = access_size - 1;
5317 /* Allow zero-byte read from PTR_TO_CTX */
5318 if (access_size == 0)
5319 return zero_size_allowed ? 0 : -EACCES;
5321 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5326 default: /* scalar_value or invalid ptr */
5327 /* Allow zero-byte read from NULL, regardless of pointer type */
5328 if (zero_size_allowed && access_size == 0 &&
5329 register_is_null(reg))
5332 verbose(env, "R%d type=%s ", regno,
5333 reg_type_str(env, reg->type));
5334 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5339 static int check_mem_size_reg(struct bpf_verifier_env *env,
5340 struct bpf_reg_state *reg, u32 regno,
5341 bool zero_size_allowed,
5342 struct bpf_call_arg_meta *meta)
5346 /* This is used to refine r0 return value bounds for helpers
5347 * that enforce this value as an upper bound on return values.
5348 * See do_refine_retval_range() for helpers that can refine
5349 * the return value. C type of helper is u32 so we pull register
5350 * bound from umax_value however, if negative verifier errors
5351 * out. Only upper bounds can be learned because retval is an
5352 * int type and negative retvals are allowed.
5354 meta->msize_max_value = reg->umax_value;
5356 /* The register is SCALAR_VALUE; the access check
5357 * happens using its boundaries.
5359 if (!tnum_is_const(reg->var_off))
5360 /* For unprivileged variable accesses, disable raw
5361 * mode so that the program is required to
5362 * initialize all the memory that the helper could
5363 * just partially fill up.
5367 if (reg->smin_value < 0) {
5368 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5373 if (reg->umin_value == 0) {
5374 err = check_helper_mem_access(env, regno - 1, 0,
5381 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5382 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5386 err = check_helper_mem_access(env, regno - 1,
5388 zero_size_allowed, meta);
5390 err = mark_chain_precision(env, regno);
5394 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5395 u32 regno, u32 mem_size)
5397 bool may_be_null = type_may_be_null(reg->type);
5398 struct bpf_reg_state saved_reg;
5399 struct bpf_call_arg_meta meta;
5402 if (register_is_null(reg))
5405 memset(&meta, 0, sizeof(meta));
5406 /* Assuming that the register contains a value check if the memory
5407 * access is safe. Temporarily save and restore the register's state as
5408 * the conversion shouldn't be visible to a caller.
5412 mark_ptr_not_null_reg(reg);
5415 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5416 /* Check access for BPF_WRITE */
5417 meta.raw_mode = true;
5418 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5426 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5429 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5430 bool may_be_null = type_may_be_null(mem_reg->type);
5431 struct bpf_reg_state saved_reg;
5432 struct bpf_call_arg_meta meta;
5435 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5437 memset(&meta, 0, sizeof(meta));
5440 saved_reg = *mem_reg;
5441 mark_ptr_not_null_reg(mem_reg);
5444 err = check_mem_size_reg(env, reg, regno, true, &meta);
5445 /* Check access for BPF_WRITE */
5446 meta.raw_mode = true;
5447 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5450 *mem_reg = saved_reg;
5454 /* Implementation details:
5455 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5456 * Two bpf_map_lookups (even with the same key) will have different reg->id.
5457 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5458 * value_or_null->value transition, since the verifier only cares about
5459 * the range of access to valid map value pointer and doesn't care about actual
5460 * address of the map element.
5461 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5462 * reg->id > 0 after value_or_null->value transition. By doing so
5463 * two bpf_map_lookups will be considered two different pointers that
5464 * point to different bpf_spin_locks.
5465 * The verifier allows taking only one bpf_spin_lock at a time to avoid
5467 * Since only one bpf_spin_lock is allowed the checks are simpler than
5468 * reg_is_refcounted() logic. The verifier needs to remember only
5469 * one spin_lock instead of array of acquired_refs.
5470 * cur_state->active_spin_lock remembers which map value element got locked
5471 * and clears it after bpf_spin_unlock.
5473 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5476 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5477 struct bpf_verifier_state *cur = env->cur_state;
5478 bool is_const = tnum_is_const(reg->var_off);
5479 struct bpf_map *map = reg->map_ptr;
5480 u64 val = reg->var_off.value;
5484 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5490 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5494 if (!map_value_has_spin_lock(map)) {
5495 if (map->spin_lock_off == -E2BIG)
5497 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5499 else if (map->spin_lock_off == -ENOENT)
5501 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5505 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5509 if (map->spin_lock_off != val + reg->off) {
5510 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5515 if (cur->active_spin_lock) {
5517 "Locking two bpf_spin_locks are not allowed\n");
5520 cur->active_spin_lock = reg->id;
5522 if (!cur->active_spin_lock) {
5523 verbose(env, "bpf_spin_unlock without taking a lock\n");
5526 if (cur->active_spin_lock != reg->id) {
5527 verbose(env, "bpf_spin_unlock of different lock\n");
5530 cur->active_spin_lock = 0;
5535 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5536 struct bpf_call_arg_meta *meta)
5538 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5539 bool is_const = tnum_is_const(reg->var_off);
5540 struct bpf_map *map = reg->map_ptr;
5541 u64 val = reg->var_off.value;
5545 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5550 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5554 if (!map_value_has_timer(map)) {
5555 if (map->timer_off == -E2BIG)
5557 "map '%s' has more than one 'struct bpf_timer'\n",
5559 else if (map->timer_off == -ENOENT)
5561 "map '%s' doesn't have 'struct bpf_timer'\n",
5565 "map '%s' is not a struct type or bpf_timer is mangled\n",
5569 if (map->timer_off != val + reg->off) {
5570 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5571 val + reg->off, map->timer_off);
5574 if (meta->map_ptr) {
5575 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5578 meta->map_uid = reg->map_uid;
5579 meta->map_ptr = map;
5583 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5584 struct bpf_call_arg_meta *meta)
5586 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5587 struct bpf_map_value_off_desc *off_desc;
5588 struct bpf_map *map_ptr = reg->map_ptr;
5592 if (!tnum_is_const(reg->var_off)) {
5594 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5598 if (!map_ptr->btf) {
5599 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5603 if (!map_value_has_kptrs(map_ptr)) {
5604 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5606 verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5607 BPF_MAP_VALUE_OFF_MAX);
5608 else if (ret == -EEXIST)
5609 verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5611 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5615 meta->map_ptr = map_ptr;
5616 kptr_off = reg->off + reg->var_off.value;
5617 off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5619 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5622 if (off_desc->type != BPF_KPTR_REF) {
5623 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5626 meta->kptr_off_desc = off_desc;
5630 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5632 return type == ARG_CONST_SIZE ||
5633 type == ARG_CONST_SIZE_OR_ZERO;
5636 static bool arg_type_is_release(enum bpf_arg_type type)
5638 return type & OBJ_RELEASE;
5641 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5643 return base_type(type) == ARG_PTR_TO_DYNPTR;
5646 static int int_ptr_type_to_size(enum bpf_arg_type type)
5648 if (type == ARG_PTR_TO_INT)
5650 else if (type == ARG_PTR_TO_LONG)
5656 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5657 const struct bpf_call_arg_meta *meta,
5658 enum bpf_arg_type *arg_type)
5660 if (!meta->map_ptr) {
5661 /* kernel subsystem misconfigured verifier */
5662 verbose(env, "invalid map_ptr to access map->type\n");
5666 switch (meta->map_ptr->map_type) {
5667 case BPF_MAP_TYPE_SOCKMAP:
5668 case BPF_MAP_TYPE_SOCKHASH:
5669 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5670 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5672 verbose(env, "invalid arg_type for sockmap/sockhash\n");
5676 case BPF_MAP_TYPE_BLOOM_FILTER:
5677 if (meta->func_id == BPF_FUNC_map_peek_elem)
5678 *arg_type = ARG_PTR_TO_MAP_VALUE;
5686 struct bpf_reg_types {
5687 const enum bpf_reg_type types[10];
5691 static const struct bpf_reg_types map_key_value_types = {
5701 static const struct bpf_reg_types sock_types = {
5711 static const struct bpf_reg_types btf_id_sock_common_types = {
5719 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5723 static const struct bpf_reg_types mem_types = {
5731 PTR_TO_MEM | MEM_ALLOC,
5736 static const struct bpf_reg_types int_ptr_types = {
5746 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5747 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5748 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5749 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5750 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5751 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5752 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5753 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5754 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5755 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5756 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5757 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5758 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5759 static const struct bpf_reg_types dynptr_types = {
5762 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5766 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5767 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
5768 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
5769 [ARG_CONST_SIZE] = &scalar_types,
5770 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
5771 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
5772 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
5773 [ARG_PTR_TO_CTX] = &context_types,
5774 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
5776 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5778 [ARG_PTR_TO_SOCKET] = &fullsock_types,
5779 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
5780 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
5781 [ARG_PTR_TO_MEM] = &mem_types,
5782 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
5783 [ARG_PTR_TO_INT] = &int_ptr_types,
5784 [ARG_PTR_TO_LONG] = &int_ptr_types,
5785 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
5786 [ARG_PTR_TO_FUNC] = &func_ptr_types,
5787 [ARG_PTR_TO_STACK] = &stack_ptr_types,
5788 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
5789 [ARG_PTR_TO_TIMER] = &timer_types,
5790 [ARG_PTR_TO_KPTR] = &kptr_types,
5791 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
5794 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5795 enum bpf_arg_type arg_type,
5796 const u32 *arg_btf_id,
5797 struct bpf_call_arg_meta *meta)
5799 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5800 enum bpf_reg_type expected, type = reg->type;
5801 const struct bpf_reg_types *compatible;
5804 compatible = compatible_reg_types[base_type(arg_type)];
5806 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5810 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5811 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5813 * Same for MAYBE_NULL:
5815 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5816 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5818 * Therefore we fold these flags depending on the arg_type before comparison.
5820 if (arg_type & MEM_RDONLY)
5821 type &= ~MEM_RDONLY;
5822 if (arg_type & PTR_MAYBE_NULL)
5823 type &= ~PTR_MAYBE_NULL;
5825 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5826 expected = compatible->types[i];
5827 if (expected == NOT_INIT)
5830 if (type == expected)
5834 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5835 for (j = 0; j + 1 < i; j++)
5836 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5837 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5841 if (reg->type == PTR_TO_BTF_ID) {
5842 /* For bpf_sk_release, it needs to match against first member
5843 * 'struct sock_common', hence make an exception for it. This
5844 * allows bpf_sk_release to work for multiple socket types.
5846 bool strict_type_match = arg_type_is_release(arg_type) &&
5847 meta->func_id != BPF_FUNC_sk_release;
5850 if (!compatible->btf_id) {
5851 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5854 arg_btf_id = compatible->btf_id;
5857 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5858 if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5861 if (arg_btf_id == BPF_PTR_POISON) {
5862 verbose(env, "verifier internal error:");
5863 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5868 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5869 btf_vmlinux, *arg_btf_id,
5870 strict_type_match)) {
5871 verbose(env, "R%d is of type %s but %s is expected\n",
5872 regno, kernel_type_name(reg->btf, reg->btf_id),
5873 kernel_type_name(btf_vmlinux, *arg_btf_id));
5882 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5883 const struct bpf_reg_state *reg, int regno,
5884 enum bpf_arg_type arg_type)
5886 enum bpf_reg_type type = reg->type;
5887 bool fixed_off_ok = false;
5889 switch ((u32)type) {
5890 /* Pointer types where reg offset is explicitly allowed: */
5892 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5893 verbose(env, "cannot pass in dynptr at an offset\n");
5898 case PTR_TO_PACKET_META:
5899 case PTR_TO_MAP_KEY:
5900 case PTR_TO_MAP_VALUE:
5902 case PTR_TO_MEM | MEM_RDONLY:
5903 case PTR_TO_MEM | MEM_ALLOC:
5905 case PTR_TO_BUF | MEM_RDONLY:
5907 /* Some of the argument types nevertheless require a
5908 * zero register offset.
5910 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5913 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5917 /* When referenced PTR_TO_BTF_ID is passed to release function,
5918 * it's fixed offset must be 0. In the other cases, fixed offset
5921 if (arg_type_is_release(arg_type) && reg->off) {
5922 verbose(env, "R%d must have zero offset when passed to release func\n",
5926 /* For arg is release pointer, fixed_off_ok must be false, but
5927 * we already checked and rejected reg->off != 0 above, so set
5928 * to true to allow fixed offset for all other cases.
5930 fixed_off_ok = true;
5935 return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5938 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5940 struct bpf_func_state *state = func(env, reg);
5941 int spi = get_spi(reg->off);
5943 return state->stack[spi].spilled_ptr.id;
5946 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5947 struct bpf_call_arg_meta *meta,
5948 const struct bpf_func_proto *fn)
5950 u32 regno = BPF_REG_1 + arg;
5951 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5952 enum bpf_arg_type arg_type = fn->arg_type[arg];
5953 enum bpf_reg_type type = reg->type;
5954 u32 *arg_btf_id = NULL;
5957 if (arg_type == ARG_DONTCARE)
5960 err = check_reg_arg(env, regno, SRC_OP);
5964 if (arg_type == ARG_ANYTHING) {
5965 if (is_pointer_value(env, regno)) {
5966 verbose(env, "R%d leaks addr into helper function\n",
5973 if (type_is_pkt_pointer(type) &&
5974 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5975 verbose(env, "helper access to the packet is not allowed\n");
5979 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5980 err = resolve_map_arg_type(env, meta, &arg_type);
5985 if (register_is_null(reg) && type_may_be_null(arg_type))
5986 /* A NULL register has a SCALAR_VALUE type, so skip
5989 goto skip_type_check;
5991 /* arg_btf_id and arg_size are in a union. */
5992 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5993 arg_btf_id = fn->arg_btf_id[arg];
5995 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5999 err = check_func_arg_reg_off(env, reg, regno, arg_type);
6004 if (arg_type_is_release(arg_type)) {
6005 if (arg_type_is_dynptr(arg_type)) {
6006 struct bpf_func_state *state = func(env, reg);
6007 int spi = get_spi(reg->off);
6009 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6010 !state->stack[spi].spilled_ptr.id) {
6011 verbose(env, "arg %d is an unacquired reference\n", regno);
6014 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
6015 verbose(env, "R%d must be referenced when passed to release function\n",
6019 if (meta->release_regno) {
6020 verbose(env, "verifier internal error: more than one release argument\n");
6023 meta->release_regno = regno;
6026 if (reg->ref_obj_id) {
6027 if (meta->ref_obj_id) {
6028 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6029 regno, reg->ref_obj_id,
6033 meta->ref_obj_id = reg->ref_obj_id;
6036 switch (base_type(arg_type)) {
6037 case ARG_CONST_MAP_PTR:
6038 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6039 if (meta->map_ptr) {
6040 /* Use map_uid (which is unique id of inner map) to reject:
6041 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6042 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6043 * if (inner_map1 && inner_map2) {
6044 * timer = bpf_map_lookup_elem(inner_map1);
6046 * // mismatch would have been allowed
6047 * bpf_timer_init(timer, inner_map2);
6050 * Comparing map_ptr is enough to distinguish normal and outer maps.
6052 if (meta->map_ptr != reg->map_ptr ||
6053 meta->map_uid != reg->map_uid) {
6055 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6056 meta->map_uid, reg->map_uid);
6060 meta->map_ptr = reg->map_ptr;
6061 meta->map_uid = reg->map_uid;
6063 case ARG_PTR_TO_MAP_KEY:
6064 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6065 * check that [key, key + map->key_size) are within
6066 * stack limits and initialized
6068 if (!meta->map_ptr) {
6069 /* in function declaration map_ptr must come before
6070 * map_key, so that it's verified and known before
6071 * we have to check map_key here. Otherwise it means
6072 * that kernel subsystem misconfigured verifier
6074 verbose(env, "invalid map_ptr to access map->key\n");
6077 err = check_helper_mem_access(env, regno,
6078 meta->map_ptr->key_size, false,
6081 case ARG_PTR_TO_MAP_VALUE:
6082 if (type_may_be_null(arg_type) && register_is_null(reg))
6085 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6086 * check [value, value + map->value_size) validity
6088 if (!meta->map_ptr) {
6089 /* kernel subsystem misconfigured verifier */
6090 verbose(env, "invalid map_ptr to access map->value\n");
6093 meta->raw_mode = arg_type & MEM_UNINIT;
6094 err = check_helper_mem_access(env, regno,
6095 meta->map_ptr->value_size, false,
6098 case ARG_PTR_TO_PERCPU_BTF_ID:
6100 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6103 meta->ret_btf = reg->btf;
6104 meta->ret_btf_id = reg->btf_id;
6106 case ARG_PTR_TO_SPIN_LOCK:
6107 if (meta->func_id == BPF_FUNC_spin_lock) {
6108 if (process_spin_lock(env, regno, true))
6110 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6111 if (process_spin_lock(env, regno, false))
6114 verbose(env, "verifier internal error\n");
6118 case ARG_PTR_TO_TIMER:
6119 if (process_timer_func(env, regno, meta))
6122 case ARG_PTR_TO_FUNC:
6123 meta->subprogno = reg->subprogno;
6125 case ARG_PTR_TO_MEM:
6126 /* The access to this pointer is only checked when we hit the
6127 * next is_mem_size argument below.
6129 meta->raw_mode = arg_type & MEM_UNINIT;
6130 if (arg_type & MEM_FIXED_SIZE) {
6131 err = check_helper_mem_access(env, regno,
6132 fn->arg_size[arg], false,
6136 case ARG_CONST_SIZE:
6137 err = check_mem_size_reg(env, reg, regno, false, meta);
6139 case ARG_CONST_SIZE_OR_ZERO:
6140 err = check_mem_size_reg(env, reg, regno, true, meta);
6142 case ARG_PTR_TO_DYNPTR:
6143 /* We only need to check for initialized / uninitialized helper
6144 * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6145 * assumption is that if it is, that a helper function
6146 * initialized the dynptr on behalf of the BPF program.
6148 if (base_type(reg->type) == PTR_TO_DYNPTR)
6150 if (arg_type & MEM_UNINIT) {
6151 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6152 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6156 /* We only support one dynptr being uninitialized at the moment,
6157 * which is sufficient for the helper functions we have right now.
6159 if (meta->uninit_dynptr_regno) {
6160 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6164 meta->uninit_dynptr_regno = regno;
6165 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6167 "Expected an initialized dynptr as arg #%d\n",
6170 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6171 const char *err_extra = "";
6173 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6174 case DYNPTR_TYPE_LOCAL:
6175 err_extra = "local";
6177 case DYNPTR_TYPE_RINGBUF:
6178 err_extra = "ringbuf";
6181 err_extra = "<unknown>";
6185 "Expected a dynptr of type %s as arg #%d\n",
6186 err_extra, arg + 1);
6190 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6191 if (!tnum_is_const(reg->var_off)) {
6192 verbose(env, "R%d is not a known constant'\n",
6196 meta->mem_size = reg->var_off.value;
6197 err = mark_chain_precision(env, regno);
6201 case ARG_PTR_TO_INT:
6202 case ARG_PTR_TO_LONG:
6204 int size = int_ptr_type_to_size(arg_type);
6206 err = check_helper_mem_access(env, regno, size, false, meta);
6209 err = check_ptr_alignment(env, reg, 0, size, true);
6212 case ARG_PTR_TO_CONST_STR:
6214 struct bpf_map *map = reg->map_ptr;
6219 if (!bpf_map_is_rdonly(map)) {
6220 verbose(env, "R%d does not point to a readonly map'\n", regno);
6224 if (!tnum_is_const(reg->var_off)) {
6225 verbose(env, "R%d is not a constant address'\n", regno);
6229 if (!map->ops->map_direct_value_addr) {
6230 verbose(env, "no direct value access support for this map type\n");
6234 err = check_map_access(env, regno, reg->off,
6235 map->value_size - reg->off, false,
6240 map_off = reg->off + reg->var_off.value;
6241 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6243 verbose(env, "direct value access on string failed\n");
6247 str_ptr = (char *)(long)(map_addr);
6248 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6249 verbose(env, "string is not zero-terminated\n");
6254 case ARG_PTR_TO_KPTR:
6255 if (process_kptr_func(env, regno, meta))
6263 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6265 enum bpf_attach_type eatype = env->prog->expected_attach_type;
6266 enum bpf_prog_type type = resolve_prog_type(env->prog);
6268 if (func_id != BPF_FUNC_map_update_elem)
6271 /* It's not possible to get access to a locked struct sock in these
6272 * contexts, so updating is safe.
6275 case BPF_PROG_TYPE_TRACING:
6276 if (eatype == BPF_TRACE_ITER)
6279 case BPF_PROG_TYPE_SOCKET_FILTER:
6280 case BPF_PROG_TYPE_SCHED_CLS:
6281 case BPF_PROG_TYPE_SCHED_ACT:
6282 case BPF_PROG_TYPE_XDP:
6283 case BPF_PROG_TYPE_SK_REUSEPORT:
6284 case BPF_PROG_TYPE_FLOW_DISSECTOR:
6285 case BPF_PROG_TYPE_SK_LOOKUP:
6291 verbose(env, "cannot update sockmap in this context\n");
6295 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6297 return env->prog->jit_requested &&
6298 bpf_jit_supports_subprog_tailcalls();
6301 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6302 struct bpf_map *map, int func_id)
6307 /* We need a two way check, first is from map perspective ... */
6308 switch (map->map_type) {
6309 case BPF_MAP_TYPE_PROG_ARRAY:
6310 if (func_id != BPF_FUNC_tail_call)
6313 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6314 if (func_id != BPF_FUNC_perf_event_read &&
6315 func_id != BPF_FUNC_perf_event_output &&
6316 func_id != BPF_FUNC_skb_output &&
6317 func_id != BPF_FUNC_perf_event_read_value &&
6318 func_id != BPF_FUNC_xdp_output)
6321 case BPF_MAP_TYPE_RINGBUF:
6322 if (func_id != BPF_FUNC_ringbuf_output &&
6323 func_id != BPF_FUNC_ringbuf_reserve &&
6324 func_id != BPF_FUNC_ringbuf_query &&
6325 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6326 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6327 func_id != BPF_FUNC_ringbuf_discard_dynptr)
6330 case BPF_MAP_TYPE_USER_RINGBUF:
6331 if (func_id != BPF_FUNC_user_ringbuf_drain)
6334 case BPF_MAP_TYPE_STACK_TRACE:
6335 if (func_id != BPF_FUNC_get_stackid)
6338 case BPF_MAP_TYPE_CGROUP_ARRAY:
6339 if (func_id != BPF_FUNC_skb_under_cgroup &&
6340 func_id != BPF_FUNC_current_task_under_cgroup)
6343 case BPF_MAP_TYPE_CGROUP_STORAGE:
6344 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6345 if (func_id != BPF_FUNC_get_local_storage)
6348 case BPF_MAP_TYPE_DEVMAP:
6349 case BPF_MAP_TYPE_DEVMAP_HASH:
6350 if (func_id != BPF_FUNC_redirect_map &&
6351 func_id != BPF_FUNC_map_lookup_elem)
6354 /* Restrict bpf side of cpumap and xskmap, open when use-cases
6357 case BPF_MAP_TYPE_CPUMAP:
6358 if (func_id != BPF_FUNC_redirect_map)
6361 case BPF_MAP_TYPE_XSKMAP:
6362 if (func_id != BPF_FUNC_redirect_map &&
6363 func_id != BPF_FUNC_map_lookup_elem)
6366 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6367 case BPF_MAP_TYPE_HASH_OF_MAPS:
6368 if (func_id != BPF_FUNC_map_lookup_elem)
6371 case BPF_MAP_TYPE_SOCKMAP:
6372 if (func_id != BPF_FUNC_sk_redirect_map &&
6373 func_id != BPF_FUNC_sock_map_update &&
6374 func_id != BPF_FUNC_map_delete_elem &&
6375 func_id != BPF_FUNC_msg_redirect_map &&
6376 func_id != BPF_FUNC_sk_select_reuseport &&
6377 func_id != BPF_FUNC_map_lookup_elem &&
6378 !may_update_sockmap(env, func_id))
6381 case BPF_MAP_TYPE_SOCKHASH:
6382 if (func_id != BPF_FUNC_sk_redirect_hash &&
6383 func_id != BPF_FUNC_sock_hash_update &&
6384 func_id != BPF_FUNC_map_delete_elem &&
6385 func_id != BPF_FUNC_msg_redirect_hash &&
6386 func_id != BPF_FUNC_sk_select_reuseport &&
6387 func_id != BPF_FUNC_map_lookup_elem &&
6388 !may_update_sockmap(env, func_id))
6391 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6392 if (func_id != BPF_FUNC_sk_select_reuseport)
6395 case BPF_MAP_TYPE_QUEUE:
6396 case BPF_MAP_TYPE_STACK:
6397 if (func_id != BPF_FUNC_map_peek_elem &&
6398 func_id != BPF_FUNC_map_pop_elem &&
6399 func_id != BPF_FUNC_map_push_elem)
6402 case BPF_MAP_TYPE_SK_STORAGE:
6403 if (func_id != BPF_FUNC_sk_storage_get &&
6404 func_id != BPF_FUNC_sk_storage_delete)
6407 case BPF_MAP_TYPE_INODE_STORAGE:
6408 if (func_id != BPF_FUNC_inode_storage_get &&
6409 func_id != BPF_FUNC_inode_storage_delete)
6412 case BPF_MAP_TYPE_TASK_STORAGE:
6413 if (func_id != BPF_FUNC_task_storage_get &&
6414 func_id != BPF_FUNC_task_storage_delete)
6417 case BPF_MAP_TYPE_BLOOM_FILTER:
6418 if (func_id != BPF_FUNC_map_peek_elem &&
6419 func_id != BPF_FUNC_map_push_elem)
6426 /* ... and second from the function itself. */
6428 case BPF_FUNC_tail_call:
6429 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6431 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6432 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6436 case BPF_FUNC_perf_event_read:
6437 case BPF_FUNC_perf_event_output:
6438 case BPF_FUNC_perf_event_read_value:
6439 case BPF_FUNC_skb_output:
6440 case BPF_FUNC_xdp_output:
6441 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6444 case BPF_FUNC_ringbuf_output:
6445 case BPF_FUNC_ringbuf_reserve:
6446 case BPF_FUNC_ringbuf_query:
6447 case BPF_FUNC_ringbuf_reserve_dynptr:
6448 case BPF_FUNC_ringbuf_submit_dynptr:
6449 case BPF_FUNC_ringbuf_discard_dynptr:
6450 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6453 case BPF_FUNC_user_ringbuf_drain:
6454 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6457 case BPF_FUNC_get_stackid:
6458 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6461 case BPF_FUNC_current_task_under_cgroup:
6462 case BPF_FUNC_skb_under_cgroup:
6463 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6466 case BPF_FUNC_redirect_map:
6467 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6468 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6469 map->map_type != BPF_MAP_TYPE_CPUMAP &&
6470 map->map_type != BPF_MAP_TYPE_XSKMAP)
6473 case BPF_FUNC_sk_redirect_map:
6474 case BPF_FUNC_msg_redirect_map:
6475 case BPF_FUNC_sock_map_update:
6476 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6479 case BPF_FUNC_sk_redirect_hash:
6480 case BPF_FUNC_msg_redirect_hash:
6481 case BPF_FUNC_sock_hash_update:
6482 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6485 case BPF_FUNC_get_local_storage:
6486 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6487 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6490 case BPF_FUNC_sk_select_reuseport:
6491 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6492 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6493 map->map_type != BPF_MAP_TYPE_SOCKHASH)
6496 case BPF_FUNC_map_pop_elem:
6497 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6498 map->map_type != BPF_MAP_TYPE_STACK)
6501 case BPF_FUNC_map_peek_elem:
6502 case BPF_FUNC_map_push_elem:
6503 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6504 map->map_type != BPF_MAP_TYPE_STACK &&
6505 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6508 case BPF_FUNC_map_lookup_percpu_elem:
6509 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6510 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6511 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6514 case BPF_FUNC_sk_storage_get:
6515 case BPF_FUNC_sk_storage_delete:
6516 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6519 case BPF_FUNC_inode_storage_get:
6520 case BPF_FUNC_inode_storage_delete:
6521 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6524 case BPF_FUNC_task_storage_get:
6525 case BPF_FUNC_task_storage_delete:
6526 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6535 verbose(env, "cannot pass map_type %d into func %s#%d\n",
6536 map->map_type, func_id_name(func_id), func_id);
6540 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6544 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6546 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6548 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6550 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6552 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6555 /* We only support one arg being in raw mode at the moment,
6556 * which is sufficient for the helper functions we have
6562 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6564 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6565 bool has_size = fn->arg_size[arg] != 0;
6566 bool is_next_size = false;
6568 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6569 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6571 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6572 return is_next_size;
6574 return has_size == is_next_size || is_next_size == is_fixed;
6577 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6579 /* bpf_xxx(..., buf, len) call will access 'len'
6580 * bytes from memory 'buf'. Both arg types need
6581 * to be paired, so make sure there's no buggy
6582 * helper function specification.
6584 if (arg_type_is_mem_size(fn->arg1_type) ||
6585 check_args_pair_invalid(fn, 0) ||
6586 check_args_pair_invalid(fn, 1) ||
6587 check_args_pair_invalid(fn, 2) ||
6588 check_args_pair_invalid(fn, 3) ||
6589 check_args_pair_invalid(fn, 4))
6595 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6599 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6600 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6603 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6604 /* arg_btf_id and arg_size are in a union. */
6605 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6606 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6613 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6615 return check_raw_mode_ok(fn) &&
6616 check_arg_pair_ok(fn) &&
6617 check_btf_id_ok(fn) ? 0 : -EINVAL;
6620 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6621 * are now invalid, so turn them into unknown SCALAR_VALUE.
6623 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6625 struct bpf_func_state *state;
6626 struct bpf_reg_state *reg;
6628 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6629 if (reg_is_pkt_pointer_any(reg))
6630 __mark_reg_unknown(env, reg);
6636 BEYOND_PKT_END = -2,
6639 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6641 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6642 struct bpf_reg_state *reg = &state->regs[regn];
6644 if (reg->type != PTR_TO_PACKET)
6645 /* PTR_TO_PACKET_META is not supported yet */
6648 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6649 * How far beyond pkt_end it goes is unknown.
6650 * if (!range_open) it's the case of pkt >= pkt_end
6651 * if (range_open) it's the case of pkt > pkt_end
6652 * hence this pointer is at least 1 byte bigger than pkt_end
6655 reg->range = BEYOND_PKT_END;
6657 reg->range = AT_PKT_END;
6660 /* The pointer with the specified id has released its reference to kernel
6661 * resources. Identify all copies of the same pointer and clear the reference.
6663 static int release_reference(struct bpf_verifier_env *env,
6666 struct bpf_func_state *state;
6667 struct bpf_reg_state *reg;
6670 err = release_reference_state(cur_func(env), ref_obj_id);
6674 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6675 if (reg->ref_obj_id == ref_obj_id) {
6676 if (!env->allow_ptr_leaks)
6677 __mark_reg_not_init(env, reg);
6679 __mark_reg_unknown(env, reg);
6686 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6687 struct bpf_reg_state *regs)
6691 /* after the call registers r0 - r5 were scratched */
6692 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6693 mark_reg_not_init(env, regs, caller_saved[i]);
6694 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6698 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6699 struct bpf_func_state *caller,
6700 struct bpf_func_state *callee,
6703 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6704 int *insn_idx, int subprog,
6705 set_callee_state_fn set_callee_state_cb)
6707 struct bpf_verifier_state *state = env->cur_state;
6708 struct bpf_func_info_aux *func_info_aux;
6709 struct bpf_func_state *caller, *callee;
6711 bool is_global = false;
6713 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6714 verbose(env, "the call stack of %d frames is too deep\n",
6715 state->curframe + 2);
6719 caller = state->frame[state->curframe];
6720 if (state->frame[state->curframe + 1]) {
6721 verbose(env, "verifier bug. Frame %d already allocated\n",
6722 state->curframe + 1);
6726 func_info_aux = env->prog->aux->func_info_aux;
6728 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6729 err = btf_check_subprog_call(env, subprog, caller->regs);
6734 verbose(env, "Caller passes invalid args into func#%d\n",
6738 if (env->log.level & BPF_LOG_LEVEL)
6740 "Func#%d is global and valid. Skipping.\n",
6742 clear_caller_saved_regs(env, caller->regs);
6744 /* All global functions return a 64-bit SCALAR_VALUE */
6745 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6746 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6748 /* continue with next insn after call */
6753 if (insn->code == (BPF_JMP | BPF_CALL) &&
6754 insn->src_reg == 0 &&
6755 insn->imm == BPF_FUNC_timer_set_callback) {
6756 struct bpf_verifier_state *async_cb;
6758 /* there is no real recursion here. timer callbacks are async */
6759 env->subprog_info[subprog].is_async_cb = true;
6760 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6761 *insn_idx, subprog);
6764 callee = async_cb->frame[0];
6765 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6767 /* Convert bpf_timer_set_callback() args into timer callback args */
6768 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6772 clear_caller_saved_regs(env, caller->regs);
6773 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6774 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6775 /* continue with next insn after call */
6779 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6782 state->frame[state->curframe + 1] = callee;
6784 /* callee cannot access r0, r6 - r9 for reading and has to write
6785 * into its own stack before reading from it.
6786 * callee can read/write into caller's stack
6788 init_func_state(env, callee,
6789 /* remember the callsite, it will be used by bpf_exit */
6790 *insn_idx /* callsite */,
6791 state->curframe + 1 /* frameno within this callchain */,
6792 subprog /* subprog number within this prog */);
6794 /* Transfer references to the callee */
6795 err = copy_reference_state(callee, caller);
6799 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6803 clear_caller_saved_regs(env, caller->regs);
6805 /* only increment it after check_reg_arg() finished */
6808 /* and go analyze first insn of the callee */
6809 *insn_idx = env->subprog_info[subprog].start - 1;
6811 if (env->log.level & BPF_LOG_LEVEL) {
6812 verbose(env, "caller:\n");
6813 print_verifier_state(env, caller, true);
6814 verbose(env, "callee:\n");
6815 print_verifier_state(env, callee, true);
6820 free_func_state(callee);
6821 state->frame[state->curframe + 1] = NULL;
6825 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6826 struct bpf_func_state *caller,
6827 struct bpf_func_state *callee)
6829 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6830 * void *callback_ctx, u64 flags);
6831 * callback_fn(struct bpf_map *map, void *key, void *value,
6832 * void *callback_ctx);
6834 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6836 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6837 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6838 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6840 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6841 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6842 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6844 /* pointer to stack or null */
6845 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6848 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6852 static int set_callee_state(struct bpf_verifier_env *env,
6853 struct bpf_func_state *caller,
6854 struct bpf_func_state *callee, int insn_idx)
6858 /* copy r1 - r5 args that callee can access. The copy includes parent
6859 * pointers, which connects us up to the liveness chain
6861 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6862 callee->regs[i] = caller->regs[i];
6866 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6869 int subprog, target_insn;
6871 target_insn = *insn_idx + insn->imm + 1;
6872 subprog = find_subprog(env, target_insn);
6874 verbose(env, "verifier bug. No program starts at insn %d\n",
6879 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6882 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6883 struct bpf_func_state *caller,
6884 struct bpf_func_state *callee,
6887 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6888 struct bpf_map *map;
6891 if (bpf_map_ptr_poisoned(insn_aux)) {
6892 verbose(env, "tail_call abusing map_ptr\n");
6896 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6897 if (!map->ops->map_set_for_each_callback_args ||
6898 !map->ops->map_for_each_callback) {
6899 verbose(env, "callback function not allowed for map\n");
6903 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6907 callee->in_callback_fn = true;
6908 callee->callback_ret_range = tnum_range(0, 1);
6912 static int set_loop_callback_state(struct bpf_verifier_env *env,
6913 struct bpf_func_state *caller,
6914 struct bpf_func_state *callee,
6917 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6919 * callback_fn(u32 index, void *callback_ctx);
6921 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6922 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6925 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6926 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6927 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6929 callee->in_callback_fn = true;
6930 callee->callback_ret_range = tnum_range(0, 1);
6934 static int set_timer_callback_state(struct bpf_verifier_env *env,
6935 struct bpf_func_state *caller,
6936 struct bpf_func_state *callee,
6939 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6941 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6942 * callback_fn(struct bpf_map *map, void *key, void *value);
6944 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6945 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6946 callee->regs[BPF_REG_1].map_ptr = map_ptr;
6948 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6949 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6950 callee->regs[BPF_REG_2].map_ptr = map_ptr;
6952 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6953 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6954 callee->regs[BPF_REG_3].map_ptr = map_ptr;
6957 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6958 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6959 callee->in_async_callback_fn = true;
6960 callee->callback_ret_range = tnum_range(0, 1);
6964 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6965 struct bpf_func_state *caller,
6966 struct bpf_func_state *callee,
6969 /* bpf_find_vma(struct task_struct *task, u64 addr,
6970 * void *callback_fn, void *callback_ctx, u64 flags)
6971 * (callback_fn)(struct task_struct *task,
6972 * struct vm_area_struct *vma, void *callback_ctx);
6974 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6976 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6977 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6978 callee->regs[BPF_REG_2].btf = btf_vmlinux;
6979 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6981 /* pointer to stack or null */
6982 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6985 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6986 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6987 callee->in_callback_fn = true;
6988 callee->callback_ret_range = tnum_range(0, 1);
6992 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
6993 struct bpf_func_state *caller,
6994 struct bpf_func_state *callee,
6997 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
6998 * callback_ctx, u64 flags);
6999 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
7001 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7002 callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
7003 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7004 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7007 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7008 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7009 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7011 callee->in_callback_fn = true;
7012 callee->callback_ret_range = tnum_range(0, 1);
7016 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7018 struct bpf_verifier_state *state = env->cur_state;
7019 struct bpf_func_state *caller, *callee;
7020 struct bpf_reg_state *r0;
7023 callee = state->frame[state->curframe];
7024 r0 = &callee->regs[BPF_REG_0];
7025 if (r0->type == PTR_TO_STACK) {
7026 /* technically it's ok to return caller's stack pointer
7027 * (or caller's caller's pointer) back to the caller,
7028 * since these pointers are valid. Only current stack
7029 * pointer will be invalid as soon as function exits,
7030 * but let's be conservative
7032 verbose(env, "cannot return stack pointer to the caller\n");
7036 caller = state->frame[state->curframe - 1];
7037 if (callee->in_callback_fn) {
7038 /* enforce R0 return value range [0, 1]. */
7039 struct tnum range = callee->callback_ret_range;
7041 if (r0->type != SCALAR_VALUE) {
7042 verbose(env, "R0 not a scalar value\n");
7045 if (!tnum_in(range, r0->var_off)) {
7046 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7050 /* return to the caller whatever r0 had in the callee */
7051 caller->regs[BPF_REG_0] = *r0;
7054 /* callback_fn frame should have released its own additions to parent's
7055 * reference state at this point, or check_reference_leak would
7056 * complain, hence it must be the same as the caller. There is no need
7059 if (!callee->in_callback_fn) {
7060 /* Transfer references to the caller */
7061 err = copy_reference_state(caller, callee);
7066 *insn_idx = callee->callsite + 1;
7067 if (env->log.level & BPF_LOG_LEVEL) {
7068 verbose(env, "returning from callee:\n");
7069 print_verifier_state(env, callee, true);
7070 verbose(env, "to caller at %d:\n", *insn_idx);
7071 print_verifier_state(env, caller, true);
7073 /* clear everything in the callee */
7074 free_func_state(callee);
7075 state->frame[state->curframe--] = NULL;
7079 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7081 struct bpf_call_arg_meta *meta)
7083 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
7085 if (ret_type != RET_INTEGER ||
7086 (func_id != BPF_FUNC_get_stack &&
7087 func_id != BPF_FUNC_get_task_stack &&
7088 func_id != BPF_FUNC_probe_read_str &&
7089 func_id != BPF_FUNC_probe_read_kernel_str &&
7090 func_id != BPF_FUNC_probe_read_user_str))
7093 ret_reg->smax_value = meta->msize_max_value;
7094 ret_reg->s32_max_value = meta->msize_max_value;
7095 ret_reg->smin_value = -MAX_ERRNO;
7096 ret_reg->s32_min_value = -MAX_ERRNO;
7097 reg_bounds_sync(ret_reg);
7101 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7102 int func_id, int insn_idx)
7104 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7105 struct bpf_map *map = meta->map_ptr;
7107 if (func_id != BPF_FUNC_tail_call &&
7108 func_id != BPF_FUNC_map_lookup_elem &&
7109 func_id != BPF_FUNC_map_update_elem &&
7110 func_id != BPF_FUNC_map_delete_elem &&
7111 func_id != BPF_FUNC_map_push_elem &&
7112 func_id != BPF_FUNC_map_pop_elem &&
7113 func_id != BPF_FUNC_map_peek_elem &&
7114 func_id != BPF_FUNC_for_each_map_elem &&
7115 func_id != BPF_FUNC_redirect_map &&
7116 func_id != BPF_FUNC_map_lookup_percpu_elem)
7120 verbose(env, "kernel subsystem misconfigured verifier\n");
7124 /* In case of read-only, some additional restrictions
7125 * need to be applied in order to prevent altering the
7126 * state of the map from program side.
7128 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7129 (func_id == BPF_FUNC_map_delete_elem ||
7130 func_id == BPF_FUNC_map_update_elem ||
7131 func_id == BPF_FUNC_map_push_elem ||
7132 func_id == BPF_FUNC_map_pop_elem)) {
7133 verbose(env, "write into map forbidden\n");
7137 if (!BPF_MAP_PTR(aux->map_ptr_state))
7138 bpf_map_ptr_store(aux, meta->map_ptr,
7139 !meta->map_ptr->bypass_spec_v1);
7140 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7141 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7142 !meta->map_ptr->bypass_spec_v1);
7147 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7148 int func_id, int insn_idx)
7150 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7151 struct bpf_reg_state *regs = cur_regs(env), *reg;
7152 struct bpf_map *map = meta->map_ptr;
7156 if (func_id != BPF_FUNC_tail_call)
7158 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7159 verbose(env, "kernel subsystem misconfigured verifier\n");
7163 reg = ®s[BPF_REG_3];
7164 val = reg->var_off.value;
7165 max = map->max_entries;
7167 if (!(register_is_const(reg) && val < max)) {
7168 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7172 err = mark_chain_precision(env, BPF_REG_3);
7175 if (bpf_map_key_unseen(aux))
7176 bpf_map_key_store(aux, val);
7177 else if (!bpf_map_key_poisoned(aux) &&
7178 bpf_map_key_immediate(aux) != val)
7179 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7183 static int check_reference_leak(struct bpf_verifier_env *env)
7185 struct bpf_func_state *state = cur_func(env);
7186 bool refs_lingering = false;
7189 if (state->frameno && !state->in_callback_fn)
7192 for (i = 0; i < state->acquired_refs; i++) {
7193 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7195 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7196 state->refs[i].id, state->refs[i].insn_idx);
7197 refs_lingering = true;
7199 return refs_lingering ? -EINVAL : 0;
7202 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7203 struct bpf_reg_state *regs)
7205 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
7206 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
7207 struct bpf_map *fmt_map = fmt_reg->map_ptr;
7208 int err, fmt_map_off, num_args;
7212 /* data must be an array of u64 */
7213 if (data_len_reg->var_off.value % 8)
7215 num_args = data_len_reg->var_off.value / 8;
7217 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7218 * and map_direct_value_addr is set.
7220 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7221 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7224 verbose(env, "verifier bug\n");
7227 fmt = (char *)(long)fmt_addr + fmt_map_off;
7229 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7230 * can focus on validating the format specifiers.
7232 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7234 verbose(env, "Invalid format string\n");
7239 static int check_get_func_ip(struct bpf_verifier_env *env)
7241 enum bpf_prog_type type = resolve_prog_type(env->prog);
7242 int func_id = BPF_FUNC_get_func_ip;
7244 if (type == BPF_PROG_TYPE_TRACING) {
7245 if (!bpf_prog_has_trampoline(env->prog)) {
7246 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7247 func_id_name(func_id), func_id);
7251 } else if (type == BPF_PROG_TYPE_KPROBE) {
7255 verbose(env, "func %s#%d not supported for program type %d\n",
7256 func_id_name(func_id), func_id, type);
7260 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7262 return &env->insn_aux_data[env->insn_idx];
7265 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7267 struct bpf_reg_state *regs = cur_regs(env);
7268 struct bpf_reg_state *reg = ®s[BPF_REG_4];
7269 bool reg_is_null = register_is_null(reg);
7272 mark_chain_precision(env, BPF_REG_4);
7277 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7279 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7281 if (!state->initialized) {
7282 state->initialized = 1;
7283 state->fit_for_inline = loop_flag_is_zero(env);
7284 state->callback_subprogno = subprogno;
7288 if (!state->fit_for_inline)
7291 state->fit_for_inline = (loop_flag_is_zero(env) &&
7292 state->callback_subprogno == subprogno);
7295 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7298 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7299 const struct bpf_func_proto *fn = NULL;
7300 enum bpf_return_type ret_type;
7301 enum bpf_type_flag ret_flag;
7302 struct bpf_reg_state *regs;
7303 struct bpf_call_arg_meta meta;
7304 int insn_idx = *insn_idx_p;
7306 int i, err, func_id;
7308 /* find function prototype */
7309 func_id = insn->imm;
7310 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7311 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7316 if (env->ops->get_func_proto)
7317 fn = env->ops->get_func_proto(func_id, env->prog);
7319 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7324 /* eBPF programs must be GPL compatible to use GPL-ed functions */
7325 if (!env->prog->gpl_compatible && fn->gpl_only) {
7326 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7330 if (fn->allowed && !fn->allowed(env->prog)) {
7331 verbose(env, "helper call is not allowed in probe\n");
7335 /* With LD_ABS/IND some JITs save/restore skb from r1. */
7336 changes_data = bpf_helper_changes_pkt_data(fn->func);
7337 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7338 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7339 func_id_name(func_id), func_id);
7343 memset(&meta, 0, sizeof(meta));
7344 meta.pkt_access = fn->pkt_access;
7346 err = check_func_proto(fn, func_id);
7348 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7349 func_id_name(func_id), func_id);
7353 meta.func_id = func_id;
7355 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7356 err = check_func_arg(env, i, &meta, fn);
7361 err = record_func_map(env, &meta, func_id, insn_idx);
7365 err = record_func_key(env, &meta, func_id, insn_idx);
7369 /* Mark slots with STACK_MISC in case of raw mode, stack offset
7370 * is inferred from register state.
7372 for (i = 0; i < meta.access_size; i++) {
7373 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7374 BPF_WRITE, -1, false);
7379 regs = cur_regs(env);
7381 if (meta.uninit_dynptr_regno) {
7382 /* we write BPF_DW bits (8 bytes) at a time */
7383 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7384 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7385 i, BPF_DW, BPF_WRITE, -1, false);
7390 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno],
7391 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7397 if (meta.release_regno) {
7399 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7400 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
7401 else if (meta.ref_obj_id)
7402 err = release_reference(env, meta.ref_obj_id);
7403 /* meta.ref_obj_id can only be 0 if register that is meant to be
7404 * released is NULL, which must be > R0.
7406 else if (register_is_null(®s[meta.release_regno]))
7409 verbose(env, "func %s#%d reference has not been acquired before\n",
7410 func_id_name(func_id), func_id);
7416 case BPF_FUNC_tail_call:
7417 err = check_reference_leak(env);
7419 verbose(env, "tail_call would lead to reference leak\n");
7423 case BPF_FUNC_get_local_storage:
7424 /* check that flags argument in get_local_storage(map, flags) is 0,
7425 * this is required because get_local_storage() can't return an error.
7427 if (!register_is_null(®s[BPF_REG_2])) {
7428 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7432 case BPF_FUNC_for_each_map_elem:
7433 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7434 set_map_elem_callback_state);
7436 case BPF_FUNC_timer_set_callback:
7437 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7438 set_timer_callback_state);
7440 case BPF_FUNC_find_vma:
7441 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7442 set_find_vma_callback_state);
7444 case BPF_FUNC_snprintf:
7445 err = check_bpf_snprintf_call(env, regs);
7448 update_loop_inline_state(env, meta.subprogno);
7449 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7450 set_loop_callback_state);
7452 case BPF_FUNC_dynptr_from_mem:
7453 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7454 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7455 reg_type_str(env, regs[BPF_REG_1].type));
7459 case BPF_FUNC_set_retval:
7460 if (prog_type == BPF_PROG_TYPE_LSM &&
7461 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7462 if (!env->prog->aux->attach_func_proto->type) {
7463 /* Make sure programs that attach to void
7464 * hooks don't try to modify return value.
7466 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7471 case BPF_FUNC_dynptr_data:
7472 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7473 if (arg_type_is_dynptr(fn->arg_type[i])) {
7474 struct bpf_reg_state *reg = ®s[BPF_REG_1 + i];
7476 if (meta.ref_obj_id) {
7477 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7481 if (base_type(reg->type) != PTR_TO_DYNPTR)
7482 /* Find the id of the dynptr we're
7483 * tracking the reference of
7485 meta.ref_obj_id = stack_slot_get_id(env, reg);
7489 if (i == MAX_BPF_FUNC_REG_ARGS) {
7490 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7494 case BPF_FUNC_user_ringbuf_drain:
7495 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7496 set_user_ringbuf_callback_state);
7503 /* reset caller saved regs */
7504 for (i = 0; i < CALLER_SAVED_REGS; i++) {
7505 mark_reg_not_init(env, regs, caller_saved[i]);
7506 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7509 /* helper call returns 64-bit value. */
7510 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7512 /* update return register (already marked as written above) */
7513 ret_type = fn->ret_type;
7514 ret_flag = type_flag(ret_type);
7516 switch (base_type(ret_type)) {
7518 /* sets type to SCALAR_VALUE */
7519 mark_reg_unknown(env, regs, BPF_REG_0);
7522 regs[BPF_REG_0].type = NOT_INIT;
7524 case RET_PTR_TO_MAP_VALUE:
7525 /* There is no offset yet applied, variable or fixed */
7526 mark_reg_known_zero(env, regs, BPF_REG_0);
7527 /* remember map_ptr, so that check_map_access()
7528 * can check 'value_size' boundary of memory access
7529 * to map element returned from bpf_map_lookup_elem()
7531 if (meta.map_ptr == NULL) {
7533 "kernel subsystem misconfigured verifier\n");
7536 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7537 regs[BPF_REG_0].map_uid = meta.map_uid;
7538 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7539 if (!type_may_be_null(ret_type) &&
7540 map_value_has_spin_lock(meta.map_ptr)) {
7541 regs[BPF_REG_0].id = ++env->id_gen;
7544 case RET_PTR_TO_SOCKET:
7545 mark_reg_known_zero(env, regs, BPF_REG_0);
7546 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7548 case RET_PTR_TO_SOCK_COMMON:
7549 mark_reg_known_zero(env, regs, BPF_REG_0);
7550 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7552 case RET_PTR_TO_TCP_SOCK:
7553 mark_reg_known_zero(env, regs, BPF_REG_0);
7554 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7556 case RET_PTR_TO_ALLOC_MEM:
7557 mark_reg_known_zero(env, regs, BPF_REG_0);
7558 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7559 regs[BPF_REG_0].mem_size = meta.mem_size;
7561 case RET_PTR_TO_MEM_OR_BTF_ID:
7563 const struct btf_type *t;
7565 mark_reg_known_zero(env, regs, BPF_REG_0);
7566 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7567 if (!btf_type_is_struct(t)) {
7569 const struct btf_type *ret;
7572 /* resolve the type size of ksym. */
7573 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7575 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7576 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7577 tname, PTR_ERR(ret));
7580 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7581 regs[BPF_REG_0].mem_size = tsize;
7583 /* MEM_RDONLY may be carried from ret_flag, but it
7584 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7585 * it will confuse the check of PTR_TO_BTF_ID in
7586 * check_mem_access().
7588 ret_flag &= ~MEM_RDONLY;
7590 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7591 regs[BPF_REG_0].btf = meta.ret_btf;
7592 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7596 case RET_PTR_TO_BTF_ID:
7598 struct btf *ret_btf;
7601 mark_reg_known_zero(env, regs, BPF_REG_0);
7602 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7603 if (func_id == BPF_FUNC_kptr_xchg) {
7604 ret_btf = meta.kptr_off_desc->kptr.btf;
7605 ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7607 if (fn->ret_btf_id == BPF_PTR_POISON) {
7608 verbose(env, "verifier internal error:");
7609 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7610 func_id_name(func_id));
7613 ret_btf = btf_vmlinux;
7614 ret_btf_id = *fn->ret_btf_id;
7616 if (ret_btf_id == 0) {
7617 verbose(env, "invalid return type %u of func %s#%d\n",
7618 base_type(ret_type), func_id_name(func_id),
7622 regs[BPF_REG_0].btf = ret_btf;
7623 regs[BPF_REG_0].btf_id = ret_btf_id;
7627 verbose(env, "unknown return type %u of func %s#%d\n",
7628 base_type(ret_type), func_id_name(func_id), func_id);
7632 if (type_may_be_null(regs[BPF_REG_0].type))
7633 regs[BPF_REG_0].id = ++env->id_gen;
7635 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7636 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7637 func_id_name(func_id), func_id);
7641 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7642 /* For release_reference() */
7643 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7644 } else if (is_acquire_function(func_id, meta.map_ptr)) {
7645 int id = acquire_reference_state(env, insn_idx);
7649 /* For mark_ptr_or_null_reg() */
7650 regs[BPF_REG_0].id = id;
7651 /* For release_reference() */
7652 regs[BPF_REG_0].ref_obj_id = id;
7655 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7657 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7661 if ((func_id == BPF_FUNC_get_stack ||
7662 func_id == BPF_FUNC_get_task_stack) &&
7663 !env->prog->has_callchain_buf) {
7664 const char *err_str;
7666 #ifdef CONFIG_PERF_EVENTS
7667 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7668 err_str = "cannot get callchain buffer for func %s#%d\n";
7671 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7674 verbose(env, err_str, func_id_name(func_id), func_id);
7678 env->prog->has_callchain_buf = true;
7681 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7682 env->prog->call_get_stack = true;
7684 if (func_id == BPF_FUNC_get_func_ip) {
7685 if (check_get_func_ip(env))
7687 env->prog->call_get_func_ip = true;
7691 clear_all_pkt_pointers(env);
7695 /* mark_btf_func_reg_size() is used when the reg size is determined by
7696 * the BTF func_proto's return value size and argument.
7698 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7701 struct bpf_reg_state *reg = &cur_regs(env)[regno];
7703 if (regno == BPF_REG_0) {
7704 /* Function return value */
7705 reg->live |= REG_LIVE_WRITTEN;
7706 reg->subreg_def = reg_size == sizeof(u64) ?
7707 DEF_NOT_SUBREG : env->insn_idx + 1;
7709 /* Function argument */
7710 if (reg_size == sizeof(u64)) {
7711 mark_insn_zext(env, reg);
7712 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7714 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7719 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7722 const struct btf_type *t, *func, *func_proto, *ptr_type;
7723 struct bpf_reg_state *regs = cur_regs(env);
7724 struct bpf_kfunc_arg_meta meta = { 0 };
7725 const char *func_name, *ptr_type_name;
7726 u32 i, nargs, func_id, ptr_type_id;
7727 int err, insn_idx = *insn_idx_p;
7728 const struct btf_param *args;
7729 struct btf *desc_btf;
7733 /* skip for now, but return error when we find this in fixup_kfunc_call */
7737 desc_btf = find_kfunc_desc_btf(env, insn->off);
7738 if (IS_ERR(desc_btf))
7739 return PTR_ERR(desc_btf);
7741 func_id = insn->imm;
7742 func = btf_type_by_id(desc_btf, func_id);
7743 func_name = btf_name_by_offset(desc_btf, func->name_off);
7744 func_proto = btf_type_by_id(desc_btf, func->type);
7746 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7748 verbose(env, "calling kernel function %s is not allowed\n",
7752 if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7753 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7757 acq = *kfunc_flags & KF_ACQUIRE;
7759 meta.flags = *kfunc_flags;
7761 /* Check the arguments */
7762 err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7765 /* In case of release function, we get register number of refcounted
7766 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7769 err = release_reference(env, regs[err].ref_obj_id);
7771 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7772 func_name, func_id);
7777 for (i = 0; i < CALLER_SAVED_REGS; i++)
7778 mark_reg_not_init(env, regs, caller_saved[i]);
7780 /* Check return type */
7781 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7783 if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7784 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7788 if (btf_type_is_scalar(t)) {
7789 mark_reg_unknown(env, regs, BPF_REG_0);
7790 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7791 } else if (btf_type_is_ptr(t)) {
7792 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7794 if (!btf_type_is_struct(ptr_type)) {
7795 if (!meta.r0_size) {
7796 ptr_type_name = btf_name_by_offset(desc_btf,
7797 ptr_type->name_off);
7799 "kernel function %s returns pointer type %s %s is not supported\n",
7801 btf_type_str(ptr_type),
7806 mark_reg_known_zero(env, regs, BPF_REG_0);
7807 regs[BPF_REG_0].type = PTR_TO_MEM;
7808 regs[BPF_REG_0].mem_size = meta.r0_size;
7811 regs[BPF_REG_0].type |= MEM_RDONLY;
7813 /* Ensures we don't access the memory after a release_reference() */
7814 if (meta.ref_obj_id)
7815 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7817 mark_reg_known_zero(env, regs, BPF_REG_0);
7818 regs[BPF_REG_0].btf = desc_btf;
7819 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7820 regs[BPF_REG_0].btf_id = ptr_type_id;
7822 if (*kfunc_flags & KF_RET_NULL) {
7823 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7824 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7825 regs[BPF_REG_0].id = ++env->id_gen;
7827 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7829 int id = acquire_reference_state(env, insn_idx);
7833 regs[BPF_REG_0].id = id;
7834 regs[BPF_REG_0].ref_obj_id = id;
7836 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7838 nargs = btf_type_vlen(func_proto);
7839 args = (const struct btf_param *)(func_proto + 1);
7840 for (i = 0; i < nargs; i++) {
7843 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7844 if (btf_type_is_ptr(t))
7845 mark_btf_func_reg_size(env, regno, sizeof(void *));
7847 /* scalar. ensured by btf_check_kfunc_arg_match() */
7848 mark_btf_func_reg_size(env, regno, t->size);
7854 static bool signed_add_overflows(s64 a, s64 b)
7856 /* Do the add in u64, where overflow is well-defined */
7857 s64 res = (s64)((u64)a + (u64)b);
7864 static bool signed_add32_overflows(s32 a, s32 b)
7866 /* Do the add in u32, where overflow is well-defined */
7867 s32 res = (s32)((u32)a + (u32)b);
7874 static bool signed_sub_overflows(s64 a, s64 b)
7876 /* Do the sub in u64, where overflow is well-defined */
7877 s64 res = (s64)((u64)a - (u64)b);
7884 static bool signed_sub32_overflows(s32 a, s32 b)
7886 /* Do the sub in u32, where overflow is well-defined */
7887 s32 res = (s32)((u32)a - (u32)b);
7894 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7895 const struct bpf_reg_state *reg,
7896 enum bpf_reg_type type)
7898 bool known = tnum_is_const(reg->var_off);
7899 s64 val = reg->var_off.value;
7900 s64 smin = reg->smin_value;
7902 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7903 verbose(env, "math between %s pointer and %lld is not allowed\n",
7904 reg_type_str(env, type), val);
7908 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7909 verbose(env, "%s pointer offset %d is not allowed\n",
7910 reg_type_str(env, type), reg->off);
7914 if (smin == S64_MIN) {
7915 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7916 reg_type_str(env, type));
7920 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7921 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7922 smin, reg_type_str(env, type));
7937 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7938 u32 *alu_limit, bool mask_to_left)
7940 u32 max = 0, ptr_limit = 0;
7942 switch (ptr_reg->type) {
7944 /* Offset 0 is out-of-bounds, but acceptable start for the
7945 * left direction, see BPF_REG_FP. Also, unknown scalar
7946 * offset where we would need to deal with min/max bounds is
7947 * currently prohibited for unprivileged.
7949 max = MAX_BPF_STACK + mask_to_left;
7950 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7952 case PTR_TO_MAP_VALUE:
7953 max = ptr_reg->map_ptr->value_size;
7954 ptr_limit = (mask_to_left ?
7955 ptr_reg->smin_value :
7956 ptr_reg->umax_value) + ptr_reg->off;
7962 if (ptr_limit >= max)
7963 return REASON_LIMIT;
7964 *alu_limit = ptr_limit;
7968 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7969 const struct bpf_insn *insn)
7971 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7974 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7975 u32 alu_state, u32 alu_limit)
7977 /* If we arrived here from different branches with different
7978 * state or limits to sanitize, then this won't work.
7980 if (aux->alu_state &&
7981 (aux->alu_state != alu_state ||
7982 aux->alu_limit != alu_limit))
7983 return REASON_PATHS;
7985 /* Corresponding fixup done in do_misc_fixups(). */
7986 aux->alu_state = alu_state;
7987 aux->alu_limit = alu_limit;
7991 static int sanitize_val_alu(struct bpf_verifier_env *env,
7992 struct bpf_insn *insn)
7994 struct bpf_insn_aux_data *aux = cur_aux(env);
7996 if (can_skip_alu_sanitation(env, insn))
7999 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
8002 static bool sanitize_needed(u8 opcode)
8004 return opcode == BPF_ADD || opcode == BPF_SUB;
8007 struct bpf_sanitize_info {
8008 struct bpf_insn_aux_data aux;
8012 static struct bpf_verifier_state *
8013 sanitize_speculative_path(struct bpf_verifier_env *env,
8014 const struct bpf_insn *insn,
8015 u32 next_idx, u32 curr_idx)
8017 struct bpf_verifier_state *branch;
8018 struct bpf_reg_state *regs;
8020 branch = push_stack(env, next_idx, curr_idx, true);
8021 if (branch && insn) {
8022 regs = branch->frame[branch->curframe]->regs;
8023 if (BPF_SRC(insn->code) == BPF_K) {
8024 mark_reg_unknown(env, regs, insn->dst_reg);
8025 } else if (BPF_SRC(insn->code) == BPF_X) {
8026 mark_reg_unknown(env, regs, insn->dst_reg);
8027 mark_reg_unknown(env, regs, insn->src_reg);
8033 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
8034 struct bpf_insn *insn,
8035 const struct bpf_reg_state *ptr_reg,
8036 const struct bpf_reg_state *off_reg,
8037 struct bpf_reg_state *dst_reg,
8038 struct bpf_sanitize_info *info,
8039 const bool commit_window)
8041 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
8042 struct bpf_verifier_state *vstate = env->cur_state;
8043 bool off_is_imm = tnum_is_const(off_reg->var_off);
8044 bool off_is_neg = off_reg->smin_value < 0;
8045 bool ptr_is_dst_reg = ptr_reg == dst_reg;
8046 u8 opcode = BPF_OP(insn->code);
8047 u32 alu_state, alu_limit;
8048 struct bpf_reg_state tmp;
8052 if (can_skip_alu_sanitation(env, insn))
8055 /* We already marked aux for masking from non-speculative
8056 * paths, thus we got here in the first place. We only care
8057 * to explore bad access from here.
8059 if (vstate->speculative)
8062 if (!commit_window) {
8063 if (!tnum_is_const(off_reg->var_off) &&
8064 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8065 return REASON_BOUNDS;
8067 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
8068 (opcode == BPF_SUB && !off_is_neg);
8071 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8075 if (commit_window) {
8076 /* In commit phase we narrow the masking window based on
8077 * the observed pointer move after the simulated operation.
8079 alu_state = info->aux.alu_state;
8080 alu_limit = abs(info->aux.alu_limit - alu_limit);
8082 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8083 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8084 alu_state |= ptr_is_dst_reg ?
8085 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8087 /* Limit pruning on unknown scalars to enable deep search for
8088 * potential masking differences from other program paths.
8091 env->explore_alu_limits = true;
8094 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8098 /* If we're in commit phase, we're done here given we already
8099 * pushed the truncated dst_reg into the speculative verification
8102 * Also, when register is a known constant, we rewrite register-based
8103 * operation to immediate-based, and thus do not need masking (and as
8104 * a consequence, do not need to simulate the zero-truncation either).
8106 if (commit_window || off_is_imm)
8109 /* Simulate and find potential out-of-bounds access under
8110 * speculative execution from truncation as a result of
8111 * masking when off was not within expected range. If off
8112 * sits in dst, then we temporarily need to move ptr there
8113 * to simulate dst (== 0) +/-= ptr. Needed, for example,
8114 * for cases where we use K-based arithmetic in one direction
8115 * and truncated reg-based in the other in order to explore
8118 if (!ptr_is_dst_reg) {
8120 copy_register_state(dst_reg, ptr_reg);
8122 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8124 if (!ptr_is_dst_reg && ret)
8126 return !ret ? REASON_STACK : 0;
8129 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8131 struct bpf_verifier_state *vstate = env->cur_state;
8133 /* If we simulate paths under speculation, we don't update the
8134 * insn as 'seen' such that when we verify unreachable paths in
8135 * the non-speculative domain, sanitize_dead_code() can still
8136 * rewrite/sanitize them.
8138 if (!vstate->speculative)
8139 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8142 static int sanitize_err(struct bpf_verifier_env *env,
8143 const struct bpf_insn *insn, int reason,
8144 const struct bpf_reg_state *off_reg,
8145 const struct bpf_reg_state *dst_reg)
8147 static const char *err = "pointer arithmetic with it prohibited for !root";
8148 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8149 u32 dst = insn->dst_reg, src = insn->src_reg;
8153 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8154 off_reg == dst_reg ? dst : src, err);
8157 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8158 off_reg == dst_reg ? src : dst, err);
8161 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8165 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8169 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8173 verbose(env, "verifier internal error: unknown reason (%d)\n",
8181 /* check that stack access falls within stack limits and that 'reg' doesn't
8182 * have a variable offset.
8184 * Variable offset is prohibited for unprivileged mode for simplicity since it
8185 * requires corresponding support in Spectre masking for stack ALU. See also
8186 * retrieve_ptr_limit().
8189 * 'off' includes 'reg->off'.
8191 static int check_stack_access_for_ptr_arithmetic(
8192 struct bpf_verifier_env *env,
8194 const struct bpf_reg_state *reg,
8197 if (!tnum_is_const(reg->var_off)) {
8200 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8201 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8202 regno, tn_buf, off);
8206 if (off >= 0 || off < -MAX_BPF_STACK) {
8207 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8208 "prohibited for !root; off=%d\n", regno, off);
8215 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8216 const struct bpf_insn *insn,
8217 const struct bpf_reg_state *dst_reg)
8219 u32 dst = insn->dst_reg;
8221 /* For unprivileged we require that resulting offset must be in bounds
8222 * in order to be able to sanitize access later on.
8224 if (env->bypass_spec_v1)
8227 switch (dst_reg->type) {
8229 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8230 dst_reg->off + dst_reg->var_off.value))
8233 case PTR_TO_MAP_VALUE:
8234 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8235 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8236 "prohibited for !root\n", dst);
8247 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8248 * Caller should also handle BPF_MOV case separately.
8249 * If we return -EACCES, caller may want to try again treating pointer as a
8250 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
8252 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8253 struct bpf_insn *insn,
8254 const struct bpf_reg_state *ptr_reg,
8255 const struct bpf_reg_state *off_reg)
8257 struct bpf_verifier_state *vstate = env->cur_state;
8258 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8259 struct bpf_reg_state *regs = state->regs, *dst_reg;
8260 bool known = tnum_is_const(off_reg->var_off);
8261 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8262 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8263 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8264 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8265 struct bpf_sanitize_info info = {};
8266 u8 opcode = BPF_OP(insn->code);
8267 u32 dst = insn->dst_reg;
8270 dst_reg = ®s[dst];
8272 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8273 smin_val > smax_val || umin_val > umax_val) {
8274 /* Taint dst register if offset had invalid bounds derived from
8275 * e.g. dead branches.
8277 __mark_reg_unknown(env, dst_reg);
8281 if (BPF_CLASS(insn->code) != BPF_ALU64) {
8282 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8283 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8284 __mark_reg_unknown(env, dst_reg);
8289 "R%d 32-bit pointer arithmetic prohibited\n",
8294 if (ptr_reg->type & PTR_MAYBE_NULL) {
8295 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8296 dst, reg_type_str(env, ptr_reg->type));
8300 switch (base_type(ptr_reg->type)) {
8301 case CONST_PTR_TO_MAP:
8302 /* smin_val represents the known value */
8303 if (known && smin_val == 0 && opcode == BPF_ADD)
8306 case PTR_TO_PACKET_END:
8308 case PTR_TO_SOCK_COMMON:
8309 case PTR_TO_TCP_SOCK:
8310 case PTR_TO_XDP_SOCK:
8311 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8312 dst, reg_type_str(env, ptr_reg->type));
8318 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8319 * The id may be overwritten later if we create a new variable offset.
8321 dst_reg->type = ptr_reg->type;
8322 dst_reg->id = ptr_reg->id;
8324 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8325 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8328 /* pointer types do not carry 32-bit bounds at the moment. */
8329 __mark_reg32_unbounded(dst_reg);
8331 if (sanitize_needed(opcode)) {
8332 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8335 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8340 /* We can take a fixed offset as long as it doesn't overflow
8341 * the s32 'off' field
8343 if (known && (ptr_reg->off + smin_val ==
8344 (s64)(s32)(ptr_reg->off + smin_val))) {
8345 /* pointer += K. Accumulate it into fixed offset */
8346 dst_reg->smin_value = smin_ptr;
8347 dst_reg->smax_value = smax_ptr;
8348 dst_reg->umin_value = umin_ptr;
8349 dst_reg->umax_value = umax_ptr;
8350 dst_reg->var_off = ptr_reg->var_off;
8351 dst_reg->off = ptr_reg->off + smin_val;
8352 dst_reg->raw = ptr_reg->raw;
8355 /* A new variable offset is created. Note that off_reg->off
8356 * == 0, since it's a scalar.
8357 * dst_reg gets the pointer type and since some positive
8358 * integer value was added to the pointer, give it a new 'id'
8359 * if it's a PTR_TO_PACKET.
8360 * this creates a new 'base' pointer, off_reg (variable) gets
8361 * added into the variable offset, and we copy the fixed offset
8364 if (signed_add_overflows(smin_ptr, smin_val) ||
8365 signed_add_overflows(smax_ptr, smax_val)) {
8366 dst_reg->smin_value = S64_MIN;
8367 dst_reg->smax_value = S64_MAX;
8369 dst_reg->smin_value = smin_ptr + smin_val;
8370 dst_reg->smax_value = smax_ptr + smax_val;
8372 if (umin_ptr + umin_val < umin_ptr ||
8373 umax_ptr + umax_val < umax_ptr) {
8374 dst_reg->umin_value = 0;
8375 dst_reg->umax_value = U64_MAX;
8377 dst_reg->umin_value = umin_ptr + umin_val;
8378 dst_reg->umax_value = umax_ptr + umax_val;
8380 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8381 dst_reg->off = ptr_reg->off;
8382 dst_reg->raw = ptr_reg->raw;
8383 if (reg_is_pkt_pointer(ptr_reg)) {
8384 dst_reg->id = ++env->id_gen;
8385 /* something was added to pkt_ptr, set range to zero */
8386 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8390 if (dst_reg == off_reg) {
8391 /* scalar -= pointer. Creates an unknown scalar */
8392 verbose(env, "R%d tried to subtract pointer from scalar\n",
8396 /* We don't allow subtraction from FP, because (according to
8397 * test_verifier.c test "invalid fp arithmetic", JITs might not
8398 * be able to deal with it.
8400 if (ptr_reg->type == PTR_TO_STACK) {
8401 verbose(env, "R%d subtraction from stack pointer prohibited\n",
8405 if (known && (ptr_reg->off - smin_val ==
8406 (s64)(s32)(ptr_reg->off - smin_val))) {
8407 /* pointer -= K. Subtract it from fixed offset */
8408 dst_reg->smin_value = smin_ptr;
8409 dst_reg->smax_value = smax_ptr;
8410 dst_reg->umin_value = umin_ptr;
8411 dst_reg->umax_value = umax_ptr;
8412 dst_reg->var_off = ptr_reg->var_off;
8413 dst_reg->id = ptr_reg->id;
8414 dst_reg->off = ptr_reg->off - smin_val;
8415 dst_reg->raw = ptr_reg->raw;
8418 /* A new variable offset is created. If the subtrahend is known
8419 * nonnegative, then any reg->range we had before is still good.
8421 if (signed_sub_overflows(smin_ptr, smax_val) ||
8422 signed_sub_overflows(smax_ptr, smin_val)) {
8423 /* Overflow possible, we know nothing */
8424 dst_reg->smin_value = S64_MIN;
8425 dst_reg->smax_value = S64_MAX;
8427 dst_reg->smin_value = smin_ptr - smax_val;
8428 dst_reg->smax_value = smax_ptr - smin_val;
8430 if (umin_ptr < umax_val) {
8431 /* Overflow possible, we know nothing */
8432 dst_reg->umin_value = 0;
8433 dst_reg->umax_value = U64_MAX;
8435 /* Cannot overflow (as long as bounds are consistent) */
8436 dst_reg->umin_value = umin_ptr - umax_val;
8437 dst_reg->umax_value = umax_ptr - umin_val;
8439 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8440 dst_reg->off = ptr_reg->off;
8441 dst_reg->raw = ptr_reg->raw;
8442 if (reg_is_pkt_pointer(ptr_reg)) {
8443 dst_reg->id = ++env->id_gen;
8444 /* something was added to pkt_ptr, set range to zero */
8446 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8452 /* bitwise ops on pointers are troublesome, prohibit. */
8453 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8454 dst, bpf_alu_string[opcode >> 4]);
8457 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8458 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8459 dst, bpf_alu_string[opcode >> 4]);
8463 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8465 reg_bounds_sync(dst_reg);
8466 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8468 if (sanitize_needed(opcode)) {
8469 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8472 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8478 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8479 struct bpf_reg_state *src_reg)
8481 s32 smin_val = src_reg->s32_min_value;
8482 s32 smax_val = src_reg->s32_max_value;
8483 u32 umin_val = src_reg->u32_min_value;
8484 u32 umax_val = src_reg->u32_max_value;
8486 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8487 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8488 dst_reg->s32_min_value = S32_MIN;
8489 dst_reg->s32_max_value = S32_MAX;
8491 dst_reg->s32_min_value += smin_val;
8492 dst_reg->s32_max_value += smax_val;
8494 if (dst_reg->u32_min_value + umin_val < umin_val ||
8495 dst_reg->u32_max_value + umax_val < umax_val) {
8496 dst_reg->u32_min_value = 0;
8497 dst_reg->u32_max_value = U32_MAX;
8499 dst_reg->u32_min_value += umin_val;
8500 dst_reg->u32_max_value += umax_val;
8504 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8505 struct bpf_reg_state *src_reg)
8507 s64 smin_val = src_reg->smin_value;
8508 s64 smax_val = src_reg->smax_value;
8509 u64 umin_val = src_reg->umin_value;
8510 u64 umax_val = src_reg->umax_value;
8512 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8513 signed_add_overflows(dst_reg->smax_value, smax_val)) {
8514 dst_reg->smin_value = S64_MIN;
8515 dst_reg->smax_value = S64_MAX;
8517 dst_reg->smin_value += smin_val;
8518 dst_reg->smax_value += smax_val;
8520 if (dst_reg->umin_value + umin_val < umin_val ||
8521 dst_reg->umax_value + umax_val < umax_val) {
8522 dst_reg->umin_value = 0;
8523 dst_reg->umax_value = U64_MAX;
8525 dst_reg->umin_value += umin_val;
8526 dst_reg->umax_value += umax_val;
8530 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8531 struct bpf_reg_state *src_reg)
8533 s32 smin_val = src_reg->s32_min_value;
8534 s32 smax_val = src_reg->s32_max_value;
8535 u32 umin_val = src_reg->u32_min_value;
8536 u32 umax_val = src_reg->u32_max_value;
8538 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8539 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8540 /* Overflow possible, we know nothing */
8541 dst_reg->s32_min_value = S32_MIN;
8542 dst_reg->s32_max_value = S32_MAX;
8544 dst_reg->s32_min_value -= smax_val;
8545 dst_reg->s32_max_value -= smin_val;
8547 if (dst_reg->u32_min_value < umax_val) {
8548 /* Overflow possible, we know nothing */
8549 dst_reg->u32_min_value = 0;
8550 dst_reg->u32_max_value = U32_MAX;
8552 /* Cannot overflow (as long as bounds are consistent) */
8553 dst_reg->u32_min_value -= umax_val;
8554 dst_reg->u32_max_value -= umin_val;
8558 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8559 struct bpf_reg_state *src_reg)
8561 s64 smin_val = src_reg->smin_value;
8562 s64 smax_val = src_reg->smax_value;
8563 u64 umin_val = src_reg->umin_value;
8564 u64 umax_val = src_reg->umax_value;
8566 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8567 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8568 /* Overflow possible, we know nothing */
8569 dst_reg->smin_value = S64_MIN;
8570 dst_reg->smax_value = S64_MAX;
8572 dst_reg->smin_value -= smax_val;
8573 dst_reg->smax_value -= smin_val;
8575 if (dst_reg->umin_value < umax_val) {
8576 /* Overflow possible, we know nothing */
8577 dst_reg->umin_value = 0;
8578 dst_reg->umax_value = U64_MAX;
8580 /* Cannot overflow (as long as bounds are consistent) */
8581 dst_reg->umin_value -= umax_val;
8582 dst_reg->umax_value -= umin_val;
8586 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8587 struct bpf_reg_state *src_reg)
8589 s32 smin_val = src_reg->s32_min_value;
8590 u32 umin_val = src_reg->u32_min_value;
8591 u32 umax_val = src_reg->u32_max_value;
8593 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8594 /* Ain't nobody got time to multiply that sign */
8595 __mark_reg32_unbounded(dst_reg);
8598 /* Both values are positive, so we can work with unsigned and
8599 * copy the result to signed (unless it exceeds S32_MAX).
8601 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8602 /* Potential overflow, we know nothing */
8603 __mark_reg32_unbounded(dst_reg);
8606 dst_reg->u32_min_value *= umin_val;
8607 dst_reg->u32_max_value *= umax_val;
8608 if (dst_reg->u32_max_value > S32_MAX) {
8609 /* Overflow possible, we know nothing */
8610 dst_reg->s32_min_value = S32_MIN;
8611 dst_reg->s32_max_value = S32_MAX;
8613 dst_reg->s32_min_value = dst_reg->u32_min_value;
8614 dst_reg->s32_max_value = dst_reg->u32_max_value;
8618 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8619 struct bpf_reg_state *src_reg)
8621 s64 smin_val = src_reg->smin_value;
8622 u64 umin_val = src_reg->umin_value;
8623 u64 umax_val = src_reg->umax_value;
8625 if (smin_val < 0 || dst_reg->smin_value < 0) {
8626 /* Ain't nobody got time to multiply that sign */
8627 __mark_reg64_unbounded(dst_reg);
8630 /* Both values are positive, so we can work with unsigned and
8631 * copy the result to signed (unless it exceeds S64_MAX).
8633 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8634 /* Potential overflow, we know nothing */
8635 __mark_reg64_unbounded(dst_reg);
8638 dst_reg->umin_value *= umin_val;
8639 dst_reg->umax_value *= umax_val;
8640 if (dst_reg->umax_value > S64_MAX) {
8641 /* Overflow possible, we know nothing */
8642 dst_reg->smin_value = S64_MIN;
8643 dst_reg->smax_value = S64_MAX;
8645 dst_reg->smin_value = dst_reg->umin_value;
8646 dst_reg->smax_value = dst_reg->umax_value;
8650 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8651 struct bpf_reg_state *src_reg)
8653 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8654 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8655 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8656 s32 smin_val = src_reg->s32_min_value;
8657 u32 umax_val = src_reg->u32_max_value;
8659 if (src_known && dst_known) {
8660 __mark_reg32_known(dst_reg, var32_off.value);
8664 /* We get our minimum from the var_off, since that's inherently
8665 * bitwise. Our maximum is the minimum of the operands' maxima.
8667 dst_reg->u32_min_value = var32_off.value;
8668 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8669 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8670 /* Lose signed bounds when ANDing negative numbers,
8671 * ain't nobody got time for that.
8673 dst_reg->s32_min_value = S32_MIN;
8674 dst_reg->s32_max_value = S32_MAX;
8676 /* ANDing two positives gives a positive, so safe to
8677 * cast result into s64.
8679 dst_reg->s32_min_value = dst_reg->u32_min_value;
8680 dst_reg->s32_max_value = dst_reg->u32_max_value;
8684 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8685 struct bpf_reg_state *src_reg)
8687 bool src_known = tnum_is_const(src_reg->var_off);
8688 bool dst_known = tnum_is_const(dst_reg->var_off);
8689 s64 smin_val = src_reg->smin_value;
8690 u64 umax_val = src_reg->umax_value;
8692 if (src_known && dst_known) {
8693 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8697 /* We get our minimum from the var_off, since that's inherently
8698 * bitwise. Our maximum is the minimum of the operands' maxima.
8700 dst_reg->umin_value = dst_reg->var_off.value;
8701 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8702 if (dst_reg->smin_value < 0 || smin_val < 0) {
8703 /* Lose signed bounds when ANDing negative numbers,
8704 * ain't nobody got time for that.
8706 dst_reg->smin_value = S64_MIN;
8707 dst_reg->smax_value = S64_MAX;
8709 /* ANDing two positives gives a positive, so safe to
8710 * cast result into s64.
8712 dst_reg->smin_value = dst_reg->umin_value;
8713 dst_reg->smax_value = dst_reg->umax_value;
8715 /* We may learn something more from the var_off */
8716 __update_reg_bounds(dst_reg);
8719 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8720 struct bpf_reg_state *src_reg)
8722 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8723 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8724 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8725 s32 smin_val = src_reg->s32_min_value;
8726 u32 umin_val = src_reg->u32_min_value;
8728 if (src_known && dst_known) {
8729 __mark_reg32_known(dst_reg, var32_off.value);
8733 /* We get our maximum from the var_off, and our minimum is the
8734 * maximum of the operands' minima
8736 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8737 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8738 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8739 /* Lose signed bounds when ORing negative numbers,
8740 * ain't nobody got time for that.
8742 dst_reg->s32_min_value = S32_MIN;
8743 dst_reg->s32_max_value = S32_MAX;
8745 /* ORing two positives gives a positive, so safe to
8746 * cast result into s64.
8748 dst_reg->s32_min_value = dst_reg->u32_min_value;
8749 dst_reg->s32_max_value = dst_reg->u32_max_value;
8753 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8754 struct bpf_reg_state *src_reg)
8756 bool src_known = tnum_is_const(src_reg->var_off);
8757 bool dst_known = tnum_is_const(dst_reg->var_off);
8758 s64 smin_val = src_reg->smin_value;
8759 u64 umin_val = src_reg->umin_value;
8761 if (src_known && dst_known) {
8762 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8766 /* We get our maximum from the var_off, and our minimum is the
8767 * maximum of the operands' minima
8769 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8770 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8771 if (dst_reg->smin_value < 0 || smin_val < 0) {
8772 /* Lose signed bounds when ORing negative numbers,
8773 * ain't nobody got time for that.
8775 dst_reg->smin_value = S64_MIN;
8776 dst_reg->smax_value = S64_MAX;
8778 /* ORing two positives gives a positive, so safe to
8779 * cast result into s64.
8781 dst_reg->smin_value = dst_reg->umin_value;
8782 dst_reg->smax_value = dst_reg->umax_value;
8784 /* We may learn something more from the var_off */
8785 __update_reg_bounds(dst_reg);
8788 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8789 struct bpf_reg_state *src_reg)
8791 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8792 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8793 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8794 s32 smin_val = src_reg->s32_min_value;
8796 if (src_known && dst_known) {
8797 __mark_reg32_known(dst_reg, var32_off.value);
8801 /* We get both minimum and maximum from the var32_off. */
8802 dst_reg->u32_min_value = var32_off.value;
8803 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8805 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8806 /* XORing two positive sign numbers gives a positive,
8807 * so safe to cast u32 result into s32.
8809 dst_reg->s32_min_value = dst_reg->u32_min_value;
8810 dst_reg->s32_max_value = dst_reg->u32_max_value;
8812 dst_reg->s32_min_value = S32_MIN;
8813 dst_reg->s32_max_value = S32_MAX;
8817 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8818 struct bpf_reg_state *src_reg)
8820 bool src_known = tnum_is_const(src_reg->var_off);
8821 bool dst_known = tnum_is_const(dst_reg->var_off);
8822 s64 smin_val = src_reg->smin_value;
8824 if (src_known && dst_known) {
8825 /* dst_reg->var_off.value has been updated earlier */
8826 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8830 /* We get both minimum and maximum from the var_off. */
8831 dst_reg->umin_value = dst_reg->var_off.value;
8832 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8834 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8835 /* XORing two positive sign numbers gives a positive,
8836 * so safe to cast u64 result into s64.
8838 dst_reg->smin_value = dst_reg->umin_value;
8839 dst_reg->smax_value = dst_reg->umax_value;
8841 dst_reg->smin_value = S64_MIN;
8842 dst_reg->smax_value = S64_MAX;
8845 __update_reg_bounds(dst_reg);
8848 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8849 u64 umin_val, u64 umax_val)
8851 /* We lose all sign bit information (except what we can pick
8854 dst_reg->s32_min_value = S32_MIN;
8855 dst_reg->s32_max_value = S32_MAX;
8856 /* If we might shift our top bit out, then we know nothing */
8857 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8858 dst_reg->u32_min_value = 0;
8859 dst_reg->u32_max_value = U32_MAX;
8861 dst_reg->u32_min_value <<= umin_val;
8862 dst_reg->u32_max_value <<= umax_val;
8866 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8867 struct bpf_reg_state *src_reg)
8869 u32 umax_val = src_reg->u32_max_value;
8870 u32 umin_val = src_reg->u32_min_value;
8871 /* u32 alu operation will zext upper bits */
8872 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8874 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8875 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8876 /* Not required but being careful mark reg64 bounds as unknown so
8877 * that we are forced to pick them up from tnum and zext later and
8878 * if some path skips this step we are still safe.
8880 __mark_reg64_unbounded(dst_reg);
8881 __update_reg32_bounds(dst_reg);
8884 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8885 u64 umin_val, u64 umax_val)
8887 /* Special case <<32 because it is a common compiler pattern to sign
8888 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8889 * positive we know this shift will also be positive so we can track
8890 * bounds correctly. Otherwise we lose all sign bit information except
8891 * what we can pick up from var_off. Perhaps we can generalize this
8892 * later to shifts of any length.
8894 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8895 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8897 dst_reg->smax_value = S64_MAX;
8899 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8900 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8902 dst_reg->smin_value = S64_MIN;
8904 /* If we might shift our top bit out, then we know nothing */
8905 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8906 dst_reg->umin_value = 0;
8907 dst_reg->umax_value = U64_MAX;
8909 dst_reg->umin_value <<= umin_val;
8910 dst_reg->umax_value <<= umax_val;
8914 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8915 struct bpf_reg_state *src_reg)
8917 u64 umax_val = src_reg->umax_value;
8918 u64 umin_val = src_reg->umin_value;
8920 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8921 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8922 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8924 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8925 /* We may learn something more from the var_off */
8926 __update_reg_bounds(dst_reg);
8929 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8930 struct bpf_reg_state *src_reg)
8932 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8933 u32 umax_val = src_reg->u32_max_value;
8934 u32 umin_val = src_reg->u32_min_value;
8936 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8937 * be negative, then either:
8938 * 1) src_reg might be zero, so the sign bit of the result is
8939 * unknown, so we lose our signed bounds
8940 * 2) it's known negative, thus the unsigned bounds capture the
8942 * 3) the signed bounds cross zero, so they tell us nothing
8944 * If the value in dst_reg is known nonnegative, then again the
8945 * unsigned bounds capture the signed bounds.
8946 * Thus, in all cases it suffices to blow away our signed bounds
8947 * and rely on inferring new ones from the unsigned bounds and
8948 * var_off of the result.
8950 dst_reg->s32_min_value = S32_MIN;
8951 dst_reg->s32_max_value = S32_MAX;
8953 dst_reg->var_off = tnum_rshift(subreg, umin_val);
8954 dst_reg->u32_min_value >>= umax_val;
8955 dst_reg->u32_max_value >>= umin_val;
8957 __mark_reg64_unbounded(dst_reg);
8958 __update_reg32_bounds(dst_reg);
8961 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8962 struct bpf_reg_state *src_reg)
8964 u64 umax_val = src_reg->umax_value;
8965 u64 umin_val = src_reg->umin_value;
8967 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8968 * be negative, then either:
8969 * 1) src_reg might be zero, so the sign bit of the result is
8970 * unknown, so we lose our signed bounds
8971 * 2) it's known negative, thus the unsigned bounds capture the
8973 * 3) the signed bounds cross zero, so they tell us nothing
8975 * If the value in dst_reg is known nonnegative, then again the
8976 * unsigned bounds capture the signed bounds.
8977 * Thus, in all cases it suffices to blow away our signed bounds
8978 * and rely on inferring new ones from the unsigned bounds and
8979 * var_off of the result.
8981 dst_reg->smin_value = S64_MIN;
8982 dst_reg->smax_value = S64_MAX;
8983 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8984 dst_reg->umin_value >>= umax_val;
8985 dst_reg->umax_value >>= umin_val;
8987 /* Its not easy to operate on alu32 bounds here because it depends
8988 * on bits being shifted in. Take easy way out and mark unbounded
8989 * so we can recalculate later from tnum.
8991 __mark_reg32_unbounded(dst_reg);
8992 __update_reg_bounds(dst_reg);
8995 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8996 struct bpf_reg_state *src_reg)
8998 u64 umin_val = src_reg->u32_min_value;
9000 /* Upon reaching here, src_known is true and
9001 * umax_val is equal to umin_val.
9003 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
9004 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
9006 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
9008 /* blow away the dst_reg umin_value/umax_value and rely on
9009 * dst_reg var_off to refine the result.
9011 dst_reg->u32_min_value = 0;
9012 dst_reg->u32_max_value = U32_MAX;
9014 __mark_reg64_unbounded(dst_reg);
9015 __update_reg32_bounds(dst_reg);
9018 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
9019 struct bpf_reg_state *src_reg)
9021 u64 umin_val = src_reg->umin_value;
9023 /* Upon reaching here, src_known is true and umax_val is equal
9026 dst_reg->smin_value >>= umin_val;
9027 dst_reg->smax_value >>= umin_val;
9029 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
9031 /* blow away the dst_reg umin_value/umax_value and rely on
9032 * dst_reg var_off to refine the result.
9034 dst_reg->umin_value = 0;
9035 dst_reg->umax_value = U64_MAX;
9037 /* Its not easy to operate on alu32 bounds here because it depends
9038 * on bits being shifted in from upper 32-bits. Take easy way out
9039 * and mark unbounded so we can recalculate later from tnum.
9041 __mark_reg32_unbounded(dst_reg);
9042 __update_reg_bounds(dst_reg);
9045 /* WARNING: This function does calculations on 64-bit values, but the actual
9046 * execution may occur on 32-bit values. Therefore, things like bitshifts
9047 * need extra checks in the 32-bit case.
9049 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9050 struct bpf_insn *insn,
9051 struct bpf_reg_state *dst_reg,
9052 struct bpf_reg_state src_reg)
9054 struct bpf_reg_state *regs = cur_regs(env);
9055 u8 opcode = BPF_OP(insn->code);
9057 s64 smin_val, smax_val;
9058 u64 umin_val, umax_val;
9059 s32 s32_min_val, s32_max_val;
9060 u32 u32_min_val, u32_max_val;
9061 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9062 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9065 smin_val = src_reg.smin_value;
9066 smax_val = src_reg.smax_value;
9067 umin_val = src_reg.umin_value;
9068 umax_val = src_reg.umax_value;
9070 s32_min_val = src_reg.s32_min_value;
9071 s32_max_val = src_reg.s32_max_value;
9072 u32_min_val = src_reg.u32_min_value;
9073 u32_max_val = src_reg.u32_max_value;
9076 src_known = tnum_subreg_is_const(src_reg.var_off);
9078 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9079 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9080 /* Taint dst register if offset had invalid bounds
9081 * derived from e.g. dead branches.
9083 __mark_reg_unknown(env, dst_reg);
9087 src_known = tnum_is_const(src_reg.var_off);
9089 (smin_val != smax_val || umin_val != umax_val)) ||
9090 smin_val > smax_val || umin_val > umax_val) {
9091 /* Taint dst register if offset had invalid bounds
9092 * derived from e.g. dead branches.
9094 __mark_reg_unknown(env, dst_reg);
9100 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9101 __mark_reg_unknown(env, dst_reg);
9105 if (sanitize_needed(opcode)) {
9106 ret = sanitize_val_alu(env, insn);
9108 return sanitize_err(env, insn, ret, NULL, NULL);
9111 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9112 * There are two classes of instructions: The first class we track both
9113 * alu32 and alu64 sign/unsigned bounds independently this provides the
9114 * greatest amount of precision when alu operations are mixed with jmp32
9115 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9116 * and BPF_OR. This is possible because these ops have fairly easy to
9117 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9118 * See alu32 verifier tests for examples. The second class of
9119 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9120 * with regards to tracking sign/unsigned bounds because the bits may
9121 * cross subreg boundaries in the alu64 case. When this happens we mark
9122 * the reg unbounded in the subreg bound space and use the resulting
9123 * tnum to calculate an approximation of the sign/unsigned bounds.
9127 scalar32_min_max_add(dst_reg, &src_reg);
9128 scalar_min_max_add(dst_reg, &src_reg);
9129 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9132 scalar32_min_max_sub(dst_reg, &src_reg);
9133 scalar_min_max_sub(dst_reg, &src_reg);
9134 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9137 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9138 scalar32_min_max_mul(dst_reg, &src_reg);
9139 scalar_min_max_mul(dst_reg, &src_reg);
9142 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9143 scalar32_min_max_and(dst_reg, &src_reg);
9144 scalar_min_max_and(dst_reg, &src_reg);
9147 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9148 scalar32_min_max_or(dst_reg, &src_reg);
9149 scalar_min_max_or(dst_reg, &src_reg);
9152 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9153 scalar32_min_max_xor(dst_reg, &src_reg);
9154 scalar_min_max_xor(dst_reg, &src_reg);
9157 if (umax_val >= insn_bitness) {
9158 /* Shifts greater than 31 or 63 are undefined.
9159 * This includes shifts by a negative number.
9161 mark_reg_unknown(env, regs, insn->dst_reg);
9165 scalar32_min_max_lsh(dst_reg, &src_reg);
9167 scalar_min_max_lsh(dst_reg, &src_reg);
9170 if (umax_val >= insn_bitness) {
9171 /* Shifts greater than 31 or 63 are undefined.
9172 * This includes shifts by a negative number.
9174 mark_reg_unknown(env, regs, insn->dst_reg);
9178 scalar32_min_max_rsh(dst_reg, &src_reg);
9180 scalar_min_max_rsh(dst_reg, &src_reg);
9183 if (umax_val >= insn_bitness) {
9184 /* Shifts greater than 31 or 63 are undefined.
9185 * This includes shifts by a negative number.
9187 mark_reg_unknown(env, regs, insn->dst_reg);
9191 scalar32_min_max_arsh(dst_reg, &src_reg);
9193 scalar_min_max_arsh(dst_reg, &src_reg);
9196 mark_reg_unknown(env, regs, insn->dst_reg);
9200 /* ALU32 ops are zero extended into 64bit register */
9202 zext_32_to_64(dst_reg);
9203 reg_bounds_sync(dst_reg);
9207 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9210 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9211 struct bpf_insn *insn)
9213 struct bpf_verifier_state *vstate = env->cur_state;
9214 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9215 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9216 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9217 u8 opcode = BPF_OP(insn->code);
9220 dst_reg = ®s[insn->dst_reg];
9222 if (dst_reg->type != SCALAR_VALUE)
9225 /* Make sure ID is cleared otherwise dst_reg min/max could be
9226 * incorrectly propagated into other registers by find_equal_scalars()
9229 if (BPF_SRC(insn->code) == BPF_X) {
9230 src_reg = ®s[insn->src_reg];
9231 if (src_reg->type != SCALAR_VALUE) {
9232 if (dst_reg->type != SCALAR_VALUE) {
9233 /* Combining two pointers by any ALU op yields
9234 * an arbitrary scalar. Disallow all math except
9235 * pointer subtraction
9237 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9238 mark_reg_unknown(env, regs, insn->dst_reg);
9241 verbose(env, "R%d pointer %s pointer prohibited\n",
9243 bpf_alu_string[opcode >> 4]);
9246 /* scalar += pointer
9247 * This is legal, but we have to reverse our
9248 * src/dest handling in computing the range
9250 err = mark_chain_precision(env, insn->dst_reg);
9253 return adjust_ptr_min_max_vals(env, insn,
9256 } else if (ptr_reg) {
9257 /* pointer += scalar */
9258 err = mark_chain_precision(env, insn->src_reg);
9261 return adjust_ptr_min_max_vals(env, insn,
9263 } else if (dst_reg->precise) {
9264 /* if dst_reg is precise, src_reg should be precise as well */
9265 err = mark_chain_precision(env, insn->src_reg);
9270 /* Pretend the src is a reg with a known value, since we only
9271 * need to be able to read from this state.
9273 off_reg.type = SCALAR_VALUE;
9274 __mark_reg_known(&off_reg, insn->imm);
9276 if (ptr_reg) /* pointer += K */
9277 return adjust_ptr_min_max_vals(env, insn,
9281 /* Got here implies adding two SCALAR_VALUEs */
9282 if (WARN_ON_ONCE(ptr_reg)) {
9283 print_verifier_state(env, state, true);
9284 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9287 if (WARN_ON(!src_reg)) {
9288 print_verifier_state(env, state, true);
9289 verbose(env, "verifier internal error: no src_reg\n");
9292 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9295 /* check validity of 32-bit and 64-bit arithmetic operations */
9296 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9298 struct bpf_reg_state *regs = cur_regs(env);
9299 u8 opcode = BPF_OP(insn->code);
9302 if (opcode == BPF_END || opcode == BPF_NEG) {
9303 if (opcode == BPF_NEG) {
9304 if (BPF_SRC(insn->code) != BPF_K ||
9305 insn->src_reg != BPF_REG_0 ||
9306 insn->off != 0 || insn->imm != 0) {
9307 verbose(env, "BPF_NEG uses reserved fields\n");
9311 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9312 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9313 BPF_CLASS(insn->code) == BPF_ALU64) {
9314 verbose(env, "BPF_END uses reserved fields\n");
9319 /* check src operand */
9320 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9324 if (is_pointer_value(env, insn->dst_reg)) {
9325 verbose(env, "R%d pointer arithmetic prohibited\n",
9330 /* check dest operand */
9331 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9335 } else if (opcode == BPF_MOV) {
9337 if (BPF_SRC(insn->code) == BPF_X) {
9338 if (insn->imm != 0 || insn->off != 0) {
9339 verbose(env, "BPF_MOV uses reserved fields\n");
9343 /* check src operand */
9344 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9348 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9349 verbose(env, "BPF_MOV uses reserved fields\n");
9354 /* check dest operand, mark as required later */
9355 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9359 if (BPF_SRC(insn->code) == BPF_X) {
9360 struct bpf_reg_state *src_reg = regs + insn->src_reg;
9361 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9363 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9365 * copy register state to dest reg
9367 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9368 /* Assign src and dst registers the same ID
9369 * that will be used by find_equal_scalars()
9370 * to propagate min/max range.
9372 src_reg->id = ++env->id_gen;
9373 copy_register_state(dst_reg, src_reg);
9374 dst_reg->live |= REG_LIVE_WRITTEN;
9375 dst_reg->subreg_def = DEF_NOT_SUBREG;
9378 if (is_pointer_value(env, insn->src_reg)) {
9380 "R%d partial copy of pointer\n",
9383 } else if (src_reg->type == SCALAR_VALUE) {
9384 copy_register_state(dst_reg, src_reg);
9385 /* Make sure ID is cleared otherwise
9386 * dst_reg min/max could be incorrectly
9387 * propagated into src_reg by find_equal_scalars()
9390 dst_reg->live |= REG_LIVE_WRITTEN;
9391 dst_reg->subreg_def = env->insn_idx + 1;
9393 mark_reg_unknown(env, regs,
9396 zext_32_to_64(dst_reg);
9397 reg_bounds_sync(dst_reg);
9401 * remember the value we stored into this reg
9403 /* clear any state __mark_reg_known doesn't set */
9404 mark_reg_unknown(env, regs, insn->dst_reg);
9405 regs[insn->dst_reg].type = SCALAR_VALUE;
9406 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9407 __mark_reg_known(regs + insn->dst_reg,
9410 __mark_reg_known(regs + insn->dst_reg,
9415 } else if (opcode > BPF_END) {
9416 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9419 } else { /* all other ALU ops: and, sub, xor, add, ... */
9421 if (BPF_SRC(insn->code) == BPF_X) {
9422 if (insn->imm != 0 || insn->off != 0) {
9423 verbose(env, "BPF_ALU uses reserved fields\n");
9426 /* check src1 operand */
9427 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9431 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9432 verbose(env, "BPF_ALU uses reserved fields\n");
9437 /* check src2 operand */
9438 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9442 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9443 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9444 verbose(env, "div by zero\n");
9448 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9449 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9450 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9452 if (insn->imm < 0 || insn->imm >= size) {
9453 verbose(env, "invalid shift %d\n", insn->imm);
9458 /* check dest operand */
9459 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9463 return adjust_reg_min_max_vals(env, insn);
9469 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9470 struct bpf_reg_state *dst_reg,
9471 enum bpf_reg_type type,
9472 bool range_right_open)
9474 struct bpf_func_state *state;
9475 struct bpf_reg_state *reg;
9478 if (dst_reg->off < 0 ||
9479 (dst_reg->off == 0 && range_right_open))
9480 /* This doesn't give us any range */
9483 if (dst_reg->umax_value > MAX_PACKET_OFF ||
9484 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9485 /* Risk of overflow. For instance, ptr + (1<<63) may be less
9486 * than pkt_end, but that's because it's also less than pkt.
9490 new_range = dst_reg->off;
9491 if (range_right_open)
9494 /* Examples for register markings:
9496 * pkt_data in dst register:
9500 * if (r2 > pkt_end) goto <handle exception>
9505 * if (r2 < pkt_end) goto <access okay>
9506 * <handle exception>
9509 * r2 == dst_reg, pkt_end == src_reg
9510 * r2=pkt(id=n,off=8,r=0)
9511 * r3=pkt(id=n,off=0,r=0)
9513 * pkt_data in src register:
9517 * if (pkt_end >= r2) goto <access okay>
9518 * <handle exception>
9522 * if (pkt_end <= r2) goto <handle exception>
9526 * pkt_end == dst_reg, r2 == src_reg
9527 * r2=pkt(id=n,off=8,r=0)
9528 * r3=pkt(id=n,off=0,r=0)
9530 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9531 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9532 * and [r3, r3 + 8-1) respectively is safe to access depending on
9536 /* If our ids match, then we must have the same max_value. And we
9537 * don't care about the other reg's fixed offset, since if it's too big
9538 * the range won't allow anything.
9539 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9541 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9542 if (reg->type == type && reg->id == dst_reg->id)
9543 /* keep the maximum range already checked */
9544 reg->range = max(reg->range, new_range);
9548 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9550 struct tnum subreg = tnum_subreg(reg->var_off);
9551 s32 sval = (s32)val;
9555 if (tnum_is_const(subreg))
9556 return !!tnum_equals_const(subreg, val);
9559 if (tnum_is_const(subreg))
9560 return !tnum_equals_const(subreg, val);
9563 if ((~subreg.mask & subreg.value) & val)
9565 if (!((subreg.mask | subreg.value) & val))
9569 if (reg->u32_min_value > val)
9571 else if (reg->u32_max_value <= val)
9575 if (reg->s32_min_value > sval)
9577 else if (reg->s32_max_value <= sval)
9581 if (reg->u32_max_value < val)
9583 else if (reg->u32_min_value >= val)
9587 if (reg->s32_max_value < sval)
9589 else if (reg->s32_min_value >= sval)
9593 if (reg->u32_min_value >= val)
9595 else if (reg->u32_max_value < val)
9599 if (reg->s32_min_value >= sval)
9601 else if (reg->s32_max_value < sval)
9605 if (reg->u32_max_value <= val)
9607 else if (reg->u32_min_value > val)
9611 if (reg->s32_max_value <= sval)
9613 else if (reg->s32_min_value > sval)
9622 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9624 s64 sval = (s64)val;
9628 if (tnum_is_const(reg->var_off))
9629 return !!tnum_equals_const(reg->var_off, val);
9632 if (tnum_is_const(reg->var_off))
9633 return !tnum_equals_const(reg->var_off, val);
9636 if ((~reg->var_off.mask & reg->var_off.value) & val)
9638 if (!((reg->var_off.mask | reg->var_off.value) & val))
9642 if (reg->umin_value > val)
9644 else if (reg->umax_value <= val)
9648 if (reg->smin_value > sval)
9650 else if (reg->smax_value <= sval)
9654 if (reg->umax_value < val)
9656 else if (reg->umin_value >= val)
9660 if (reg->smax_value < sval)
9662 else if (reg->smin_value >= sval)
9666 if (reg->umin_value >= val)
9668 else if (reg->umax_value < val)
9672 if (reg->smin_value >= sval)
9674 else if (reg->smax_value < sval)
9678 if (reg->umax_value <= val)
9680 else if (reg->umin_value > val)
9684 if (reg->smax_value <= sval)
9686 else if (reg->smin_value > sval)
9694 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9696 * 1 - branch will be taken and "goto target" will be executed
9697 * 0 - branch will not be taken and fall-through to next insn
9698 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9701 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9704 if (__is_pointer_value(false, reg)) {
9705 if (!reg_type_not_null(reg->type))
9708 /* If pointer is valid tests against zero will fail so we can
9709 * use this to direct branch taken.
9725 return is_branch32_taken(reg, val, opcode);
9726 return is_branch64_taken(reg, val, opcode);
9729 static int flip_opcode(u32 opcode)
9731 /* How can we transform "a <op> b" into "b <op> a"? */
9732 static const u8 opcode_flip[16] = {
9733 /* these stay the same */
9734 [BPF_JEQ >> 4] = BPF_JEQ,
9735 [BPF_JNE >> 4] = BPF_JNE,
9736 [BPF_JSET >> 4] = BPF_JSET,
9737 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9738 [BPF_JGE >> 4] = BPF_JLE,
9739 [BPF_JGT >> 4] = BPF_JLT,
9740 [BPF_JLE >> 4] = BPF_JGE,
9741 [BPF_JLT >> 4] = BPF_JGT,
9742 [BPF_JSGE >> 4] = BPF_JSLE,
9743 [BPF_JSGT >> 4] = BPF_JSLT,
9744 [BPF_JSLE >> 4] = BPF_JSGE,
9745 [BPF_JSLT >> 4] = BPF_JSGT
9747 return opcode_flip[opcode >> 4];
9750 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9751 struct bpf_reg_state *src_reg,
9754 struct bpf_reg_state *pkt;
9756 if (src_reg->type == PTR_TO_PACKET_END) {
9758 } else if (dst_reg->type == PTR_TO_PACKET_END) {
9760 opcode = flip_opcode(opcode);
9765 if (pkt->range >= 0)
9770 /* pkt <= pkt_end */
9774 if (pkt->range == BEYOND_PKT_END)
9775 /* pkt has at last one extra byte beyond pkt_end */
9776 return opcode == BPF_JGT;
9782 /* pkt >= pkt_end */
9783 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9784 return opcode == BPF_JGE;
9790 /* Adjusts the register min/max values in the case that the dst_reg is the
9791 * variable register that we are working on, and src_reg is a constant or we're
9792 * simply doing a BPF_K check.
9793 * In JEQ/JNE cases we also adjust the var_off values.
9795 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9796 struct bpf_reg_state *false_reg,
9798 u8 opcode, bool is_jmp32)
9800 struct tnum false_32off = tnum_subreg(false_reg->var_off);
9801 struct tnum false_64off = false_reg->var_off;
9802 struct tnum true_32off = tnum_subreg(true_reg->var_off);
9803 struct tnum true_64off = true_reg->var_off;
9804 s64 sval = (s64)val;
9805 s32 sval32 = (s32)val32;
9807 /* If the dst_reg is a pointer, we can't learn anything about its
9808 * variable offset from the compare (unless src_reg were a pointer into
9809 * the same object, but we don't bother with that.
9810 * Since false_reg and true_reg have the same type by construction, we
9811 * only need to check one of them for pointerness.
9813 if (__is_pointer_value(false, false_reg))
9817 /* JEQ/JNE comparison doesn't change the register equivalence.
9820 * if (r1 == 42) goto label;
9822 * label: // here both r1 and r2 are known to be 42.
9824 * Hence when marking register as known preserve it's ID.
9828 __mark_reg32_known(true_reg, val32);
9829 true_32off = tnum_subreg(true_reg->var_off);
9831 ___mark_reg_known(true_reg, val);
9832 true_64off = true_reg->var_off;
9837 __mark_reg32_known(false_reg, val32);
9838 false_32off = tnum_subreg(false_reg->var_off);
9840 ___mark_reg_known(false_reg, val);
9841 false_64off = false_reg->var_off;
9846 false_32off = tnum_and(false_32off, tnum_const(~val32));
9847 if (is_power_of_2(val32))
9848 true_32off = tnum_or(true_32off,
9851 false_64off = tnum_and(false_64off, tnum_const(~val));
9852 if (is_power_of_2(val))
9853 true_64off = tnum_or(true_64off,
9861 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
9862 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9864 false_reg->u32_max_value = min(false_reg->u32_max_value,
9866 true_reg->u32_min_value = max(true_reg->u32_min_value,
9869 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
9870 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9872 false_reg->umax_value = min(false_reg->umax_value, false_umax);
9873 true_reg->umin_value = max(true_reg->umin_value, true_umin);
9881 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
9882 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9884 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9885 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9887 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
9888 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9890 false_reg->smax_value = min(false_reg->smax_value, false_smax);
9891 true_reg->smin_value = max(true_reg->smin_value, true_smin);
9899 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
9900 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9902 false_reg->u32_min_value = max(false_reg->u32_min_value,
9904 true_reg->u32_max_value = min(true_reg->u32_max_value,
9907 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
9908 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9910 false_reg->umin_value = max(false_reg->umin_value, false_umin);
9911 true_reg->umax_value = min(true_reg->umax_value, true_umax);
9919 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
9920 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9922 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9923 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9925 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
9926 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9928 false_reg->smin_value = max(false_reg->smin_value, false_smin);
9929 true_reg->smax_value = min(true_reg->smax_value, true_smax);
9938 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9939 tnum_subreg(false_32off));
9940 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9941 tnum_subreg(true_32off));
9942 __reg_combine_32_into_64(false_reg);
9943 __reg_combine_32_into_64(true_reg);
9945 false_reg->var_off = false_64off;
9946 true_reg->var_off = true_64off;
9947 __reg_combine_64_into_32(false_reg);
9948 __reg_combine_64_into_32(true_reg);
9952 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9955 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9956 struct bpf_reg_state *false_reg,
9958 u8 opcode, bool is_jmp32)
9960 opcode = flip_opcode(opcode);
9961 /* This uses zero as "not present in table"; luckily the zero opcode,
9962 * BPF_JA, can't get here.
9965 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9968 /* Regs are known to be equal, so intersect their min/max/var_off */
9969 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9970 struct bpf_reg_state *dst_reg)
9972 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9973 dst_reg->umin_value);
9974 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9975 dst_reg->umax_value);
9976 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9977 dst_reg->smin_value);
9978 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9979 dst_reg->smax_value);
9980 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9982 reg_bounds_sync(src_reg);
9983 reg_bounds_sync(dst_reg);
9986 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9987 struct bpf_reg_state *true_dst,
9988 struct bpf_reg_state *false_src,
9989 struct bpf_reg_state *false_dst,
9994 __reg_combine_min_max(true_src, true_dst);
9997 __reg_combine_min_max(false_src, false_dst);
10002 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
10003 struct bpf_reg_state *reg, u32 id,
10006 if (type_may_be_null(reg->type) && reg->id == id &&
10007 !WARN_ON_ONCE(!reg->id)) {
10008 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
10009 !tnum_equals_const(reg->var_off, 0) ||
10011 /* Old offset (both fixed and variable parts) should
10012 * have been known-zero, because we don't allow pointer
10013 * arithmetic on pointers that might be NULL. If we
10014 * see this happening, don't convert the register.
10019 reg->type = SCALAR_VALUE;
10020 /* We don't need id and ref_obj_id from this point
10021 * onwards anymore, thus we should better reset it,
10022 * so that state pruning has chances to take effect.
10025 reg->ref_obj_id = 0;
10030 mark_ptr_not_null_reg(reg);
10032 if (!reg_may_point_to_spin_lock(reg)) {
10033 /* For not-NULL ptr, reg->ref_obj_id will be reset
10034 * in release_reference().
10036 * reg->id is still used by spin_lock ptr. Other
10037 * than spin_lock ptr type, reg->id can be reset.
10044 /* The logic is similar to find_good_pkt_pointers(), both could eventually
10045 * be folded together at some point.
10047 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
10050 struct bpf_func_state *state = vstate->frame[vstate->curframe];
10051 struct bpf_reg_state *regs = state->regs, *reg;
10052 u32 ref_obj_id = regs[regno].ref_obj_id;
10053 u32 id = regs[regno].id;
10055 if (ref_obj_id && ref_obj_id == id && is_null)
10056 /* regs[regno] is in the " == NULL" branch.
10057 * No one could have freed the reference state before
10058 * doing the NULL check.
10060 WARN_ON_ONCE(release_reference_state(state, id));
10062 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10063 mark_ptr_or_null_reg(state, reg, id, is_null);
10067 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10068 struct bpf_reg_state *dst_reg,
10069 struct bpf_reg_state *src_reg,
10070 struct bpf_verifier_state *this_branch,
10071 struct bpf_verifier_state *other_branch)
10073 if (BPF_SRC(insn->code) != BPF_X)
10076 /* Pointers are always 64-bit. */
10077 if (BPF_CLASS(insn->code) == BPF_JMP32)
10080 switch (BPF_OP(insn->code)) {
10082 if ((dst_reg->type == PTR_TO_PACKET &&
10083 src_reg->type == PTR_TO_PACKET_END) ||
10084 (dst_reg->type == PTR_TO_PACKET_META &&
10085 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10086 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10087 find_good_pkt_pointers(this_branch, dst_reg,
10088 dst_reg->type, false);
10089 mark_pkt_end(other_branch, insn->dst_reg, true);
10090 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10091 src_reg->type == PTR_TO_PACKET) ||
10092 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10093 src_reg->type == PTR_TO_PACKET_META)) {
10094 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
10095 find_good_pkt_pointers(other_branch, src_reg,
10096 src_reg->type, true);
10097 mark_pkt_end(this_branch, insn->src_reg, false);
10103 if ((dst_reg->type == PTR_TO_PACKET &&
10104 src_reg->type == PTR_TO_PACKET_END) ||
10105 (dst_reg->type == PTR_TO_PACKET_META &&
10106 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10107 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10108 find_good_pkt_pointers(other_branch, dst_reg,
10109 dst_reg->type, true);
10110 mark_pkt_end(this_branch, insn->dst_reg, false);
10111 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10112 src_reg->type == PTR_TO_PACKET) ||
10113 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10114 src_reg->type == PTR_TO_PACKET_META)) {
10115 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
10116 find_good_pkt_pointers(this_branch, src_reg,
10117 src_reg->type, false);
10118 mark_pkt_end(other_branch, insn->src_reg, true);
10124 if ((dst_reg->type == PTR_TO_PACKET &&
10125 src_reg->type == PTR_TO_PACKET_END) ||
10126 (dst_reg->type == PTR_TO_PACKET_META &&
10127 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10128 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10129 find_good_pkt_pointers(this_branch, dst_reg,
10130 dst_reg->type, true);
10131 mark_pkt_end(other_branch, insn->dst_reg, false);
10132 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10133 src_reg->type == PTR_TO_PACKET) ||
10134 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10135 src_reg->type == PTR_TO_PACKET_META)) {
10136 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10137 find_good_pkt_pointers(other_branch, src_reg,
10138 src_reg->type, false);
10139 mark_pkt_end(this_branch, insn->src_reg, true);
10145 if ((dst_reg->type == PTR_TO_PACKET &&
10146 src_reg->type == PTR_TO_PACKET_END) ||
10147 (dst_reg->type == PTR_TO_PACKET_META &&
10148 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10149 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10150 find_good_pkt_pointers(other_branch, dst_reg,
10151 dst_reg->type, false);
10152 mark_pkt_end(this_branch, insn->dst_reg, true);
10153 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10154 src_reg->type == PTR_TO_PACKET) ||
10155 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10156 src_reg->type == PTR_TO_PACKET_META)) {
10157 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10158 find_good_pkt_pointers(this_branch, src_reg,
10159 src_reg->type, true);
10160 mark_pkt_end(other_branch, insn->src_reg, false);
10172 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10173 struct bpf_reg_state *known_reg)
10175 struct bpf_func_state *state;
10176 struct bpf_reg_state *reg;
10178 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10179 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10180 copy_register_state(reg, known_reg);
10184 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10185 struct bpf_insn *insn, int *insn_idx)
10187 struct bpf_verifier_state *this_branch = env->cur_state;
10188 struct bpf_verifier_state *other_branch;
10189 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10190 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10191 u8 opcode = BPF_OP(insn->code);
10196 /* Only conditional jumps are expected to reach here. */
10197 if (opcode == BPF_JA || opcode > BPF_JSLE) {
10198 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10202 if (BPF_SRC(insn->code) == BPF_X) {
10203 if (insn->imm != 0) {
10204 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10208 /* check src1 operand */
10209 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10213 if (is_pointer_value(env, insn->src_reg)) {
10214 verbose(env, "R%d pointer comparison prohibited\n",
10218 src_reg = ®s[insn->src_reg];
10220 if (insn->src_reg != BPF_REG_0) {
10221 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10226 /* check src2 operand */
10227 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10231 dst_reg = ®s[insn->dst_reg];
10232 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10234 if (BPF_SRC(insn->code) == BPF_K) {
10235 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10236 } else if (src_reg->type == SCALAR_VALUE &&
10237 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10238 pred = is_branch_taken(dst_reg,
10239 tnum_subreg(src_reg->var_off).value,
10242 } else if (src_reg->type == SCALAR_VALUE &&
10243 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10244 pred = is_branch_taken(dst_reg,
10245 src_reg->var_off.value,
10248 } else if (reg_is_pkt_pointer_any(dst_reg) &&
10249 reg_is_pkt_pointer_any(src_reg) &&
10251 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10255 /* If we get here with a dst_reg pointer type it is because
10256 * above is_branch_taken() special cased the 0 comparison.
10258 if (!__is_pointer_value(false, dst_reg))
10259 err = mark_chain_precision(env, insn->dst_reg);
10260 if (BPF_SRC(insn->code) == BPF_X && !err &&
10261 !__is_pointer_value(false, src_reg))
10262 err = mark_chain_precision(env, insn->src_reg);
10268 /* Only follow the goto, ignore fall-through. If needed, push
10269 * the fall-through branch for simulation under speculative
10272 if (!env->bypass_spec_v1 &&
10273 !sanitize_speculative_path(env, insn, *insn_idx + 1,
10276 *insn_idx += insn->off;
10278 } else if (pred == 0) {
10279 /* Only follow the fall-through branch, since that's where the
10280 * program will go. If needed, push the goto branch for
10281 * simulation under speculative execution.
10283 if (!env->bypass_spec_v1 &&
10284 !sanitize_speculative_path(env, insn,
10285 *insn_idx + insn->off + 1,
10291 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10295 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10297 /* detect if we are comparing against a constant value so we can adjust
10298 * our min/max values for our dst register.
10299 * this is only legit if both are scalars (or pointers to the same
10300 * object, I suppose, but we don't support that right now), because
10301 * otherwise the different base pointers mean the offsets aren't
10304 if (BPF_SRC(insn->code) == BPF_X) {
10305 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
10307 if (dst_reg->type == SCALAR_VALUE &&
10308 src_reg->type == SCALAR_VALUE) {
10309 if (tnum_is_const(src_reg->var_off) ||
10311 tnum_is_const(tnum_subreg(src_reg->var_off))))
10312 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10314 src_reg->var_off.value,
10315 tnum_subreg(src_reg->var_off).value,
10317 else if (tnum_is_const(dst_reg->var_off) ||
10319 tnum_is_const(tnum_subreg(dst_reg->var_off))))
10320 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10322 dst_reg->var_off.value,
10323 tnum_subreg(dst_reg->var_off).value,
10325 else if (!is_jmp32 &&
10326 (opcode == BPF_JEQ || opcode == BPF_JNE))
10327 /* Comparing for equality, we can combine knowledge */
10328 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10329 &other_branch_regs[insn->dst_reg],
10330 src_reg, dst_reg, opcode);
10332 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10333 find_equal_scalars(this_branch, src_reg);
10334 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10338 } else if (dst_reg->type == SCALAR_VALUE) {
10339 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10340 dst_reg, insn->imm, (u32)insn->imm,
10344 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10345 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10346 find_equal_scalars(this_branch, dst_reg);
10347 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10350 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10351 * NOTE: these optimizations below are related with pointer comparison
10352 * which will never be JMP32.
10354 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10355 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10356 type_may_be_null(dst_reg->type)) {
10357 /* Mark all identical registers in each branch as either
10358 * safe or unknown depending R == 0 or R != 0 conditional.
10360 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10361 opcode == BPF_JNE);
10362 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10363 opcode == BPF_JEQ);
10364 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
10365 this_branch, other_branch) &&
10366 is_pointer_value(env, insn->dst_reg)) {
10367 verbose(env, "R%d pointer comparison prohibited\n",
10371 if (env->log.level & BPF_LOG_LEVEL)
10372 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10376 /* verify BPF_LD_IMM64 instruction */
10377 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10379 struct bpf_insn_aux_data *aux = cur_aux(env);
10380 struct bpf_reg_state *regs = cur_regs(env);
10381 struct bpf_reg_state *dst_reg;
10382 struct bpf_map *map;
10385 if (BPF_SIZE(insn->code) != BPF_DW) {
10386 verbose(env, "invalid BPF_LD_IMM insn\n");
10389 if (insn->off != 0) {
10390 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10394 err = check_reg_arg(env, insn->dst_reg, DST_OP);
10398 dst_reg = ®s[insn->dst_reg];
10399 if (insn->src_reg == 0) {
10400 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10402 dst_reg->type = SCALAR_VALUE;
10403 __mark_reg_known(®s[insn->dst_reg], imm);
10407 /* All special src_reg cases are listed below. From this point onwards
10408 * we either succeed and assign a corresponding dst_reg->type after
10409 * zeroing the offset, or fail and reject the program.
10411 mark_reg_known_zero(env, regs, insn->dst_reg);
10413 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10414 dst_reg->type = aux->btf_var.reg_type;
10415 switch (base_type(dst_reg->type)) {
10417 dst_reg->mem_size = aux->btf_var.mem_size;
10419 case PTR_TO_BTF_ID:
10420 dst_reg->btf = aux->btf_var.btf;
10421 dst_reg->btf_id = aux->btf_var.btf_id;
10424 verbose(env, "bpf verifier is misconfigured\n");
10430 if (insn->src_reg == BPF_PSEUDO_FUNC) {
10431 struct bpf_prog_aux *aux = env->prog->aux;
10432 u32 subprogno = find_subprog(env,
10433 env->insn_idx + insn->imm + 1);
10435 if (!aux->func_info) {
10436 verbose(env, "missing btf func_info\n");
10439 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10440 verbose(env, "callback function not static\n");
10444 dst_reg->type = PTR_TO_FUNC;
10445 dst_reg->subprogno = subprogno;
10449 map = env->used_maps[aux->map_index];
10450 dst_reg->map_ptr = map;
10452 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10453 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10454 dst_reg->type = PTR_TO_MAP_VALUE;
10455 dst_reg->off = aux->map_off;
10456 if (map_value_has_spin_lock(map))
10457 dst_reg->id = ++env->id_gen;
10458 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10459 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10460 dst_reg->type = CONST_PTR_TO_MAP;
10462 verbose(env, "bpf verifier is misconfigured\n");
10469 static bool may_access_skb(enum bpf_prog_type type)
10472 case BPF_PROG_TYPE_SOCKET_FILTER:
10473 case BPF_PROG_TYPE_SCHED_CLS:
10474 case BPF_PROG_TYPE_SCHED_ACT:
10481 /* verify safety of LD_ABS|LD_IND instructions:
10482 * - they can only appear in the programs where ctx == skb
10483 * - since they are wrappers of function calls, they scratch R1-R5 registers,
10484 * preserve R6-R9, and store return value into R0
10487 * ctx == skb == R6 == CTX
10490 * SRC == any register
10491 * IMM == 32-bit immediate
10494 * R0 - 8/16/32-bit skb data converted to cpu endianness
10496 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10498 struct bpf_reg_state *regs = cur_regs(env);
10499 static const int ctx_reg = BPF_REG_6;
10500 u8 mode = BPF_MODE(insn->code);
10503 if (!may_access_skb(resolve_prog_type(env->prog))) {
10504 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10508 if (!env->ops->gen_ld_abs) {
10509 verbose(env, "bpf verifier is misconfigured\n");
10513 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10514 BPF_SIZE(insn->code) == BPF_DW ||
10515 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10516 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10520 /* check whether implicit source operand (register R6) is readable */
10521 err = check_reg_arg(env, ctx_reg, SRC_OP);
10525 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10526 * gen_ld_abs() may terminate the program at runtime, leading to
10529 err = check_reference_leak(env);
10531 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10535 if (env->cur_state->active_spin_lock) {
10536 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10540 if (regs[ctx_reg].type != PTR_TO_CTX) {
10542 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10546 if (mode == BPF_IND) {
10547 /* check explicit source operand */
10548 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10553 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
10557 /* reset caller saved regs to unreadable */
10558 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10559 mark_reg_not_init(env, regs, caller_saved[i]);
10560 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10563 /* mark destination R0 register as readable, since it contains
10564 * the value fetched from the packet.
10565 * Already marked as written above.
10567 mark_reg_unknown(env, regs, BPF_REG_0);
10568 /* ld_abs load up to 32-bit skb data. */
10569 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10573 static int check_return_code(struct bpf_verifier_env *env)
10575 struct tnum enforce_attach_type_range = tnum_unknown;
10576 const struct bpf_prog *prog = env->prog;
10577 struct bpf_reg_state *reg;
10578 struct tnum range = tnum_range(0, 1);
10579 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10581 struct bpf_func_state *frame = env->cur_state->frame[0];
10582 const bool is_subprog = frame->subprogno;
10584 /* LSM and struct_ops func-ptr's return type could be "void" */
10586 switch (prog_type) {
10587 case BPF_PROG_TYPE_LSM:
10588 if (prog->expected_attach_type == BPF_LSM_CGROUP)
10589 /* See below, can be 0 or 0-1 depending on hook. */
10592 case BPF_PROG_TYPE_STRUCT_OPS:
10593 if (!prog->aux->attach_func_proto->type)
10601 /* eBPF calling convention is such that R0 is used
10602 * to return the value from eBPF program.
10603 * Make sure that it's readable at this time
10604 * of bpf_exit, which means that program wrote
10605 * something into it earlier
10607 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10611 if (is_pointer_value(env, BPF_REG_0)) {
10612 verbose(env, "R0 leaks addr as return value\n");
10616 reg = cur_regs(env) + BPF_REG_0;
10618 if (frame->in_async_callback_fn) {
10619 /* enforce return zero from async callbacks like timer */
10620 if (reg->type != SCALAR_VALUE) {
10621 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10622 reg_type_str(env, reg->type));
10626 if (!tnum_in(tnum_const(0), reg->var_off)) {
10627 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10634 if (reg->type != SCALAR_VALUE) {
10635 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10636 reg_type_str(env, reg->type));
10642 switch (prog_type) {
10643 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10644 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10645 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10646 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10647 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10648 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10649 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10650 range = tnum_range(1, 1);
10651 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10652 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10653 range = tnum_range(0, 3);
10655 case BPF_PROG_TYPE_CGROUP_SKB:
10656 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10657 range = tnum_range(0, 3);
10658 enforce_attach_type_range = tnum_range(2, 3);
10661 case BPF_PROG_TYPE_CGROUP_SOCK:
10662 case BPF_PROG_TYPE_SOCK_OPS:
10663 case BPF_PROG_TYPE_CGROUP_DEVICE:
10664 case BPF_PROG_TYPE_CGROUP_SYSCTL:
10665 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10667 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10668 if (!env->prog->aux->attach_btf_id)
10670 range = tnum_const(0);
10672 case BPF_PROG_TYPE_TRACING:
10673 switch (env->prog->expected_attach_type) {
10674 case BPF_TRACE_FENTRY:
10675 case BPF_TRACE_FEXIT:
10676 range = tnum_const(0);
10678 case BPF_TRACE_RAW_TP:
10679 case BPF_MODIFY_RETURN:
10681 case BPF_TRACE_ITER:
10687 case BPF_PROG_TYPE_SK_LOOKUP:
10688 range = tnum_range(SK_DROP, SK_PASS);
10691 case BPF_PROG_TYPE_LSM:
10692 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10693 /* Regular BPF_PROG_TYPE_LSM programs can return
10698 if (!env->prog->aux->attach_func_proto->type) {
10699 /* Make sure programs that attach to void
10700 * hooks don't try to modify return value.
10702 range = tnum_range(1, 1);
10706 case BPF_PROG_TYPE_EXT:
10707 /* freplace program can return anything as its return value
10708 * depends on the to-be-replaced kernel func or bpf program.
10714 if (reg->type != SCALAR_VALUE) {
10715 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10716 reg_type_str(env, reg->type));
10720 if (!tnum_in(range, reg->var_off)) {
10721 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10722 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10723 prog_type == BPF_PROG_TYPE_LSM &&
10724 !prog->aux->attach_func_proto->type)
10725 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10729 if (!tnum_is_unknown(enforce_attach_type_range) &&
10730 tnum_in(enforce_attach_type_range, reg->var_off))
10731 env->prog->enforce_expected_attach_type = 1;
10735 /* non-recursive DFS pseudo code
10736 * 1 procedure DFS-iterative(G,v):
10737 * 2 label v as discovered
10738 * 3 let S be a stack
10740 * 5 while S is not empty
10742 * 7 if t is what we're looking for:
10744 * 9 for all edges e in G.adjacentEdges(t) do
10745 * 10 if edge e is already labelled
10746 * 11 continue with the next edge
10747 * 12 w <- G.adjacentVertex(t,e)
10748 * 13 if vertex w is not discovered and not explored
10749 * 14 label e as tree-edge
10750 * 15 label w as discovered
10753 * 18 else if vertex w is discovered
10754 * 19 label e as back-edge
10756 * 21 // vertex w is explored
10757 * 22 label e as forward- or cross-edge
10758 * 23 label t as explored
10762 * 0x10 - discovered
10763 * 0x11 - discovered and fall-through edge labelled
10764 * 0x12 - discovered and fall-through and branch edges labelled
10775 static u32 state_htab_size(struct bpf_verifier_env *env)
10777 return env->prog->len;
10780 static struct bpf_verifier_state_list **explored_state(
10781 struct bpf_verifier_env *env,
10784 struct bpf_verifier_state *cur = env->cur_state;
10785 struct bpf_func_state *state = cur->frame[cur->curframe];
10787 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10790 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10792 env->insn_aux_data[idx].prune_point = true;
10796 DONE_EXPLORING = 0,
10797 KEEP_EXPLORING = 1,
10800 /* t, w, e - match pseudo-code above:
10801 * t - index of current instruction
10802 * w - next instruction
10805 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10808 int *insn_stack = env->cfg.insn_stack;
10809 int *insn_state = env->cfg.insn_state;
10811 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10812 return DONE_EXPLORING;
10814 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10815 return DONE_EXPLORING;
10817 if (w < 0 || w >= env->prog->len) {
10818 verbose_linfo(env, t, "%d: ", t);
10819 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10824 /* mark branch target for state pruning */
10825 init_explored_state(env, w);
10827 if (insn_state[w] == 0) {
10829 insn_state[t] = DISCOVERED | e;
10830 insn_state[w] = DISCOVERED;
10831 if (env->cfg.cur_stack >= env->prog->len)
10833 insn_stack[env->cfg.cur_stack++] = w;
10834 return KEEP_EXPLORING;
10835 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10836 if (loop_ok && env->bpf_capable)
10837 return DONE_EXPLORING;
10838 verbose_linfo(env, t, "%d: ", t);
10839 verbose_linfo(env, w, "%d: ", w);
10840 verbose(env, "back-edge from insn %d to %d\n", t, w);
10842 } else if (insn_state[w] == EXPLORED) {
10843 /* forward- or cross-edge */
10844 insn_state[t] = DISCOVERED | e;
10846 verbose(env, "insn state internal bug\n");
10849 return DONE_EXPLORING;
10852 static int visit_func_call_insn(int t, int insn_cnt,
10853 struct bpf_insn *insns,
10854 struct bpf_verifier_env *env,
10859 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10863 if (t + 1 < insn_cnt)
10864 init_explored_state(env, t + 1);
10865 if (visit_callee) {
10866 init_explored_state(env, t);
10867 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10868 /* It's ok to allow recursion from CFG point of
10869 * view. __check_func_call() will do the actual
10872 bpf_pseudo_func(insns + t));
10877 /* Visits the instruction at index t and returns one of the following:
10878 * < 0 - an error occurred
10879 * DONE_EXPLORING - the instruction was fully explored
10880 * KEEP_EXPLORING - there is still work to be done before it is fully explored
10882 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10884 struct bpf_insn *insns = env->prog->insnsi;
10887 if (bpf_pseudo_func(insns + t))
10888 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10890 /* All non-branch instructions have a single fall-through edge. */
10891 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10892 BPF_CLASS(insns[t].code) != BPF_JMP32)
10893 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10895 switch (BPF_OP(insns[t].code)) {
10897 return DONE_EXPLORING;
10900 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10901 /* Mark this call insn to trigger is_state_visited() check
10902 * before call itself is processed by __check_func_call().
10903 * Otherwise new async state will be pushed for further
10906 init_explored_state(env, t);
10907 return visit_func_call_insn(t, insn_cnt, insns, env,
10908 insns[t].src_reg == BPF_PSEUDO_CALL);
10911 if (BPF_SRC(insns[t].code) != BPF_K)
10914 /* unconditional jump with single edge */
10915 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10920 /* unconditional jmp is not a good pruning point,
10921 * but it's marked, since backtracking needs
10922 * to record jmp history in is_state_visited().
10924 init_explored_state(env, t + insns[t].off + 1);
10925 /* tell verifier to check for equivalent states
10926 * after every call and jump
10928 if (t + 1 < insn_cnt)
10929 init_explored_state(env, t + 1);
10934 /* conditional jump with two edges */
10935 init_explored_state(env, t);
10936 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10940 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10944 /* non-recursive depth-first-search to detect loops in BPF program
10945 * loop == back-edge in directed graph
10947 static int check_cfg(struct bpf_verifier_env *env)
10949 int insn_cnt = env->prog->len;
10950 int *insn_stack, *insn_state;
10954 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10958 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10960 kvfree(insn_state);
10964 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10965 insn_stack[0] = 0; /* 0 is the first instruction */
10966 env->cfg.cur_stack = 1;
10968 while (env->cfg.cur_stack > 0) {
10969 int t = insn_stack[env->cfg.cur_stack - 1];
10971 ret = visit_insn(t, insn_cnt, env);
10973 case DONE_EXPLORING:
10974 insn_state[t] = EXPLORED;
10975 env->cfg.cur_stack--;
10977 case KEEP_EXPLORING:
10981 verbose(env, "visit_insn internal bug\n");
10988 if (env->cfg.cur_stack < 0) {
10989 verbose(env, "pop stack internal bug\n");
10994 for (i = 0; i < insn_cnt; i++) {
10995 if (insn_state[i] != EXPLORED) {
10996 verbose(env, "unreachable insn %d\n", i);
11001 ret = 0; /* cfg looks good */
11004 kvfree(insn_state);
11005 kvfree(insn_stack);
11006 env->cfg.insn_state = env->cfg.insn_stack = NULL;
11010 static int check_abnormal_return(struct bpf_verifier_env *env)
11014 for (i = 1; i < env->subprog_cnt; i++) {
11015 if (env->subprog_info[i].has_ld_abs) {
11016 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
11019 if (env->subprog_info[i].has_tail_call) {
11020 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
11027 /* The minimum supported BTF func info size */
11028 #define MIN_BPF_FUNCINFO_SIZE 8
11029 #define MAX_FUNCINFO_REC_SIZE 252
11031 static int check_btf_func(struct bpf_verifier_env *env,
11032 const union bpf_attr *attr,
11035 const struct btf_type *type, *func_proto, *ret_type;
11036 u32 i, nfuncs, urec_size, min_size;
11037 u32 krec_size = sizeof(struct bpf_func_info);
11038 struct bpf_func_info *krecord;
11039 struct bpf_func_info_aux *info_aux = NULL;
11040 struct bpf_prog *prog;
11041 const struct btf *btf;
11043 u32 prev_offset = 0;
11044 bool scalar_return;
11047 nfuncs = attr->func_info_cnt;
11049 if (check_abnormal_return(env))
11054 if (nfuncs != env->subprog_cnt) {
11055 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11059 urec_size = attr->func_info_rec_size;
11060 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11061 urec_size > MAX_FUNCINFO_REC_SIZE ||
11062 urec_size % sizeof(u32)) {
11063 verbose(env, "invalid func info rec size %u\n", urec_size);
11068 btf = prog->aux->btf;
11070 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11071 min_size = min_t(u32, krec_size, urec_size);
11073 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11076 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11080 for (i = 0; i < nfuncs; i++) {
11081 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11083 if (ret == -E2BIG) {
11084 verbose(env, "nonzero tailing record in func info");
11085 /* set the size kernel expects so loader can zero
11086 * out the rest of the record.
11088 if (copy_to_bpfptr_offset(uattr,
11089 offsetof(union bpf_attr, func_info_rec_size),
11090 &min_size, sizeof(min_size)))
11096 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11101 /* check insn_off */
11104 if (krecord[i].insn_off) {
11106 "nonzero insn_off %u for the first func info record",
11107 krecord[i].insn_off);
11110 } else if (krecord[i].insn_off <= prev_offset) {
11112 "same or smaller insn offset (%u) than previous func info record (%u)",
11113 krecord[i].insn_off, prev_offset);
11117 if (env->subprog_info[i].start != krecord[i].insn_off) {
11118 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11122 /* check type_id */
11123 type = btf_type_by_id(btf, krecord[i].type_id);
11124 if (!type || !btf_type_is_func(type)) {
11125 verbose(env, "invalid type id %d in func info",
11126 krecord[i].type_id);
11129 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11131 func_proto = btf_type_by_id(btf, type->type);
11132 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11133 /* btf_func_check() already verified it during BTF load */
11135 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11137 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11138 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11139 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11142 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11143 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11147 prev_offset = krecord[i].insn_off;
11148 bpfptr_add(&urecord, urec_size);
11151 prog->aux->func_info = krecord;
11152 prog->aux->func_info_cnt = nfuncs;
11153 prog->aux->func_info_aux = info_aux;
11162 static void adjust_btf_func(struct bpf_verifier_env *env)
11164 struct bpf_prog_aux *aux = env->prog->aux;
11167 if (!aux->func_info)
11170 for (i = 0; i < env->subprog_cnt; i++)
11171 aux->func_info[i].insn_off = env->subprog_info[i].start;
11174 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
11175 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
11177 static int check_btf_line(struct bpf_verifier_env *env,
11178 const union bpf_attr *attr,
11181 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11182 struct bpf_subprog_info *sub;
11183 struct bpf_line_info *linfo;
11184 struct bpf_prog *prog;
11185 const struct btf *btf;
11189 nr_linfo = attr->line_info_cnt;
11192 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11195 rec_size = attr->line_info_rec_size;
11196 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11197 rec_size > MAX_LINEINFO_REC_SIZE ||
11198 rec_size & (sizeof(u32) - 1))
11201 /* Need to zero it in case the userspace may
11202 * pass in a smaller bpf_line_info object.
11204 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11205 GFP_KERNEL | __GFP_NOWARN);
11210 btf = prog->aux->btf;
11213 sub = env->subprog_info;
11214 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11215 expected_size = sizeof(struct bpf_line_info);
11216 ncopy = min_t(u32, expected_size, rec_size);
11217 for (i = 0; i < nr_linfo; i++) {
11218 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11220 if (err == -E2BIG) {
11221 verbose(env, "nonzero tailing record in line_info");
11222 if (copy_to_bpfptr_offset(uattr,
11223 offsetof(union bpf_attr, line_info_rec_size),
11224 &expected_size, sizeof(expected_size)))
11230 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11236 * Check insn_off to ensure
11237 * 1) strictly increasing AND
11238 * 2) bounded by prog->len
11240 * The linfo[0].insn_off == 0 check logically falls into
11241 * the later "missing bpf_line_info for func..." case
11242 * because the first linfo[0].insn_off must be the
11243 * first sub also and the first sub must have
11244 * subprog_info[0].start == 0.
11246 if ((i && linfo[i].insn_off <= prev_offset) ||
11247 linfo[i].insn_off >= prog->len) {
11248 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11249 i, linfo[i].insn_off, prev_offset,
11255 if (!prog->insnsi[linfo[i].insn_off].code) {
11257 "Invalid insn code at line_info[%u].insn_off\n",
11263 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11264 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11265 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11270 if (s != env->subprog_cnt) {
11271 if (linfo[i].insn_off == sub[s].start) {
11272 sub[s].linfo_idx = i;
11274 } else if (sub[s].start < linfo[i].insn_off) {
11275 verbose(env, "missing bpf_line_info for func#%u\n", s);
11281 prev_offset = linfo[i].insn_off;
11282 bpfptr_add(&ulinfo, rec_size);
11285 if (s != env->subprog_cnt) {
11286 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11287 env->subprog_cnt - s, s);
11292 prog->aux->linfo = linfo;
11293 prog->aux->nr_linfo = nr_linfo;
11302 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
11303 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
11305 static int check_core_relo(struct bpf_verifier_env *env,
11306 const union bpf_attr *attr,
11309 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11310 struct bpf_core_relo core_relo = {};
11311 struct bpf_prog *prog = env->prog;
11312 const struct btf *btf = prog->aux->btf;
11313 struct bpf_core_ctx ctx = {
11317 bpfptr_t u_core_relo;
11320 nr_core_relo = attr->core_relo_cnt;
11323 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11326 rec_size = attr->core_relo_rec_size;
11327 if (rec_size < MIN_CORE_RELO_SIZE ||
11328 rec_size > MAX_CORE_RELO_SIZE ||
11329 rec_size % sizeof(u32))
11332 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11333 expected_size = sizeof(struct bpf_core_relo);
11334 ncopy = min_t(u32, expected_size, rec_size);
11336 /* Unlike func_info and line_info, copy and apply each CO-RE
11337 * relocation record one at a time.
11339 for (i = 0; i < nr_core_relo; i++) {
11340 /* future proofing when sizeof(bpf_core_relo) changes */
11341 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11343 if (err == -E2BIG) {
11344 verbose(env, "nonzero tailing record in core_relo");
11345 if (copy_to_bpfptr_offset(uattr,
11346 offsetof(union bpf_attr, core_relo_rec_size),
11347 &expected_size, sizeof(expected_size)))
11353 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11358 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11359 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11360 i, core_relo.insn_off, prog->len);
11365 err = bpf_core_apply(&ctx, &core_relo, i,
11366 &prog->insnsi[core_relo.insn_off / 8]);
11369 bpfptr_add(&u_core_relo, rec_size);
11374 static int check_btf_info(struct bpf_verifier_env *env,
11375 const union bpf_attr *attr,
11381 if (!attr->func_info_cnt && !attr->line_info_cnt) {
11382 if (check_abnormal_return(env))
11387 btf = btf_get_by_fd(attr->prog_btf_fd);
11389 return PTR_ERR(btf);
11390 if (btf_is_kernel(btf)) {
11394 env->prog->aux->btf = btf;
11396 err = check_btf_func(env, attr, uattr);
11400 err = check_btf_line(env, attr, uattr);
11404 err = check_core_relo(env, attr, uattr);
11411 /* check %cur's range satisfies %old's */
11412 static bool range_within(struct bpf_reg_state *old,
11413 struct bpf_reg_state *cur)
11415 return old->umin_value <= cur->umin_value &&
11416 old->umax_value >= cur->umax_value &&
11417 old->smin_value <= cur->smin_value &&
11418 old->smax_value >= cur->smax_value &&
11419 old->u32_min_value <= cur->u32_min_value &&
11420 old->u32_max_value >= cur->u32_max_value &&
11421 old->s32_min_value <= cur->s32_min_value &&
11422 old->s32_max_value >= cur->s32_max_value;
11425 /* If in the old state two registers had the same id, then they need to have
11426 * the same id in the new state as well. But that id could be different from
11427 * the old state, so we need to track the mapping from old to new ids.
11428 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11429 * regs with old id 5 must also have new id 9 for the new state to be safe. But
11430 * regs with a different old id could still have new id 9, we don't care about
11432 * So we look through our idmap to see if this old id has been seen before. If
11433 * so, we require the new id to match; otherwise, we add the id pair to the map.
11435 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11439 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11440 if (!idmap[i].old) {
11441 /* Reached an empty slot; haven't seen this id before */
11442 idmap[i].old = old_id;
11443 idmap[i].cur = cur_id;
11446 if (idmap[i].old == old_id)
11447 return idmap[i].cur == cur_id;
11449 /* We ran out of idmap slots, which should be impossible */
11454 static void clean_func_state(struct bpf_verifier_env *env,
11455 struct bpf_func_state *st)
11457 enum bpf_reg_liveness live;
11460 for (i = 0; i < BPF_REG_FP; i++) {
11461 live = st->regs[i].live;
11462 /* liveness must not touch this register anymore */
11463 st->regs[i].live |= REG_LIVE_DONE;
11464 if (!(live & REG_LIVE_READ))
11465 /* since the register is unused, clear its state
11466 * to make further comparison simpler
11468 __mark_reg_not_init(env, &st->regs[i]);
11471 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11472 live = st->stack[i].spilled_ptr.live;
11473 /* liveness must not touch this stack slot anymore */
11474 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11475 if (!(live & REG_LIVE_READ)) {
11476 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11477 for (j = 0; j < BPF_REG_SIZE; j++)
11478 st->stack[i].slot_type[j] = STACK_INVALID;
11483 static void clean_verifier_state(struct bpf_verifier_env *env,
11484 struct bpf_verifier_state *st)
11488 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11489 /* all regs in this state in all frames were already marked */
11492 for (i = 0; i <= st->curframe; i++)
11493 clean_func_state(env, st->frame[i]);
11496 /* the parentage chains form a tree.
11497 * the verifier states are added to state lists at given insn and
11498 * pushed into state stack for future exploration.
11499 * when the verifier reaches bpf_exit insn some of the verifer states
11500 * stored in the state lists have their final liveness state already,
11501 * but a lot of states will get revised from liveness point of view when
11502 * the verifier explores other branches.
11505 * 2: if r1 == 100 goto pc+1
11508 * when the verifier reaches exit insn the register r0 in the state list of
11509 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11510 * of insn 2 and goes exploring further. At the insn 4 it will walk the
11511 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11513 * Since the verifier pushes the branch states as it sees them while exploring
11514 * the program the condition of walking the branch instruction for the second
11515 * time means that all states below this branch were already explored and
11516 * their final liveness marks are already propagated.
11517 * Hence when the verifier completes the search of state list in is_state_visited()
11518 * we can call this clean_live_states() function to mark all liveness states
11519 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11520 * will not be used.
11521 * This function also clears the registers and stack for states that !READ
11522 * to simplify state merging.
11524 * Important note here that walking the same branch instruction in the callee
11525 * doesn't meant that the states are DONE. The verifier has to compare
11528 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11529 struct bpf_verifier_state *cur)
11531 struct bpf_verifier_state_list *sl;
11534 sl = *explored_state(env, insn);
11536 if (sl->state.branches)
11538 if (sl->state.insn_idx != insn ||
11539 sl->state.curframe != cur->curframe)
11541 for (i = 0; i <= cur->curframe; i++)
11542 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11544 clean_verifier_state(env, &sl->state);
11550 /* Returns true if (rold safe implies rcur safe) */
11551 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11552 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11556 if (!(rold->live & REG_LIVE_READ))
11557 /* explored state didn't use this */
11560 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11562 if (rold->type == PTR_TO_STACK)
11563 /* two stack pointers are equal only if they're pointing to
11564 * the same stack frame, since fp-8 in foo != fp-8 in bar
11566 return equal && rold->frameno == rcur->frameno;
11571 if (rold->type == NOT_INIT)
11572 /* explored state can't have used this */
11574 if (rcur->type == NOT_INIT)
11576 switch (base_type(rold->type)) {
11578 if (env->explore_alu_limits)
11580 if (rcur->type == SCALAR_VALUE) {
11581 if (!rold->precise && !rcur->precise)
11583 /* new val must satisfy old val knowledge */
11584 return range_within(rold, rcur) &&
11585 tnum_in(rold->var_off, rcur->var_off);
11587 /* We're trying to use a pointer in place of a scalar.
11588 * Even if the scalar was unbounded, this could lead to
11589 * pointer leaks because scalars are allowed to leak
11590 * while pointers are not. We could make this safe in
11591 * special cases if root is calling us, but it's
11592 * probably not worth the hassle.
11596 case PTR_TO_MAP_KEY:
11597 case PTR_TO_MAP_VALUE:
11598 /* a PTR_TO_MAP_VALUE could be safe to use as a
11599 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11600 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11601 * checked, doing so could have affected others with the same
11602 * id, and we can't check for that because we lost the id when
11603 * we converted to a PTR_TO_MAP_VALUE.
11605 if (type_may_be_null(rold->type)) {
11606 if (!type_may_be_null(rcur->type))
11608 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11610 /* Check our ids match any regs they're supposed to */
11611 return check_ids(rold->id, rcur->id, idmap);
11614 /* If the new min/max/var_off satisfy the old ones and
11615 * everything else matches, we are OK.
11616 * 'id' is not compared, since it's only used for maps with
11617 * bpf_spin_lock inside map element and in such cases if
11618 * the rest of the prog is valid for one map element then
11619 * it's valid for all map elements regardless of the key
11620 * used in bpf_map_lookup()
11622 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11623 range_within(rold, rcur) &&
11624 tnum_in(rold->var_off, rcur->var_off);
11625 case PTR_TO_PACKET_META:
11626 case PTR_TO_PACKET:
11627 if (rcur->type != rold->type)
11629 /* We must have at least as much range as the old ptr
11630 * did, so that any accesses which were safe before are
11631 * still safe. This is true even if old range < old off,
11632 * since someone could have accessed through (ptr - k), or
11633 * even done ptr -= k in a register, to get a safe access.
11635 if (rold->range > rcur->range)
11637 /* If the offsets don't match, we can't trust our alignment;
11638 * nor can we be sure that we won't fall out of range.
11640 if (rold->off != rcur->off)
11642 /* id relations must be preserved */
11643 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11645 /* new val must satisfy old val knowledge */
11646 return range_within(rold, rcur) &&
11647 tnum_in(rold->var_off, rcur->var_off);
11649 case CONST_PTR_TO_MAP:
11650 case PTR_TO_PACKET_END:
11651 case PTR_TO_FLOW_KEYS:
11652 case PTR_TO_SOCKET:
11653 case PTR_TO_SOCK_COMMON:
11654 case PTR_TO_TCP_SOCK:
11655 case PTR_TO_XDP_SOCK:
11656 /* Only valid matches are exact, which memcmp() above
11657 * would have accepted
11660 /* Don't know what's going on, just say it's not safe */
11664 /* Shouldn't get here; if we do, say it's not safe */
11669 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11670 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11674 /* walk slots of the explored stack and ignore any additional
11675 * slots in the current stack, since explored(safe) state
11678 for (i = 0; i < old->allocated_stack; i++) {
11679 spi = i / BPF_REG_SIZE;
11681 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11682 i += BPF_REG_SIZE - 1;
11683 /* explored state didn't use this */
11687 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11690 /* explored stack has more populated slots than current stack
11691 * and these slots were used
11693 if (i >= cur->allocated_stack)
11696 /* if old state was safe with misc data in the stack
11697 * it will be safe with zero-initialized stack.
11698 * The opposite is not true
11700 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11701 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11703 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11704 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11705 /* Ex: old explored (safe) state has STACK_SPILL in
11706 * this stack slot, but current has STACK_MISC ->
11707 * this verifier states are not equivalent,
11708 * return false to continue verification of this path
11711 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11713 if (!is_spilled_reg(&old->stack[spi]))
11715 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11716 &cur->stack[spi].spilled_ptr, idmap))
11717 /* when explored and current stack slot are both storing
11718 * spilled registers, check that stored pointers types
11719 * are the same as well.
11720 * Ex: explored safe path could have stored
11721 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11722 * but current path has stored:
11723 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11724 * such verifier states are not equivalent.
11725 * return false to continue verification of this path
11732 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11734 if (old->acquired_refs != cur->acquired_refs)
11736 return !memcmp(old->refs, cur->refs,
11737 sizeof(*old->refs) * old->acquired_refs);
11740 /* compare two verifier states
11742 * all states stored in state_list are known to be valid, since
11743 * verifier reached 'bpf_exit' instruction through them
11745 * this function is called when verifier exploring different branches of
11746 * execution popped from the state stack. If it sees an old state that has
11747 * more strict register state and more strict stack state then this execution
11748 * branch doesn't need to be explored further, since verifier already
11749 * concluded that more strict state leads to valid finish.
11751 * Therefore two states are equivalent if register state is more conservative
11752 * and explored stack state is more conservative than the current one.
11755 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11756 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11758 * In other words if current stack state (one being explored) has more
11759 * valid slots than old one that already passed validation, it means
11760 * the verifier can stop exploring and conclude that current state is valid too
11762 * Similarly with registers. If explored state has register type as invalid
11763 * whereas register type in current state is meaningful, it means that
11764 * the current state will reach 'bpf_exit' instruction safely
11766 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11767 struct bpf_func_state *cur)
11771 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11772 for (i = 0; i < MAX_BPF_REG; i++)
11773 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11774 env->idmap_scratch))
11777 if (!stacksafe(env, old, cur, env->idmap_scratch))
11780 if (!refsafe(old, cur))
11786 static bool states_equal(struct bpf_verifier_env *env,
11787 struct bpf_verifier_state *old,
11788 struct bpf_verifier_state *cur)
11792 if (old->curframe != cur->curframe)
11795 /* Verification state from speculative execution simulation
11796 * must never prune a non-speculative execution one.
11798 if (old->speculative && !cur->speculative)
11801 if (old->active_spin_lock != cur->active_spin_lock)
11804 /* for states to be equal callsites have to be the same
11805 * and all frame states need to be equivalent
11807 for (i = 0; i <= old->curframe; i++) {
11808 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11810 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11816 /* Return 0 if no propagation happened. Return negative error code if error
11817 * happened. Otherwise, return the propagated bit.
11819 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11820 struct bpf_reg_state *reg,
11821 struct bpf_reg_state *parent_reg)
11823 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11824 u8 flag = reg->live & REG_LIVE_READ;
11827 /* When comes here, read flags of PARENT_REG or REG could be any of
11828 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11829 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11831 if (parent_flag == REG_LIVE_READ64 ||
11832 /* Or if there is no read flag from REG. */
11834 /* Or if the read flag from REG is the same as PARENT_REG. */
11835 parent_flag == flag)
11838 err = mark_reg_read(env, reg, parent_reg, flag);
11845 /* A write screens off any subsequent reads; but write marks come from the
11846 * straight-line code between a state and its parent. When we arrive at an
11847 * equivalent state (jump target or such) we didn't arrive by the straight-line
11848 * code, so read marks in the state must propagate to the parent regardless
11849 * of the state's write marks. That's what 'parent == state->parent' comparison
11850 * in mark_reg_read() is for.
11852 static int propagate_liveness(struct bpf_verifier_env *env,
11853 const struct bpf_verifier_state *vstate,
11854 struct bpf_verifier_state *vparent)
11856 struct bpf_reg_state *state_reg, *parent_reg;
11857 struct bpf_func_state *state, *parent;
11858 int i, frame, err = 0;
11860 if (vparent->curframe != vstate->curframe) {
11861 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11862 vparent->curframe, vstate->curframe);
11865 /* Propagate read liveness of registers... */
11866 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11867 for (frame = 0; frame <= vstate->curframe; frame++) {
11868 parent = vparent->frame[frame];
11869 state = vstate->frame[frame];
11870 parent_reg = parent->regs;
11871 state_reg = state->regs;
11872 /* We don't need to worry about FP liveness, it's read-only */
11873 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11874 err = propagate_liveness_reg(env, &state_reg[i],
11878 if (err == REG_LIVE_READ64)
11879 mark_insn_zext(env, &parent_reg[i]);
11882 /* Propagate stack slots. */
11883 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11884 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11885 parent_reg = &parent->stack[i].spilled_ptr;
11886 state_reg = &state->stack[i].spilled_ptr;
11887 err = propagate_liveness_reg(env, state_reg,
11896 /* find precise scalars in the previous equivalent state and
11897 * propagate them into the current state
11899 static int propagate_precision(struct bpf_verifier_env *env,
11900 const struct bpf_verifier_state *old)
11902 struct bpf_reg_state *state_reg;
11903 struct bpf_func_state *state;
11904 int i, err = 0, fr;
11906 for (fr = old->curframe; fr >= 0; fr--) {
11907 state = old->frame[fr];
11908 state_reg = state->regs;
11909 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11910 if (state_reg->type != SCALAR_VALUE ||
11911 !state_reg->precise)
11913 if (env->log.level & BPF_LOG_LEVEL2)
11914 verbose(env, "frame %d: propagating r%d\n", i, fr);
11915 err = mark_chain_precision_frame(env, fr, i);
11920 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11921 if (!is_spilled_reg(&state->stack[i]))
11923 state_reg = &state->stack[i].spilled_ptr;
11924 if (state_reg->type != SCALAR_VALUE ||
11925 !state_reg->precise)
11927 if (env->log.level & BPF_LOG_LEVEL2)
11928 verbose(env, "frame %d: propagating fp%d\n",
11929 (-i - 1) * BPF_REG_SIZE, fr);
11930 err = mark_chain_precision_stack_frame(env, fr, i);
11938 static bool states_maybe_looping(struct bpf_verifier_state *old,
11939 struct bpf_verifier_state *cur)
11941 struct bpf_func_state *fold, *fcur;
11942 int i, fr = cur->curframe;
11944 if (old->curframe != fr)
11947 fold = old->frame[fr];
11948 fcur = cur->frame[fr];
11949 for (i = 0; i < MAX_BPF_REG; i++)
11950 if (memcmp(&fold->regs[i], &fcur->regs[i],
11951 offsetof(struct bpf_reg_state, parent)))
11957 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11959 struct bpf_verifier_state_list *new_sl;
11960 struct bpf_verifier_state_list *sl, **pprev;
11961 struct bpf_verifier_state *cur = env->cur_state, *new;
11962 int i, j, err, states_cnt = 0;
11963 bool add_new_state = env->test_state_freq ? true : false;
11965 cur->last_insn_idx = env->prev_insn_idx;
11966 if (!env->insn_aux_data[insn_idx].prune_point)
11967 /* this 'insn_idx' instruction wasn't marked, so we will not
11968 * be doing state search here
11972 /* bpf progs typically have pruning point every 4 instructions
11973 * http://vger.kernel.org/bpfconf2019.html#session-1
11974 * Do not add new state for future pruning if the verifier hasn't seen
11975 * at least 2 jumps and at least 8 instructions.
11976 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11977 * In tests that amounts to up to 50% reduction into total verifier
11978 * memory consumption and 20% verifier time speedup.
11980 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11981 env->insn_processed - env->prev_insn_processed >= 8)
11982 add_new_state = true;
11984 pprev = explored_state(env, insn_idx);
11987 clean_live_states(env, insn_idx, cur);
11991 if (sl->state.insn_idx != insn_idx)
11994 if (sl->state.branches) {
11995 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11997 if (frame->in_async_callback_fn &&
11998 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11999 /* Different async_entry_cnt means that the verifier is
12000 * processing another entry into async callback.
12001 * Seeing the same state is not an indication of infinite
12002 * loop or infinite recursion.
12003 * But finding the same state doesn't mean that it's safe
12004 * to stop processing the current state. The previous state
12005 * hasn't yet reached bpf_exit, since state.branches > 0.
12006 * Checking in_async_callback_fn alone is not enough either.
12007 * Since the verifier still needs to catch infinite loops
12008 * inside async callbacks.
12010 } else if (states_maybe_looping(&sl->state, cur) &&
12011 states_equal(env, &sl->state, cur)) {
12012 verbose_linfo(env, insn_idx, "; ");
12013 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
12016 /* if the verifier is processing a loop, avoid adding new state
12017 * too often, since different loop iterations have distinct
12018 * states and may not help future pruning.
12019 * This threshold shouldn't be too low to make sure that
12020 * a loop with large bound will be rejected quickly.
12021 * The most abusive loop will be:
12023 * if r1 < 1000000 goto pc-2
12024 * 1M insn_procssed limit / 100 == 10k peak states.
12025 * This threshold shouldn't be too high either, since states
12026 * at the end of the loop are likely to be useful in pruning.
12028 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
12029 env->insn_processed - env->prev_insn_processed < 100)
12030 add_new_state = false;
12033 if (states_equal(env, &sl->state, cur)) {
12035 /* reached equivalent register/stack state,
12036 * prune the search.
12037 * Registers read by the continuation are read by us.
12038 * If we have any write marks in env->cur_state, they
12039 * will prevent corresponding reads in the continuation
12040 * from reaching our parent (an explored_state). Our
12041 * own state will get the read marks recorded, but
12042 * they'll be immediately forgotten as we're pruning
12043 * this state and will pop a new one.
12045 err = propagate_liveness(env, &sl->state, cur);
12047 /* if previous state reached the exit with precision and
12048 * current state is equivalent to it (except precsion marks)
12049 * the precision needs to be propagated back in
12050 * the current state.
12052 err = err ? : push_jmp_history(env, cur);
12053 err = err ? : propagate_precision(env, &sl->state);
12059 /* when new state is not going to be added do not increase miss count.
12060 * Otherwise several loop iterations will remove the state
12061 * recorded earlier. The goal of these heuristics is to have
12062 * states from some iterations of the loop (some in the beginning
12063 * and some at the end) to help pruning.
12067 /* heuristic to determine whether this state is beneficial
12068 * to keep checking from state equivalence point of view.
12069 * Higher numbers increase max_states_per_insn and verification time,
12070 * but do not meaningfully decrease insn_processed.
12072 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12073 /* the state is unlikely to be useful. Remove it to
12074 * speed up verification
12077 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12078 u32 br = sl->state.branches;
12081 "BUG live_done but branches_to_explore %d\n",
12083 free_verifier_state(&sl->state, false);
12085 env->peak_states--;
12087 /* cannot free this state, since parentage chain may
12088 * walk it later. Add it for free_list instead to
12089 * be freed at the end of verification
12091 sl->next = env->free_list;
12092 env->free_list = sl;
12102 if (env->max_states_per_insn < states_cnt)
12103 env->max_states_per_insn = states_cnt;
12105 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12106 return push_jmp_history(env, cur);
12108 if (!add_new_state)
12109 return push_jmp_history(env, cur);
12111 /* There were no equivalent states, remember the current one.
12112 * Technically the current state is not proven to be safe yet,
12113 * but it will either reach outer most bpf_exit (which means it's safe)
12114 * or it will be rejected. When there are no loops the verifier won't be
12115 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12116 * again on the way to bpf_exit.
12117 * When looping the sl->state.branches will be > 0 and this state
12118 * will not be considered for equivalence until branches == 0.
12120 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12123 env->total_states++;
12124 env->peak_states++;
12125 env->prev_jmps_processed = env->jmps_processed;
12126 env->prev_insn_processed = env->insn_processed;
12128 /* add new state to the head of linked list */
12129 new = &new_sl->state;
12130 err = copy_verifier_state(new, cur);
12132 free_verifier_state(new, false);
12136 new->insn_idx = insn_idx;
12137 WARN_ONCE(new->branches != 1,
12138 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12141 cur->first_insn_idx = insn_idx;
12142 clear_jmp_history(cur);
12143 new_sl->next = *explored_state(env, insn_idx);
12144 *explored_state(env, insn_idx) = new_sl;
12145 /* connect new state to parentage chain. Current frame needs all
12146 * registers connected. Only r6 - r9 of the callers are alive (pushed
12147 * to the stack implicitly by JITs) so in callers' frames connect just
12148 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12149 * the state of the call instruction (with WRITTEN set), and r0 comes
12150 * from callee with its full parentage chain, anyway.
12152 /* clear write marks in current state: the writes we did are not writes
12153 * our child did, so they don't screen off its reads from us.
12154 * (There are no read marks in current state, because reads always mark
12155 * their parent and current state never has children yet. Only
12156 * explored_states can get read marks.)
12158 for (j = 0; j <= cur->curframe; j++) {
12159 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12160 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12161 for (i = 0; i < BPF_REG_FP; i++)
12162 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12165 /* all stack frames are accessible from callee, clear them all */
12166 for (j = 0; j <= cur->curframe; j++) {
12167 struct bpf_func_state *frame = cur->frame[j];
12168 struct bpf_func_state *newframe = new->frame[j];
12170 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12171 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12172 frame->stack[i].spilled_ptr.parent =
12173 &newframe->stack[i].spilled_ptr;
12179 /* Return true if it's OK to have the same insn return a different type. */
12180 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12182 switch (base_type(type)) {
12184 case PTR_TO_SOCKET:
12185 case PTR_TO_SOCK_COMMON:
12186 case PTR_TO_TCP_SOCK:
12187 case PTR_TO_XDP_SOCK:
12188 case PTR_TO_BTF_ID:
12195 /* If an instruction was previously used with particular pointer types, then we
12196 * need to be careful to avoid cases such as the below, where it may be ok
12197 * for one branch accessing the pointer, but not ok for the other branch:
12202 * R1 = some_other_valid_ptr;
12205 * R2 = *(u32 *)(R1 + 0);
12207 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12209 return src != prev && (!reg_type_mismatch_ok(src) ||
12210 !reg_type_mismatch_ok(prev));
12213 static int do_check(struct bpf_verifier_env *env)
12215 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12216 struct bpf_verifier_state *state = env->cur_state;
12217 struct bpf_insn *insns = env->prog->insnsi;
12218 struct bpf_reg_state *regs;
12219 int insn_cnt = env->prog->len;
12220 bool do_print_state = false;
12221 int prev_insn_idx = -1;
12224 struct bpf_insn *insn;
12228 env->prev_insn_idx = prev_insn_idx;
12229 if (env->insn_idx >= insn_cnt) {
12230 verbose(env, "invalid insn idx %d insn_cnt %d\n",
12231 env->insn_idx, insn_cnt);
12235 insn = &insns[env->insn_idx];
12236 class = BPF_CLASS(insn->code);
12238 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12240 "BPF program is too large. Processed %d insn\n",
12241 env->insn_processed);
12245 err = is_state_visited(env, env->insn_idx);
12249 /* found equivalent state, can prune the search */
12250 if (env->log.level & BPF_LOG_LEVEL) {
12251 if (do_print_state)
12252 verbose(env, "\nfrom %d to %d%s: safe\n",
12253 env->prev_insn_idx, env->insn_idx,
12254 env->cur_state->speculative ?
12255 " (speculative execution)" : "");
12257 verbose(env, "%d: safe\n", env->insn_idx);
12259 goto process_bpf_exit;
12262 if (signal_pending(current))
12265 if (need_resched())
12268 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12269 verbose(env, "\nfrom %d to %d%s:",
12270 env->prev_insn_idx, env->insn_idx,
12271 env->cur_state->speculative ?
12272 " (speculative execution)" : "");
12273 print_verifier_state(env, state->frame[state->curframe], true);
12274 do_print_state = false;
12277 if (env->log.level & BPF_LOG_LEVEL) {
12278 const struct bpf_insn_cbs cbs = {
12279 .cb_call = disasm_kfunc_name,
12280 .cb_print = verbose,
12281 .private_data = env,
12284 if (verifier_state_scratched(env))
12285 print_insn_state(env, state->frame[state->curframe]);
12287 verbose_linfo(env, env->insn_idx, "; ");
12288 env->prev_log_len = env->log.len_used;
12289 verbose(env, "%d: ", env->insn_idx);
12290 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12291 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12292 env->prev_log_len = env->log.len_used;
12295 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12296 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12297 env->prev_insn_idx);
12302 regs = cur_regs(env);
12303 sanitize_mark_insn_seen(env);
12304 prev_insn_idx = env->insn_idx;
12306 if (class == BPF_ALU || class == BPF_ALU64) {
12307 err = check_alu_op(env, insn);
12311 } else if (class == BPF_LDX) {
12312 enum bpf_reg_type *prev_src_type, src_reg_type;
12314 /* check for reserved fields is already done */
12316 /* check src operand */
12317 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12321 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12325 src_reg_type = regs[insn->src_reg].type;
12327 /* check that memory (src_reg + off) is readable,
12328 * the state of dst_reg will be updated by this func
12330 err = check_mem_access(env, env->insn_idx, insn->src_reg,
12331 insn->off, BPF_SIZE(insn->code),
12332 BPF_READ, insn->dst_reg, false);
12336 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12338 if (*prev_src_type == NOT_INIT) {
12339 /* saw a valid insn
12340 * dst_reg = *(u32 *)(src_reg + off)
12341 * save type to validate intersecting paths
12343 *prev_src_type = src_reg_type;
12345 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12346 /* ABuser program is trying to use the same insn
12347 * dst_reg = *(u32*) (src_reg + off)
12348 * with different pointer types:
12349 * src_reg == ctx in one branch and
12350 * src_reg == stack|map in some other branch.
12353 verbose(env, "same insn cannot be used with different pointers\n");
12357 } else if (class == BPF_STX) {
12358 enum bpf_reg_type *prev_dst_type, dst_reg_type;
12360 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12361 err = check_atomic(env, env->insn_idx, insn);
12368 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12369 verbose(env, "BPF_STX uses reserved fields\n");
12373 /* check src1 operand */
12374 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12377 /* check src2 operand */
12378 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12382 dst_reg_type = regs[insn->dst_reg].type;
12384 /* check that memory (dst_reg + off) is writeable */
12385 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12386 insn->off, BPF_SIZE(insn->code),
12387 BPF_WRITE, insn->src_reg, false);
12391 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12393 if (*prev_dst_type == NOT_INIT) {
12394 *prev_dst_type = dst_reg_type;
12395 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12396 verbose(env, "same insn cannot be used with different pointers\n");
12400 } else if (class == BPF_ST) {
12401 if (BPF_MODE(insn->code) != BPF_MEM ||
12402 insn->src_reg != BPF_REG_0) {
12403 verbose(env, "BPF_ST uses reserved fields\n");
12406 /* check src operand */
12407 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12411 if (is_ctx_reg(env, insn->dst_reg)) {
12412 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12414 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12418 /* check that memory (dst_reg + off) is writeable */
12419 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12420 insn->off, BPF_SIZE(insn->code),
12421 BPF_WRITE, -1, false);
12425 } else if (class == BPF_JMP || class == BPF_JMP32) {
12426 u8 opcode = BPF_OP(insn->code);
12428 env->jmps_processed++;
12429 if (opcode == BPF_CALL) {
12430 if (BPF_SRC(insn->code) != BPF_K ||
12431 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12432 && insn->off != 0) ||
12433 (insn->src_reg != BPF_REG_0 &&
12434 insn->src_reg != BPF_PSEUDO_CALL &&
12435 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12436 insn->dst_reg != BPF_REG_0 ||
12437 class == BPF_JMP32) {
12438 verbose(env, "BPF_CALL uses reserved fields\n");
12442 if (env->cur_state->active_spin_lock &&
12443 (insn->src_reg == BPF_PSEUDO_CALL ||
12444 insn->imm != BPF_FUNC_spin_unlock)) {
12445 verbose(env, "function calls are not allowed while holding a lock\n");
12448 if (insn->src_reg == BPF_PSEUDO_CALL)
12449 err = check_func_call(env, insn, &env->insn_idx);
12450 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12451 err = check_kfunc_call(env, insn, &env->insn_idx);
12453 err = check_helper_call(env, insn, &env->insn_idx);
12456 } else if (opcode == BPF_JA) {
12457 if (BPF_SRC(insn->code) != BPF_K ||
12459 insn->src_reg != BPF_REG_0 ||
12460 insn->dst_reg != BPF_REG_0 ||
12461 class == BPF_JMP32) {
12462 verbose(env, "BPF_JA uses reserved fields\n");
12466 env->insn_idx += insn->off + 1;
12469 } else if (opcode == BPF_EXIT) {
12470 if (BPF_SRC(insn->code) != BPF_K ||
12472 insn->src_reg != BPF_REG_0 ||
12473 insn->dst_reg != BPF_REG_0 ||
12474 class == BPF_JMP32) {
12475 verbose(env, "BPF_EXIT uses reserved fields\n");
12479 if (env->cur_state->active_spin_lock) {
12480 verbose(env, "bpf_spin_unlock is missing\n");
12484 /* We must do check_reference_leak here before
12485 * prepare_func_exit to handle the case when
12486 * state->curframe > 0, it may be a callback
12487 * function, for which reference_state must
12488 * match caller reference state when it exits.
12490 err = check_reference_leak(env);
12494 if (state->curframe) {
12495 /* exit from nested function */
12496 err = prepare_func_exit(env, &env->insn_idx);
12499 do_print_state = true;
12503 err = check_return_code(env);
12507 mark_verifier_state_scratched(env);
12508 update_branch_counts(env, env->cur_state);
12509 err = pop_stack(env, &prev_insn_idx,
12510 &env->insn_idx, pop_log);
12512 if (err != -ENOENT)
12516 do_print_state = true;
12520 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12524 } else if (class == BPF_LD) {
12525 u8 mode = BPF_MODE(insn->code);
12527 if (mode == BPF_ABS || mode == BPF_IND) {
12528 err = check_ld_abs(env, insn);
12532 } else if (mode == BPF_IMM) {
12533 err = check_ld_imm(env, insn);
12538 sanitize_mark_insn_seen(env);
12540 verbose(env, "invalid BPF_LD mode\n");
12544 verbose(env, "unknown insn class %d\n", class);
12554 static int find_btf_percpu_datasec(struct btf *btf)
12556 const struct btf_type *t;
12561 * Both vmlinux and module each have their own ".data..percpu"
12562 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12563 * types to look at only module's own BTF types.
12565 n = btf_nr_types(btf);
12566 if (btf_is_module(btf))
12567 i = btf_nr_types(btf_vmlinux);
12571 for(; i < n; i++) {
12572 t = btf_type_by_id(btf, i);
12573 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12576 tname = btf_name_by_offset(btf, t->name_off);
12577 if (!strcmp(tname, ".data..percpu"))
12584 /* replace pseudo btf_id with kernel symbol address */
12585 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12586 struct bpf_insn *insn,
12587 struct bpf_insn_aux_data *aux)
12589 const struct btf_var_secinfo *vsi;
12590 const struct btf_type *datasec;
12591 struct btf_mod_pair *btf_mod;
12592 const struct btf_type *t;
12593 const char *sym_name;
12594 bool percpu = false;
12595 u32 type, id = insn->imm;
12599 int i, btf_fd, err;
12601 btf_fd = insn[1].imm;
12603 btf = btf_get_by_fd(btf_fd);
12605 verbose(env, "invalid module BTF object FD specified.\n");
12609 if (!btf_vmlinux) {
12610 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12617 t = btf_type_by_id(btf, id);
12619 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12624 if (!btf_type_is_var(t)) {
12625 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12630 sym_name = btf_name_by_offset(btf, t->name_off);
12631 addr = kallsyms_lookup_name(sym_name);
12633 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12639 datasec_id = find_btf_percpu_datasec(btf);
12640 if (datasec_id > 0) {
12641 datasec = btf_type_by_id(btf, datasec_id);
12642 for_each_vsi(i, datasec, vsi) {
12643 if (vsi->type == id) {
12650 insn[0].imm = (u32)addr;
12651 insn[1].imm = addr >> 32;
12654 t = btf_type_skip_modifiers(btf, type, NULL);
12656 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12657 aux->btf_var.btf = btf;
12658 aux->btf_var.btf_id = type;
12659 } else if (!btf_type_is_struct(t)) {
12660 const struct btf_type *ret;
12664 /* resolve the type size of ksym. */
12665 ret = btf_resolve_size(btf, t, &tsize);
12667 tname = btf_name_by_offset(btf, t->name_off);
12668 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12669 tname, PTR_ERR(ret));
12673 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12674 aux->btf_var.mem_size = tsize;
12676 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12677 aux->btf_var.btf = btf;
12678 aux->btf_var.btf_id = type;
12681 /* check whether we recorded this BTF (and maybe module) already */
12682 for (i = 0; i < env->used_btf_cnt; i++) {
12683 if (env->used_btfs[i].btf == btf) {
12689 if (env->used_btf_cnt >= MAX_USED_BTFS) {
12694 btf_mod = &env->used_btfs[env->used_btf_cnt];
12695 btf_mod->btf = btf;
12696 btf_mod->module = NULL;
12698 /* if we reference variables from kernel module, bump its refcount */
12699 if (btf_is_module(btf)) {
12700 btf_mod->module = btf_try_get_module(btf);
12701 if (!btf_mod->module) {
12707 env->used_btf_cnt++;
12715 static bool is_tracing_prog_type(enum bpf_prog_type type)
12718 case BPF_PROG_TYPE_KPROBE:
12719 case BPF_PROG_TYPE_TRACEPOINT:
12720 case BPF_PROG_TYPE_PERF_EVENT:
12721 case BPF_PROG_TYPE_RAW_TRACEPOINT:
12722 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12729 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12730 struct bpf_map *map,
12731 struct bpf_prog *prog)
12734 enum bpf_prog_type prog_type = resolve_prog_type(prog);
12736 if (map_value_has_spin_lock(map)) {
12737 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12738 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12742 if (is_tracing_prog_type(prog_type)) {
12743 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12747 if (prog->aux->sleepable) {
12748 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12753 if (map_value_has_timer(map)) {
12754 if (is_tracing_prog_type(prog_type)) {
12755 verbose(env, "tracing progs cannot use bpf_timer yet\n");
12760 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12761 !bpf_offload_prog_map_match(prog, map)) {
12762 verbose(env, "offload device mismatch between prog and map\n");
12766 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12767 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12771 if (prog->aux->sleepable)
12772 switch (map->map_type) {
12773 case BPF_MAP_TYPE_HASH:
12774 case BPF_MAP_TYPE_LRU_HASH:
12775 case BPF_MAP_TYPE_ARRAY:
12776 case BPF_MAP_TYPE_PERCPU_HASH:
12777 case BPF_MAP_TYPE_PERCPU_ARRAY:
12778 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12779 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12780 case BPF_MAP_TYPE_HASH_OF_MAPS:
12781 case BPF_MAP_TYPE_RINGBUF:
12782 case BPF_MAP_TYPE_USER_RINGBUF:
12783 case BPF_MAP_TYPE_INODE_STORAGE:
12784 case BPF_MAP_TYPE_SK_STORAGE:
12785 case BPF_MAP_TYPE_TASK_STORAGE:
12789 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12796 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12798 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12799 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12802 /* find and rewrite pseudo imm in ld_imm64 instructions:
12804 * 1. if it accesses map FD, replace it with actual map pointer.
12805 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12807 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12809 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12811 struct bpf_insn *insn = env->prog->insnsi;
12812 int insn_cnt = env->prog->len;
12815 err = bpf_prog_calc_tag(env->prog);
12819 for (i = 0; i < insn_cnt; i++, insn++) {
12820 if (BPF_CLASS(insn->code) == BPF_LDX &&
12821 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12822 verbose(env, "BPF_LDX uses reserved fields\n");
12826 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12827 struct bpf_insn_aux_data *aux;
12828 struct bpf_map *map;
12833 if (i == insn_cnt - 1 || insn[1].code != 0 ||
12834 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12835 insn[1].off != 0) {
12836 verbose(env, "invalid bpf_ld_imm64 insn\n");
12840 if (insn[0].src_reg == 0)
12841 /* valid generic load 64-bit imm */
12844 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12845 aux = &env->insn_aux_data[i];
12846 err = check_pseudo_btf_id(env, insn, aux);
12852 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12853 aux = &env->insn_aux_data[i];
12854 aux->ptr_type = PTR_TO_FUNC;
12858 /* In final convert_pseudo_ld_imm64() step, this is
12859 * converted into regular 64-bit imm load insn.
12861 switch (insn[0].src_reg) {
12862 case BPF_PSEUDO_MAP_VALUE:
12863 case BPF_PSEUDO_MAP_IDX_VALUE:
12865 case BPF_PSEUDO_MAP_FD:
12866 case BPF_PSEUDO_MAP_IDX:
12867 if (insn[1].imm == 0)
12871 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12875 switch (insn[0].src_reg) {
12876 case BPF_PSEUDO_MAP_IDX_VALUE:
12877 case BPF_PSEUDO_MAP_IDX:
12878 if (bpfptr_is_null(env->fd_array)) {
12879 verbose(env, "fd_idx without fd_array is invalid\n");
12882 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12883 insn[0].imm * sizeof(fd),
12893 map = __bpf_map_get(f);
12895 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12897 return PTR_ERR(map);
12900 err = check_map_prog_compatibility(env, map, env->prog);
12906 aux = &env->insn_aux_data[i];
12907 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12908 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12909 addr = (unsigned long)map;
12911 u32 off = insn[1].imm;
12913 if (off >= BPF_MAX_VAR_OFF) {
12914 verbose(env, "direct value offset of %u is not allowed\n", off);
12919 if (!map->ops->map_direct_value_addr) {
12920 verbose(env, "no direct value access support for this map type\n");
12925 err = map->ops->map_direct_value_addr(map, &addr, off);
12927 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12928 map->value_size, off);
12933 aux->map_off = off;
12937 insn[0].imm = (u32)addr;
12938 insn[1].imm = addr >> 32;
12940 /* check whether we recorded this map already */
12941 for (j = 0; j < env->used_map_cnt; j++) {
12942 if (env->used_maps[j] == map) {
12943 aux->map_index = j;
12949 if (env->used_map_cnt >= MAX_USED_MAPS) {
12954 /* hold the map. If the program is rejected by verifier,
12955 * the map will be released by release_maps() or it
12956 * will be used by the valid program until it's unloaded
12957 * and all maps are released in free_used_maps()
12961 aux->map_index = env->used_map_cnt;
12962 env->used_maps[env->used_map_cnt++] = map;
12964 if (bpf_map_is_cgroup_storage(map) &&
12965 bpf_cgroup_storage_assign(env->prog->aux, map)) {
12966 verbose(env, "only one cgroup storage of each type is allowed\n");
12978 /* Basic sanity check before we invest more work here. */
12979 if (!bpf_opcode_in_insntable(insn->code)) {
12980 verbose(env, "unknown opcode %02x\n", insn->code);
12985 /* now all pseudo BPF_LD_IMM64 instructions load valid
12986 * 'struct bpf_map *' into a register instead of user map_fd.
12987 * These pointers will be used later by verifier to validate map access.
12992 /* drop refcnt of maps used by the rejected program */
12993 static void release_maps(struct bpf_verifier_env *env)
12995 __bpf_free_used_maps(env->prog->aux, env->used_maps,
12996 env->used_map_cnt);
12999 /* drop refcnt of maps used by the rejected program */
13000 static void release_btfs(struct bpf_verifier_env *env)
13002 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
13003 env->used_btf_cnt);
13006 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
13007 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
13009 struct bpf_insn *insn = env->prog->insnsi;
13010 int insn_cnt = env->prog->len;
13013 for (i = 0; i < insn_cnt; i++, insn++) {
13014 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
13016 if (insn->src_reg == BPF_PSEUDO_FUNC)
13022 /* single env->prog->insni[off] instruction was replaced with the range
13023 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
13024 * [0, off) and [off, end) to new locations, so the patched range stays zero
13026 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
13027 struct bpf_insn_aux_data *new_data,
13028 struct bpf_prog *new_prog, u32 off, u32 cnt)
13030 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
13031 struct bpf_insn *insn = new_prog->insnsi;
13032 u32 old_seen = old_data[off].seen;
13036 /* aux info at OFF always needs adjustment, no matter fast path
13037 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
13038 * original insn at old prog.
13040 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
13044 prog_len = new_prog->len;
13046 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
13047 memcpy(new_data + off + cnt - 1, old_data + off,
13048 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
13049 for (i = off; i < off + cnt - 1; i++) {
13050 /* Expand insni[off]'s seen count to the patched range. */
13051 new_data[i].seen = old_seen;
13052 new_data[i].zext_dst = insn_has_def32(env, insn + i);
13054 env->insn_aux_data = new_data;
13058 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13064 /* NOTE: fake 'exit' subprog should be updated as well. */
13065 for (i = 0; i <= env->subprog_cnt; i++) {
13066 if (env->subprog_info[i].start <= off)
13068 env->subprog_info[i].start += len - 1;
13072 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13074 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13075 int i, sz = prog->aux->size_poke_tab;
13076 struct bpf_jit_poke_descriptor *desc;
13078 for (i = 0; i < sz; i++) {
13080 if (desc->insn_idx <= off)
13082 desc->insn_idx += len - 1;
13086 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13087 const struct bpf_insn *patch, u32 len)
13089 struct bpf_prog *new_prog;
13090 struct bpf_insn_aux_data *new_data = NULL;
13093 new_data = vzalloc(array_size(env->prog->len + len - 1,
13094 sizeof(struct bpf_insn_aux_data)));
13099 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13100 if (IS_ERR(new_prog)) {
13101 if (PTR_ERR(new_prog) == -ERANGE)
13103 "insn %d cannot be patched due to 16-bit range\n",
13104 env->insn_aux_data[off].orig_idx);
13108 adjust_insn_aux_data(env, new_data, new_prog, off, len);
13109 adjust_subprog_starts(env, off, len);
13110 adjust_poke_descs(new_prog, off, len);
13114 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13119 /* find first prog starting at or after off (first to remove) */
13120 for (i = 0; i < env->subprog_cnt; i++)
13121 if (env->subprog_info[i].start >= off)
13123 /* find first prog starting at or after off + cnt (first to stay) */
13124 for (j = i; j < env->subprog_cnt; j++)
13125 if (env->subprog_info[j].start >= off + cnt)
13127 /* if j doesn't start exactly at off + cnt, we are just removing
13128 * the front of previous prog
13130 if (env->subprog_info[j].start != off + cnt)
13134 struct bpf_prog_aux *aux = env->prog->aux;
13137 /* move fake 'exit' subprog as well */
13138 move = env->subprog_cnt + 1 - j;
13140 memmove(env->subprog_info + i,
13141 env->subprog_info + j,
13142 sizeof(*env->subprog_info) * move);
13143 env->subprog_cnt -= j - i;
13145 /* remove func_info */
13146 if (aux->func_info) {
13147 move = aux->func_info_cnt - j;
13149 memmove(aux->func_info + i,
13150 aux->func_info + j,
13151 sizeof(*aux->func_info) * move);
13152 aux->func_info_cnt -= j - i;
13153 /* func_info->insn_off is set after all code rewrites,
13154 * in adjust_btf_func() - no need to adjust
13158 /* convert i from "first prog to remove" to "first to adjust" */
13159 if (env->subprog_info[i].start == off)
13163 /* update fake 'exit' subprog as well */
13164 for (; i <= env->subprog_cnt; i++)
13165 env->subprog_info[i].start -= cnt;
13170 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13173 struct bpf_prog *prog = env->prog;
13174 u32 i, l_off, l_cnt, nr_linfo;
13175 struct bpf_line_info *linfo;
13177 nr_linfo = prog->aux->nr_linfo;
13181 linfo = prog->aux->linfo;
13183 /* find first line info to remove, count lines to be removed */
13184 for (i = 0; i < nr_linfo; i++)
13185 if (linfo[i].insn_off >= off)
13190 for (; i < nr_linfo; i++)
13191 if (linfo[i].insn_off < off + cnt)
13196 /* First live insn doesn't match first live linfo, it needs to "inherit"
13197 * last removed linfo. prog is already modified, so prog->len == off
13198 * means no live instructions after (tail of the program was removed).
13200 if (prog->len != off && l_cnt &&
13201 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13203 linfo[--i].insn_off = off + cnt;
13206 /* remove the line info which refer to the removed instructions */
13208 memmove(linfo + l_off, linfo + i,
13209 sizeof(*linfo) * (nr_linfo - i));
13211 prog->aux->nr_linfo -= l_cnt;
13212 nr_linfo = prog->aux->nr_linfo;
13215 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13216 for (i = l_off; i < nr_linfo; i++)
13217 linfo[i].insn_off -= cnt;
13219 /* fix up all subprogs (incl. 'exit') which start >= off */
13220 for (i = 0; i <= env->subprog_cnt; i++)
13221 if (env->subprog_info[i].linfo_idx > l_off) {
13222 /* program may have started in the removed region but
13223 * may not be fully removed
13225 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13226 env->subprog_info[i].linfo_idx -= l_cnt;
13228 env->subprog_info[i].linfo_idx = l_off;
13234 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13236 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13237 unsigned int orig_prog_len = env->prog->len;
13240 if (bpf_prog_is_dev_bound(env->prog->aux))
13241 bpf_prog_offload_remove_insns(env, off, cnt);
13243 err = bpf_remove_insns(env->prog, off, cnt);
13247 err = adjust_subprog_starts_after_remove(env, off, cnt);
13251 err = bpf_adj_linfo_after_remove(env, off, cnt);
13255 memmove(aux_data + off, aux_data + off + cnt,
13256 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13261 /* The verifier does more data flow analysis than llvm and will not
13262 * explore branches that are dead at run time. Malicious programs can
13263 * have dead code too. Therefore replace all dead at-run-time code
13266 * Just nops are not optimal, e.g. if they would sit at the end of the
13267 * program and through another bug we would manage to jump there, then
13268 * we'd execute beyond program memory otherwise. Returning exception
13269 * code also wouldn't work since we can have subprogs where the dead
13270 * code could be located.
13272 static void sanitize_dead_code(struct bpf_verifier_env *env)
13274 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13275 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13276 struct bpf_insn *insn = env->prog->insnsi;
13277 const int insn_cnt = env->prog->len;
13280 for (i = 0; i < insn_cnt; i++) {
13281 if (aux_data[i].seen)
13283 memcpy(insn + i, &trap, sizeof(trap));
13284 aux_data[i].zext_dst = false;
13288 static bool insn_is_cond_jump(u8 code)
13292 if (BPF_CLASS(code) == BPF_JMP32)
13295 if (BPF_CLASS(code) != BPF_JMP)
13299 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13302 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13304 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13305 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13306 struct bpf_insn *insn = env->prog->insnsi;
13307 const int insn_cnt = env->prog->len;
13310 for (i = 0; i < insn_cnt; i++, insn++) {
13311 if (!insn_is_cond_jump(insn->code))
13314 if (!aux_data[i + 1].seen)
13315 ja.off = insn->off;
13316 else if (!aux_data[i + 1 + insn->off].seen)
13321 if (bpf_prog_is_dev_bound(env->prog->aux))
13322 bpf_prog_offload_replace_insn(env, i, &ja);
13324 memcpy(insn, &ja, sizeof(ja));
13328 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13330 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13331 int insn_cnt = env->prog->len;
13334 for (i = 0; i < insn_cnt; i++) {
13338 while (i + j < insn_cnt && !aux_data[i + j].seen)
13343 err = verifier_remove_insns(env, i, j);
13346 insn_cnt = env->prog->len;
13352 static int opt_remove_nops(struct bpf_verifier_env *env)
13354 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13355 struct bpf_insn *insn = env->prog->insnsi;
13356 int insn_cnt = env->prog->len;
13359 for (i = 0; i < insn_cnt; i++) {
13360 if (memcmp(&insn[i], &ja, sizeof(ja)))
13363 err = verifier_remove_insns(env, i, 1);
13373 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13374 const union bpf_attr *attr)
13376 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13377 struct bpf_insn_aux_data *aux = env->insn_aux_data;
13378 int i, patch_len, delta = 0, len = env->prog->len;
13379 struct bpf_insn *insns = env->prog->insnsi;
13380 struct bpf_prog *new_prog;
13383 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13384 zext_patch[1] = BPF_ZEXT_REG(0);
13385 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13386 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13387 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13388 for (i = 0; i < len; i++) {
13389 int adj_idx = i + delta;
13390 struct bpf_insn insn;
13393 insn = insns[adj_idx];
13394 load_reg = insn_def_regno(&insn);
13395 if (!aux[adj_idx].zext_dst) {
13403 class = BPF_CLASS(code);
13404 if (load_reg == -1)
13407 /* NOTE: arg "reg" (the fourth one) is only used for
13408 * BPF_STX + SRC_OP, so it is safe to pass NULL
13411 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13412 if (class == BPF_LD &&
13413 BPF_MODE(code) == BPF_IMM)
13418 /* ctx load could be transformed into wider load. */
13419 if (class == BPF_LDX &&
13420 aux[adj_idx].ptr_type == PTR_TO_CTX)
13423 imm_rnd = get_random_u32();
13424 rnd_hi32_patch[0] = insn;
13425 rnd_hi32_patch[1].imm = imm_rnd;
13426 rnd_hi32_patch[3].dst_reg = load_reg;
13427 patch = rnd_hi32_patch;
13429 goto apply_patch_buffer;
13432 /* Add in an zero-extend instruction if a) the JIT has requested
13433 * it or b) it's a CMPXCHG.
13435 * The latter is because: BPF_CMPXCHG always loads a value into
13436 * R0, therefore always zero-extends. However some archs'
13437 * equivalent instruction only does this load when the
13438 * comparison is successful. This detail of CMPXCHG is
13439 * orthogonal to the general zero-extension behaviour of the
13440 * CPU, so it's treated independently of bpf_jit_needs_zext.
13442 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13445 /* Zero-extension is done by the caller. */
13446 if (bpf_pseudo_kfunc_call(&insn))
13449 if (WARN_ON(load_reg == -1)) {
13450 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13454 zext_patch[0] = insn;
13455 zext_patch[1].dst_reg = load_reg;
13456 zext_patch[1].src_reg = load_reg;
13457 patch = zext_patch;
13459 apply_patch_buffer:
13460 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13463 env->prog = new_prog;
13464 insns = new_prog->insnsi;
13465 aux = env->insn_aux_data;
13466 delta += patch_len - 1;
13472 /* convert load instructions that access fields of a context type into a
13473 * sequence of instructions that access fields of the underlying structure:
13474 * struct __sk_buff -> struct sk_buff
13475 * struct bpf_sock_ops -> struct sock
13477 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13479 const struct bpf_verifier_ops *ops = env->ops;
13480 int i, cnt, size, ctx_field_size, delta = 0;
13481 const int insn_cnt = env->prog->len;
13482 struct bpf_insn insn_buf[16], *insn;
13483 u32 target_size, size_default, off;
13484 struct bpf_prog *new_prog;
13485 enum bpf_access_type type;
13486 bool is_narrower_load;
13488 if (ops->gen_prologue || env->seen_direct_write) {
13489 if (!ops->gen_prologue) {
13490 verbose(env, "bpf verifier is misconfigured\n");
13493 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13495 if (cnt >= ARRAY_SIZE(insn_buf)) {
13496 verbose(env, "bpf verifier is misconfigured\n");
13499 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13503 env->prog = new_prog;
13508 if (bpf_prog_is_dev_bound(env->prog->aux))
13511 insn = env->prog->insnsi + delta;
13513 for (i = 0; i < insn_cnt; i++, insn++) {
13514 bpf_convert_ctx_access_t convert_ctx_access;
13517 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13518 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13519 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13520 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13523 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13524 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13525 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13526 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13527 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13528 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13529 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13530 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13532 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13537 if (type == BPF_WRITE &&
13538 env->insn_aux_data[i + delta].sanitize_stack_spill) {
13539 struct bpf_insn patch[] = {
13544 cnt = ARRAY_SIZE(patch);
13545 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13550 env->prog = new_prog;
13551 insn = new_prog->insnsi + i + delta;
13558 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13560 if (!ops->convert_ctx_access)
13562 convert_ctx_access = ops->convert_ctx_access;
13564 case PTR_TO_SOCKET:
13565 case PTR_TO_SOCK_COMMON:
13566 convert_ctx_access = bpf_sock_convert_ctx_access;
13568 case PTR_TO_TCP_SOCK:
13569 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13571 case PTR_TO_XDP_SOCK:
13572 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13574 case PTR_TO_BTF_ID:
13575 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13576 if (type == BPF_READ) {
13577 insn->code = BPF_LDX | BPF_PROBE_MEM |
13578 BPF_SIZE((insn)->code);
13579 env->prog->aux->num_exentries++;
13586 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13587 size = BPF_LDST_BYTES(insn);
13589 /* If the read access is a narrower load of the field,
13590 * convert to a 4/8-byte load, to minimum program type specific
13591 * convert_ctx_access changes. If conversion is successful,
13592 * we will apply proper mask to the result.
13594 is_narrower_load = size < ctx_field_size;
13595 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13597 if (is_narrower_load) {
13600 if (type == BPF_WRITE) {
13601 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13606 if (ctx_field_size == 4)
13608 else if (ctx_field_size == 8)
13609 size_code = BPF_DW;
13611 insn->off = off & ~(size_default - 1);
13612 insn->code = BPF_LDX | BPF_MEM | size_code;
13616 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13618 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13619 (ctx_field_size && !target_size)) {
13620 verbose(env, "bpf verifier is misconfigured\n");
13624 if (is_narrower_load && size < target_size) {
13625 u8 shift = bpf_ctx_narrow_access_offset(
13626 off, size, size_default) * 8;
13627 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13628 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13631 if (ctx_field_size <= 4) {
13633 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13636 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13637 (1 << size * 8) - 1);
13640 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13643 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13644 (1ULL << size * 8) - 1);
13648 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13654 /* keep walking new program and skip insns we just inserted */
13655 env->prog = new_prog;
13656 insn = new_prog->insnsi + i + delta;
13662 static int jit_subprogs(struct bpf_verifier_env *env)
13664 struct bpf_prog *prog = env->prog, **func, *tmp;
13665 int i, j, subprog_start, subprog_end = 0, len, subprog;
13666 struct bpf_map *map_ptr;
13667 struct bpf_insn *insn;
13668 void *old_bpf_func;
13669 int err, num_exentries;
13671 if (env->subprog_cnt <= 1)
13674 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13675 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13678 /* Upon error here we cannot fall back to interpreter but
13679 * need a hard reject of the program. Thus -EFAULT is
13680 * propagated in any case.
13682 subprog = find_subprog(env, i + insn->imm + 1);
13684 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13685 i + insn->imm + 1);
13688 /* temporarily remember subprog id inside insn instead of
13689 * aux_data, since next loop will split up all insns into funcs
13691 insn->off = subprog;
13692 /* remember original imm in case JIT fails and fallback
13693 * to interpreter will be needed
13695 env->insn_aux_data[i].call_imm = insn->imm;
13696 /* point imm to __bpf_call_base+1 from JITs point of view */
13698 if (bpf_pseudo_func(insn))
13699 /* jit (e.g. x86_64) may emit fewer instructions
13700 * if it learns a u32 imm is the same as a u64 imm.
13701 * Force a non zero here.
13706 err = bpf_prog_alloc_jited_linfo(prog);
13708 goto out_undo_insn;
13711 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13713 goto out_undo_insn;
13715 for (i = 0; i < env->subprog_cnt; i++) {
13716 subprog_start = subprog_end;
13717 subprog_end = env->subprog_info[i + 1].start;
13719 len = subprog_end - subprog_start;
13720 /* bpf_prog_run() doesn't call subprogs directly,
13721 * hence main prog stats include the runtime of subprogs.
13722 * subprogs don't have IDs and not reachable via prog_get_next_id
13723 * func[i]->stats will never be accessed and stays NULL
13725 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13728 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13729 len * sizeof(struct bpf_insn));
13730 func[i]->type = prog->type;
13731 func[i]->len = len;
13732 if (bpf_prog_calc_tag(func[i]))
13734 func[i]->is_func = 1;
13735 func[i]->aux->func_idx = i;
13736 /* Below members will be freed only at prog->aux */
13737 func[i]->aux->btf = prog->aux->btf;
13738 func[i]->aux->func_info = prog->aux->func_info;
13739 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13740 func[i]->aux->poke_tab = prog->aux->poke_tab;
13741 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13743 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13744 struct bpf_jit_poke_descriptor *poke;
13746 poke = &prog->aux->poke_tab[j];
13747 if (poke->insn_idx < subprog_end &&
13748 poke->insn_idx >= subprog_start)
13749 poke->aux = func[i]->aux;
13752 func[i]->aux->name[0] = 'F';
13753 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13754 func[i]->jit_requested = 1;
13755 func[i]->blinding_requested = prog->blinding_requested;
13756 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13757 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13758 func[i]->aux->linfo = prog->aux->linfo;
13759 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13760 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13761 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13763 insn = func[i]->insnsi;
13764 for (j = 0; j < func[i]->len; j++, insn++) {
13765 if (BPF_CLASS(insn->code) == BPF_LDX &&
13766 BPF_MODE(insn->code) == BPF_PROBE_MEM)
13769 func[i]->aux->num_exentries = num_exentries;
13770 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13771 func[i] = bpf_int_jit_compile(func[i]);
13772 if (!func[i]->jited) {
13779 /* at this point all bpf functions were successfully JITed
13780 * now populate all bpf_calls with correct addresses and
13781 * run last pass of JIT
13783 for (i = 0; i < env->subprog_cnt; i++) {
13784 insn = func[i]->insnsi;
13785 for (j = 0; j < func[i]->len; j++, insn++) {
13786 if (bpf_pseudo_func(insn)) {
13787 subprog = insn->off;
13788 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13789 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13792 if (!bpf_pseudo_call(insn))
13794 subprog = insn->off;
13795 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13798 /* we use the aux data to keep a list of the start addresses
13799 * of the JITed images for each function in the program
13801 * for some architectures, such as powerpc64, the imm field
13802 * might not be large enough to hold the offset of the start
13803 * address of the callee's JITed image from __bpf_call_base
13805 * in such cases, we can lookup the start address of a callee
13806 * by using its subprog id, available from the off field of
13807 * the call instruction, as an index for this list
13809 func[i]->aux->func = func;
13810 func[i]->aux->func_cnt = env->subprog_cnt;
13812 for (i = 0; i < env->subprog_cnt; i++) {
13813 old_bpf_func = func[i]->bpf_func;
13814 tmp = bpf_int_jit_compile(func[i]);
13815 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13816 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13823 /* finally lock prog and jit images for all functions and
13824 * populate kallsysm
13826 for (i = 0; i < env->subprog_cnt; i++) {
13827 bpf_prog_lock_ro(func[i]);
13828 bpf_prog_kallsyms_add(func[i]);
13831 /* Last step: make now unused interpreter insns from main
13832 * prog consistent for later dump requests, so they can
13833 * later look the same as if they were interpreted only.
13835 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13836 if (bpf_pseudo_func(insn)) {
13837 insn[0].imm = env->insn_aux_data[i].call_imm;
13838 insn[1].imm = insn->off;
13842 if (!bpf_pseudo_call(insn))
13844 insn->off = env->insn_aux_data[i].call_imm;
13845 subprog = find_subprog(env, i + insn->off + 1);
13846 insn->imm = subprog;
13850 prog->bpf_func = func[0]->bpf_func;
13851 prog->jited_len = func[0]->jited_len;
13852 prog->aux->func = func;
13853 prog->aux->func_cnt = env->subprog_cnt;
13854 bpf_prog_jit_attempt_done(prog);
13857 /* We failed JIT'ing, so at this point we need to unregister poke
13858 * descriptors from subprogs, so that kernel is not attempting to
13859 * patch it anymore as we're freeing the subprog JIT memory.
13861 for (i = 0; i < prog->aux->size_poke_tab; i++) {
13862 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13863 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13865 /* At this point we're guaranteed that poke descriptors are not
13866 * live anymore. We can just unlink its descriptor table as it's
13867 * released with the main prog.
13869 for (i = 0; i < env->subprog_cnt; i++) {
13872 func[i]->aux->poke_tab = NULL;
13873 bpf_jit_free(func[i]);
13877 /* cleanup main prog to be interpreted */
13878 prog->jit_requested = 0;
13879 prog->blinding_requested = 0;
13880 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13881 if (!bpf_pseudo_call(insn))
13884 insn->imm = env->insn_aux_data[i].call_imm;
13886 bpf_prog_jit_attempt_done(prog);
13890 static int fixup_call_args(struct bpf_verifier_env *env)
13892 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13893 struct bpf_prog *prog = env->prog;
13894 struct bpf_insn *insn = prog->insnsi;
13895 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13900 if (env->prog->jit_requested &&
13901 !bpf_prog_is_dev_bound(env->prog->aux)) {
13902 err = jit_subprogs(env);
13905 if (err == -EFAULT)
13908 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13909 if (has_kfunc_call) {
13910 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13913 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13914 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13915 * have to be rejected, since interpreter doesn't support them yet.
13917 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13920 for (i = 0; i < prog->len; i++, insn++) {
13921 if (bpf_pseudo_func(insn)) {
13922 /* When JIT fails the progs with callback calls
13923 * have to be rejected, since interpreter doesn't support them yet.
13925 verbose(env, "callbacks are not allowed in non-JITed programs\n");
13929 if (!bpf_pseudo_call(insn))
13931 depth = get_callee_stack_depth(env, insn, i);
13934 bpf_patch_call_args(insn, depth);
13941 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13942 struct bpf_insn *insn)
13944 const struct bpf_kfunc_desc *desc;
13947 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13951 /* insn->imm has the btf func_id. Replace it with
13952 * an address (relative to __bpf_base_call).
13954 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13956 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13961 insn->imm = desc->imm;
13966 /* Do various post-verification rewrites in a single program pass.
13967 * These rewrites simplify JIT and interpreter implementations.
13969 static int do_misc_fixups(struct bpf_verifier_env *env)
13971 struct bpf_prog *prog = env->prog;
13972 enum bpf_attach_type eatype = prog->expected_attach_type;
13973 enum bpf_prog_type prog_type = resolve_prog_type(prog);
13974 struct bpf_insn *insn = prog->insnsi;
13975 const struct bpf_func_proto *fn;
13976 const int insn_cnt = prog->len;
13977 const struct bpf_map_ops *ops;
13978 struct bpf_insn_aux_data *aux;
13979 struct bpf_insn insn_buf[16];
13980 struct bpf_prog *new_prog;
13981 struct bpf_map *map_ptr;
13982 int i, ret, cnt, delta = 0;
13984 for (i = 0; i < insn_cnt; i++, insn++) {
13985 /* Make divide-by-zero exceptions impossible. */
13986 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13987 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13988 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13989 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13990 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13991 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13992 struct bpf_insn *patchlet;
13993 struct bpf_insn chk_and_div[] = {
13994 /* [R,W]x div 0 -> 0 */
13995 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13996 BPF_JNE | BPF_K, insn->src_reg,
13998 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13999 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14002 struct bpf_insn chk_and_mod[] = {
14003 /* [R,W]x mod 0 -> [R,W]x */
14004 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14005 BPF_JEQ | BPF_K, insn->src_reg,
14006 0, 1 + (is64 ? 0 : 1), 0),
14008 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14009 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
14012 patchlet = isdiv ? chk_and_div : chk_and_mod;
14013 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
14014 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
14016 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
14021 env->prog = prog = new_prog;
14022 insn = new_prog->insnsi + i + delta;
14026 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
14027 if (BPF_CLASS(insn->code) == BPF_LD &&
14028 (BPF_MODE(insn->code) == BPF_ABS ||
14029 BPF_MODE(insn->code) == BPF_IND)) {
14030 cnt = env->ops->gen_ld_abs(insn, insn_buf);
14031 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14032 verbose(env, "bpf verifier is misconfigured\n");
14036 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14041 env->prog = prog = new_prog;
14042 insn = new_prog->insnsi + i + delta;
14046 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
14047 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
14048 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
14049 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
14050 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
14051 struct bpf_insn *patch = &insn_buf[0];
14052 bool issrc, isneg, isimm;
14055 aux = &env->insn_aux_data[i + delta];
14056 if (!aux->alu_state ||
14057 aux->alu_state == BPF_ALU_NON_POINTER)
14060 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14061 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14062 BPF_ALU_SANITIZE_SRC;
14063 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14065 off_reg = issrc ? insn->src_reg : insn->dst_reg;
14067 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14070 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14071 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14072 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14073 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14074 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14075 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14076 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14079 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14080 insn->src_reg = BPF_REG_AX;
14082 insn->code = insn->code == code_add ?
14083 code_sub : code_add;
14085 if (issrc && isneg && !isimm)
14086 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14087 cnt = patch - insn_buf;
14089 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14094 env->prog = prog = new_prog;
14095 insn = new_prog->insnsi + i + delta;
14099 if (insn->code != (BPF_JMP | BPF_CALL))
14101 if (insn->src_reg == BPF_PSEUDO_CALL)
14103 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14104 ret = fixup_kfunc_call(env, insn);
14110 if (insn->imm == BPF_FUNC_get_route_realm)
14111 prog->dst_needed = 1;
14112 if (insn->imm == BPF_FUNC_get_prandom_u32)
14113 bpf_user_rnd_init_once();
14114 if (insn->imm == BPF_FUNC_override_return)
14115 prog->kprobe_override = 1;
14116 if (insn->imm == BPF_FUNC_tail_call) {
14117 /* If we tail call into other programs, we
14118 * cannot make any assumptions since they can
14119 * be replaced dynamically during runtime in
14120 * the program array.
14122 prog->cb_access = 1;
14123 if (!allow_tail_call_in_subprogs(env))
14124 prog->aux->stack_depth = MAX_BPF_STACK;
14125 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14127 /* mark bpf_tail_call as different opcode to avoid
14128 * conditional branch in the interpreter for every normal
14129 * call and to prevent accidental JITing by JIT compiler
14130 * that doesn't support bpf_tail_call yet
14133 insn->code = BPF_JMP | BPF_TAIL_CALL;
14135 aux = &env->insn_aux_data[i + delta];
14136 if (env->bpf_capable && !prog->blinding_requested &&
14137 prog->jit_requested &&
14138 !bpf_map_key_poisoned(aux) &&
14139 !bpf_map_ptr_poisoned(aux) &&
14140 !bpf_map_ptr_unpriv(aux)) {
14141 struct bpf_jit_poke_descriptor desc = {
14142 .reason = BPF_POKE_REASON_TAIL_CALL,
14143 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14144 .tail_call.key = bpf_map_key_immediate(aux),
14145 .insn_idx = i + delta,
14148 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14150 verbose(env, "adding tail call poke descriptor failed\n");
14154 insn->imm = ret + 1;
14158 if (!bpf_map_ptr_unpriv(aux))
14161 /* instead of changing every JIT dealing with tail_call
14162 * emit two extra insns:
14163 * if (index >= max_entries) goto out;
14164 * index &= array->index_mask;
14165 * to avoid out-of-bounds cpu speculation
14167 if (bpf_map_ptr_poisoned(aux)) {
14168 verbose(env, "tail_call abusing map_ptr\n");
14172 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14173 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14174 map_ptr->max_entries, 2);
14175 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14176 container_of(map_ptr,
14179 insn_buf[2] = *insn;
14181 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14186 env->prog = prog = new_prog;
14187 insn = new_prog->insnsi + i + delta;
14191 if (insn->imm == BPF_FUNC_timer_set_callback) {
14192 /* The verifier will process callback_fn as many times as necessary
14193 * with different maps and the register states prepared by
14194 * set_timer_callback_state will be accurate.
14196 * The following use case is valid:
14197 * map1 is shared by prog1, prog2, prog3.
14198 * prog1 calls bpf_timer_init for some map1 elements
14199 * prog2 calls bpf_timer_set_callback for some map1 elements.
14200 * Those that were not bpf_timer_init-ed will return -EINVAL.
14201 * prog3 calls bpf_timer_start for some map1 elements.
14202 * Those that were not both bpf_timer_init-ed and
14203 * bpf_timer_set_callback-ed will return -EINVAL.
14205 struct bpf_insn ld_addrs[2] = {
14206 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14209 insn_buf[0] = ld_addrs[0];
14210 insn_buf[1] = ld_addrs[1];
14211 insn_buf[2] = *insn;
14214 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14219 env->prog = prog = new_prog;
14220 insn = new_prog->insnsi + i + delta;
14221 goto patch_call_imm;
14224 if (insn->imm == BPF_FUNC_task_storage_get ||
14225 insn->imm == BPF_FUNC_sk_storage_get ||
14226 insn->imm == BPF_FUNC_inode_storage_get) {
14227 if (env->prog->aux->sleepable)
14228 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14230 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14231 insn_buf[1] = *insn;
14234 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14239 env->prog = prog = new_prog;
14240 insn = new_prog->insnsi + i + delta;
14241 goto patch_call_imm;
14244 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14245 * and other inlining handlers are currently limited to 64 bit
14248 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14249 (insn->imm == BPF_FUNC_map_lookup_elem ||
14250 insn->imm == BPF_FUNC_map_update_elem ||
14251 insn->imm == BPF_FUNC_map_delete_elem ||
14252 insn->imm == BPF_FUNC_map_push_elem ||
14253 insn->imm == BPF_FUNC_map_pop_elem ||
14254 insn->imm == BPF_FUNC_map_peek_elem ||
14255 insn->imm == BPF_FUNC_redirect_map ||
14256 insn->imm == BPF_FUNC_for_each_map_elem ||
14257 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14258 aux = &env->insn_aux_data[i + delta];
14259 if (bpf_map_ptr_poisoned(aux))
14260 goto patch_call_imm;
14262 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14263 ops = map_ptr->ops;
14264 if (insn->imm == BPF_FUNC_map_lookup_elem &&
14265 ops->map_gen_lookup) {
14266 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14267 if (cnt == -EOPNOTSUPP)
14268 goto patch_map_ops_generic;
14269 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14270 verbose(env, "bpf verifier is misconfigured\n");
14274 new_prog = bpf_patch_insn_data(env, i + delta,
14280 env->prog = prog = new_prog;
14281 insn = new_prog->insnsi + i + delta;
14285 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14286 (void *(*)(struct bpf_map *map, void *key))NULL));
14287 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14288 (int (*)(struct bpf_map *map, void *key))NULL));
14289 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14290 (int (*)(struct bpf_map *map, void *key, void *value,
14292 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14293 (int (*)(struct bpf_map *map, void *value,
14295 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14296 (int (*)(struct bpf_map *map, void *value))NULL));
14297 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14298 (int (*)(struct bpf_map *map, void *value))NULL));
14299 BUILD_BUG_ON(!__same_type(ops->map_redirect,
14300 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14301 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14302 (int (*)(struct bpf_map *map,
14303 bpf_callback_t callback_fn,
14304 void *callback_ctx,
14306 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14307 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14309 patch_map_ops_generic:
14310 switch (insn->imm) {
14311 case BPF_FUNC_map_lookup_elem:
14312 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14314 case BPF_FUNC_map_update_elem:
14315 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14317 case BPF_FUNC_map_delete_elem:
14318 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14320 case BPF_FUNC_map_push_elem:
14321 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14323 case BPF_FUNC_map_pop_elem:
14324 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14326 case BPF_FUNC_map_peek_elem:
14327 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14329 case BPF_FUNC_redirect_map:
14330 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14332 case BPF_FUNC_for_each_map_elem:
14333 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14335 case BPF_FUNC_map_lookup_percpu_elem:
14336 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14340 goto patch_call_imm;
14343 /* Implement bpf_jiffies64 inline. */
14344 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14345 insn->imm == BPF_FUNC_jiffies64) {
14346 struct bpf_insn ld_jiffies_addr[2] = {
14347 BPF_LD_IMM64(BPF_REG_0,
14348 (unsigned long)&jiffies),
14351 insn_buf[0] = ld_jiffies_addr[0];
14352 insn_buf[1] = ld_jiffies_addr[1];
14353 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14357 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14363 env->prog = prog = new_prog;
14364 insn = new_prog->insnsi + i + delta;
14368 /* Implement bpf_get_func_arg inline. */
14369 if (prog_type == BPF_PROG_TYPE_TRACING &&
14370 insn->imm == BPF_FUNC_get_func_arg) {
14371 /* Load nr_args from ctx - 8 */
14372 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14373 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14374 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14375 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14376 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14377 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14378 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14379 insn_buf[7] = BPF_JMP_A(1);
14380 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14383 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14388 env->prog = prog = new_prog;
14389 insn = new_prog->insnsi + i + delta;
14393 /* Implement bpf_get_func_ret inline. */
14394 if (prog_type == BPF_PROG_TYPE_TRACING &&
14395 insn->imm == BPF_FUNC_get_func_ret) {
14396 if (eatype == BPF_TRACE_FEXIT ||
14397 eatype == BPF_MODIFY_RETURN) {
14398 /* Load nr_args from ctx - 8 */
14399 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14400 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14401 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14402 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14403 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14404 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14407 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14411 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14416 env->prog = prog = new_prog;
14417 insn = new_prog->insnsi + i + delta;
14421 /* Implement get_func_arg_cnt inline. */
14422 if (prog_type == BPF_PROG_TYPE_TRACING &&
14423 insn->imm == BPF_FUNC_get_func_arg_cnt) {
14424 /* Load nr_args from ctx - 8 */
14425 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14427 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14431 env->prog = prog = new_prog;
14432 insn = new_prog->insnsi + i + delta;
14436 /* Implement bpf_get_func_ip inline. */
14437 if (prog_type == BPF_PROG_TYPE_TRACING &&
14438 insn->imm == BPF_FUNC_get_func_ip) {
14439 /* Load IP address from ctx - 16 */
14440 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14442 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14446 env->prog = prog = new_prog;
14447 insn = new_prog->insnsi + i + delta;
14452 fn = env->ops->get_func_proto(insn->imm, env->prog);
14453 /* all functions that have prototype and verifier allowed
14454 * programs to call them, must be real in-kernel functions
14458 "kernel subsystem misconfigured func %s#%d\n",
14459 func_id_name(insn->imm), insn->imm);
14462 insn->imm = fn->func - __bpf_call_base;
14465 /* Since poke tab is now finalized, publish aux to tracker. */
14466 for (i = 0; i < prog->aux->size_poke_tab; i++) {
14467 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14468 if (!map_ptr->ops->map_poke_track ||
14469 !map_ptr->ops->map_poke_untrack ||
14470 !map_ptr->ops->map_poke_run) {
14471 verbose(env, "bpf verifier is misconfigured\n");
14475 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14477 verbose(env, "tracking tail call prog failed\n");
14482 sort_kfunc_descs_by_imm(env->prog);
14487 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14490 u32 callback_subprogno,
14493 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14494 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14495 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14496 int reg_loop_max = BPF_REG_6;
14497 int reg_loop_cnt = BPF_REG_7;
14498 int reg_loop_ctx = BPF_REG_8;
14500 struct bpf_prog *new_prog;
14501 u32 callback_start;
14502 u32 call_insn_offset;
14503 s32 callback_offset;
14505 /* This represents an inlined version of bpf_iter.c:bpf_loop,
14506 * be careful to modify this code in sync.
14508 struct bpf_insn insn_buf[] = {
14509 /* Return error and jump to the end of the patch if
14510 * expected number of iterations is too big.
14512 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14513 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14514 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14515 /* spill R6, R7, R8 to use these as loop vars */
14516 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14517 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14518 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14519 /* initialize loop vars */
14520 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14521 BPF_MOV32_IMM(reg_loop_cnt, 0),
14522 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14524 * if reg_loop_cnt >= reg_loop_max skip the loop body
14526 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14528 * correct callback offset would be set after patching
14530 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14531 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14533 /* increment loop counter */
14534 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14535 /* jump to loop header if callback returned 0 */
14536 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14537 /* return value of bpf_loop,
14538 * set R0 to the number of iterations
14540 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14541 /* restore original values of R6, R7, R8 */
14542 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14543 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14544 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14547 *cnt = ARRAY_SIZE(insn_buf);
14548 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14552 /* callback start is known only after patching */
14553 callback_start = env->subprog_info[callback_subprogno].start;
14554 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14555 call_insn_offset = position + 12;
14556 callback_offset = callback_start - call_insn_offset - 1;
14557 new_prog->insnsi[call_insn_offset].imm = callback_offset;
14562 static bool is_bpf_loop_call(struct bpf_insn *insn)
14564 return insn->code == (BPF_JMP | BPF_CALL) &&
14565 insn->src_reg == 0 &&
14566 insn->imm == BPF_FUNC_loop;
14569 /* For all sub-programs in the program (including main) check
14570 * insn_aux_data to see if there are bpf_loop calls that require
14571 * inlining. If such calls are found the calls are replaced with a
14572 * sequence of instructions produced by `inline_bpf_loop` function and
14573 * subprog stack_depth is increased by the size of 3 registers.
14574 * This stack space is used to spill values of the R6, R7, R8. These
14575 * registers are used to store the loop bound, counter and context
14578 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14580 struct bpf_subprog_info *subprogs = env->subprog_info;
14581 int i, cur_subprog = 0, cnt, delta = 0;
14582 struct bpf_insn *insn = env->prog->insnsi;
14583 int insn_cnt = env->prog->len;
14584 u16 stack_depth = subprogs[cur_subprog].stack_depth;
14585 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14586 u16 stack_depth_extra = 0;
14588 for (i = 0; i < insn_cnt; i++, insn++) {
14589 struct bpf_loop_inline_state *inline_state =
14590 &env->insn_aux_data[i + delta].loop_inline_state;
14592 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14593 struct bpf_prog *new_prog;
14595 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14596 new_prog = inline_bpf_loop(env,
14598 -(stack_depth + stack_depth_extra),
14599 inline_state->callback_subprogno,
14605 env->prog = new_prog;
14606 insn = new_prog->insnsi + i + delta;
14609 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14610 subprogs[cur_subprog].stack_depth += stack_depth_extra;
14612 stack_depth = subprogs[cur_subprog].stack_depth;
14613 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14614 stack_depth_extra = 0;
14618 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14623 static void free_states(struct bpf_verifier_env *env)
14625 struct bpf_verifier_state_list *sl, *sln;
14628 sl = env->free_list;
14631 free_verifier_state(&sl->state, false);
14635 env->free_list = NULL;
14637 if (!env->explored_states)
14640 for (i = 0; i < state_htab_size(env); i++) {
14641 sl = env->explored_states[i];
14645 free_verifier_state(&sl->state, false);
14649 env->explored_states[i] = NULL;
14653 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14655 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14656 struct bpf_verifier_state *state;
14657 struct bpf_reg_state *regs;
14660 env->prev_linfo = NULL;
14663 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14666 state->curframe = 0;
14667 state->speculative = false;
14668 state->branches = 1;
14669 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14670 if (!state->frame[0]) {
14674 env->cur_state = state;
14675 init_func_state(env, state->frame[0],
14676 BPF_MAIN_FUNC /* callsite */,
14680 regs = state->frame[state->curframe]->regs;
14681 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14682 ret = btf_prepare_func_args(env, subprog, regs);
14685 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14686 if (regs[i].type == PTR_TO_CTX)
14687 mark_reg_known_zero(env, regs, i);
14688 else if (regs[i].type == SCALAR_VALUE)
14689 mark_reg_unknown(env, regs, i);
14690 else if (base_type(regs[i].type) == PTR_TO_MEM) {
14691 const u32 mem_size = regs[i].mem_size;
14693 mark_reg_known_zero(env, regs, i);
14694 regs[i].mem_size = mem_size;
14695 regs[i].id = ++env->id_gen;
14699 /* 1st arg to a function */
14700 regs[BPF_REG_1].type = PTR_TO_CTX;
14701 mark_reg_known_zero(env, regs, BPF_REG_1);
14702 ret = btf_check_subprog_arg_match(env, subprog, regs);
14703 if (ret == -EFAULT)
14704 /* unlikely verifier bug. abort.
14705 * ret == 0 and ret < 0 are sadly acceptable for
14706 * main() function due to backward compatibility.
14707 * Like socket filter program may be written as:
14708 * int bpf_prog(struct pt_regs *ctx)
14709 * and never dereference that ctx in the program.
14710 * 'struct pt_regs' is a type mismatch for socket
14711 * filter that should be using 'struct __sk_buff'.
14716 ret = do_check(env);
14718 /* check for NULL is necessary, since cur_state can be freed inside
14719 * do_check() under memory pressure.
14721 if (env->cur_state) {
14722 free_verifier_state(env->cur_state, true);
14723 env->cur_state = NULL;
14725 while (!pop_stack(env, NULL, NULL, false));
14726 if (!ret && pop_log)
14727 bpf_vlog_reset(&env->log, 0);
14732 /* Verify all global functions in a BPF program one by one based on their BTF.
14733 * All global functions must pass verification. Otherwise the whole program is rejected.
14744 * foo() will be verified first for R1=any_scalar_value. During verification it
14745 * will be assumed that bar() already verified successfully and call to bar()
14746 * from foo() will be checked for type match only. Later bar() will be verified
14747 * independently to check that it's safe for R1=any_scalar_value.
14749 static int do_check_subprogs(struct bpf_verifier_env *env)
14751 struct bpf_prog_aux *aux = env->prog->aux;
14754 if (!aux->func_info)
14757 for (i = 1; i < env->subprog_cnt; i++) {
14758 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14760 env->insn_idx = env->subprog_info[i].start;
14761 WARN_ON_ONCE(env->insn_idx == 0);
14762 ret = do_check_common(env, i);
14765 } else if (env->log.level & BPF_LOG_LEVEL) {
14767 "Func#%d is safe for any args that match its prototype\n",
14774 static int do_check_main(struct bpf_verifier_env *env)
14779 ret = do_check_common(env, 0);
14781 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14786 static void print_verification_stats(struct bpf_verifier_env *env)
14790 if (env->log.level & BPF_LOG_STATS) {
14791 verbose(env, "verification time %lld usec\n",
14792 div_u64(env->verification_time, 1000));
14793 verbose(env, "stack depth ");
14794 for (i = 0; i < env->subprog_cnt; i++) {
14795 u32 depth = env->subprog_info[i].stack_depth;
14797 verbose(env, "%d", depth);
14798 if (i + 1 < env->subprog_cnt)
14801 verbose(env, "\n");
14803 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14804 "total_states %d peak_states %d mark_read %d\n",
14805 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14806 env->max_states_per_insn, env->total_states,
14807 env->peak_states, env->longest_mark_read_walk);
14810 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14812 const struct btf_type *t, *func_proto;
14813 const struct bpf_struct_ops *st_ops;
14814 const struct btf_member *member;
14815 struct bpf_prog *prog = env->prog;
14816 u32 btf_id, member_idx;
14819 if (!prog->gpl_compatible) {
14820 verbose(env, "struct ops programs must have a GPL compatible license\n");
14824 btf_id = prog->aux->attach_btf_id;
14825 st_ops = bpf_struct_ops_find(btf_id);
14827 verbose(env, "attach_btf_id %u is not a supported struct\n",
14833 member_idx = prog->expected_attach_type;
14834 if (member_idx >= btf_type_vlen(t)) {
14835 verbose(env, "attach to invalid member idx %u of struct %s\n",
14836 member_idx, st_ops->name);
14840 member = &btf_type_member(t)[member_idx];
14841 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14842 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14845 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14846 mname, member_idx, st_ops->name);
14850 if (st_ops->check_member) {
14851 int err = st_ops->check_member(t, member);
14854 verbose(env, "attach to unsupported member %s of struct %s\n",
14855 mname, st_ops->name);
14860 prog->aux->attach_func_proto = func_proto;
14861 prog->aux->attach_func_name = mname;
14862 env->ops = st_ops->verifier_ops;
14866 #define SECURITY_PREFIX "security_"
14868 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14870 if (within_error_injection_list(addr) ||
14871 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14877 /* list of non-sleepable functions that are otherwise on
14878 * ALLOW_ERROR_INJECTION list
14880 BTF_SET_START(btf_non_sleepable_error_inject)
14881 /* Three functions below can be called from sleepable and non-sleepable context.
14882 * Assume non-sleepable from bpf safety point of view.
14884 BTF_ID(func, __filemap_add_folio)
14885 BTF_ID(func, should_fail_alloc_page)
14886 BTF_ID(func, should_failslab)
14887 BTF_SET_END(btf_non_sleepable_error_inject)
14889 static int check_non_sleepable_error_inject(u32 btf_id)
14891 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14894 int bpf_check_attach_target(struct bpf_verifier_log *log,
14895 const struct bpf_prog *prog,
14896 const struct bpf_prog *tgt_prog,
14898 struct bpf_attach_target_info *tgt_info)
14900 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14901 const char prefix[] = "btf_trace_";
14902 int ret = 0, subprog = -1, i;
14903 const struct btf_type *t;
14904 bool conservative = true;
14910 bpf_log(log, "Tracing programs must provide btf_id\n");
14913 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14916 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14919 t = btf_type_by_id(btf, btf_id);
14921 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14924 tname = btf_name_by_offset(btf, t->name_off);
14926 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14930 struct bpf_prog_aux *aux = tgt_prog->aux;
14932 for (i = 0; i < aux->func_info_cnt; i++)
14933 if (aux->func_info[i].type_id == btf_id) {
14937 if (subprog == -1) {
14938 bpf_log(log, "Subprog %s doesn't exist\n", tname);
14941 conservative = aux->func_info_aux[subprog].unreliable;
14942 if (prog_extension) {
14943 if (conservative) {
14945 "Cannot replace static functions\n");
14948 if (!prog->jit_requested) {
14950 "Extension programs should be JITed\n");
14954 if (!tgt_prog->jited) {
14955 bpf_log(log, "Can attach to only JITed progs\n");
14958 if (tgt_prog->type == prog->type) {
14959 /* Cannot fentry/fexit another fentry/fexit program.
14960 * Cannot attach program extension to another extension.
14961 * It's ok to attach fentry/fexit to extension program.
14963 bpf_log(log, "Cannot recursively attach\n");
14966 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14968 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14969 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14970 /* Program extensions can extend all program types
14971 * except fentry/fexit. The reason is the following.
14972 * The fentry/fexit programs are used for performance
14973 * analysis, stats and can be attached to any program
14974 * type except themselves. When extension program is
14975 * replacing XDP function it is necessary to allow
14976 * performance analysis of all functions. Both original
14977 * XDP program and its program extension. Hence
14978 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14979 * allowed. If extending of fentry/fexit was allowed it
14980 * would be possible to create long call chain
14981 * fentry->extension->fentry->extension beyond
14982 * reasonable stack size. Hence extending fentry is not
14985 bpf_log(log, "Cannot extend fentry/fexit\n");
14989 if (prog_extension) {
14990 bpf_log(log, "Cannot replace kernel functions\n");
14995 switch (prog->expected_attach_type) {
14996 case BPF_TRACE_RAW_TP:
14999 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
15002 if (!btf_type_is_typedef(t)) {
15003 bpf_log(log, "attach_btf_id %u is not a typedef\n",
15007 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
15008 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
15012 tname += sizeof(prefix) - 1;
15013 t = btf_type_by_id(btf, t->type);
15014 if (!btf_type_is_ptr(t))
15015 /* should never happen in valid vmlinux build */
15017 t = btf_type_by_id(btf, t->type);
15018 if (!btf_type_is_func_proto(t))
15019 /* should never happen in valid vmlinux build */
15023 case BPF_TRACE_ITER:
15024 if (!btf_type_is_func(t)) {
15025 bpf_log(log, "attach_btf_id %u is not a function\n",
15029 t = btf_type_by_id(btf, t->type);
15030 if (!btf_type_is_func_proto(t))
15032 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15037 if (!prog_extension)
15040 case BPF_MODIFY_RETURN:
15042 case BPF_LSM_CGROUP:
15043 case BPF_TRACE_FENTRY:
15044 case BPF_TRACE_FEXIT:
15045 if (!btf_type_is_func(t)) {
15046 bpf_log(log, "attach_btf_id %u is not a function\n",
15050 if (prog_extension &&
15051 btf_check_type_match(log, prog, btf, t))
15053 t = btf_type_by_id(btf, t->type);
15054 if (!btf_type_is_func_proto(t))
15057 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15058 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15059 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15062 if (tgt_prog && conservative)
15065 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15071 addr = (long) tgt_prog->bpf_func;
15073 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15075 addr = kallsyms_lookup_name(tname);
15078 "The address of function %s cannot be found\n",
15084 if (prog->aux->sleepable) {
15086 switch (prog->type) {
15087 case BPF_PROG_TYPE_TRACING:
15088 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
15089 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15091 if (!check_non_sleepable_error_inject(btf_id) &&
15092 within_error_injection_list(addr))
15095 case BPF_PROG_TYPE_LSM:
15096 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
15097 * Only some of them are sleepable.
15099 if (bpf_lsm_is_sleepable_hook(btf_id))
15106 bpf_log(log, "%s is not sleepable\n", tname);
15109 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15111 bpf_log(log, "can't modify return codes of BPF programs\n");
15114 ret = check_attach_modify_return(addr, tname);
15116 bpf_log(log, "%s() is not modifiable\n", tname);
15123 tgt_info->tgt_addr = addr;
15124 tgt_info->tgt_name = tname;
15125 tgt_info->tgt_type = t;
15129 BTF_SET_START(btf_id_deny)
15132 BTF_ID(func, migrate_disable)
15133 BTF_ID(func, migrate_enable)
15135 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15136 BTF_ID(func, rcu_read_unlock_strict)
15138 BTF_SET_END(btf_id_deny)
15140 static int check_attach_btf_id(struct bpf_verifier_env *env)
15142 struct bpf_prog *prog = env->prog;
15143 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15144 struct bpf_attach_target_info tgt_info = {};
15145 u32 btf_id = prog->aux->attach_btf_id;
15146 struct bpf_trampoline *tr;
15150 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15151 if (prog->aux->sleepable)
15152 /* attach_btf_id checked to be zero already */
15154 verbose(env, "Syscall programs can only be sleepable\n");
15158 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15159 prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15160 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15164 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15165 return check_struct_ops_btf_id(env);
15167 if (prog->type != BPF_PROG_TYPE_TRACING &&
15168 prog->type != BPF_PROG_TYPE_LSM &&
15169 prog->type != BPF_PROG_TYPE_EXT)
15172 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15176 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15177 /* to make freplace equivalent to their targets, they need to
15178 * inherit env->ops and expected_attach_type for the rest of the
15181 env->ops = bpf_verifier_ops[tgt_prog->type];
15182 prog->expected_attach_type = tgt_prog->expected_attach_type;
15185 /* store info about the attachment target that will be used later */
15186 prog->aux->attach_func_proto = tgt_info.tgt_type;
15187 prog->aux->attach_func_name = tgt_info.tgt_name;
15190 prog->aux->saved_dst_prog_type = tgt_prog->type;
15191 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15194 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15195 prog->aux->attach_btf_trace = true;
15197 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15198 if (!bpf_iter_prog_supported(prog))
15203 if (prog->type == BPF_PROG_TYPE_LSM) {
15204 ret = bpf_lsm_verify_prog(&env->log, prog);
15207 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15208 btf_id_set_contains(&btf_id_deny, btf_id)) {
15212 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15213 tr = bpf_trampoline_get(key, &tgt_info);
15217 prog->aux->dst_trampoline = tr;
15221 struct btf *bpf_get_btf_vmlinux(void)
15223 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15224 mutex_lock(&bpf_verifier_lock);
15226 btf_vmlinux = btf_parse_vmlinux();
15227 mutex_unlock(&bpf_verifier_lock);
15229 return btf_vmlinux;
15232 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15234 u64 start_time = ktime_get_ns();
15235 struct bpf_verifier_env *env;
15236 struct bpf_verifier_log *log;
15237 int i, len, ret = -EINVAL;
15240 /* no program is valid */
15241 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15244 /* 'struct bpf_verifier_env' can be global, but since it's not small,
15245 * allocate/free it every time bpf_check() is called
15247 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15252 len = (*prog)->len;
15253 env->insn_aux_data =
15254 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15256 if (!env->insn_aux_data)
15258 for (i = 0; i < len; i++)
15259 env->insn_aux_data[i].orig_idx = i;
15261 env->ops = bpf_verifier_ops[env->prog->type];
15262 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15263 is_priv = bpf_capable();
15265 bpf_get_btf_vmlinux();
15267 /* grab the mutex to protect few globals used by verifier */
15269 mutex_lock(&bpf_verifier_lock);
15271 if (attr->log_level || attr->log_buf || attr->log_size) {
15272 /* user requested verbose verifier output
15273 * and supplied buffer to store the verification trace
15275 log->level = attr->log_level;
15276 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15277 log->len_total = attr->log_size;
15279 /* log attributes have to be sane */
15280 if (!bpf_verifier_log_attr_valid(log)) {
15286 mark_verifier_state_clean(env);
15288 if (IS_ERR(btf_vmlinux)) {
15289 /* Either gcc or pahole or kernel are broken. */
15290 verbose(env, "in-kernel BTF is malformed\n");
15291 ret = PTR_ERR(btf_vmlinux);
15292 goto skip_full_check;
15295 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15296 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15297 env->strict_alignment = true;
15298 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15299 env->strict_alignment = false;
15301 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15302 env->allow_uninit_stack = bpf_allow_uninit_stack();
15303 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15304 env->bypass_spec_v1 = bpf_bypass_spec_v1();
15305 env->bypass_spec_v4 = bpf_bypass_spec_v4();
15306 env->bpf_capable = bpf_capable();
15309 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15311 env->explored_states = kvcalloc(state_htab_size(env),
15312 sizeof(struct bpf_verifier_state_list *),
15315 if (!env->explored_states)
15316 goto skip_full_check;
15318 ret = add_subprog_and_kfunc(env);
15320 goto skip_full_check;
15322 ret = check_subprogs(env);
15324 goto skip_full_check;
15326 ret = check_btf_info(env, attr, uattr);
15328 goto skip_full_check;
15330 ret = check_attach_btf_id(env);
15332 goto skip_full_check;
15334 ret = resolve_pseudo_ldimm64(env);
15336 goto skip_full_check;
15338 if (bpf_prog_is_dev_bound(env->prog->aux)) {
15339 ret = bpf_prog_offload_verifier_prep(env->prog);
15341 goto skip_full_check;
15344 ret = check_cfg(env);
15346 goto skip_full_check;
15348 ret = do_check_subprogs(env);
15349 ret = ret ?: do_check_main(env);
15351 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15352 ret = bpf_prog_offload_finalize(env);
15355 kvfree(env->explored_states);
15358 ret = check_max_stack_depth(env);
15360 /* instruction rewrites happen after this point */
15362 ret = optimize_bpf_loop(env);
15366 opt_hard_wire_dead_code_branches(env);
15368 ret = opt_remove_dead_code(env);
15370 ret = opt_remove_nops(env);
15373 sanitize_dead_code(env);
15377 /* program is valid, convert *(u32*)(ctx + off) accesses */
15378 ret = convert_ctx_accesses(env);
15381 ret = do_misc_fixups(env);
15383 /* do 32-bit optimization after insn patching has done so those patched
15384 * insns could be handled correctly.
15386 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15387 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15388 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15393 ret = fixup_call_args(env);
15395 env->verification_time = ktime_get_ns() - start_time;
15396 print_verification_stats(env);
15397 env->prog->aux->verified_insns = env->insn_processed;
15399 if (log->level && bpf_verifier_log_full(log))
15401 if (log->level && !log->ubuf) {
15403 goto err_release_maps;
15407 goto err_release_maps;
15409 if (env->used_map_cnt) {
15410 /* if program passed verifier, update used_maps in bpf_prog_info */
15411 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15412 sizeof(env->used_maps[0]),
15415 if (!env->prog->aux->used_maps) {
15417 goto err_release_maps;
15420 memcpy(env->prog->aux->used_maps, env->used_maps,
15421 sizeof(env->used_maps[0]) * env->used_map_cnt);
15422 env->prog->aux->used_map_cnt = env->used_map_cnt;
15424 if (env->used_btf_cnt) {
15425 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15426 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15427 sizeof(env->used_btfs[0]),
15429 if (!env->prog->aux->used_btfs) {
15431 goto err_release_maps;
15434 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15435 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15436 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15438 if (env->used_map_cnt || env->used_btf_cnt) {
15439 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15440 * bpf_ld_imm64 instructions
15442 convert_pseudo_ld_imm64(env);
15445 adjust_btf_func(env);
15448 if (!env->prog->aux->used_maps)
15449 /* if we didn't copy map pointers into bpf_prog_info, release
15450 * them now. Otherwise free_used_maps() will release them.
15453 if (!env->prog->aux->used_btfs)
15456 /* extension progs temporarily inherit the attach_type of their targets
15457 for verification purposes, so set it back to zero before returning
15459 if (env->prog->type == BPF_PROG_TYPE_EXT)
15460 env->prog->expected_attach_type = 0;
15465 mutex_unlock(&bpf_verifier_lock);
15466 vfree(env->insn_aux_data);