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) {
2686 } else if (class == BPF_LD) {
2687 if (!(*reg_mask & dreg))
2690 /* It's ld_imm64 or ld_abs or ld_ind.
2691 * For ld_imm64 no further tracking of precision
2692 * into parent is necessary
2694 if (mode == BPF_IND || mode == BPF_ABS)
2695 /* to be analyzed */
2701 /* the scalar precision tracking algorithm:
2702 * . at the start all registers have precise=false.
2703 * . scalar ranges are tracked as normal through alu and jmp insns.
2704 * . once precise value of the scalar register is used in:
2705 * . ptr + scalar alu
2706 * . if (scalar cond K|scalar)
2707 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2708 * backtrack through the verifier states and mark all registers and
2709 * stack slots with spilled constants that these scalar regisers
2710 * should be precise.
2711 * . during state pruning two registers (or spilled stack slots)
2712 * are equivalent if both are not precise.
2714 * Note the verifier cannot simply walk register parentage chain,
2715 * since many different registers and stack slots could have been
2716 * used to compute single precise scalar.
2718 * The approach of starting with precise=true for all registers and then
2719 * backtrack to mark a register as not precise when the verifier detects
2720 * that program doesn't care about specific value (e.g., when helper
2721 * takes register as ARG_ANYTHING parameter) is not safe.
2723 * It's ok to walk single parentage chain of the verifier states.
2724 * It's possible that this backtracking will go all the way till 1st insn.
2725 * All other branches will be explored for needing precision later.
2727 * The backtracking needs to deal with cases like:
2728 * 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)
2731 * if r5 > 0x79f goto pc+7
2732 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2735 * call bpf_perf_event_output#25
2736 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2740 * call foo // uses callee's r6 inside to compute r0
2744 * to track above reg_mask/stack_mask needs to be independent for each frame.
2746 * Also if parent's curframe > frame where backtracking started,
2747 * the verifier need to mark registers in both frames, otherwise callees
2748 * may incorrectly prune callers. This is similar to
2749 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2751 * For now backtracking falls back into conservative marking.
2753 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2754 struct bpf_verifier_state *st)
2756 struct bpf_func_state *func;
2757 struct bpf_reg_state *reg;
2760 /* big hammer: mark all scalars precise in this path.
2761 * pop_stack may still get !precise scalars.
2763 for (; st; st = st->parent)
2764 for (i = 0; i <= st->curframe; i++) {
2765 func = st->frame[i];
2766 for (j = 0; j < BPF_REG_FP; j++) {
2767 reg = &func->regs[j];
2768 if (reg->type != SCALAR_VALUE)
2770 reg->precise = true;
2772 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2773 if (!is_spilled_reg(&func->stack[j]))
2775 reg = &func->stack[j].spilled_ptr;
2776 if (reg->type != SCALAR_VALUE)
2778 reg->precise = true;
2783 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2786 struct bpf_verifier_state *st = env->cur_state;
2787 int first_idx = st->first_insn_idx;
2788 int last_idx = env->insn_idx;
2789 struct bpf_func_state *func;
2790 struct bpf_reg_state *reg;
2791 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2792 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2793 bool skip_first = true;
2794 bool new_marks = false;
2797 if (!env->bpf_capable)
2800 func = st->frame[frame];
2802 reg = &func->regs[regno];
2803 if (reg->type != SCALAR_VALUE) {
2804 WARN_ONCE(1, "backtracing misuse");
2811 reg->precise = true;
2815 if (!is_spilled_reg(&func->stack[spi])) {
2819 reg = &func->stack[spi].spilled_ptr;
2820 if (reg->type != SCALAR_VALUE) {
2828 reg->precise = true;
2834 if (!reg_mask && !stack_mask)
2837 DECLARE_BITMAP(mask, 64);
2838 u32 history = st->jmp_history_cnt;
2840 if (env->log.level & BPF_LOG_LEVEL2)
2841 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2842 for (i = last_idx;;) {
2847 err = backtrack_insn(env, i, ®_mask, &stack_mask);
2849 if (err == -ENOTSUPP) {
2850 mark_all_scalars_precise(env, st);
2855 if (!reg_mask && !stack_mask)
2856 /* Found assignment(s) into tracked register in this state.
2857 * Since this state is already marked, just return.
2858 * Nothing to be tracked further in the parent state.
2863 i = get_prev_insn_idx(st, i, &history);
2864 if (i >= env->prog->len) {
2865 /* This can happen if backtracking reached insn 0
2866 * and there are still reg_mask or stack_mask
2868 * It means the backtracking missed the spot where
2869 * particular register was initialized with a constant.
2871 verbose(env, "BUG backtracking idx %d\n", i);
2872 WARN_ONCE(1, "verifier backtracking bug");
2881 func = st->frame[frame];
2882 bitmap_from_u64(mask, reg_mask);
2883 for_each_set_bit(i, mask, 32) {
2884 reg = &func->regs[i];
2885 if (reg->type != SCALAR_VALUE) {
2886 reg_mask &= ~(1u << i);
2891 reg->precise = true;
2894 bitmap_from_u64(mask, stack_mask);
2895 for_each_set_bit(i, mask, 64) {
2896 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2897 /* the sequence of instructions:
2899 * 3: (7b) *(u64 *)(r3 -8) = r0
2900 * 4: (79) r4 = *(u64 *)(r10 -8)
2901 * doesn't contain jmps. It's backtracked
2902 * as a single block.
2903 * During backtracking insn 3 is not recognized as
2904 * stack access, so at the end of backtracking
2905 * stack slot fp-8 is still marked in stack_mask.
2906 * However the parent state may not have accessed
2907 * fp-8 and it's "unallocated" stack space.
2908 * In such case fallback to conservative.
2910 mark_all_scalars_precise(env, st);
2914 if (!is_spilled_reg(&func->stack[i])) {
2915 stack_mask &= ~(1ull << i);
2918 reg = &func->stack[i].spilled_ptr;
2919 if (reg->type != SCALAR_VALUE) {
2920 stack_mask &= ~(1ull << i);
2925 reg->precise = true;
2927 if (env->log.level & BPF_LOG_LEVEL2) {
2928 verbose(env, "parent %s regs=%x stack=%llx marks:",
2929 new_marks ? "didn't have" : "already had",
2930 reg_mask, stack_mask);
2931 print_verifier_state(env, func, true);
2934 if (!reg_mask && !stack_mask)
2939 last_idx = st->last_insn_idx;
2940 first_idx = st->first_insn_idx;
2945 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2947 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2950 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2952 return __mark_chain_precision(env, frame, regno, -1);
2955 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2957 return __mark_chain_precision(env, frame, -1, spi);
2960 static bool is_spillable_regtype(enum bpf_reg_type type)
2962 switch (base_type(type)) {
2963 case PTR_TO_MAP_VALUE:
2967 case PTR_TO_PACKET_META:
2968 case PTR_TO_PACKET_END:
2969 case PTR_TO_FLOW_KEYS:
2970 case CONST_PTR_TO_MAP:
2972 case PTR_TO_SOCK_COMMON:
2973 case PTR_TO_TCP_SOCK:
2974 case PTR_TO_XDP_SOCK:
2979 case PTR_TO_MAP_KEY:
2986 /* Does this register contain a constant zero? */
2987 static bool register_is_null(struct bpf_reg_state *reg)
2989 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2992 static bool register_is_const(struct bpf_reg_state *reg)
2994 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2997 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2999 return tnum_is_unknown(reg->var_off) &&
3000 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3001 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3002 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3003 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3006 static bool register_is_bounded(struct bpf_reg_state *reg)
3008 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3011 static bool __is_pointer_value(bool allow_ptr_leaks,
3012 const struct bpf_reg_state *reg)
3014 if (allow_ptr_leaks)
3017 return reg->type != SCALAR_VALUE;
3020 /* Copy src state preserving dst->parent and dst->live fields */
3021 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3023 struct bpf_reg_state *parent = dst->parent;
3024 enum bpf_reg_liveness live = dst->live;
3027 dst->parent = parent;
3031 static void save_register_state(struct bpf_func_state *state,
3032 int spi, struct bpf_reg_state *reg,
3037 copy_register_state(&state->stack[spi].spilled_ptr, reg);
3038 if (size == BPF_REG_SIZE)
3039 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3041 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3042 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3044 /* size < 8 bytes spill */
3046 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3049 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3050 * stack boundary and alignment are checked in check_mem_access()
3052 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3053 /* stack frame we're writing to */
3054 struct bpf_func_state *state,
3055 int off, int size, int value_regno,
3058 struct bpf_func_state *cur; /* state of the current function */
3059 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3060 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3061 struct bpf_reg_state *reg = NULL;
3063 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3066 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3067 * so it's aligned access and [off, off + size) are within stack limits
3069 if (!env->allow_ptr_leaks &&
3070 state->stack[spi].slot_type[0] == STACK_SPILL &&
3071 size != BPF_REG_SIZE) {
3072 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3076 cur = env->cur_state->frame[env->cur_state->curframe];
3077 if (value_regno >= 0)
3078 reg = &cur->regs[value_regno];
3079 if (!env->bypass_spec_v4) {
3080 bool sanitize = reg && is_spillable_regtype(reg->type);
3082 for (i = 0; i < size; i++) {
3083 u8 type = state->stack[spi].slot_type[i];
3085 if (type != STACK_MISC && type != STACK_ZERO) {
3092 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3095 mark_stack_slot_scratched(env, spi);
3096 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3097 !register_is_null(reg) && env->bpf_capable) {
3098 if (dst_reg != BPF_REG_FP) {
3099 /* The backtracking logic can only recognize explicit
3100 * stack slot address like [fp - 8]. Other spill of
3101 * scalar via different register has to be conservative.
3102 * Backtrack from here and mark all registers as precise
3103 * that contributed into 'reg' being a constant.
3105 err = mark_chain_precision(env, value_regno);
3109 save_register_state(state, spi, reg, size);
3110 } else if (reg && is_spillable_regtype(reg->type)) {
3111 /* register containing pointer is being spilled into stack */
3112 if (size != BPF_REG_SIZE) {
3113 verbose_linfo(env, insn_idx, "; ");
3114 verbose(env, "invalid size of register spill\n");
3117 if (state != cur && reg->type == PTR_TO_STACK) {
3118 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3121 save_register_state(state, spi, reg, size);
3123 u8 type = STACK_MISC;
3125 /* regular write of data into stack destroys any spilled ptr */
3126 state->stack[spi].spilled_ptr.type = NOT_INIT;
3127 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3128 if (is_spilled_reg(&state->stack[spi]))
3129 for (i = 0; i < BPF_REG_SIZE; i++)
3130 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3132 /* only mark the slot as written if all 8 bytes were written
3133 * otherwise read propagation may incorrectly stop too soon
3134 * when stack slots are partially written.
3135 * This heuristic means that read propagation will be
3136 * conservative, since it will add reg_live_read marks
3137 * to stack slots all the way to first state when programs
3138 * writes+reads less than 8 bytes
3140 if (size == BPF_REG_SIZE)
3141 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3143 /* when we zero initialize stack slots mark them as such */
3144 if (reg && register_is_null(reg)) {
3145 /* backtracking doesn't work for STACK_ZERO yet. */
3146 err = mark_chain_precision(env, value_regno);
3152 /* Mark slots affected by this stack write. */
3153 for (i = 0; i < size; i++)
3154 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3160 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3161 * known to contain a variable offset.
3162 * This function checks whether the write is permitted and conservatively
3163 * tracks the effects of the write, considering that each stack slot in the
3164 * dynamic range is potentially written to.
3166 * 'off' includes 'regno->off'.
3167 * 'value_regno' can be -1, meaning that an unknown value is being written to
3170 * Spilled pointers in range are not marked as written because we don't know
3171 * what's going to be actually written. This means that read propagation for
3172 * future reads cannot be terminated by this write.
3174 * For privileged programs, uninitialized stack slots are considered
3175 * initialized by this write (even though we don't know exactly what offsets
3176 * are going to be written to). The idea is that we don't want the verifier to
3177 * reject future reads that access slots written to through variable offsets.
3179 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3180 /* func where register points to */
3181 struct bpf_func_state *state,
3182 int ptr_regno, int off, int size,
3183 int value_regno, int insn_idx)
3185 struct bpf_func_state *cur; /* state of the current function */
3186 int min_off, max_off;
3188 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3189 bool writing_zero = false;
3190 /* set if the fact that we're writing a zero is used to let any
3191 * stack slots remain STACK_ZERO
3193 bool zero_used = false;
3195 cur = env->cur_state->frame[env->cur_state->curframe];
3196 ptr_reg = &cur->regs[ptr_regno];
3197 min_off = ptr_reg->smin_value + off;
3198 max_off = ptr_reg->smax_value + off + size;
3199 if (value_regno >= 0)
3200 value_reg = &cur->regs[value_regno];
3201 if (value_reg && register_is_null(value_reg))
3202 writing_zero = true;
3204 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3209 /* Variable offset writes destroy any spilled pointers in range. */
3210 for (i = min_off; i < max_off; i++) {
3211 u8 new_type, *stype;
3215 spi = slot / BPF_REG_SIZE;
3216 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3217 mark_stack_slot_scratched(env, spi);
3219 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3220 /* Reject the write if range we may write to has not
3221 * been initialized beforehand. If we didn't reject
3222 * here, the ptr status would be erased below (even
3223 * though not all slots are actually overwritten),
3224 * possibly opening the door to leaks.
3226 * We do however catch STACK_INVALID case below, and
3227 * only allow reading possibly uninitialized memory
3228 * later for CAP_PERFMON, as the write may not happen to
3231 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3236 /* Erase all spilled pointers. */
3237 state->stack[spi].spilled_ptr.type = NOT_INIT;
3239 /* Update the slot type. */
3240 new_type = STACK_MISC;
3241 if (writing_zero && *stype == STACK_ZERO) {
3242 new_type = STACK_ZERO;
3245 /* If the slot is STACK_INVALID, we check whether it's OK to
3246 * pretend that it will be initialized by this write. The slot
3247 * might not actually be written to, and so if we mark it as
3248 * initialized future reads might leak uninitialized memory.
3249 * For privileged programs, we will accept such reads to slots
3250 * that may or may not be written because, if we're reject
3251 * them, the error would be too confusing.
3253 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3254 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3261 /* backtracking doesn't work for STACK_ZERO yet. */
3262 err = mark_chain_precision(env, value_regno);
3269 /* When register 'dst_regno' is assigned some values from stack[min_off,
3270 * max_off), we set the register's type according to the types of the
3271 * respective stack slots. If all the stack values are known to be zeros, then
3272 * so is the destination reg. Otherwise, the register is considered to be
3273 * SCALAR. This function does not deal with register filling; the caller must
3274 * ensure that all spilled registers in the stack range have been marked as
3277 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3278 /* func where src register points to */
3279 struct bpf_func_state *ptr_state,
3280 int min_off, int max_off, int dst_regno)
3282 struct bpf_verifier_state *vstate = env->cur_state;
3283 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3288 for (i = min_off; i < max_off; i++) {
3290 spi = slot / BPF_REG_SIZE;
3291 stype = ptr_state->stack[spi].slot_type;
3292 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3296 if (zeros == max_off - min_off) {
3297 /* any access_size read into register is zero extended,
3298 * so the whole register == const_zero
3300 __mark_reg_const_zero(&state->regs[dst_regno]);
3301 /* backtracking doesn't support STACK_ZERO yet,
3302 * so mark it precise here, so that later
3303 * backtracking can stop here.
3304 * Backtracking may not need this if this register
3305 * doesn't participate in pointer adjustment.
3306 * Forward propagation of precise flag is not
3307 * necessary either. This mark is only to stop
3308 * backtracking. Any register that contributed
3309 * to const 0 was marked precise before spill.
3311 state->regs[dst_regno].precise = true;
3313 /* have read misc data from the stack */
3314 mark_reg_unknown(env, state->regs, dst_regno);
3316 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3319 /* Read the stack at 'off' and put the results into the register indicated by
3320 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3323 * 'dst_regno' can be -1, meaning that the read value is not going to a
3326 * The access is assumed to be within the current stack bounds.
3328 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3329 /* func where src register points to */
3330 struct bpf_func_state *reg_state,
3331 int off, int size, int dst_regno)
3333 struct bpf_verifier_state *vstate = env->cur_state;
3334 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3335 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3336 struct bpf_reg_state *reg;
3339 stype = reg_state->stack[spi].slot_type;
3340 reg = ®_state->stack[spi].spilled_ptr;
3342 if (is_spilled_reg(®_state->stack[spi])) {
3345 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3348 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3349 if (reg->type != SCALAR_VALUE) {
3350 verbose_linfo(env, env->insn_idx, "; ");
3351 verbose(env, "invalid size of register fill\n");
3355 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3359 if (!(off % BPF_REG_SIZE) && size == spill_size) {
3360 /* The earlier check_reg_arg() has decided the
3361 * subreg_def for this insn. Save it first.
3363 s32 subreg_def = state->regs[dst_regno].subreg_def;
3365 copy_register_state(&state->regs[dst_regno], reg);
3366 state->regs[dst_regno].subreg_def = subreg_def;
3368 for (i = 0; i < size; i++) {
3369 type = stype[(slot - i) % BPF_REG_SIZE];
3370 if (type == STACK_SPILL)
3372 if (type == STACK_MISC)
3374 verbose(env, "invalid read from stack off %d+%d size %d\n",
3378 mark_reg_unknown(env, state->regs, dst_regno);
3380 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3384 if (dst_regno >= 0) {
3385 /* restore register state from stack */
3386 copy_register_state(&state->regs[dst_regno], reg);
3387 /* mark reg as written since spilled pointer state likely
3388 * has its liveness marks cleared by is_state_visited()
3389 * which resets stack/reg liveness for state transitions
3391 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3392 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3393 /* If dst_regno==-1, the caller is asking us whether
3394 * it is acceptable to use this value as a SCALAR_VALUE
3396 * We must not allow unprivileged callers to do that
3397 * with spilled pointers.
3399 verbose(env, "leaking pointer from stack off %d\n",
3403 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3405 for (i = 0; i < size; i++) {
3406 type = stype[(slot - i) % BPF_REG_SIZE];
3407 if (type == STACK_MISC)
3409 if (type == STACK_ZERO)
3411 verbose(env, "invalid read from stack off %d+%d size %d\n",
3415 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3417 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3422 enum bpf_access_src {
3423 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
3424 ACCESS_HELPER = 2, /* the access is performed by a helper */
3427 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3428 int regno, int off, int access_size,
3429 bool zero_size_allowed,
3430 enum bpf_access_src type,
3431 struct bpf_call_arg_meta *meta);
3433 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3435 return cur_regs(env) + regno;
3438 /* Read the stack at 'ptr_regno + off' and put the result into the register
3440 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3441 * but not its variable offset.
3442 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3444 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3445 * filling registers (i.e. reads of spilled register cannot be detected when
3446 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3447 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3448 * offset; for a fixed offset check_stack_read_fixed_off should be used
3451 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3452 int ptr_regno, int off, int size, int dst_regno)
3454 /* The state of the source register. */
3455 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3456 struct bpf_func_state *ptr_state = func(env, reg);
3458 int min_off, max_off;
3460 /* Note that we pass a NULL meta, so raw access will not be permitted.
3462 err = check_stack_range_initialized(env, ptr_regno, off, size,
3463 false, ACCESS_DIRECT, NULL);
3467 min_off = reg->smin_value + off;
3468 max_off = reg->smax_value + off;
3469 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3473 /* check_stack_read dispatches to check_stack_read_fixed_off or
3474 * check_stack_read_var_off.
3476 * The caller must ensure that the offset falls within the allocated stack
3479 * 'dst_regno' is a register which will receive the value from the stack. It
3480 * can be -1, meaning that the read value is not going to a register.
3482 static int check_stack_read(struct bpf_verifier_env *env,
3483 int ptr_regno, int off, int size,
3486 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3487 struct bpf_func_state *state = func(env, reg);
3489 /* Some accesses are only permitted with a static offset. */
3490 bool var_off = !tnum_is_const(reg->var_off);
3492 /* The offset is required to be static when reads don't go to a
3493 * register, in order to not leak pointers (see
3494 * check_stack_read_fixed_off).
3496 if (dst_regno < 0 && var_off) {
3499 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3500 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3504 /* Variable offset is prohibited for unprivileged mode for simplicity
3505 * since it requires corresponding support in Spectre masking for stack
3506 * ALU. See also retrieve_ptr_limit().
3508 if (!env->bypass_spec_v1 && var_off) {
3511 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3512 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3518 off += reg->var_off.value;
3519 err = check_stack_read_fixed_off(env, state, off, size,
3522 /* Variable offset stack reads need more conservative handling
3523 * than fixed offset ones. Note that dst_regno >= 0 on this
3526 err = check_stack_read_var_off(env, ptr_regno, off, size,
3533 /* check_stack_write dispatches to check_stack_write_fixed_off or
3534 * check_stack_write_var_off.
3536 * 'ptr_regno' is the register used as a pointer into the stack.
3537 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3538 * 'value_regno' is the register whose value we're writing to the stack. It can
3539 * be -1, meaning that we're not writing from a register.
3541 * The caller must ensure that the offset falls within the maximum stack size.
3543 static int check_stack_write(struct bpf_verifier_env *env,
3544 int ptr_regno, int off, int size,
3545 int value_regno, int insn_idx)
3547 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3548 struct bpf_func_state *state = func(env, reg);
3551 if (tnum_is_const(reg->var_off)) {
3552 off += reg->var_off.value;
3553 err = check_stack_write_fixed_off(env, state, off, size,
3554 value_regno, insn_idx);
3556 /* Variable offset stack reads need more conservative handling
3557 * than fixed offset ones.
3559 err = check_stack_write_var_off(env, state,
3560 ptr_regno, off, size,
3561 value_regno, insn_idx);
3566 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3567 int off, int size, enum bpf_access_type type)
3569 struct bpf_reg_state *regs = cur_regs(env);
3570 struct bpf_map *map = regs[regno].map_ptr;
3571 u32 cap = bpf_map_flags_to_cap(map);
3573 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3574 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3575 map->value_size, off, size);
3579 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3580 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3581 map->value_size, off, size);
3588 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3589 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3590 int off, int size, u32 mem_size,
3591 bool zero_size_allowed)
3593 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3594 struct bpf_reg_state *reg;
3596 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3599 reg = &cur_regs(env)[regno];
3600 switch (reg->type) {
3601 case PTR_TO_MAP_KEY:
3602 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3603 mem_size, off, size);
3605 case PTR_TO_MAP_VALUE:
3606 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3607 mem_size, off, size);
3610 case PTR_TO_PACKET_META:
3611 case PTR_TO_PACKET_END:
3612 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3613 off, size, regno, reg->id, off, mem_size);
3617 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3618 mem_size, off, size);
3624 /* check read/write into a memory region with possible variable offset */
3625 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3626 int off, int size, u32 mem_size,
3627 bool zero_size_allowed)
3629 struct bpf_verifier_state *vstate = env->cur_state;
3630 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3631 struct bpf_reg_state *reg = &state->regs[regno];
3634 /* We may have adjusted the register pointing to memory region, so we
3635 * need to try adding each of min_value and max_value to off
3636 * to make sure our theoretical access will be safe.
3638 * The minimum value is only important with signed
3639 * comparisons where we can't assume the floor of a
3640 * value is 0. If we are using signed variables for our
3641 * index'es we need to make sure that whatever we use
3642 * will have a set floor within our range.
3644 if (reg->smin_value < 0 &&
3645 (reg->smin_value == S64_MIN ||
3646 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3647 reg->smin_value + off < 0)) {
3648 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3652 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3653 mem_size, zero_size_allowed);
3655 verbose(env, "R%d min value is outside of the allowed memory range\n",
3660 /* If we haven't set a max value then we need to bail since we can't be
3661 * sure we won't do bad things.
3662 * If reg->umax_value + off could overflow, treat that as unbounded too.
3664 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3665 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3669 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3670 mem_size, zero_size_allowed);
3672 verbose(env, "R%d max value is outside of the allowed memory range\n",
3680 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3681 const struct bpf_reg_state *reg, int regno,
3684 /* Access to this pointer-typed register or passing it to a helper
3685 * is only allowed in its original, unmodified form.
3689 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3690 reg_type_str(env, reg->type), regno, reg->off);
3694 if (!fixed_off_ok && reg->off) {
3695 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3696 reg_type_str(env, reg->type), regno, reg->off);
3700 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3703 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3704 verbose(env, "variable %s access var_off=%s disallowed\n",
3705 reg_type_str(env, reg->type), tn_buf);
3712 int check_ptr_off_reg(struct bpf_verifier_env *env,
3713 const struct bpf_reg_state *reg, int regno)
3715 return __check_ptr_off_reg(env, reg, regno, false);
3718 static int map_kptr_match_type(struct bpf_verifier_env *env,
3719 struct bpf_map_value_off_desc *off_desc,
3720 struct bpf_reg_state *reg, u32 regno)
3722 const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3723 int perm_flags = PTR_MAYBE_NULL;
3724 const char *reg_name = "";
3726 /* Only unreferenced case accepts untrusted pointers */
3727 if (off_desc->type == BPF_KPTR_UNREF)
3728 perm_flags |= PTR_UNTRUSTED;
3730 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3733 if (!btf_is_kernel(reg->btf)) {
3734 verbose(env, "R%d must point to kernel BTF\n", regno);
3737 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3738 reg_name = kernel_type_name(reg->btf, reg->btf_id);
3740 /* For ref_ptr case, release function check should ensure we get one
3741 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3742 * normal store of unreferenced kptr, we must ensure var_off is zero.
3743 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3744 * reg->off and reg->ref_obj_id are not needed here.
3746 if (__check_ptr_off_reg(env, reg, regno, true))
3749 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3750 * we also need to take into account the reg->off.
3752 * We want to support cases like:
3760 * v = func(); // PTR_TO_BTF_ID
3761 * val->foo = v; // reg->off is zero, btf and btf_id match type
3762 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3763 * // first member type of struct after comparison fails
3764 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3767 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3768 * is zero. We must also ensure that btf_struct_ids_match does not walk
3769 * the struct to match type against first member of struct, i.e. reject
3770 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3771 * strict mode to true for type match.
3773 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3774 off_desc->kptr.btf, off_desc->kptr.btf_id,
3775 off_desc->type == BPF_KPTR_REF))
3779 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3780 reg_type_str(env, reg->type), reg_name);
3781 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3782 if (off_desc->type == BPF_KPTR_UNREF)
3783 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3790 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3791 int value_regno, int insn_idx,
3792 struct bpf_map_value_off_desc *off_desc)
3794 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3795 int class = BPF_CLASS(insn->code);
3796 struct bpf_reg_state *val_reg;
3798 /* Things we already checked for in check_map_access and caller:
3799 * - Reject cases where variable offset may touch kptr
3800 * - size of access (must be BPF_DW)
3801 * - tnum_is_const(reg->var_off)
3802 * - off_desc->offset == off + reg->var_off.value
3804 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3805 if (BPF_MODE(insn->code) != BPF_MEM) {
3806 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3810 /* We only allow loading referenced kptr, since it will be marked as
3811 * untrusted, similar to unreferenced kptr.
3813 if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3814 verbose(env, "store to referenced kptr disallowed\n");
3818 if (class == BPF_LDX) {
3819 val_reg = reg_state(env, value_regno);
3820 /* We can simply mark the value_regno receiving the pointer
3821 * value from map as PTR_TO_BTF_ID, with the correct type.
3823 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3824 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3825 /* For mark_ptr_or_null_reg */
3826 val_reg->id = ++env->id_gen;
3827 } else if (class == BPF_STX) {
3828 val_reg = reg_state(env, value_regno);
3829 if (!register_is_null(val_reg) &&
3830 map_kptr_match_type(env, off_desc, val_reg, value_regno))
3832 } else if (class == BPF_ST) {
3834 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3839 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3845 /* check read/write into a map element with possible variable offset */
3846 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3847 int off, int size, bool zero_size_allowed,
3848 enum bpf_access_src src)
3850 struct bpf_verifier_state *vstate = env->cur_state;
3851 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3852 struct bpf_reg_state *reg = &state->regs[regno];
3853 struct bpf_map *map = reg->map_ptr;
3856 err = check_mem_region_access(env, regno, off, size, map->value_size,
3861 if (map_value_has_spin_lock(map)) {
3862 u32 lock = map->spin_lock_off;
3864 /* if any part of struct bpf_spin_lock can be touched by
3865 * load/store reject this program.
3866 * To check that [x1, x2) overlaps with [y1, y2)
3867 * it is sufficient to check x1 < y2 && y1 < x2.
3869 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3870 lock < reg->umax_value + off + size) {
3871 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3875 if (map_value_has_timer(map)) {
3876 u32 t = map->timer_off;
3878 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3879 t < reg->umax_value + off + size) {
3880 verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3884 if (map_value_has_kptrs(map)) {
3885 struct bpf_map_value_off *tab = map->kptr_off_tab;
3888 for (i = 0; i < tab->nr_off; i++) {
3889 u32 p = tab->off[i].offset;
3891 if (reg->smin_value + off < p + sizeof(u64) &&
3892 p < reg->umax_value + off + size) {
3893 if (src != ACCESS_DIRECT) {
3894 verbose(env, "kptr cannot be accessed indirectly by helper\n");
3897 if (!tnum_is_const(reg->var_off)) {
3898 verbose(env, "kptr access cannot have variable offset\n");
3901 if (p != off + reg->var_off.value) {
3902 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3903 p, off + reg->var_off.value);
3906 if (size != bpf_size_to_bytes(BPF_DW)) {
3907 verbose(env, "kptr access size must be BPF_DW\n");
3917 #define MAX_PACKET_OFF 0xffff
3919 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3920 const struct bpf_call_arg_meta *meta,
3921 enum bpf_access_type t)
3923 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3925 switch (prog_type) {
3926 /* Program types only with direct read access go here! */
3927 case BPF_PROG_TYPE_LWT_IN:
3928 case BPF_PROG_TYPE_LWT_OUT:
3929 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3930 case BPF_PROG_TYPE_SK_REUSEPORT:
3931 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3932 case BPF_PROG_TYPE_CGROUP_SKB:
3937 /* Program types with direct read + write access go here! */
3938 case BPF_PROG_TYPE_SCHED_CLS:
3939 case BPF_PROG_TYPE_SCHED_ACT:
3940 case BPF_PROG_TYPE_XDP:
3941 case BPF_PROG_TYPE_LWT_XMIT:
3942 case BPF_PROG_TYPE_SK_SKB:
3943 case BPF_PROG_TYPE_SK_MSG:
3945 return meta->pkt_access;
3947 env->seen_direct_write = true;
3950 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3952 env->seen_direct_write = true;
3961 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3962 int size, bool zero_size_allowed)
3964 struct bpf_reg_state *regs = cur_regs(env);
3965 struct bpf_reg_state *reg = ®s[regno];
3968 /* We may have added a variable offset to the packet pointer; but any
3969 * reg->range we have comes after that. We are only checking the fixed
3973 /* We don't allow negative numbers, because we aren't tracking enough
3974 * detail to prove they're safe.
3976 if (reg->smin_value < 0) {
3977 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3982 err = reg->range < 0 ? -EINVAL :
3983 __check_mem_access(env, regno, off, size, reg->range,
3986 verbose(env, "R%d offset is outside of the packet\n", regno);
3990 /* __check_mem_access has made sure "off + size - 1" is within u16.
3991 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3992 * otherwise find_good_pkt_pointers would have refused to set range info
3993 * that __check_mem_access would have rejected this pkt access.
3994 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3996 env->prog->aux->max_pkt_offset =
3997 max_t(u32, env->prog->aux->max_pkt_offset,
3998 off + reg->umax_value + size - 1);
4003 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
4004 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4005 enum bpf_access_type t, enum bpf_reg_type *reg_type,
4006 struct btf **btf, u32 *btf_id)
4008 struct bpf_insn_access_aux info = {
4009 .reg_type = *reg_type,
4013 if (env->ops->is_valid_access &&
4014 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4015 /* A non zero info.ctx_field_size indicates that this field is a
4016 * candidate for later verifier transformation to load the whole
4017 * field and then apply a mask when accessed with a narrower
4018 * access than actual ctx access size. A zero info.ctx_field_size
4019 * will only allow for whole field access and rejects any other
4020 * type of narrower access.
4022 *reg_type = info.reg_type;
4024 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4026 *btf_id = info.btf_id;
4028 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4030 /* remember the offset of last byte accessed in ctx */
4031 if (env->prog->aux->max_ctx_offset < off + size)
4032 env->prog->aux->max_ctx_offset = off + size;
4036 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4040 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4043 if (size < 0 || off < 0 ||
4044 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4045 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4052 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4053 u32 regno, int off, int size,
4054 enum bpf_access_type t)
4056 struct bpf_reg_state *regs = cur_regs(env);
4057 struct bpf_reg_state *reg = ®s[regno];
4058 struct bpf_insn_access_aux info = {};
4061 if (reg->smin_value < 0) {
4062 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4067 switch (reg->type) {
4068 case PTR_TO_SOCK_COMMON:
4069 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4072 valid = bpf_sock_is_valid_access(off, size, t, &info);
4074 case PTR_TO_TCP_SOCK:
4075 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4077 case PTR_TO_XDP_SOCK:
4078 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4086 env->insn_aux_data[insn_idx].ctx_field_size =
4087 info.ctx_field_size;
4091 verbose(env, "R%d invalid %s access off=%d size=%d\n",
4092 regno, reg_type_str(env, reg->type), off, size);
4097 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4099 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4102 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4104 const struct bpf_reg_state *reg = reg_state(env, regno);
4106 return reg->type == PTR_TO_CTX;
4109 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4111 const struct bpf_reg_state *reg = reg_state(env, regno);
4113 return type_is_sk_pointer(reg->type);
4116 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4118 const struct bpf_reg_state *reg = reg_state(env, regno);
4120 return type_is_pkt_pointer(reg->type);
4123 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4125 const struct bpf_reg_state *reg = reg_state(env, regno);
4127 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4128 return reg->type == PTR_TO_FLOW_KEYS;
4131 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4132 const struct bpf_reg_state *reg,
4133 int off, int size, bool strict)
4135 struct tnum reg_off;
4138 /* Byte size accesses are always allowed. */
4139 if (!strict || size == 1)
4142 /* For platforms that do not have a Kconfig enabling
4143 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4144 * NET_IP_ALIGN is universally set to '2'. And on platforms
4145 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4146 * to this code only in strict mode where we want to emulate
4147 * the NET_IP_ALIGN==2 checking. Therefore use an
4148 * unconditional IP align value of '2'.
4152 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4153 if (!tnum_is_aligned(reg_off, size)) {
4156 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4158 "misaligned packet access off %d+%s+%d+%d size %d\n",
4159 ip_align, tn_buf, reg->off, off, size);
4166 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4167 const struct bpf_reg_state *reg,
4168 const char *pointer_desc,
4169 int off, int size, bool strict)
4171 struct tnum reg_off;
4173 /* Byte size accesses are always allowed. */
4174 if (!strict || size == 1)
4177 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4178 if (!tnum_is_aligned(reg_off, size)) {
4181 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4182 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4183 pointer_desc, tn_buf, reg->off, off, size);
4190 static int check_ptr_alignment(struct bpf_verifier_env *env,
4191 const struct bpf_reg_state *reg, int off,
4192 int size, bool strict_alignment_once)
4194 bool strict = env->strict_alignment || strict_alignment_once;
4195 const char *pointer_desc = "";
4197 switch (reg->type) {
4199 case PTR_TO_PACKET_META:
4200 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4201 * right in front, treat it the very same way.
4203 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4204 case PTR_TO_FLOW_KEYS:
4205 pointer_desc = "flow keys ";
4207 case PTR_TO_MAP_KEY:
4208 pointer_desc = "key ";
4210 case PTR_TO_MAP_VALUE:
4211 pointer_desc = "value ";
4214 pointer_desc = "context ";
4217 pointer_desc = "stack ";
4218 /* The stack spill tracking logic in check_stack_write_fixed_off()
4219 * and check_stack_read_fixed_off() relies on stack accesses being
4225 pointer_desc = "sock ";
4227 case PTR_TO_SOCK_COMMON:
4228 pointer_desc = "sock_common ";
4230 case PTR_TO_TCP_SOCK:
4231 pointer_desc = "tcp_sock ";
4233 case PTR_TO_XDP_SOCK:
4234 pointer_desc = "xdp_sock ";
4239 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4243 static int update_stack_depth(struct bpf_verifier_env *env,
4244 const struct bpf_func_state *func,
4247 u16 stack = env->subprog_info[func->subprogno].stack_depth;
4252 /* update known max for given subprogram */
4253 env->subprog_info[func->subprogno].stack_depth = -off;
4257 /* starting from main bpf function walk all instructions of the function
4258 * and recursively walk all callees that given function can call.
4259 * Ignore jump and exit insns.
4260 * Since recursion is prevented by check_cfg() this algorithm
4261 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4263 static int check_max_stack_depth(struct bpf_verifier_env *env)
4265 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4266 struct bpf_subprog_info *subprog = env->subprog_info;
4267 struct bpf_insn *insn = env->prog->insnsi;
4268 bool tail_call_reachable = false;
4269 int ret_insn[MAX_CALL_FRAMES];
4270 int ret_prog[MAX_CALL_FRAMES];
4274 /* protect against potential stack overflow that might happen when
4275 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4276 * depth for such case down to 256 so that the worst case scenario
4277 * would result in 8k stack size (32 which is tailcall limit * 256 =
4280 * To get the idea what might happen, see an example:
4281 * func1 -> sub rsp, 128
4282 * subfunc1 -> sub rsp, 256
4283 * tailcall1 -> add rsp, 256
4284 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4285 * subfunc2 -> sub rsp, 64
4286 * subfunc22 -> sub rsp, 128
4287 * tailcall2 -> add rsp, 128
4288 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4290 * tailcall will unwind the current stack frame but it will not get rid
4291 * of caller's stack as shown on the example above.
4293 if (idx && subprog[idx].has_tail_call && depth >= 256) {
4295 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4299 /* round up to 32-bytes, since this is granularity
4300 * of interpreter stack size
4302 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4303 if (depth > MAX_BPF_STACK) {
4304 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4309 subprog_end = subprog[idx + 1].start;
4310 for (; i < subprog_end; i++) {
4313 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4315 /* remember insn and function to return to */
4316 ret_insn[frame] = i + 1;
4317 ret_prog[frame] = idx;
4319 /* find the callee */
4320 next_insn = i + insn[i].imm + 1;
4321 idx = find_subprog(env, next_insn);
4323 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4327 if (subprog[idx].is_async_cb) {
4328 if (subprog[idx].has_tail_call) {
4329 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4332 /* async callbacks don't increase bpf prog stack size */
4337 if (subprog[idx].has_tail_call)
4338 tail_call_reachable = true;
4341 if (frame >= MAX_CALL_FRAMES) {
4342 verbose(env, "the call stack of %d frames is too deep !\n",
4348 /* if tail call got detected across bpf2bpf calls then mark each of the
4349 * currently present subprog frames as tail call reachable subprogs;
4350 * this info will be utilized by JIT so that we will be preserving the
4351 * tail call counter throughout bpf2bpf calls combined with tailcalls
4353 if (tail_call_reachable)
4354 for (j = 0; j < frame; j++)
4355 subprog[ret_prog[j]].tail_call_reachable = true;
4356 if (subprog[0].tail_call_reachable)
4357 env->prog->aux->tail_call_reachable = true;
4359 /* end of for() loop means the last insn of the 'subprog'
4360 * was reached. Doesn't matter whether it was JA or EXIT
4364 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4366 i = ret_insn[frame];
4367 idx = ret_prog[frame];
4371 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4372 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4373 const struct bpf_insn *insn, int idx)
4375 int start = idx + insn->imm + 1, subprog;
4377 subprog = find_subprog(env, start);
4379 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4383 return env->subprog_info[subprog].stack_depth;
4387 static int __check_buffer_access(struct bpf_verifier_env *env,
4388 const char *buf_info,
4389 const struct bpf_reg_state *reg,
4390 int regno, int off, int size)
4394 "R%d invalid %s buffer access: off=%d, size=%d\n",
4395 regno, buf_info, off, size);
4398 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4401 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4403 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4404 regno, off, tn_buf);
4411 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4412 const struct bpf_reg_state *reg,
4413 int regno, int off, int size)
4417 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4421 if (off + size > env->prog->aux->max_tp_access)
4422 env->prog->aux->max_tp_access = off + size;
4427 static int check_buffer_access(struct bpf_verifier_env *env,
4428 const struct bpf_reg_state *reg,
4429 int regno, int off, int size,
4430 bool zero_size_allowed,
4433 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4436 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4440 if (off + size > *max_access)
4441 *max_access = off + size;
4446 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4447 static void zext_32_to_64(struct bpf_reg_state *reg)
4449 reg->var_off = tnum_subreg(reg->var_off);
4450 __reg_assign_32_into_64(reg);
4453 /* truncate register to smaller size (in bytes)
4454 * must be called with size < BPF_REG_SIZE
4456 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4460 /* clear high bits in bit representation */
4461 reg->var_off = tnum_cast(reg->var_off, size);
4463 /* fix arithmetic bounds */
4464 mask = ((u64)1 << (size * 8)) - 1;
4465 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4466 reg->umin_value &= mask;
4467 reg->umax_value &= mask;
4469 reg->umin_value = 0;
4470 reg->umax_value = mask;
4472 reg->smin_value = reg->umin_value;
4473 reg->smax_value = reg->umax_value;
4475 /* If size is smaller than 32bit register the 32bit register
4476 * values are also truncated so we push 64-bit bounds into
4477 * 32-bit bounds. Above were truncated < 32-bits already.
4481 __reg_combine_64_into_32(reg);
4484 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4486 /* A map is considered read-only if the following condition are true:
4488 * 1) BPF program side cannot change any of the map content. The
4489 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4490 * and was set at map creation time.
4491 * 2) The map value(s) have been initialized from user space by a
4492 * loader and then "frozen", such that no new map update/delete
4493 * operations from syscall side are possible for the rest of
4494 * the map's lifetime from that point onwards.
4495 * 3) Any parallel/pending map update/delete operations from syscall
4496 * side have been completed. Only after that point, it's safe to
4497 * assume that map value(s) are immutable.
4499 return (map->map_flags & BPF_F_RDONLY_PROG) &&
4500 READ_ONCE(map->frozen) &&
4501 !bpf_map_write_active(map);
4504 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4510 err = map->ops->map_direct_value_addr(map, &addr, off);
4513 ptr = (void *)(long)addr + off;
4517 *val = (u64)*(u8 *)ptr;
4520 *val = (u64)*(u16 *)ptr;
4523 *val = (u64)*(u32 *)ptr;
4534 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4535 struct bpf_reg_state *regs,
4536 int regno, int off, int size,
4537 enum bpf_access_type atype,
4540 struct bpf_reg_state *reg = regs + regno;
4541 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4542 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4543 enum bpf_type_flag flag = 0;
4549 "R%d is ptr_%s invalid negative access: off=%d\n",
4553 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4556 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4558 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4559 regno, tname, off, tn_buf);
4563 if (reg->type & MEM_USER) {
4565 "R%d is ptr_%s access user memory: off=%d\n",
4570 if (reg->type & MEM_PERCPU) {
4572 "R%d is ptr_%s access percpu memory: off=%d\n",
4577 if (env->ops->btf_struct_access) {
4578 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4579 off, size, atype, &btf_id, &flag);
4581 if (atype != BPF_READ) {
4582 verbose(env, "only read is supported\n");
4586 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4587 atype, &btf_id, &flag);
4593 /* If this is an untrusted pointer, all pointers formed by walking it
4594 * also inherit the untrusted flag.
4596 if (type_flag(reg->type) & PTR_UNTRUSTED)
4597 flag |= PTR_UNTRUSTED;
4599 if (atype == BPF_READ && value_regno >= 0)
4600 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4605 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4606 struct bpf_reg_state *regs,
4607 int regno, int off, int size,
4608 enum bpf_access_type atype,
4611 struct bpf_reg_state *reg = regs + regno;
4612 struct bpf_map *map = reg->map_ptr;
4613 enum bpf_type_flag flag = 0;
4614 const struct btf_type *t;
4620 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4624 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4625 verbose(env, "map_ptr access not supported for map type %d\n",
4630 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4631 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4633 if (!env->allow_ptr_to_map_access) {
4635 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4641 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4646 if (atype != BPF_READ) {
4647 verbose(env, "only read from %s is supported\n", tname);
4651 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4655 if (value_regno >= 0)
4656 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4661 /* Check that the stack access at the given offset is within bounds. The
4662 * maximum valid offset is -1.
4664 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4665 * -state->allocated_stack for reads.
4667 static int check_stack_slot_within_bounds(int off,
4668 struct bpf_func_state *state,
4669 enum bpf_access_type t)
4674 min_valid_off = -MAX_BPF_STACK;
4676 min_valid_off = -state->allocated_stack;
4678 if (off < min_valid_off || off > -1)
4683 /* Check that the stack access at 'regno + off' falls within the maximum stack
4686 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4688 static int check_stack_access_within_bounds(
4689 struct bpf_verifier_env *env,
4690 int regno, int off, int access_size,
4691 enum bpf_access_src src, enum bpf_access_type type)
4693 struct bpf_reg_state *regs = cur_regs(env);
4694 struct bpf_reg_state *reg = regs + regno;
4695 struct bpf_func_state *state = func(env, reg);
4696 int min_off, max_off;
4700 if (src == ACCESS_HELPER)
4701 /* We don't know if helpers are reading or writing (or both). */
4702 err_extra = " indirect access to";
4703 else if (type == BPF_READ)
4704 err_extra = " read from";
4706 err_extra = " write to";
4708 if (tnum_is_const(reg->var_off)) {
4709 min_off = reg->var_off.value + off;
4710 if (access_size > 0)
4711 max_off = min_off + access_size - 1;
4715 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4716 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4717 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4721 min_off = reg->smin_value + off;
4722 if (access_size > 0)
4723 max_off = reg->smax_value + off + access_size - 1;
4728 err = check_stack_slot_within_bounds(min_off, state, type);
4730 err = check_stack_slot_within_bounds(max_off, state, type);
4733 if (tnum_is_const(reg->var_off)) {
4734 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4735 err_extra, regno, off, access_size);
4739 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4740 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4741 err_extra, regno, tn_buf, access_size);
4747 /* check whether memory at (regno + off) is accessible for t = (read | write)
4748 * if t==write, value_regno is a register which value is stored into memory
4749 * if t==read, value_regno is a register which will receive the value from memory
4750 * if t==write && value_regno==-1, some unknown value is stored into memory
4751 * if t==read && value_regno==-1, don't care what we read from memory
4753 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4754 int off, int bpf_size, enum bpf_access_type t,
4755 int value_regno, bool strict_alignment_once)
4757 struct bpf_reg_state *regs = cur_regs(env);
4758 struct bpf_reg_state *reg = regs + regno;
4759 struct bpf_func_state *state;
4762 size = bpf_size_to_bytes(bpf_size);
4766 /* alignment checks will add in reg->off themselves */
4767 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4771 /* for access checks, reg->off is just part of off */
4774 if (reg->type == PTR_TO_MAP_KEY) {
4775 if (t == BPF_WRITE) {
4776 verbose(env, "write to change key R%d not allowed\n", regno);
4780 err = check_mem_region_access(env, regno, off, size,
4781 reg->map_ptr->key_size, false);
4784 if (value_regno >= 0)
4785 mark_reg_unknown(env, regs, value_regno);
4786 } else if (reg->type == PTR_TO_MAP_VALUE) {
4787 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4789 if (t == BPF_WRITE && value_regno >= 0 &&
4790 is_pointer_value(env, value_regno)) {
4791 verbose(env, "R%d leaks addr into map\n", value_regno);
4794 err = check_map_access_type(env, regno, off, size, t);
4797 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4800 if (tnum_is_const(reg->var_off))
4801 kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4802 off + reg->var_off.value);
4803 if (kptr_off_desc) {
4804 err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4806 } else if (t == BPF_READ && value_regno >= 0) {
4807 struct bpf_map *map = reg->map_ptr;
4809 /* if map is read-only, track its contents as scalars */
4810 if (tnum_is_const(reg->var_off) &&
4811 bpf_map_is_rdonly(map) &&
4812 map->ops->map_direct_value_addr) {
4813 int map_off = off + reg->var_off.value;
4816 err = bpf_map_direct_read(map, map_off, size,
4821 regs[value_regno].type = SCALAR_VALUE;
4822 __mark_reg_known(®s[value_regno], val);
4824 mark_reg_unknown(env, regs, value_regno);
4827 } else if (base_type(reg->type) == PTR_TO_MEM) {
4828 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4830 if (type_may_be_null(reg->type)) {
4831 verbose(env, "R%d invalid mem access '%s'\n", regno,
4832 reg_type_str(env, reg->type));
4836 if (t == BPF_WRITE && rdonly_mem) {
4837 verbose(env, "R%d cannot write into %s\n",
4838 regno, reg_type_str(env, reg->type));
4842 if (t == BPF_WRITE && value_regno >= 0 &&
4843 is_pointer_value(env, value_regno)) {
4844 verbose(env, "R%d leaks addr into mem\n", value_regno);
4848 err = check_mem_region_access(env, regno, off, size,
4849 reg->mem_size, false);
4850 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4851 mark_reg_unknown(env, regs, value_regno);
4852 } else if (reg->type == PTR_TO_CTX) {
4853 enum bpf_reg_type reg_type = SCALAR_VALUE;
4854 struct btf *btf = NULL;
4857 if (t == BPF_WRITE && value_regno >= 0 &&
4858 is_pointer_value(env, value_regno)) {
4859 verbose(env, "R%d leaks addr into ctx\n", value_regno);
4863 err = check_ptr_off_reg(env, reg, regno);
4867 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
4870 verbose_linfo(env, insn_idx, "; ");
4871 if (!err && t == BPF_READ && value_regno >= 0) {
4872 /* ctx access returns either a scalar, or a
4873 * PTR_TO_PACKET[_META,_END]. In the latter
4874 * case, we know the offset is zero.
4876 if (reg_type == SCALAR_VALUE) {
4877 mark_reg_unknown(env, regs, value_regno);
4879 mark_reg_known_zero(env, regs,
4881 if (type_may_be_null(reg_type))
4882 regs[value_regno].id = ++env->id_gen;
4883 /* A load of ctx field could have different
4884 * actual load size with the one encoded in the
4885 * insn. When the dst is PTR, it is for sure not
4888 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4889 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4890 regs[value_regno].btf = btf;
4891 regs[value_regno].btf_id = btf_id;
4894 regs[value_regno].type = reg_type;
4897 } else if (reg->type == PTR_TO_STACK) {
4898 /* Basic bounds checks. */
4899 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4903 state = func(env, reg);
4904 err = update_stack_depth(env, state, off);
4909 err = check_stack_read(env, regno, off, size,
4912 err = check_stack_write(env, regno, off, size,
4913 value_regno, insn_idx);
4914 } else if (reg_is_pkt_pointer(reg)) {
4915 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4916 verbose(env, "cannot write into packet\n");
4919 if (t == BPF_WRITE && value_regno >= 0 &&
4920 is_pointer_value(env, value_regno)) {
4921 verbose(env, "R%d leaks addr into packet\n",
4925 err = check_packet_access(env, regno, off, size, false);
4926 if (!err && t == BPF_READ && value_regno >= 0)
4927 mark_reg_unknown(env, regs, value_regno);
4928 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4929 if (t == BPF_WRITE && value_regno >= 0 &&
4930 is_pointer_value(env, value_regno)) {
4931 verbose(env, "R%d leaks addr into flow keys\n",
4936 err = check_flow_keys_access(env, off, size);
4937 if (!err && t == BPF_READ && value_regno >= 0)
4938 mark_reg_unknown(env, regs, value_regno);
4939 } else if (type_is_sk_pointer(reg->type)) {
4940 if (t == BPF_WRITE) {
4941 verbose(env, "R%d cannot write into %s\n",
4942 regno, reg_type_str(env, reg->type));
4945 err = check_sock_access(env, insn_idx, regno, off, size, t);
4946 if (!err && value_regno >= 0)
4947 mark_reg_unknown(env, regs, value_regno);
4948 } else if (reg->type == PTR_TO_TP_BUFFER) {
4949 err = check_tp_buffer_access(env, reg, regno, off, size);
4950 if (!err && t == BPF_READ && value_regno >= 0)
4951 mark_reg_unknown(env, regs, value_regno);
4952 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4953 !type_may_be_null(reg->type)) {
4954 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4956 } else if (reg->type == CONST_PTR_TO_MAP) {
4957 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4959 } else if (base_type(reg->type) == PTR_TO_BUF) {
4960 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4964 if (t == BPF_WRITE) {
4965 verbose(env, "R%d cannot write into %s\n",
4966 regno, reg_type_str(env, reg->type));
4969 max_access = &env->prog->aux->max_rdonly_access;
4971 max_access = &env->prog->aux->max_rdwr_access;
4974 err = check_buffer_access(env, reg, regno, off, size, false,
4977 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4978 mark_reg_unknown(env, regs, value_regno);
4980 verbose(env, "R%d invalid mem access '%s'\n", regno,
4981 reg_type_str(env, reg->type));
4985 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4986 regs[value_regno].type == SCALAR_VALUE) {
4987 /* b/h/w load zero-extends, mark upper bits as known 0 */
4988 coerce_reg_to_size(®s[value_regno], size);
4993 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4998 switch (insn->imm) {
5000 case BPF_ADD | BPF_FETCH:
5002 case BPF_AND | BPF_FETCH:
5004 case BPF_OR | BPF_FETCH:
5006 case BPF_XOR | BPF_FETCH:
5011 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5015 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5016 verbose(env, "invalid atomic operand size\n");
5020 /* check src1 operand */
5021 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5025 /* check src2 operand */
5026 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5030 if (insn->imm == BPF_CMPXCHG) {
5031 /* Check comparison of R0 with memory location */
5032 const u32 aux_reg = BPF_REG_0;
5034 err = check_reg_arg(env, aux_reg, SRC_OP);
5038 if (is_pointer_value(env, aux_reg)) {
5039 verbose(env, "R%d leaks addr into mem\n", aux_reg);
5044 if (is_pointer_value(env, insn->src_reg)) {
5045 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5049 if (is_ctx_reg(env, insn->dst_reg) ||
5050 is_pkt_reg(env, insn->dst_reg) ||
5051 is_flow_key_reg(env, insn->dst_reg) ||
5052 is_sk_reg(env, insn->dst_reg)) {
5053 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5055 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5059 if (insn->imm & BPF_FETCH) {
5060 if (insn->imm == BPF_CMPXCHG)
5061 load_reg = BPF_REG_0;
5063 load_reg = insn->src_reg;
5065 /* check and record load of old value */
5066 err = check_reg_arg(env, load_reg, DST_OP);
5070 /* This instruction accesses a memory location but doesn't
5071 * actually load it into a register.
5076 /* Check whether we can read the memory, with second call for fetch
5077 * case to simulate the register fill.
5079 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5080 BPF_SIZE(insn->code), BPF_READ, -1, true);
5081 if (!err && load_reg >= 0)
5082 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5083 BPF_SIZE(insn->code), BPF_READ, load_reg,
5088 /* Check whether we can write into the same memory. */
5089 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5090 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5097 /* When register 'regno' is used to read the stack (either directly or through
5098 * a helper function) make sure that it's within stack boundary and, depending
5099 * on the access type, that all elements of the stack are initialized.
5101 * 'off' includes 'regno->off', but not its dynamic part (if any).
5103 * All registers that have been spilled on the stack in the slots within the
5104 * read offsets are marked as read.
5106 static int check_stack_range_initialized(
5107 struct bpf_verifier_env *env, int regno, int off,
5108 int access_size, bool zero_size_allowed,
5109 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5111 struct bpf_reg_state *reg = reg_state(env, regno);
5112 struct bpf_func_state *state = func(env, reg);
5113 int err, min_off, max_off, i, j, slot, spi;
5114 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5115 enum bpf_access_type bounds_check_type;
5116 /* Some accesses can write anything into the stack, others are
5119 bool clobber = false;
5121 if (access_size == 0 && !zero_size_allowed) {
5122 verbose(env, "invalid zero-sized read\n");
5126 if (type == ACCESS_HELPER) {
5127 /* The bounds checks for writes are more permissive than for
5128 * reads. However, if raw_mode is not set, we'll do extra
5131 bounds_check_type = BPF_WRITE;
5134 bounds_check_type = BPF_READ;
5136 err = check_stack_access_within_bounds(env, regno, off, access_size,
5137 type, bounds_check_type);
5142 if (tnum_is_const(reg->var_off)) {
5143 min_off = max_off = reg->var_off.value + off;
5145 /* Variable offset is prohibited for unprivileged mode for
5146 * simplicity since it requires corresponding support in
5147 * Spectre masking for stack ALU.
5148 * See also retrieve_ptr_limit().
5150 if (!env->bypass_spec_v1) {
5153 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5154 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5155 regno, err_extra, tn_buf);
5158 /* Only initialized buffer on stack is allowed to be accessed
5159 * with variable offset. With uninitialized buffer it's hard to
5160 * guarantee that whole memory is marked as initialized on
5161 * helper return since specific bounds are unknown what may
5162 * cause uninitialized stack leaking.
5164 if (meta && meta->raw_mode)
5167 min_off = reg->smin_value + off;
5168 max_off = reg->smax_value + off;
5171 if (meta && meta->raw_mode) {
5172 meta->access_size = access_size;
5173 meta->regno = regno;
5177 for (i = min_off; i < max_off + access_size; i++) {
5181 spi = slot / BPF_REG_SIZE;
5182 if (state->allocated_stack <= slot)
5184 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5185 if (*stype == STACK_MISC)
5187 if (*stype == STACK_ZERO) {
5189 /* helper can write anything into the stack */
5190 *stype = STACK_MISC;
5195 if (is_spilled_reg(&state->stack[spi]) &&
5196 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5197 env->allow_ptr_leaks)) {
5199 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5200 for (j = 0; j < BPF_REG_SIZE; j++)
5201 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5207 if (tnum_is_const(reg->var_off)) {
5208 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5209 err_extra, regno, min_off, i - min_off, access_size);
5213 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5214 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5215 err_extra, regno, tn_buf, i - min_off, access_size);
5219 /* reading any byte out of 8-byte 'spill_slot' will cause
5220 * the whole slot to be marked as 'read'
5222 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5223 state->stack[spi].spilled_ptr.parent,
5225 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5226 * be sure that whether stack slot is written to or not. Hence,
5227 * we must still conservatively propagate reads upwards even if
5228 * helper may write to the entire memory range.
5231 return update_stack_depth(env, state, min_off);
5234 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5235 int access_size, bool zero_size_allowed,
5236 struct bpf_call_arg_meta *meta)
5238 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5241 switch (base_type(reg->type)) {
5243 case PTR_TO_PACKET_META:
5244 return check_packet_access(env, regno, reg->off, access_size,
5246 case PTR_TO_MAP_KEY:
5247 if (meta && meta->raw_mode) {
5248 verbose(env, "R%d cannot write into %s\n", regno,
5249 reg_type_str(env, reg->type));
5252 return check_mem_region_access(env, regno, reg->off, access_size,
5253 reg->map_ptr->key_size, false);
5254 case PTR_TO_MAP_VALUE:
5255 if (check_map_access_type(env, regno, reg->off, access_size,
5256 meta && meta->raw_mode ? BPF_WRITE :
5259 return check_map_access(env, regno, reg->off, access_size,
5260 zero_size_allowed, ACCESS_HELPER);
5262 if (type_is_rdonly_mem(reg->type)) {
5263 if (meta && meta->raw_mode) {
5264 verbose(env, "R%d cannot write into %s\n", regno,
5265 reg_type_str(env, reg->type));
5269 return check_mem_region_access(env, regno, reg->off,
5270 access_size, reg->mem_size,
5273 if (type_is_rdonly_mem(reg->type)) {
5274 if (meta && meta->raw_mode) {
5275 verbose(env, "R%d cannot write into %s\n", regno,
5276 reg_type_str(env, reg->type));
5280 max_access = &env->prog->aux->max_rdonly_access;
5282 max_access = &env->prog->aux->max_rdwr_access;
5284 return check_buffer_access(env, reg, regno, reg->off,
5285 access_size, zero_size_allowed,
5288 return check_stack_range_initialized(
5290 regno, reg->off, access_size,
5291 zero_size_allowed, ACCESS_HELPER, meta);
5293 /* in case the function doesn't know how to access the context,
5294 * (because we are in a program of type SYSCALL for example), we
5295 * can not statically check its size.
5296 * Dynamically check it now.
5298 if (!env->ops->convert_ctx_access) {
5299 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5300 int offset = access_size - 1;
5302 /* Allow zero-byte read from PTR_TO_CTX */
5303 if (access_size == 0)
5304 return zero_size_allowed ? 0 : -EACCES;
5306 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5311 default: /* scalar_value or invalid ptr */
5312 /* Allow zero-byte read from NULL, regardless of pointer type */
5313 if (zero_size_allowed && access_size == 0 &&
5314 register_is_null(reg))
5317 verbose(env, "R%d type=%s ", regno,
5318 reg_type_str(env, reg->type));
5319 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5324 static int check_mem_size_reg(struct bpf_verifier_env *env,
5325 struct bpf_reg_state *reg, u32 regno,
5326 bool zero_size_allowed,
5327 struct bpf_call_arg_meta *meta)
5331 /* This is used to refine r0 return value bounds for helpers
5332 * that enforce this value as an upper bound on return values.
5333 * See do_refine_retval_range() for helpers that can refine
5334 * the return value. C type of helper is u32 so we pull register
5335 * bound from umax_value however, if negative verifier errors
5336 * out. Only upper bounds can be learned because retval is an
5337 * int type and negative retvals are allowed.
5339 meta->msize_max_value = reg->umax_value;
5341 /* The register is SCALAR_VALUE; the access check
5342 * happens using its boundaries.
5344 if (!tnum_is_const(reg->var_off))
5345 /* For unprivileged variable accesses, disable raw
5346 * mode so that the program is required to
5347 * initialize all the memory that the helper could
5348 * just partially fill up.
5352 if (reg->smin_value < 0) {
5353 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5358 if (reg->umin_value == 0) {
5359 err = check_helper_mem_access(env, regno - 1, 0,
5366 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5367 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5371 err = check_helper_mem_access(env, regno - 1,
5373 zero_size_allowed, meta);
5375 err = mark_chain_precision(env, regno);
5379 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5380 u32 regno, u32 mem_size)
5382 bool may_be_null = type_may_be_null(reg->type);
5383 struct bpf_reg_state saved_reg;
5384 struct bpf_call_arg_meta meta;
5387 if (register_is_null(reg))
5390 memset(&meta, 0, sizeof(meta));
5391 /* Assuming that the register contains a value check if the memory
5392 * access is safe. Temporarily save and restore the register's state as
5393 * the conversion shouldn't be visible to a caller.
5397 mark_ptr_not_null_reg(reg);
5400 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5401 /* Check access for BPF_WRITE */
5402 meta.raw_mode = true;
5403 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5411 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5414 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5415 bool may_be_null = type_may_be_null(mem_reg->type);
5416 struct bpf_reg_state saved_reg;
5417 struct bpf_call_arg_meta meta;
5420 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5422 memset(&meta, 0, sizeof(meta));
5425 saved_reg = *mem_reg;
5426 mark_ptr_not_null_reg(mem_reg);
5429 err = check_mem_size_reg(env, reg, regno, true, &meta);
5430 /* Check access for BPF_WRITE */
5431 meta.raw_mode = true;
5432 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5435 *mem_reg = saved_reg;
5439 /* Implementation details:
5440 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5441 * Two bpf_map_lookups (even with the same key) will have different reg->id.
5442 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5443 * value_or_null->value transition, since the verifier only cares about
5444 * the range of access to valid map value pointer and doesn't care about actual
5445 * address of the map element.
5446 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5447 * reg->id > 0 after value_or_null->value transition. By doing so
5448 * two bpf_map_lookups will be considered two different pointers that
5449 * point to different bpf_spin_locks.
5450 * The verifier allows taking only one bpf_spin_lock at a time to avoid
5452 * Since only one bpf_spin_lock is allowed the checks are simpler than
5453 * reg_is_refcounted() logic. The verifier needs to remember only
5454 * one spin_lock instead of array of acquired_refs.
5455 * cur_state->active_spin_lock remembers which map value element got locked
5456 * and clears it after bpf_spin_unlock.
5458 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5461 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5462 struct bpf_verifier_state *cur = env->cur_state;
5463 bool is_const = tnum_is_const(reg->var_off);
5464 struct bpf_map *map = reg->map_ptr;
5465 u64 val = reg->var_off.value;
5469 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5475 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5479 if (!map_value_has_spin_lock(map)) {
5480 if (map->spin_lock_off == -E2BIG)
5482 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5484 else if (map->spin_lock_off == -ENOENT)
5486 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5490 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5494 if (map->spin_lock_off != val + reg->off) {
5495 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5500 if (cur->active_spin_lock) {
5502 "Locking two bpf_spin_locks are not allowed\n");
5505 cur->active_spin_lock = reg->id;
5507 if (!cur->active_spin_lock) {
5508 verbose(env, "bpf_spin_unlock without taking a lock\n");
5511 if (cur->active_spin_lock != reg->id) {
5512 verbose(env, "bpf_spin_unlock of different lock\n");
5515 cur->active_spin_lock = 0;
5520 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5521 struct bpf_call_arg_meta *meta)
5523 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5524 bool is_const = tnum_is_const(reg->var_off);
5525 struct bpf_map *map = reg->map_ptr;
5526 u64 val = reg->var_off.value;
5530 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5535 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5539 if (!map_value_has_timer(map)) {
5540 if (map->timer_off == -E2BIG)
5542 "map '%s' has more than one 'struct bpf_timer'\n",
5544 else if (map->timer_off == -ENOENT)
5546 "map '%s' doesn't have 'struct bpf_timer'\n",
5550 "map '%s' is not a struct type or bpf_timer is mangled\n",
5554 if (map->timer_off != val + reg->off) {
5555 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5556 val + reg->off, map->timer_off);
5559 if (meta->map_ptr) {
5560 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5563 meta->map_uid = reg->map_uid;
5564 meta->map_ptr = map;
5568 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5569 struct bpf_call_arg_meta *meta)
5571 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5572 struct bpf_map_value_off_desc *off_desc;
5573 struct bpf_map *map_ptr = reg->map_ptr;
5577 if (!tnum_is_const(reg->var_off)) {
5579 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5583 if (!map_ptr->btf) {
5584 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5588 if (!map_value_has_kptrs(map_ptr)) {
5589 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5591 verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5592 BPF_MAP_VALUE_OFF_MAX);
5593 else if (ret == -EEXIST)
5594 verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5596 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5600 meta->map_ptr = map_ptr;
5601 kptr_off = reg->off + reg->var_off.value;
5602 off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5604 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5607 if (off_desc->type != BPF_KPTR_REF) {
5608 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5611 meta->kptr_off_desc = off_desc;
5615 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5617 return type == ARG_CONST_SIZE ||
5618 type == ARG_CONST_SIZE_OR_ZERO;
5621 static bool arg_type_is_release(enum bpf_arg_type type)
5623 return type & OBJ_RELEASE;
5626 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5628 return base_type(type) == ARG_PTR_TO_DYNPTR;
5631 static int int_ptr_type_to_size(enum bpf_arg_type type)
5633 if (type == ARG_PTR_TO_INT)
5635 else if (type == ARG_PTR_TO_LONG)
5641 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5642 const struct bpf_call_arg_meta *meta,
5643 enum bpf_arg_type *arg_type)
5645 if (!meta->map_ptr) {
5646 /* kernel subsystem misconfigured verifier */
5647 verbose(env, "invalid map_ptr to access map->type\n");
5651 switch (meta->map_ptr->map_type) {
5652 case BPF_MAP_TYPE_SOCKMAP:
5653 case BPF_MAP_TYPE_SOCKHASH:
5654 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5655 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5657 verbose(env, "invalid arg_type for sockmap/sockhash\n");
5661 case BPF_MAP_TYPE_BLOOM_FILTER:
5662 if (meta->func_id == BPF_FUNC_map_peek_elem)
5663 *arg_type = ARG_PTR_TO_MAP_VALUE;
5671 struct bpf_reg_types {
5672 const enum bpf_reg_type types[10];
5676 static const struct bpf_reg_types map_key_value_types = {
5686 static const struct bpf_reg_types sock_types = {
5696 static const struct bpf_reg_types btf_id_sock_common_types = {
5704 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5708 static const struct bpf_reg_types mem_types = {
5716 PTR_TO_MEM | MEM_ALLOC,
5721 static const struct bpf_reg_types int_ptr_types = {
5731 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5732 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5733 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5734 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5735 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5736 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5737 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5738 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5739 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5740 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5741 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5742 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5743 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5744 static const struct bpf_reg_types dynptr_types = {
5747 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5751 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5752 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
5753 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
5754 [ARG_CONST_SIZE] = &scalar_types,
5755 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
5756 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
5757 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
5758 [ARG_PTR_TO_CTX] = &context_types,
5759 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
5761 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5763 [ARG_PTR_TO_SOCKET] = &fullsock_types,
5764 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
5765 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
5766 [ARG_PTR_TO_MEM] = &mem_types,
5767 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
5768 [ARG_PTR_TO_INT] = &int_ptr_types,
5769 [ARG_PTR_TO_LONG] = &int_ptr_types,
5770 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
5771 [ARG_PTR_TO_FUNC] = &func_ptr_types,
5772 [ARG_PTR_TO_STACK] = &stack_ptr_types,
5773 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
5774 [ARG_PTR_TO_TIMER] = &timer_types,
5775 [ARG_PTR_TO_KPTR] = &kptr_types,
5776 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
5779 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5780 enum bpf_arg_type arg_type,
5781 const u32 *arg_btf_id,
5782 struct bpf_call_arg_meta *meta)
5784 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5785 enum bpf_reg_type expected, type = reg->type;
5786 const struct bpf_reg_types *compatible;
5789 compatible = compatible_reg_types[base_type(arg_type)];
5791 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5795 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5796 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5798 * Same for MAYBE_NULL:
5800 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5801 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5803 * Therefore we fold these flags depending on the arg_type before comparison.
5805 if (arg_type & MEM_RDONLY)
5806 type &= ~MEM_RDONLY;
5807 if (arg_type & PTR_MAYBE_NULL)
5808 type &= ~PTR_MAYBE_NULL;
5810 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5811 expected = compatible->types[i];
5812 if (expected == NOT_INIT)
5815 if (type == expected)
5819 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5820 for (j = 0; j + 1 < i; j++)
5821 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5822 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5826 if (reg->type == PTR_TO_BTF_ID) {
5827 /* For bpf_sk_release, it needs to match against first member
5828 * 'struct sock_common', hence make an exception for it. This
5829 * allows bpf_sk_release to work for multiple socket types.
5831 bool strict_type_match = arg_type_is_release(arg_type) &&
5832 meta->func_id != BPF_FUNC_sk_release;
5835 if (!compatible->btf_id) {
5836 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5839 arg_btf_id = compatible->btf_id;
5842 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5843 if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5846 if (arg_btf_id == BPF_PTR_POISON) {
5847 verbose(env, "verifier internal error:");
5848 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5853 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5854 btf_vmlinux, *arg_btf_id,
5855 strict_type_match)) {
5856 verbose(env, "R%d is of type %s but %s is expected\n",
5857 regno, kernel_type_name(reg->btf, reg->btf_id),
5858 kernel_type_name(btf_vmlinux, *arg_btf_id));
5867 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5868 const struct bpf_reg_state *reg, int regno,
5869 enum bpf_arg_type arg_type)
5871 enum bpf_reg_type type = reg->type;
5872 bool fixed_off_ok = false;
5874 switch ((u32)type) {
5875 /* Pointer types where reg offset is explicitly allowed: */
5877 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5878 verbose(env, "cannot pass in dynptr at an offset\n");
5883 case PTR_TO_PACKET_META:
5884 case PTR_TO_MAP_KEY:
5885 case PTR_TO_MAP_VALUE:
5887 case PTR_TO_MEM | MEM_RDONLY:
5888 case PTR_TO_MEM | MEM_ALLOC:
5890 case PTR_TO_BUF | MEM_RDONLY:
5892 /* Some of the argument types nevertheless require a
5893 * zero register offset.
5895 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5898 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5902 /* When referenced PTR_TO_BTF_ID is passed to release function,
5903 * it's fixed offset must be 0. In the other cases, fixed offset
5906 if (arg_type_is_release(arg_type) && reg->off) {
5907 verbose(env, "R%d must have zero offset when passed to release func\n",
5911 /* For arg is release pointer, fixed_off_ok must be false, but
5912 * we already checked and rejected reg->off != 0 above, so set
5913 * to true to allow fixed offset for all other cases.
5915 fixed_off_ok = true;
5920 return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5923 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5925 struct bpf_func_state *state = func(env, reg);
5926 int spi = get_spi(reg->off);
5928 return state->stack[spi].spilled_ptr.id;
5931 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5932 struct bpf_call_arg_meta *meta,
5933 const struct bpf_func_proto *fn)
5935 u32 regno = BPF_REG_1 + arg;
5936 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5937 enum bpf_arg_type arg_type = fn->arg_type[arg];
5938 enum bpf_reg_type type = reg->type;
5939 u32 *arg_btf_id = NULL;
5942 if (arg_type == ARG_DONTCARE)
5945 err = check_reg_arg(env, regno, SRC_OP);
5949 if (arg_type == ARG_ANYTHING) {
5950 if (is_pointer_value(env, regno)) {
5951 verbose(env, "R%d leaks addr into helper function\n",
5958 if (type_is_pkt_pointer(type) &&
5959 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5960 verbose(env, "helper access to the packet is not allowed\n");
5964 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5965 err = resolve_map_arg_type(env, meta, &arg_type);
5970 if (register_is_null(reg) && type_may_be_null(arg_type))
5971 /* A NULL register has a SCALAR_VALUE type, so skip
5974 goto skip_type_check;
5976 /* arg_btf_id and arg_size are in a union. */
5977 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5978 arg_btf_id = fn->arg_btf_id[arg];
5980 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5984 err = check_func_arg_reg_off(env, reg, regno, arg_type);
5989 if (arg_type_is_release(arg_type)) {
5990 if (arg_type_is_dynptr(arg_type)) {
5991 struct bpf_func_state *state = func(env, reg);
5992 int spi = get_spi(reg->off);
5994 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
5995 !state->stack[spi].spilled_ptr.id) {
5996 verbose(env, "arg %d is an unacquired reference\n", regno);
5999 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
6000 verbose(env, "R%d must be referenced when passed to release function\n",
6004 if (meta->release_regno) {
6005 verbose(env, "verifier internal error: more than one release argument\n");
6008 meta->release_regno = regno;
6011 if (reg->ref_obj_id) {
6012 if (meta->ref_obj_id) {
6013 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6014 regno, reg->ref_obj_id,
6018 meta->ref_obj_id = reg->ref_obj_id;
6021 switch (base_type(arg_type)) {
6022 case ARG_CONST_MAP_PTR:
6023 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6024 if (meta->map_ptr) {
6025 /* Use map_uid (which is unique id of inner map) to reject:
6026 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6027 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6028 * if (inner_map1 && inner_map2) {
6029 * timer = bpf_map_lookup_elem(inner_map1);
6031 * // mismatch would have been allowed
6032 * bpf_timer_init(timer, inner_map2);
6035 * Comparing map_ptr is enough to distinguish normal and outer maps.
6037 if (meta->map_ptr != reg->map_ptr ||
6038 meta->map_uid != reg->map_uid) {
6040 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6041 meta->map_uid, reg->map_uid);
6045 meta->map_ptr = reg->map_ptr;
6046 meta->map_uid = reg->map_uid;
6048 case ARG_PTR_TO_MAP_KEY:
6049 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6050 * check that [key, key + map->key_size) are within
6051 * stack limits and initialized
6053 if (!meta->map_ptr) {
6054 /* in function declaration map_ptr must come before
6055 * map_key, so that it's verified and known before
6056 * we have to check map_key here. Otherwise it means
6057 * that kernel subsystem misconfigured verifier
6059 verbose(env, "invalid map_ptr to access map->key\n");
6062 err = check_helper_mem_access(env, regno,
6063 meta->map_ptr->key_size, false,
6066 case ARG_PTR_TO_MAP_VALUE:
6067 if (type_may_be_null(arg_type) && register_is_null(reg))
6070 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6071 * check [value, value + map->value_size) validity
6073 if (!meta->map_ptr) {
6074 /* kernel subsystem misconfigured verifier */
6075 verbose(env, "invalid map_ptr to access map->value\n");
6078 meta->raw_mode = arg_type & MEM_UNINIT;
6079 err = check_helper_mem_access(env, regno,
6080 meta->map_ptr->value_size, false,
6083 case ARG_PTR_TO_PERCPU_BTF_ID:
6085 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6088 meta->ret_btf = reg->btf;
6089 meta->ret_btf_id = reg->btf_id;
6091 case ARG_PTR_TO_SPIN_LOCK:
6092 if (meta->func_id == BPF_FUNC_spin_lock) {
6093 if (process_spin_lock(env, regno, true))
6095 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6096 if (process_spin_lock(env, regno, false))
6099 verbose(env, "verifier internal error\n");
6103 case ARG_PTR_TO_TIMER:
6104 if (process_timer_func(env, regno, meta))
6107 case ARG_PTR_TO_FUNC:
6108 meta->subprogno = reg->subprogno;
6110 case ARG_PTR_TO_MEM:
6111 /* The access to this pointer is only checked when we hit the
6112 * next is_mem_size argument below.
6114 meta->raw_mode = arg_type & MEM_UNINIT;
6115 if (arg_type & MEM_FIXED_SIZE) {
6116 err = check_helper_mem_access(env, regno,
6117 fn->arg_size[arg], false,
6121 case ARG_CONST_SIZE:
6122 err = check_mem_size_reg(env, reg, regno, false, meta);
6124 case ARG_CONST_SIZE_OR_ZERO:
6125 err = check_mem_size_reg(env, reg, regno, true, meta);
6127 case ARG_PTR_TO_DYNPTR:
6128 /* We only need to check for initialized / uninitialized helper
6129 * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6130 * assumption is that if it is, that a helper function
6131 * initialized the dynptr on behalf of the BPF program.
6133 if (base_type(reg->type) == PTR_TO_DYNPTR)
6135 if (arg_type & MEM_UNINIT) {
6136 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6137 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6141 /* We only support one dynptr being uninitialized at the moment,
6142 * which is sufficient for the helper functions we have right now.
6144 if (meta->uninit_dynptr_regno) {
6145 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6149 meta->uninit_dynptr_regno = regno;
6150 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6152 "Expected an initialized dynptr as arg #%d\n",
6155 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6156 const char *err_extra = "";
6158 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6159 case DYNPTR_TYPE_LOCAL:
6160 err_extra = "local";
6162 case DYNPTR_TYPE_RINGBUF:
6163 err_extra = "ringbuf";
6166 err_extra = "<unknown>";
6170 "Expected a dynptr of type %s as arg #%d\n",
6171 err_extra, arg + 1);
6175 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6176 if (!tnum_is_const(reg->var_off)) {
6177 verbose(env, "R%d is not a known constant'\n",
6181 meta->mem_size = reg->var_off.value;
6182 err = mark_chain_precision(env, regno);
6186 case ARG_PTR_TO_INT:
6187 case ARG_PTR_TO_LONG:
6189 int size = int_ptr_type_to_size(arg_type);
6191 err = check_helper_mem_access(env, regno, size, false, meta);
6194 err = check_ptr_alignment(env, reg, 0, size, true);
6197 case ARG_PTR_TO_CONST_STR:
6199 struct bpf_map *map = reg->map_ptr;
6204 if (!bpf_map_is_rdonly(map)) {
6205 verbose(env, "R%d does not point to a readonly map'\n", regno);
6209 if (!tnum_is_const(reg->var_off)) {
6210 verbose(env, "R%d is not a constant address'\n", regno);
6214 if (!map->ops->map_direct_value_addr) {
6215 verbose(env, "no direct value access support for this map type\n");
6219 err = check_map_access(env, regno, reg->off,
6220 map->value_size - reg->off, false,
6225 map_off = reg->off + reg->var_off.value;
6226 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6228 verbose(env, "direct value access on string failed\n");
6232 str_ptr = (char *)(long)(map_addr);
6233 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6234 verbose(env, "string is not zero-terminated\n");
6239 case ARG_PTR_TO_KPTR:
6240 if (process_kptr_func(env, regno, meta))
6248 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6250 enum bpf_attach_type eatype = env->prog->expected_attach_type;
6251 enum bpf_prog_type type = resolve_prog_type(env->prog);
6253 if (func_id != BPF_FUNC_map_update_elem)
6256 /* It's not possible to get access to a locked struct sock in these
6257 * contexts, so updating is safe.
6260 case BPF_PROG_TYPE_TRACING:
6261 if (eatype == BPF_TRACE_ITER)
6264 case BPF_PROG_TYPE_SOCKET_FILTER:
6265 case BPF_PROG_TYPE_SCHED_CLS:
6266 case BPF_PROG_TYPE_SCHED_ACT:
6267 case BPF_PROG_TYPE_XDP:
6268 case BPF_PROG_TYPE_SK_REUSEPORT:
6269 case BPF_PROG_TYPE_FLOW_DISSECTOR:
6270 case BPF_PROG_TYPE_SK_LOOKUP:
6276 verbose(env, "cannot update sockmap in this context\n");
6280 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6282 return env->prog->jit_requested &&
6283 bpf_jit_supports_subprog_tailcalls();
6286 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6287 struct bpf_map *map, int func_id)
6292 /* We need a two way check, first is from map perspective ... */
6293 switch (map->map_type) {
6294 case BPF_MAP_TYPE_PROG_ARRAY:
6295 if (func_id != BPF_FUNC_tail_call)
6298 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6299 if (func_id != BPF_FUNC_perf_event_read &&
6300 func_id != BPF_FUNC_perf_event_output &&
6301 func_id != BPF_FUNC_skb_output &&
6302 func_id != BPF_FUNC_perf_event_read_value &&
6303 func_id != BPF_FUNC_xdp_output)
6306 case BPF_MAP_TYPE_RINGBUF:
6307 if (func_id != BPF_FUNC_ringbuf_output &&
6308 func_id != BPF_FUNC_ringbuf_reserve &&
6309 func_id != BPF_FUNC_ringbuf_query &&
6310 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6311 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6312 func_id != BPF_FUNC_ringbuf_discard_dynptr)
6315 case BPF_MAP_TYPE_USER_RINGBUF:
6316 if (func_id != BPF_FUNC_user_ringbuf_drain)
6319 case BPF_MAP_TYPE_STACK_TRACE:
6320 if (func_id != BPF_FUNC_get_stackid)
6323 case BPF_MAP_TYPE_CGROUP_ARRAY:
6324 if (func_id != BPF_FUNC_skb_under_cgroup &&
6325 func_id != BPF_FUNC_current_task_under_cgroup)
6328 case BPF_MAP_TYPE_CGROUP_STORAGE:
6329 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6330 if (func_id != BPF_FUNC_get_local_storage)
6333 case BPF_MAP_TYPE_DEVMAP:
6334 case BPF_MAP_TYPE_DEVMAP_HASH:
6335 if (func_id != BPF_FUNC_redirect_map &&
6336 func_id != BPF_FUNC_map_lookup_elem)
6339 /* Restrict bpf side of cpumap and xskmap, open when use-cases
6342 case BPF_MAP_TYPE_CPUMAP:
6343 if (func_id != BPF_FUNC_redirect_map)
6346 case BPF_MAP_TYPE_XSKMAP:
6347 if (func_id != BPF_FUNC_redirect_map &&
6348 func_id != BPF_FUNC_map_lookup_elem)
6351 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6352 case BPF_MAP_TYPE_HASH_OF_MAPS:
6353 if (func_id != BPF_FUNC_map_lookup_elem)
6356 case BPF_MAP_TYPE_SOCKMAP:
6357 if (func_id != BPF_FUNC_sk_redirect_map &&
6358 func_id != BPF_FUNC_sock_map_update &&
6359 func_id != BPF_FUNC_map_delete_elem &&
6360 func_id != BPF_FUNC_msg_redirect_map &&
6361 func_id != BPF_FUNC_sk_select_reuseport &&
6362 func_id != BPF_FUNC_map_lookup_elem &&
6363 !may_update_sockmap(env, func_id))
6366 case BPF_MAP_TYPE_SOCKHASH:
6367 if (func_id != BPF_FUNC_sk_redirect_hash &&
6368 func_id != BPF_FUNC_sock_hash_update &&
6369 func_id != BPF_FUNC_map_delete_elem &&
6370 func_id != BPF_FUNC_msg_redirect_hash &&
6371 func_id != BPF_FUNC_sk_select_reuseport &&
6372 func_id != BPF_FUNC_map_lookup_elem &&
6373 !may_update_sockmap(env, func_id))
6376 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6377 if (func_id != BPF_FUNC_sk_select_reuseport)
6380 case BPF_MAP_TYPE_QUEUE:
6381 case BPF_MAP_TYPE_STACK:
6382 if (func_id != BPF_FUNC_map_peek_elem &&
6383 func_id != BPF_FUNC_map_pop_elem &&
6384 func_id != BPF_FUNC_map_push_elem)
6387 case BPF_MAP_TYPE_SK_STORAGE:
6388 if (func_id != BPF_FUNC_sk_storage_get &&
6389 func_id != BPF_FUNC_sk_storage_delete)
6392 case BPF_MAP_TYPE_INODE_STORAGE:
6393 if (func_id != BPF_FUNC_inode_storage_get &&
6394 func_id != BPF_FUNC_inode_storage_delete)
6397 case BPF_MAP_TYPE_TASK_STORAGE:
6398 if (func_id != BPF_FUNC_task_storage_get &&
6399 func_id != BPF_FUNC_task_storage_delete)
6402 case BPF_MAP_TYPE_BLOOM_FILTER:
6403 if (func_id != BPF_FUNC_map_peek_elem &&
6404 func_id != BPF_FUNC_map_push_elem)
6411 /* ... and second from the function itself. */
6413 case BPF_FUNC_tail_call:
6414 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6416 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6417 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6421 case BPF_FUNC_perf_event_read:
6422 case BPF_FUNC_perf_event_output:
6423 case BPF_FUNC_perf_event_read_value:
6424 case BPF_FUNC_skb_output:
6425 case BPF_FUNC_xdp_output:
6426 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6429 case BPF_FUNC_ringbuf_output:
6430 case BPF_FUNC_ringbuf_reserve:
6431 case BPF_FUNC_ringbuf_query:
6432 case BPF_FUNC_ringbuf_reserve_dynptr:
6433 case BPF_FUNC_ringbuf_submit_dynptr:
6434 case BPF_FUNC_ringbuf_discard_dynptr:
6435 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6438 case BPF_FUNC_user_ringbuf_drain:
6439 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6442 case BPF_FUNC_get_stackid:
6443 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6446 case BPF_FUNC_current_task_under_cgroup:
6447 case BPF_FUNC_skb_under_cgroup:
6448 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6451 case BPF_FUNC_redirect_map:
6452 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6453 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6454 map->map_type != BPF_MAP_TYPE_CPUMAP &&
6455 map->map_type != BPF_MAP_TYPE_XSKMAP)
6458 case BPF_FUNC_sk_redirect_map:
6459 case BPF_FUNC_msg_redirect_map:
6460 case BPF_FUNC_sock_map_update:
6461 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6464 case BPF_FUNC_sk_redirect_hash:
6465 case BPF_FUNC_msg_redirect_hash:
6466 case BPF_FUNC_sock_hash_update:
6467 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6470 case BPF_FUNC_get_local_storage:
6471 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6472 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6475 case BPF_FUNC_sk_select_reuseport:
6476 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6477 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6478 map->map_type != BPF_MAP_TYPE_SOCKHASH)
6481 case BPF_FUNC_map_pop_elem:
6482 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6483 map->map_type != BPF_MAP_TYPE_STACK)
6486 case BPF_FUNC_map_peek_elem:
6487 case BPF_FUNC_map_push_elem:
6488 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6489 map->map_type != BPF_MAP_TYPE_STACK &&
6490 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6493 case BPF_FUNC_map_lookup_percpu_elem:
6494 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6495 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6496 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6499 case BPF_FUNC_sk_storage_get:
6500 case BPF_FUNC_sk_storage_delete:
6501 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6504 case BPF_FUNC_inode_storage_get:
6505 case BPF_FUNC_inode_storage_delete:
6506 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6509 case BPF_FUNC_task_storage_get:
6510 case BPF_FUNC_task_storage_delete:
6511 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6520 verbose(env, "cannot pass map_type %d into func %s#%d\n",
6521 map->map_type, func_id_name(func_id), func_id);
6525 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6529 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6531 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6533 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6535 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6537 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6540 /* We only support one arg being in raw mode at the moment,
6541 * which is sufficient for the helper functions we have
6547 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6549 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6550 bool has_size = fn->arg_size[arg] != 0;
6551 bool is_next_size = false;
6553 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6554 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6556 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6557 return is_next_size;
6559 return has_size == is_next_size || is_next_size == is_fixed;
6562 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6564 /* bpf_xxx(..., buf, len) call will access 'len'
6565 * bytes from memory 'buf'. Both arg types need
6566 * to be paired, so make sure there's no buggy
6567 * helper function specification.
6569 if (arg_type_is_mem_size(fn->arg1_type) ||
6570 check_args_pair_invalid(fn, 0) ||
6571 check_args_pair_invalid(fn, 1) ||
6572 check_args_pair_invalid(fn, 2) ||
6573 check_args_pair_invalid(fn, 3) ||
6574 check_args_pair_invalid(fn, 4))
6580 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6584 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6585 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6588 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6589 /* arg_btf_id and arg_size are in a union. */
6590 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6591 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6598 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6600 return check_raw_mode_ok(fn) &&
6601 check_arg_pair_ok(fn) &&
6602 check_btf_id_ok(fn) ? 0 : -EINVAL;
6605 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6606 * are now invalid, so turn them into unknown SCALAR_VALUE.
6608 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6610 struct bpf_func_state *state;
6611 struct bpf_reg_state *reg;
6613 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6614 if (reg_is_pkt_pointer_any(reg))
6615 __mark_reg_unknown(env, reg);
6621 BEYOND_PKT_END = -2,
6624 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6626 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6627 struct bpf_reg_state *reg = &state->regs[regn];
6629 if (reg->type != PTR_TO_PACKET)
6630 /* PTR_TO_PACKET_META is not supported yet */
6633 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6634 * How far beyond pkt_end it goes is unknown.
6635 * if (!range_open) it's the case of pkt >= pkt_end
6636 * if (range_open) it's the case of pkt > pkt_end
6637 * hence this pointer is at least 1 byte bigger than pkt_end
6640 reg->range = BEYOND_PKT_END;
6642 reg->range = AT_PKT_END;
6645 /* The pointer with the specified id has released its reference to kernel
6646 * resources. Identify all copies of the same pointer and clear the reference.
6648 static int release_reference(struct bpf_verifier_env *env,
6651 struct bpf_func_state *state;
6652 struct bpf_reg_state *reg;
6655 err = release_reference_state(cur_func(env), ref_obj_id);
6659 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6660 if (reg->ref_obj_id == ref_obj_id) {
6661 if (!env->allow_ptr_leaks)
6662 __mark_reg_not_init(env, reg);
6664 __mark_reg_unknown(env, reg);
6671 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6672 struct bpf_reg_state *regs)
6676 /* after the call registers r0 - r5 were scratched */
6677 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6678 mark_reg_not_init(env, regs, caller_saved[i]);
6679 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6683 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6684 struct bpf_func_state *caller,
6685 struct bpf_func_state *callee,
6688 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6689 int *insn_idx, int subprog,
6690 set_callee_state_fn set_callee_state_cb)
6692 struct bpf_verifier_state *state = env->cur_state;
6693 struct bpf_func_info_aux *func_info_aux;
6694 struct bpf_func_state *caller, *callee;
6696 bool is_global = false;
6698 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6699 verbose(env, "the call stack of %d frames is too deep\n",
6700 state->curframe + 2);
6704 caller = state->frame[state->curframe];
6705 if (state->frame[state->curframe + 1]) {
6706 verbose(env, "verifier bug. Frame %d already allocated\n",
6707 state->curframe + 1);
6711 func_info_aux = env->prog->aux->func_info_aux;
6713 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6714 err = btf_check_subprog_call(env, subprog, caller->regs);
6719 verbose(env, "Caller passes invalid args into func#%d\n",
6723 if (env->log.level & BPF_LOG_LEVEL)
6725 "Func#%d is global and valid. Skipping.\n",
6727 clear_caller_saved_regs(env, caller->regs);
6729 /* All global functions return a 64-bit SCALAR_VALUE */
6730 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6731 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6733 /* continue with next insn after call */
6738 if (insn->code == (BPF_JMP | BPF_CALL) &&
6739 insn->src_reg == 0 &&
6740 insn->imm == BPF_FUNC_timer_set_callback) {
6741 struct bpf_verifier_state *async_cb;
6743 /* there is no real recursion here. timer callbacks are async */
6744 env->subprog_info[subprog].is_async_cb = true;
6745 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6746 *insn_idx, subprog);
6749 callee = async_cb->frame[0];
6750 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6752 /* Convert bpf_timer_set_callback() args into timer callback args */
6753 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6757 clear_caller_saved_regs(env, caller->regs);
6758 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6759 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6760 /* continue with next insn after call */
6764 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6767 state->frame[state->curframe + 1] = callee;
6769 /* callee cannot access r0, r6 - r9 for reading and has to write
6770 * into its own stack before reading from it.
6771 * callee can read/write into caller's stack
6773 init_func_state(env, callee,
6774 /* remember the callsite, it will be used by bpf_exit */
6775 *insn_idx /* callsite */,
6776 state->curframe + 1 /* frameno within this callchain */,
6777 subprog /* subprog number within this prog */);
6779 /* Transfer references to the callee */
6780 err = copy_reference_state(callee, caller);
6784 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6788 clear_caller_saved_regs(env, caller->regs);
6790 /* only increment it after check_reg_arg() finished */
6793 /* and go analyze first insn of the callee */
6794 *insn_idx = env->subprog_info[subprog].start - 1;
6796 if (env->log.level & BPF_LOG_LEVEL) {
6797 verbose(env, "caller:\n");
6798 print_verifier_state(env, caller, true);
6799 verbose(env, "callee:\n");
6800 print_verifier_state(env, callee, true);
6805 free_func_state(callee);
6806 state->frame[state->curframe + 1] = NULL;
6810 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6811 struct bpf_func_state *caller,
6812 struct bpf_func_state *callee)
6814 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6815 * void *callback_ctx, u64 flags);
6816 * callback_fn(struct bpf_map *map, void *key, void *value,
6817 * void *callback_ctx);
6819 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6821 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6822 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6823 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6825 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6826 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6827 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6829 /* pointer to stack or null */
6830 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6833 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6837 static int set_callee_state(struct bpf_verifier_env *env,
6838 struct bpf_func_state *caller,
6839 struct bpf_func_state *callee, int insn_idx)
6843 /* copy r1 - r5 args that callee can access. The copy includes parent
6844 * pointers, which connects us up to the liveness chain
6846 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6847 callee->regs[i] = caller->regs[i];
6851 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6854 int subprog, target_insn;
6856 target_insn = *insn_idx + insn->imm + 1;
6857 subprog = find_subprog(env, target_insn);
6859 verbose(env, "verifier bug. No program starts at insn %d\n",
6864 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6867 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6868 struct bpf_func_state *caller,
6869 struct bpf_func_state *callee,
6872 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6873 struct bpf_map *map;
6876 if (bpf_map_ptr_poisoned(insn_aux)) {
6877 verbose(env, "tail_call abusing map_ptr\n");
6881 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6882 if (!map->ops->map_set_for_each_callback_args ||
6883 !map->ops->map_for_each_callback) {
6884 verbose(env, "callback function not allowed for map\n");
6888 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6892 callee->in_callback_fn = true;
6893 callee->callback_ret_range = tnum_range(0, 1);
6897 static int set_loop_callback_state(struct bpf_verifier_env *env,
6898 struct bpf_func_state *caller,
6899 struct bpf_func_state *callee,
6902 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6904 * callback_fn(u32 index, void *callback_ctx);
6906 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6907 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6910 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6911 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6912 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6914 callee->in_callback_fn = true;
6915 callee->callback_ret_range = tnum_range(0, 1);
6919 static int set_timer_callback_state(struct bpf_verifier_env *env,
6920 struct bpf_func_state *caller,
6921 struct bpf_func_state *callee,
6924 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6926 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6927 * callback_fn(struct bpf_map *map, void *key, void *value);
6929 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6930 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6931 callee->regs[BPF_REG_1].map_ptr = map_ptr;
6933 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6934 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6935 callee->regs[BPF_REG_2].map_ptr = map_ptr;
6937 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6938 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6939 callee->regs[BPF_REG_3].map_ptr = map_ptr;
6942 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6943 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6944 callee->in_async_callback_fn = true;
6945 callee->callback_ret_range = tnum_range(0, 1);
6949 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6950 struct bpf_func_state *caller,
6951 struct bpf_func_state *callee,
6954 /* bpf_find_vma(struct task_struct *task, u64 addr,
6955 * void *callback_fn, void *callback_ctx, u64 flags)
6956 * (callback_fn)(struct task_struct *task,
6957 * struct vm_area_struct *vma, void *callback_ctx);
6959 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6961 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6962 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6963 callee->regs[BPF_REG_2].btf = btf_vmlinux;
6964 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6966 /* pointer to stack or null */
6967 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6970 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6971 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6972 callee->in_callback_fn = true;
6973 callee->callback_ret_range = tnum_range(0, 1);
6977 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
6978 struct bpf_func_state *caller,
6979 struct bpf_func_state *callee,
6982 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
6983 * callback_ctx, u64 flags);
6984 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
6986 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
6987 callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
6988 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6989 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6992 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6993 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6994 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6996 callee->in_callback_fn = true;
6997 callee->callback_ret_range = tnum_range(0, 1);
7001 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7003 struct bpf_verifier_state *state = env->cur_state;
7004 struct bpf_func_state *caller, *callee;
7005 struct bpf_reg_state *r0;
7008 callee = state->frame[state->curframe];
7009 r0 = &callee->regs[BPF_REG_0];
7010 if (r0->type == PTR_TO_STACK) {
7011 /* technically it's ok to return caller's stack pointer
7012 * (or caller's caller's pointer) back to the caller,
7013 * since these pointers are valid. Only current stack
7014 * pointer will be invalid as soon as function exits,
7015 * but let's be conservative
7017 verbose(env, "cannot return stack pointer to the caller\n");
7021 caller = state->frame[state->curframe - 1];
7022 if (callee->in_callback_fn) {
7023 /* enforce R0 return value range [0, 1]. */
7024 struct tnum range = callee->callback_ret_range;
7026 if (r0->type != SCALAR_VALUE) {
7027 verbose(env, "R0 not a scalar value\n");
7030 if (!tnum_in(range, r0->var_off)) {
7031 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7035 /* return to the caller whatever r0 had in the callee */
7036 caller->regs[BPF_REG_0] = *r0;
7039 /* callback_fn frame should have released its own additions to parent's
7040 * reference state at this point, or check_reference_leak would
7041 * complain, hence it must be the same as the caller. There is no need
7044 if (!callee->in_callback_fn) {
7045 /* Transfer references to the caller */
7046 err = copy_reference_state(caller, callee);
7051 *insn_idx = callee->callsite + 1;
7052 if (env->log.level & BPF_LOG_LEVEL) {
7053 verbose(env, "returning from callee:\n");
7054 print_verifier_state(env, callee, true);
7055 verbose(env, "to caller at %d:\n", *insn_idx);
7056 print_verifier_state(env, caller, true);
7058 /* clear everything in the callee */
7059 free_func_state(callee);
7060 state->frame[state->curframe--] = NULL;
7064 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7066 struct bpf_call_arg_meta *meta)
7068 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
7070 if (ret_type != RET_INTEGER ||
7071 (func_id != BPF_FUNC_get_stack &&
7072 func_id != BPF_FUNC_get_task_stack &&
7073 func_id != BPF_FUNC_probe_read_str &&
7074 func_id != BPF_FUNC_probe_read_kernel_str &&
7075 func_id != BPF_FUNC_probe_read_user_str))
7078 ret_reg->smax_value = meta->msize_max_value;
7079 ret_reg->s32_max_value = meta->msize_max_value;
7080 ret_reg->smin_value = -MAX_ERRNO;
7081 ret_reg->s32_min_value = -MAX_ERRNO;
7082 reg_bounds_sync(ret_reg);
7086 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7087 int func_id, int insn_idx)
7089 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7090 struct bpf_map *map = meta->map_ptr;
7092 if (func_id != BPF_FUNC_tail_call &&
7093 func_id != BPF_FUNC_map_lookup_elem &&
7094 func_id != BPF_FUNC_map_update_elem &&
7095 func_id != BPF_FUNC_map_delete_elem &&
7096 func_id != BPF_FUNC_map_push_elem &&
7097 func_id != BPF_FUNC_map_pop_elem &&
7098 func_id != BPF_FUNC_map_peek_elem &&
7099 func_id != BPF_FUNC_for_each_map_elem &&
7100 func_id != BPF_FUNC_redirect_map &&
7101 func_id != BPF_FUNC_map_lookup_percpu_elem)
7105 verbose(env, "kernel subsystem misconfigured verifier\n");
7109 /* In case of read-only, some additional restrictions
7110 * need to be applied in order to prevent altering the
7111 * state of the map from program side.
7113 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7114 (func_id == BPF_FUNC_map_delete_elem ||
7115 func_id == BPF_FUNC_map_update_elem ||
7116 func_id == BPF_FUNC_map_push_elem ||
7117 func_id == BPF_FUNC_map_pop_elem)) {
7118 verbose(env, "write into map forbidden\n");
7122 if (!BPF_MAP_PTR(aux->map_ptr_state))
7123 bpf_map_ptr_store(aux, meta->map_ptr,
7124 !meta->map_ptr->bypass_spec_v1);
7125 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7126 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7127 !meta->map_ptr->bypass_spec_v1);
7132 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7133 int func_id, int insn_idx)
7135 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7136 struct bpf_reg_state *regs = cur_regs(env), *reg;
7137 struct bpf_map *map = meta->map_ptr;
7141 if (func_id != BPF_FUNC_tail_call)
7143 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7144 verbose(env, "kernel subsystem misconfigured verifier\n");
7148 reg = ®s[BPF_REG_3];
7149 val = reg->var_off.value;
7150 max = map->max_entries;
7152 if (!(register_is_const(reg) && val < max)) {
7153 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7157 err = mark_chain_precision(env, BPF_REG_3);
7160 if (bpf_map_key_unseen(aux))
7161 bpf_map_key_store(aux, val);
7162 else if (!bpf_map_key_poisoned(aux) &&
7163 bpf_map_key_immediate(aux) != val)
7164 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7168 static int check_reference_leak(struct bpf_verifier_env *env)
7170 struct bpf_func_state *state = cur_func(env);
7171 bool refs_lingering = false;
7174 if (state->frameno && !state->in_callback_fn)
7177 for (i = 0; i < state->acquired_refs; i++) {
7178 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7180 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7181 state->refs[i].id, state->refs[i].insn_idx);
7182 refs_lingering = true;
7184 return refs_lingering ? -EINVAL : 0;
7187 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7188 struct bpf_reg_state *regs)
7190 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
7191 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
7192 struct bpf_map *fmt_map = fmt_reg->map_ptr;
7193 int err, fmt_map_off, num_args;
7197 /* data must be an array of u64 */
7198 if (data_len_reg->var_off.value % 8)
7200 num_args = data_len_reg->var_off.value / 8;
7202 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7203 * and map_direct_value_addr is set.
7205 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7206 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7209 verbose(env, "verifier bug\n");
7212 fmt = (char *)(long)fmt_addr + fmt_map_off;
7214 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7215 * can focus on validating the format specifiers.
7217 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7219 verbose(env, "Invalid format string\n");
7224 static int check_get_func_ip(struct bpf_verifier_env *env)
7226 enum bpf_prog_type type = resolve_prog_type(env->prog);
7227 int func_id = BPF_FUNC_get_func_ip;
7229 if (type == BPF_PROG_TYPE_TRACING) {
7230 if (!bpf_prog_has_trampoline(env->prog)) {
7231 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7232 func_id_name(func_id), func_id);
7236 } else if (type == BPF_PROG_TYPE_KPROBE) {
7240 verbose(env, "func %s#%d not supported for program type %d\n",
7241 func_id_name(func_id), func_id, type);
7245 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7247 return &env->insn_aux_data[env->insn_idx];
7250 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7252 struct bpf_reg_state *regs = cur_regs(env);
7253 struct bpf_reg_state *reg = ®s[BPF_REG_4];
7254 bool reg_is_null = register_is_null(reg);
7257 mark_chain_precision(env, BPF_REG_4);
7262 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7264 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7266 if (!state->initialized) {
7267 state->initialized = 1;
7268 state->fit_for_inline = loop_flag_is_zero(env);
7269 state->callback_subprogno = subprogno;
7273 if (!state->fit_for_inline)
7276 state->fit_for_inline = (loop_flag_is_zero(env) &&
7277 state->callback_subprogno == subprogno);
7280 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7283 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7284 const struct bpf_func_proto *fn = NULL;
7285 enum bpf_return_type ret_type;
7286 enum bpf_type_flag ret_flag;
7287 struct bpf_reg_state *regs;
7288 struct bpf_call_arg_meta meta;
7289 int insn_idx = *insn_idx_p;
7291 int i, err, func_id;
7293 /* find function prototype */
7294 func_id = insn->imm;
7295 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7296 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7301 if (env->ops->get_func_proto)
7302 fn = env->ops->get_func_proto(func_id, env->prog);
7304 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7309 /* eBPF programs must be GPL compatible to use GPL-ed functions */
7310 if (!env->prog->gpl_compatible && fn->gpl_only) {
7311 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7315 if (fn->allowed && !fn->allowed(env->prog)) {
7316 verbose(env, "helper call is not allowed in probe\n");
7320 /* With LD_ABS/IND some JITs save/restore skb from r1. */
7321 changes_data = bpf_helper_changes_pkt_data(fn->func);
7322 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7323 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7324 func_id_name(func_id), func_id);
7328 memset(&meta, 0, sizeof(meta));
7329 meta.pkt_access = fn->pkt_access;
7331 err = check_func_proto(fn, func_id);
7333 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7334 func_id_name(func_id), func_id);
7338 meta.func_id = func_id;
7340 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7341 err = check_func_arg(env, i, &meta, fn);
7346 err = record_func_map(env, &meta, func_id, insn_idx);
7350 err = record_func_key(env, &meta, func_id, insn_idx);
7354 /* Mark slots with STACK_MISC in case of raw mode, stack offset
7355 * is inferred from register state.
7357 for (i = 0; i < meta.access_size; i++) {
7358 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7359 BPF_WRITE, -1, false);
7364 regs = cur_regs(env);
7366 if (meta.uninit_dynptr_regno) {
7367 /* we write BPF_DW bits (8 bytes) at a time */
7368 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7369 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7370 i, BPF_DW, BPF_WRITE, -1, false);
7375 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno],
7376 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7382 if (meta.release_regno) {
7384 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7385 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
7386 else if (meta.ref_obj_id)
7387 err = release_reference(env, meta.ref_obj_id);
7388 /* meta.ref_obj_id can only be 0 if register that is meant to be
7389 * released is NULL, which must be > R0.
7391 else if (register_is_null(®s[meta.release_regno]))
7394 verbose(env, "func %s#%d reference has not been acquired before\n",
7395 func_id_name(func_id), func_id);
7401 case BPF_FUNC_tail_call:
7402 err = check_reference_leak(env);
7404 verbose(env, "tail_call would lead to reference leak\n");
7408 case BPF_FUNC_get_local_storage:
7409 /* check that flags argument in get_local_storage(map, flags) is 0,
7410 * this is required because get_local_storage() can't return an error.
7412 if (!register_is_null(®s[BPF_REG_2])) {
7413 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7417 case BPF_FUNC_for_each_map_elem:
7418 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7419 set_map_elem_callback_state);
7421 case BPF_FUNC_timer_set_callback:
7422 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7423 set_timer_callback_state);
7425 case BPF_FUNC_find_vma:
7426 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7427 set_find_vma_callback_state);
7429 case BPF_FUNC_snprintf:
7430 err = check_bpf_snprintf_call(env, regs);
7433 update_loop_inline_state(env, meta.subprogno);
7434 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7435 set_loop_callback_state);
7437 case BPF_FUNC_dynptr_from_mem:
7438 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7439 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7440 reg_type_str(env, regs[BPF_REG_1].type));
7444 case BPF_FUNC_set_retval:
7445 if (prog_type == BPF_PROG_TYPE_LSM &&
7446 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7447 if (!env->prog->aux->attach_func_proto->type) {
7448 /* Make sure programs that attach to void
7449 * hooks don't try to modify return value.
7451 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7456 case BPF_FUNC_dynptr_data:
7457 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7458 if (arg_type_is_dynptr(fn->arg_type[i])) {
7459 struct bpf_reg_state *reg = ®s[BPF_REG_1 + i];
7461 if (meta.ref_obj_id) {
7462 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7466 if (base_type(reg->type) != PTR_TO_DYNPTR)
7467 /* Find the id of the dynptr we're
7468 * tracking the reference of
7470 meta.ref_obj_id = stack_slot_get_id(env, reg);
7474 if (i == MAX_BPF_FUNC_REG_ARGS) {
7475 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7479 case BPF_FUNC_user_ringbuf_drain:
7480 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7481 set_user_ringbuf_callback_state);
7488 /* reset caller saved regs */
7489 for (i = 0; i < CALLER_SAVED_REGS; i++) {
7490 mark_reg_not_init(env, regs, caller_saved[i]);
7491 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7494 /* helper call returns 64-bit value. */
7495 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7497 /* update return register (already marked as written above) */
7498 ret_type = fn->ret_type;
7499 ret_flag = type_flag(ret_type);
7501 switch (base_type(ret_type)) {
7503 /* sets type to SCALAR_VALUE */
7504 mark_reg_unknown(env, regs, BPF_REG_0);
7507 regs[BPF_REG_0].type = NOT_INIT;
7509 case RET_PTR_TO_MAP_VALUE:
7510 /* There is no offset yet applied, variable or fixed */
7511 mark_reg_known_zero(env, regs, BPF_REG_0);
7512 /* remember map_ptr, so that check_map_access()
7513 * can check 'value_size' boundary of memory access
7514 * to map element returned from bpf_map_lookup_elem()
7516 if (meta.map_ptr == NULL) {
7518 "kernel subsystem misconfigured verifier\n");
7521 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7522 regs[BPF_REG_0].map_uid = meta.map_uid;
7523 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7524 if (!type_may_be_null(ret_type) &&
7525 map_value_has_spin_lock(meta.map_ptr)) {
7526 regs[BPF_REG_0].id = ++env->id_gen;
7529 case RET_PTR_TO_SOCKET:
7530 mark_reg_known_zero(env, regs, BPF_REG_0);
7531 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7533 case RET_PTR_TO_SOCK_COMMON:
7534 mark_reg_known_zero(env, regs, BPF_REG_0);
7535 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7537 case RET_PTR_TO_TCP_SOCK:
7538 mark_reg_known_zero(env, regs, BPF_REG_0);
7539 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7541 case RET_PTR_TO_ALLOC_MEM:
7542 mark_reg_known_zero(env, regs, BPF_REG_0);
7543 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7544 regs[BPF_REG_0].mem_size = meta.mem_size;
7546 case RET_PTR_TO_MEM_OR_BTF_ID:
7548 const struct btf_type *t;
7550 mark_reg_known_zero(env, regs, BPF_REG_0);
7551 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7552 if (!btf_type_is_struct(t)) {
7554 const struct btf_type *ret;
7557 /* resolve the type size of ksym. */
7558 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7560 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7561 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7562 tname, PTR_ERR(ret));
7565 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7566 regs[BPF_REG_0].mem_size = tsize;
7568 /* MEM_RDONLY may be carried from ret_flag, but it
7569 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7570 * it will confuse the check of PTR_TO_BTF_ID in
7571 * check_mem_access().
7573 ret_flag &= ~MEM_RDONLY;
7575 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7576 regs[BPF_REG_0].btf = meta.ret_btf;
7577 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7581 case RET_PTR_TO_BTF_ID:
7583 struct btf *ret_btf;
7586 mark_reg_known_zero(env, regs, BPF_REG_0);
7587 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7588 if (func_id == BPF_FUNC_kptr_xchg) {
7589 ret_btf = meta.kptr_off_desc->kptr.btf;
7590 ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7592 if (fn->ret_btf_id == BPF_PTR_POISON) {
7593 verbose(env, "verifier internal error:");
7594 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7595 func_id_name(func_id));
7598 ret_btf = btf_vmlinux;
7599 ret_btf_id = *fn->ret_btf_id;
7601 if (ret_btf_id == 0) {
7602 verbose(env, "invalid return type %u of func %s#%d\n",
7603 base_type(ret_type), func_id_name(func_id),
7607 regs[BPF_REG_0].btf = ret_btf;
7608 regs[BPF_REG_0].btf_id = ret_btf_id;
7612 verbose(env, "unknown return type %u of func %s#%d\n",
7613 base_type(ret_type), func_id_name(func_id), func_id);
7617 if (type_may_be_null(regs[BPF_REG_0].type))
7618 regs[BPF_REG_0].id = ++env->id_gen;
7620 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7621 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7622 func_id_name(func_id), func_id);
7626 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7627 /* For release_reference() */
7628 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7629 } else if (is_acquire_function(func_id, meta.map_ptr)) {
7630 int id = acquire_reference_state(env, insn_idx);
7634 /* For mark_ptr_or_null_reg() */
7635 regs[BPF_REG_0].id = id;
7636 /* For release_reference() */
7637 regs[BPF_REG_0].ref_obj_id = id;
7640 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7642 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7646 if ((func_id == BPF_FUNC_get_stack ||
7647 func_id == BPF_FUNC_get_task_stack) &&
7648 !env->prog->has_callchain_buf) {
7649 const char *err_str;
7651 #ifdef CONFIG_PERF_EVENTS
7652 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7653 err_str = "cannot get callchain buffer for func %s#%d\n";
7656 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7659 verbose(env, err_str, func_id_name(func_id), func_id);
7663 env->prog->has_callchain_buf = true;
7666 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7667 env->prog->call_get_stack = true;
7669 if (func_id == BPF_FUNC_get_func_ip) {
7670 if (check_get_func_ip(env))
7672 env->prog->call_get_func_ip = true;
7676 clear_all_pkt_pointers(env);
7680 /* mark_btf_func_reg_size() is used when the reg size is determined by
7681 * the BTF func_proto's return value size and argument.
7683 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7686 struct bpf_reg_state *reg = &cur_regs(env)[regno];
7688 if (regno == BPF_REG_0) {
7689 /* Function return value */
7690 reg->live |= REG_LIVE_WRITTEN;
7691 reg->subreg_def = reg_size == sizeof(u64) ?
7692 DEF_NOT_SUBREG : env->insn_idx + 1;
7694 /* Function argument */
7695 if (reg_size == sizeof(u64)) {
7696 mark_insn_zext(env, reg);
7697 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7699 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7704 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7707 const struct btf_type *t, *func, *func_proto, *ptr_type;
7708 struct bpf_reg_state *regs = cur_regs(env);
7709 struct bpf_kfunc_arg_meta meta = { 0 };
7710 const char *func_name, *ptr_type_name;
7711 u32 i, nargs, func_id, ptr_type_id;
7712 int err, insn_idx = *insn_idx_p;
7713 const struct btf_param *args;
7714 struct btf *desc_btf;
7718 /* skip for now, but return error when we find this in fixup_kfunc_call */
7722 desc_btf = find_kfunc_desc_btf(env, insn->off);
7723 if (IS_ERR(desc_btf))
7724 return PTR_ERR(desc_btf);
7726 func_id = insn->imm;
7727 func = btf_type_by_id(desc_btf, func_id);
7728 func_name = btf_name_by_offset(desc_btf, func->name_off);
7729 func_proto = btf_type_by_id(desc_btf, func->type);
7731 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7733 verbose(env, "calling kernel function %s is not allowed\n",
7737 if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7738 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7742 acq = *kfunc_flags & KF_ACQUIRE;
7744 meta.flags = *kfunc_flags;
7746 /* Check the arguments */
7747 err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7750 /* In case of release function, we get register number of refcounted
7751 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7754 err = release_reference(env, regs[err].ref_obj_id);
7756 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7757 func_name, func_id);
7762 for (i = 0; i < CALLER_SAVED_REGS; i++)
7763 mark_reg_not_init(env, regs, caller_saved[i]);
7765 /* Check return type */
7766 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7768 if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7769 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7773 if (btf_type_is_scalar(t)) {
7774 mark_reg_unknown(env, regs, BPF_REG_0);
7775 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7776 } else if (btf_type_is_ptr(t)) {
7777 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7779 if (!btf_type_is_struct(ptr_type)) {
7780 if (!meta.r0_size) {
7781 ptr_type_name = btf_name_by_offset(desc_btf,
7782 ptr_type->name_off);
7784 "kernel function %s returns pointer type %s %s is not supported\n",
7786 btf_type_str(ptr_type),
7791 mark_reg_known_zero(env, regs, BPF_REG_0);
7792 regs[BPF_REG_0].type = PTR_TO_MEM;
7793 regs[BPF_REG_0].mem_size = meta.r0_size;
7796 regs[BPF_REG_0].type |= MEM_RDONLY;
7798 /* Ensures we don't access the memory after a release_reference() */
7799 if (meta.ref_obj_id)
7800 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7802 mark_reg_known_zero(env, regs, BPF_REG_0);
7803 regs[BPF_REG_0].btf = desc_btf;
7804 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7805 regs[BPF_REG_0].btf_id = ptr_type_id;
7807 if (*kfunc_flags & KF_RET_NULL) {
7808 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7809 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7810 regs[BPF_REG_0].id = ++env->id_gen;
7812 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7814 int id = acquire_reference_state(env, insn_idx);
7818 regs[BPF_REG_0].id = id;
7819 regs[BPF_REG_0].ref_obj_id = id;
7821 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7823 nargs = btf_type_vlen(func_proto);
7824 args = (const struct btf_param *)(func_proto + 1);
7825 for (i = 0; i < nargs; i++) {
7828 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7829 if (btf_type_is_ptr(t))
7830 mark_btf_func_reg_size(env, regno, sizeof(void *));
7832 /* scalar. ensured by btf_check_kfunc_arg_match() */
7833 mark_btf_func_reg_size(env, regno, t->size);
7839 static bool signed_add_overflows(s64 a, s64 b)
7841 /* Do the add in u64, where overflow is well-defined */
7842 s64 res = (s64)((u64)a + (u64)b);
7849 static bool signed_add32_overflows(s32 a, s32 b)
7851 /* Do the add in u32, where overflow is well-defined */
7852 s32 res = (s32)((u32)a + (u32)b);
7859 static bool signed_sub_overflows(s64 a, s64 b)
7861 /* Do the sub in u64, where overflow is well-defined */
7862 s64 res = (s64)((u64)a - (u64)b);
7869 static bool signed_sub32_overflows(s32 a, s32 b)
7871 /* Do the sub in u32, where overflow is well-defined */
7872 s32 res = (s32)((u32)a - (u32)b);
7879 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7880 const struct bpf_reg_state *reg,
7881 enum bpf_reg_type type)
7883 bool known = tnum_is_const(reg->var_off);
7884 s64 val = reg->var_off.value;
7885 s64 smin = reg->smin_value;
7887 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7888 verbose(env, "math between %s pointer and %lld is not allowed\n",
7889 reg_type_str(env, type), val);
7893 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7894 verbose(env, "%s pointer offset %d is not allowed\n",
7895 reg_type_str(env, type), reg->off);
7899 if (smin == S64_MIN) {
7900 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7901 reg_type_str(env, type));
7905 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7906 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7907 smin, reg_type_str(env, type));
7922 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7923 u32 *alu_limit, bool mask_to_left)
7925 u32 max = 0, ptr_limit = 0;
7927 switch (ptr_reg->type) {
7929 /* Offset 0 is out-of-bounds, but acceptable start for the
7930 * left direction, see BPF_REG_FP. Also, unknown scalar
7931 * offset where we would need to deal with min/max bounds is
7932 * currently prohibited for unprivileged.
7934 max = MAX_BPF_STACK + mask_to_left;
7935 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7937 case PTR_TO_MAP_VALUE:
7938 max = ptr_reg->map_ptr->value_size;
7939 ptr_limit = (mask_to_left ?
7940 ptr_reg->smin_value :
7941 ptr_reg->umax_value) + ptr_reg->off;
7947 if (ptr_limit >= max)
7948 return REASON_LIMIT;
7949 *alu_limit = ptr_limit;
7953 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7954 const struct bpf_insn *insn)
7956 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7959 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7960 u32 alu_state, u32 alu_limit)
7962 /* If we arrived here from different branches with different
7963 * state or limits to sanitize, then this won't work.
7965 if (aux->alu_state &&
7966 (aux->alu_state != alu_state ||
7967 aux->alu_limit != alu_limit))
7968 return REASON_PATHS;
7970 /* Corresponding fixup done in do_misc_fixups(). */
7971 aux->alu_state = alu_state;
7972 aux->alu_limit = alu_limit;
7976 static int sanitize_val_alu(struct bpf_verifier_env *env,
7977 struct bpf_insn *insn)
7979 struct bpf_insn_aux_data *aux = cur_aux(env);
7981 if (can_skip_alu_sanitation(env, insn))
7984 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7987 static bool sanitize_needed(u8 opcode)
7989 return opcode == BPF_ADD || opcode == BPF_SUB;
7992 struct bpf_sanitize_info {
7993 struct bpf_insn_aux_data aux;
7997 static struct bpf_verifier_state *
7998 sanitize_speculative_path(struct bpf_verifier_env *env,
7999 const struct bpf_insn *insn,
8000 u32 next_idx, u32 curr_idx)
8002 struct bpf_verifier_state *branch;
8003 struct bpf_reg_state *regs;
8005 branch = push_stack(env, next_idx, curr_idx, true);
8006 if (branch && insn) {
8007 regs = branch->frame[branch->curframe]->regs;
8008 if (BPF_SRC(insn->code) == BPF_K) {
8009 mark_reg_unknown(env, regs, insn->dst_reg);
8010 } else if (BPF_SRC(insn->code) == BPF_X) {
8011 mark_reg_unknown(env, regs, insn->dst_reg);
8012 mark_reg_unknown(env, regs, insn->src_reg);
8018 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
8019 struct bpf_insn *insn,
8020 const struct bpf_reg_state *ptr_reg,
8021 const struct bpf_reg_state *off_reg,
8022 struct bpf_reg_state *dst_reg,
8023 struct bpf_sanitize_info *info,
8024 const bool commit_window)
8026 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
8027 struct bpf_verifier_state *vstate = env->cur_state;
8028 bool off_is_imm = tnum_is_const(off_reg->var_off);
8029 bool off_is_neg = off_reg->smin_value < 0;
8030 bool ptr_is_dst_reg = ptr_reg == dst_reg;
8031 u8 opcode = BPF_OP(insn->code);
8032 u32 alu_state, alu_limit;
8033 struct bpf_reg_state tmp;
8037 if (can_skip_alu_sanitation(env, insn))
8040 /* We already marked aux for masking from non-speculative
8041 * paths, thus we got here in the first place. We only care
8042 * to explore bad access from here.
8044 if (vstate->speculative)
8047 if (!commit_window) {
8048 if (!tnum_is_const(off_reg->var_off) &&
8049 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8050 return REASON_BOUNDS;
8052 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
8053 (opcode == BPF_SUB && !off_is_neg);
8056 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8060 if (commit_window) {
8061 /* In commit phase we narrow the masking window based on
8062 * the observed pointer move after the simulated operation.
8064 alu_state = info->aux.alu_state;
8065 alu_limit = abs(info->aux.alu_limit - alu_limit);
8067 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8068 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8069 alu_state |= ptr_is_dst_reg ?
8070 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8072 /* Limit pruning on unknown scalars to enable deep search for
8073 * potential masking differences from other program paths.
8076 env->explore_alu_limits = true;
8079 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8083 /* If we're in commit phase, we're done here given we already
8084 * pushed the truncated dst_reg into the speculative verification
8087 * Also, when register is a known constant, we rewrite register-based
8088 * operation to immediate-based, and thus do not need masking (and as
8089 * a consequence, do not need to simulate the zero-truncation either).
8091 if (commit_window || off_is_imm)
8094 /* Simulate and find potential out-of-bounds access under
8095 * speculative execution from truncation as a result of
8096 * masking when off was not within expected range. If off
8097 * sits in dst, then we temporarily need to move ptr there
8098 * to simulate dst (== 0) +/-= ptr. Needed, for example,
8099 * for cases where we use K-based arithmetic in one direction
8100 * and truncated reg-based in the other in order to explore
8103 if (!ptr_is_dst_reg) {
8105 copy_register_state(dst_reg, ptr_reg);
8107 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8109 if (!ptr_is_dst_reg && ret)
8111 return !ret ? REASON_STACK : 0;
8114 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8116 struct bpf_verifier_state *vstate = env->cur_state;
8118 /* If we simulate paths under speculation, we don't update the
8119 * insn as 'seen' such that when we verify unreachable paths in
8120 * the non-speculative domain, sanitize_dead_code() can still
8121 * rewrite/sanitize them.
8123 if (!vstate->speculative)
8124 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8127 static int sanitize_err(struct bpf_verifier_env *env,
8128 const struct bpf_insn *insn, int reason,
8129 const struct bpf_reg_state *off_reg,
8130 const struct bpf_reg_state *dst_reg)
8132 static const char *err = "pointer arithmetic with it prohibited for !root";
8133 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8134 u32 dst = insn->dst_reg, src = insn->src_reg;
8138 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8139 off_reg == dst_reg ? dst : src, err);
8142 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8143 off_reg == dst_reg ? src : dst, err);
8146 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8150 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8154 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8158 verbose(env, "verifier internal error: unknown reason (%d)\n",
8166 /* check that stack access falls within stack limits and that 'reg' doesn't
8167 * have a variable offset.
8169 * Variable offset is prohibited for unprivileged mode for simplicity since it
8170 * requires corresponding support in Spectre masking for stack ALU. See also
8171 * retrieve_ptr_limit().
8174 * 'off' includes 'reg->off'.
8176 static int check_stack_access_for_ptr_arithmetic(
8177 struct bpf_verifier_env *env,
8179 const struct bpf_reg_state *reg,
8182 if (!tnum_is_const(reg->var_off)) {
8185 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8186 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8187 regno, tn_buf, off);
8191 if (off >= 0 || off < -MAX_BPF_STACK) {
8192 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8193 "prohibited for !root; off=%d\n", regno, off);
8200 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8201 const struct bpf_insn *insn,
8202 const struct bpf_reg_state *dst_reg)
8204 u32 dst = insn->dst_reg;
8206 /* For unprivileged we require that resulting offset must be in bounds
8207 * in order to be able to sanitize access later on.
8209 if (env->bypass_spec_v1)
8212 switch (dst_reg->type) {
8214 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8215 dst_reg->off + dst_reg->var_off.value))
8218 case PTR_TO_MAP_VALUE:
8219 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8220 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8221 "prohibited for !root\n", dst);
8232 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8233 * Caller should also handle BPF_MOV case separately.
8234 * If we return -EACCES, caller may want to try again treating pointer as a
8235 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
8237 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8238 struct bpf_insn *insn,
8239 const struct bpf_reg_state *ptr_reg,
8240 const struct bpf_reg_state *off_reg)
8242 struct bpf_verifier_state *vstate = env->cur_state;
8243 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8244 struct bpf_reg_state *regs = state->regs, *dst_reg;
8245 bool known = tnum_is_const(off_reg->var_off);
8246 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8247 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8248 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8249 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8250 struct bpf_sanitize_info info = {};
8251 u8 opcode = BPF_OP(insn->code);
8252 u32 dst = insn->dst_reg;
8255 dst_reg = ®s[dst];
8257 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8258 smin_val > smax_val || umin_val > umax_val) {
8259 /* Taint dst register if offset had invalid bounds derived from
8260 * e.g. dead branches.
8262 __mark_reg_unknown(env, dst_reg);
8266 if (BPF_CLASS(insn->code) != BPF_ALU64) {
8267 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8268 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8269 __mark_reg_unknown(env, dst_reg);
8274 "R%d 32-bit pointer arithmetic prohibited\n",
8279 if (ptr_reg->type & PTR_MAYBE_NULL) {
8280 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8281 dst, reg_type_str(env, ptr_reg->type));
8285 switch (base_type(ptr_reg->type)) {
8286 case CONST_PTR_TO_MAP:
8287 /* smin_val represents the known value */
8288 if (known && smin_val == 0 && opcode == BPF_ADD)
8291 case PTR_TO_PACKET_END:
8293 case PTR_TO_SOCK_COMMON:
8294 case PTR_TO_TCP_SOCK:
8295 case PTR_TO_XDP_SOCK:
8296 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8297 dst, reg_type_str(env, ptr_reg->type));
8303 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8304 * The id may be overwritten later if we create a new variable offset.
8306 dst_reg->type = ptr_reg->type;
8307 dst_reg->id = ptr_reg->id;
8309 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8310 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8313 /* pointer types do not carry 32-bit bounds at the moment. */
8314 __mark_reg32_unbounded(dst_reg);
8316 if (sanitize_needed(opcode)) {
8317 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8320 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8325 /* We can take a fixed offset as long as it doesn't overflow
8326 * the s32 'off' field
8328 if (known && (ptr_reg->off + smin_val ==
8329 (s64)(s32)(ptr_reg->off + smin_val))) {
8330 /* pointer += K. Accumulate it into fixed offset */
8331 dst_reg->smin_value = smin_ptr;
8332 dst_reg->smax_value = smax_ptr;
8333 dst_reg->umin_value = umin_ptr;
8334 dst_reg->umax_value = umax_ptr;
8335 dst_reg->var_off = ptr_reg->var_off;
8336 dst_reg->off = ptr_reg->off + smin_val;
8337 dst_reg->raw = ptr_reg->raw;
8340 /* A new variable offset is created. Note that off_reg->off
8341 * == 0, since it's a scalar.
8342 * dst_reg gets the pointer type and since some positive
8343 * integer value was added to the pointer, give it a new 'id'
8344 * if it's a PTR_TO_PACKET.
8345 * this creates a new 'base' pointer, off_reg (variable) gets
8346 * added into the variable offset, and we copy the fixed offset
8349 if (signed_add_overflows(smin_ptr, smin_val) ||
8350 signed_add_overflows(smax_ptr, smax_val)) {
8351 dst_reg->smin_value = S64_MIN;
8352 dst_reg->smax_value = S64_MAX;
8354 dst_reg->smin_value = smin_ptr + smin_val;
8355 dst_reg->smax_value = smax_ptr + smax_val;
8357 if (umin_ptr + umin_val < umin_ptr ||
8358 umax_ptr + umax_val < umax_ptr) {
8359 dst_reg->umin_value = 0;
8360 dst_reg->umax_value = U64_MAX;
8362 dst_reg->umin_value = umin_ptr + umin_val;
8363 dst_reg->umax_value = umax_ptr + umax_val;
8365 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8366 dst_reg->off = ptr_reg->off;
8367 dst_reg->raw = ptr_reg->raw;
8368 if (reg_is_pkt_pointer(ptr_reg)) {
8369 dst_reg->id = ++env->id_gen;
8370 /* something was added to pkt_ptr, set range to zero */
8371 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8375 if (dst_reg == off_reg) {
8376 /* scalar -= pointer. Creates an unknown scalar */
8377 verbose(env, "R%d tried to subtract pointer from scalar\n",
8381 /* We don't allow subtraction from FP, because (according to
8382 * test_verifier.c test "invalid fp arithmetic", JITs might not
8383 * be able to deal with it.
8385 if (ptr_reg->type == PTR_TO_STACK) {
8386 verbose(env, "R%d subtraction from stack pointer prohibited\n",
8390 if (known && (ptr_reg->off - smin_val ==
8391 (s64)(s32)(ptr_reg->off - smin_val))) {
8392 /* pointer -= K. Subtract it from fixed offset */
8393 dst_reg->smin_value = smin_ptr;
8394 dst_reg->smax_value = smax_ptr;
8395 dst_reg->umin_value = umin_ptr;
8396 dst_reg->umax_value = umax_ptr;
8397 dst_reg->var_off = ptr_reg->var_off;
8398 dst_reg->id = ptr_reg->id;
8399 dst_reg->off = ptr_reg->off - smin_val;
8400 dst_reg->raw = ptr_reg->raw;
8403 /* A new variable offset is created. If the subtrahend is known
8404 * nonnegative, then any reg->range we had before is still good.
8406 if (signed_sub_overflows(smin_ptr, smax_val) ||
8407 signed_sub_overflows(smax_ptr, smin_val)) {
8408 /* Overflow possible, we know nothing */
8409 dst_reg->smin_value = S64_MIN;
8410 dst_reg->smax_value = S64_MAX;
8412 dst_reg->smin_value = smin_ptr - smax_val;
8413 dst_reg->smax_value = smax_ptr - smin_val;
8415 if (umin_ptr < umax_val) {
8416 /* Overflow possible, we know nothing */
8417 dst_reg->umin_value = 0;
8418 dst_reg->umax_value = U64_MAX;
8420 /* Cannot overflow (as long as bounds are consistent) */
8421 dst_reg->umin_value = umin_ptr - umax_val;
8422 dst_reg->umax_value = umax_ptr - umin_val;
8424 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8425 dst_reg->off = ptr_reg->off;
8426 dst_reg->raw = ptr_reg->raw;
8427 if (reg_is_pkt_pointer(ptr_reg)) {
8428 dst_reg->id = ++env->id_gen;
8429 /* something was added to pkt_ptr, set range to zero */
8431 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8437 /* bitwise ops on pointers are troublesome, prohibit. */
8438 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8439 dst, bpf_alu_string[opcode >> 4]);
8442 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8443 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8444 dst, bpf_alu_string[opcode >> 4]);
8448 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8450 reg_bounds_sync(dst_reg);
8451 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8453 if (sanitize_needed(opcode)) {
8454 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8457 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8463 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8464 struct bpf_reg_state *src_reg)
8466 s32 smin_val = src_reg->s32_min_value;
8467 s32 smax_val = src_reg->s32_max_value;
8468 u32 umin_val = src_reg->u32_min_value;
8469 u32 umax_val = src_reg->u32_max_value;
8471 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8472 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8473 dst_reg->s32_min_value = S32_MIN;
8474 dst_reg->s32_max_value = S32_MAX;
8476 dst_reg->s32_min_value += smin_val;
8477 dst_reg->s32_max_value += smax_val;
8479 if (dst_reg->u32_min_value + umin_val < umin_val ||
8480 dst_reg->u32_max_value + umax_val < umax_val) {
8481 dst_reg->u32_min_value = 0;
8482 dst_reg->u32_max_value = U32_MAX;
8484 dst_reg->u32_min_value += umin_val;
8485 dst_reg->u32_max_value += umax_val;
8489 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8490 struct bpf_reg_state *src_reg)
8492 s64 smin_val = src_reg->smin_value;
8493 s64 smax_val = src_reg->smax_value;
8494 u64 umin_val = src_reg->umin_value;
8495 u64 umax_val = src_reg->umax_value;
8497 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8498 signed_add_overflows(dst_reg->smax_value, smax_val)) {
8499 dst_reg->smin_value = S64_MIN;
8500 dst_reg->smax_value = S64_MAX;
8502 dst_reg->smin_value += smin_val;
8503 dst_reg->smax_value += smax_val;
8505 if (dst_reg->umin_value + umin_val < umin_val ||
8506 dst_reg->umax_value + umax_val < umax_val) {
8507 dst_reg->umin_value = 0;
8508 dst_reg->umax_value = U64_MAX;
8510 dst_reg->umin_value += umin_val;
8511 dst_reg->umax_value += umax_val;
8515 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8516 struct bpf_reg_state *src_reg)
8518 s32 smin_val = src_reg->s32_min_value;
8519 s32 smax_val = src_reg->s32_max_value;
8520 u32 umin_val = src_reg->u32_min_value;
8521 u32 umax_val = src_reg->u32_max_value;
8523 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8524 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8525 /* Overflow possible, we know nothing */
8526 dst_reg->s32_min_value = S32_MIN;
8527 dst_reg->s32_max_value = S32_MAX;
8529 dst_reg->s32_min_value -= smax_val;
8530 dst_reg->s32_max_value -= smin_val;
8532 if (dst_reg->u32_min_value < umax_val) {
8533 /* Overflow possible, we know nothing */
8534 dst_reg->u32_min_value = 0;
8535 dst_reg->u32_max_value = U32_MAX;
8537 /* Cannot overflow (as long as bounds are consistent) */
8538 dst_reg->u32_min_value -= umax_val;
8539 dst_reg->u32_max_value -= umin_val;
8543 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8544 struct bpf_reg_state *src_reg)
8546 s64 smin_val = src_reg->smin_value;
8547 s64 smax_val = src_reg->smax_value;
8548 u64 umin_val = src_reg->umin_value;
8549 u64 umax_val = src_reg->umax_value;
8551 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8552 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8553 /* Overflow possible, we know nothing */
8554 dst_reg->smin_value = S64_MIN;
8555 dst_reg->smax_value = S64_MAX;
8557 dst_reg->smin_value -= smax_val;
8558 dst_reg->smax_value -= smin_val;
8560 if (dst_reg->umin_value < umax_val) {
8561 /* Overflow possible, we know nothing */
8562 dst_reg->umin_value = 0;
8563 dst_reg->umax_value = U64_MAX;
8565 /* Cannot overflow (as long as bounds are consistent) */
8566 dst_reg->umin_value -= umax_val;
8567 dst_reg->umax_value -= umin_val;
8571 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8572 struct bpf_reg_state *src_reg)
8574 s32 smin_val = src_reg->s32_min_value;
8575 u32 umin_val = src_reg->u32_min_value;
8576 u32 umax_val = src_reg->u32_max_value;
8578 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8579 /* Ain't nobody got time to multiply that sign */
8580 __mark_reg32_unbounded(dst_reg);
8583 /* Both values are positive, so we can work with unsigned and
8584 * copy the result to signed (unless it exceeds S32_MAX).
8586 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8587 /* Potential overflow, we know nothing */
8588 __mark_reg32_unbounded(dst_reg);
8591 dst_reg->u32_min_value *= umin_val;
8592 dst_reg->u32_max_value *= umax_val;
8593 if (dst_reg->u32_max_value > S32_MAX) {
8594 /* Overflow possible, we know nothing */
8595 dst_reg->s32_min_value = S32_MIN;
8596 dst_reg->s32_max_value = S32_MAX;
8598 dst_reg->s32_min_value = dst_reg->u32_min_value;
8599 dst_reg->s32_max_value = dst_reg->u32_max_value;
8603 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8604 struct bpf_reg_state *src_reg)
8606 s64 smin_val = src_reg->smin_value;
8607 u64 umin_val = src_reg->umin_value;
8608 u64 umax_val = src_reg->umax_value;
8610 if (smin_val < 0 || dst_reg->smin_value < 0) {
8611 /* Ain't nobody got time to multiply that sign */
8612 __mark_reg64_unbounded(dst_reg);
8615 /* Both values are positive, so we can work with unsigned and
8616 * copy the result to signed (unless it exceeds S64_MAX).
8618 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8619 /* Potential overflow, we know nothing */
8620 __mark_reg64_unbounded(dst_reg);
8623 dst_reg->umin_value *= umin_val;
8624 dst_reg->umax_value *= umax_val;
8625 if (dst_reg->umax_value > S64_MAX) {
8626 /* Overflow possible, we know nothing */
8627 dst_reg->smin_value = S64_MIN;
8628 dst_reg->smax_value = S64_MAX;
8630 dst_reg->smin_value = dst_reg->umin_value;
8631 dst_reg->smax_value = dst_reg->umax_value;
8635 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8636 struct bpf_reg_state *src_reg)
8638 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8639 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8640 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8641 s32 smin_val = src_reg->s32_min_value;
8642 u32 umax_val = src_reg->u32_max_value;
8644 if (src_known && dst_known) {
8645 __mark_reg32_known(dst_reg, var32_off.value);
8649 /* We get our minimum from the var_off, since that's inherently
8650 * bitwise. Our maximum is the minimum of the operands' maxima.
8652 dst_reg->u32_min_value = var32_off.value;
8653 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8654 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8655 /* Lose signed bounds when ANDing negative numbers,
8656 * ain't nobody got time for that.
8658 dst_reg->s32_min_value = S32_MIN;
8659 dst_reg->s32_max_value = S32_MAX;
8661 /* ANDing two positives gives a positive, so safe to
8662 * cast result into s64.
8664 dst_reg->s32_min_value = dst_reg->u32_min_value;
8665 dst_reg->s32_max_value = dst_reg->u32_max_value;
8669 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8670 struct bpf_reg_state *src_reg)
8672 bool src_known = tnum_is_const(src_reg->var_off);
8673 bool dst_known = tnum_is_const(dst_reg->var_off);
8674 s64 smin_val = src_reg->smin_value;
8675 u64 umax_val = src_reg->umax_value;
8677 if (src_known && dst_known) {
8678 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8682 /* We get our minimum from the var_off, since that's inherently
8683 * bitwise. Our maximum is the minimum of the operands' maxima.
8685 dst_reg->umin_value = dst_reg->var_off.value;
8686 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8687 if (dst_reg->smin_value < 0 || smin_val < 0) {
8688 /* Lose signed bounds when ANDing negative numbers,
8689 * ain't nobody got time for that.
8691 dst_reg->smin_value = S64_MIN;
8692 dst_reg->smax_value = S64_MAX;
8694 /* ANDing two positives gives a positive, so safe to
8695 * cast result into s64.
8697 dst_reg->smin_value = dst_reg->umin_value;
8698 dst_reg->smax_value = dst_reg->umax_value;
8700 /* We may learn something more from the var_off */
8701 __update_reg_bounds(dst_reg);
8704 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8705 struct bpf_reg_state *src_reg)
8707 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8708 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8709 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8710 s32 smin_val = src_reg->s32_min_value;
8711 u32 umin_val = src_reg->u32_min_value;
8713 if (src_known && dst_known) {
8714 __mark_reg32_known(dst_reg, var32_off.value);
8718 /* We get our maximum from the var_off, and our minimum is the
8719 * maximum of the operands' minima
8721 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8722 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8723 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8724 /* Lose signed bounds when ORing negative numbers,
8725 * ain't nobody got time for that.
8727 dst_reg->s32_min_value = S32_MIN;
8728 dst_reg->s32_max_value = S32_MAX;
8730 /* ORing two positives gives a positive, so safe to
8731 * cast result into s64.
8733 dst_reg->s32_min_value = dst_reg->u32_min_value;
8734 dst_reg->s32_max_value = dst_reg->u32_max_value;
8738 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8739 struct bpf_reg_state *src_reg)
8741 bool src_known = tnum_is_const(src_reg->var_off);
8742 bool dst_known = tnum_is_const(dst_reg->var_off);
8743 s64 smin_val = src_reg->smin_value;
8744 u64 umin_val = src_reg->umin_value;
8746 if (src_known && dst_known) {
8747 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8751 /* We get our maximum from the var_off, and our minimum is the
8752 * maximum of the operands' minima
8754 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8755 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8756 if (dst_reg->smin_value < 0 || smin_val < 0) {
8757 /* Lose signed bounds when ORing negative numbers,
8758 * ain't nobody got time for that.
8760 dst_reg->smin_value = S64_MIN;
8761 dst_reg->smax_value = S64_MAX;
8763 /* ORing two positives gives a positive, so safe to
8764 * cast result into s64.
8766 dst_reg->smin_value = dst_reg->umin_value;
8767 dst_reg->smax_value = dst_reg->umax_value;
8769 /* We may learn something more from the var_off */
8770 __update_reg_bounds(dst_reg);
8773 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8774 struct bpf_reg_state *src_reg)
8776 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8777 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8778 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8779 s32 smin_val = src_reg->s32_min_value;
8781 if (src_known && dst_known) {
8782 __mark_reg32_known(dst_reg, var32_off.value);
8786 /* We get both minimum and maximum from the var32_off. */
8787 dst_reg->u32_min_value = var32_off.value;
8788 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8790 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8791 /* XORing two positive sign numbers gives a positive,
8792 * so safe to cast u32 result into s32.
8794 dst_reg->s32_min_value = dst_reg->u32_min_value;
8795 dst_reg->s32_max_value = dst_reg->u32_max_value;
8797 dst_reg->s32_min_value = S32_MIN;
8798 dst_reg->s32_max_value = S32_MAX;
8802 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8803 struct bpf_reg_state *src_reg)
8805 bool src_known = tnum_is_const(src_reg->var_off);
8806 bool dst_known = tnum_is_const(dst_reg->var_off);
8807 s64 smin_val = src_reg->smin_value;
8809 if (src_known && dst_known) {
8810 /* dst_reg->var_off.value has been updated earlier */
8811 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8815 /* We get both minimum and maximum from the var_off. */
8816 dst_reg->umin_value = dst_reg->var_off.value;
8817 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8819 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8820 /* XORing two positive sign numbers gives a positive,
8821 * so safe to cast u64 result into s64.
8823 dst_reg->smin_value = dst_reg->umin_value;
8824 dst_reg->smax_value = dst_reg->umax_value;
8826 dst_reg->smin_value = S64_MIN;
8827 dst_reg->smax_value = S64_MAX;
8830 __update_reg_bounds(dst_reg);
8833 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8834 u64 umin_val, u64 umax_val)
8836 /* We lose all sign bit information (except what we can pick
8839 dst_reg->s32_min_value = S32_MIN;
8840 dst_reg->s32_max_value = S32_MAX;
8841 /* If we might shift our top bit out, then we know nothing */
8842 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8843 dst_reg->u32_min_value = 0;
8844 dst_reg->u32_max_value = U32_MAX;
8846 dst_reg->u32_min_value <<= umin_val;
8847 dst_reg->u32_max_value <<= umax_val;
8851 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8852 struct bpf_reg_state *src_reg)
8854 u32 umax_val = src_reg->u32_max_value;
8855 u32 umin_val = src_reg->u32_min_value;
8856 /* u32 alu operation will zext upper bits */
8857 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8859 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8860 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8861 /* Not required but being careful mark reg64 bounds as unknown so
8862 * that we are forced to pick them up from tnum and zext later and
8863 * if some path skips this step we are still safe.
8865 __mark_reg64_unbounded(dst_reg);
8866 __update_reg32_bounds(dst_reg);
8869 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8870 u64 umin_val, u64 umax_val)
8872 /* Special case <<32 because it is a common compiler pattern to sign
8873 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8874 * positive we know this shift will also be positive so we can track
8875 * bounds correctly. Otherwise we lose all sign bit information except
8876 * what we can pick up from var_off. Perhaps we can generalize this
8877 * later to shifts of any length.
8879 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8880 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8882 dst_reg->smax_value = S64_MAX;
8884 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8885 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8887 dst_reg->smin_value = S64_MIN;
8889 /* If we might shift our top bit out, then we know nothing */
8890 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8891 dst_reg->umin_value = 0;
8892 dst_reg->umax_value = U64_MAX;
8894 dst_reg->umin_value <<= umin_val;
8895 dst_reg->umax_value <<= umax_val;
8899 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8900 struct bpf_reg_state *src_reg)
8902 u64 umax_val = src_reg->umax_value;
8903 u64 umin_val = src_reg->umin_value;
8905 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8906 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8907 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8909 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8910 /* We may learn something more from the var_off */
8911 __update_reg_bounds(dst_reg);
8914 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8915 struct bpf_reg_state *src_reg)
8917 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8918 u32 umax_val = src_reg->u32_max_value;
8919 u32 umin_val = src_reg->u32_min_value;
8921 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8922 * be negative, then either:
8923 * 1) src_reg might be zero, so the sign bit of the result is
8924 * unknown, so we lose our signed bounds
8925 * 2) it's known negative, thus the unsigned bounds capture the
8927 * 3) the signed bounds cross zero, so they tell us nothing
8929 * If the value in dst_reg is known nonnegative, then again the
8930 * unsigned bounds capture the signed bounds.
8931 * Thus, in all cases it suffices to blow away our signed bounds
8932 * and rely on inferring new ones from the unsigned bounds and
8933 * var_off of the result.
8935 dst_reg->s32_min_value = S32_MIN;
8936 dst_reg->s32_max_value = S32_MAX;
8938 dst_reg->var_off = tnum_rshift(subreg, umin_val);
8939 dst_reg->u32_min_value >>= umax_val;
8940 dst_reg->u32_max_value >>= umin_val;
8942 __mark_reg64_unbounded(dst_reg);
8943 __update_reg32_bounds(dst_reg);
8946 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8947 struct bpf_reg_state *src_reg)
8949 u64 umax_val = src_reg->umax_value;
8950 u64 umin_val = src_reg->umin_value;
8952 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8953 * be negative, then either:
8954 * 1) src_reg might be zero, so the sign bit of the result is
8955 * unknown, so we lose our signed bounds
8956 * 2) it's known negative, thus the unsigned bounds capture the
8958 * 3) the signed bounds cross zero, so they tell us nothing
8960 * If the value in dst_reg is known nonnegative, then again the
8961 * unsigned bounds capture the signed bounds.
8962 * Thus, in all cases it suffices to blow away our signed bounds
8963 * and rely on inferring new ones from the unsigned bounds and
8964 * var_off of the result.
8966 dst_reg->smin_value = S64_MIN;
8967 dst_reg->smax_value = S64_MAX;
8968 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8969 dst_reg->umin_value >>= umax_val;
8970 dst_reg->umax_value >>= umin_val;
8972 /* Its not easy to operate on alu32 bounds here because it depends
8973 * on bits being shifted in. Take easy way out and mark unbounded
8974 * so we can recalculate later from tnum.
8976 __mark_reg32_unbounded(dst_reg);
8977 __update_reg_bounds(dst_reg);
8980 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8981 struct bpf_reg_state *src_reg)
8983 u64 umin_val = src_reg->u32_min_value;
8985 /* Upon reaching here, src_known is true and
8986 * umax_val is equal to umin_val.
8988 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8989 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8991 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8993 /* blow away the dst_reg umin_value/umax_value and rely on
8994 * dst_reg var_off to refine the result.
8996 dst_reg->u32_min_value = 0;
8997 dst_reg->u32_max_value = U32_MAX;
8999 __mark_reg64_unbounded(dst_reg);
9000 __update_reg32_bounds(dst_reg);
9003 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
9004 struct bpf_reg_state *src_reg)
9006 u64 umin_val = src_reg->umin_value;
9008 /* Upon reaching here, src_known is true and umax_val is equal
9011 dst_reg->smin_value >>= umin_val;
9012 dst_reg->smax_value >>= umin_val;
9014 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
9016 /* blow away the dst_reg umin_value/umax_value and rely on
9017 * dst_reg var_off to refine the result.
9019 dst_reg->umin_value = 0;
9020 dst_reg->umax_value = U64_MAX;
9022 /* Its not easy to operate on alu32 bounds here because it depends
9023 * on bits being shifted in from upper 32-bits. Take easy way out
9024 * and mark unbounded so we can recalculate later from tnum.
9026 __mark_reg32_unbounded(dst_reg);
9027 __update_reg_bounds(dst_reg);
9030 /* WARNING: This function does calculations on 64-bit values, but the actual
9031 * execution may occur on 32-bit values. Therefore, things like bitshifts
9032 * need extra checks in the 32-bit case.
9034 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9035 struct bpf_insn *insn,
9036 struct bpf_reg_state *dst_reg,
9037 struct bpf_reg_state src_reg)
9039 struct bpf_reg_state *regs = cur_regs(env);
9040 u8 opcode = BPF_OP(insn->code);
9042 s64 smin_val, smax_val;
9043 u64 umin_val, umax_val;
9044 s32 s32_min_val, s32_max_val;
9045 u32 u32_min_val, u32_max_val;
9046 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9047 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9050 smin_val = src_reg.smin_value;
9051 smax_val = src_reg.smax_value;
9052 umin_val = src_reg.umin_value;
9053 umax_val = src_reg.umax_value;
9055 s32_min_val = src_reg.s32_min_value;
9056 s32_max_val = src_reg.s32_max_value;
9057 u32_min_val = src_reg.u32_min_value;
9058 u32_max_val = src_reg.u32_max_value;
9061 src_known = tnum_subreg_is_const(src_reg.var_off);
9063 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9064 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9065 /* Taint dst register if offset had invalid bounds
9066 * derived from e.g. dead branches.
9068 __mark_reg_unknown(env, dst_reg);
9072 src_known = tnum_is_const(src_reg.var_off);
9074 (smin_val != smax_val || umin_val != umax_val)) ||
9075 smin_val > smax_val || umin_val > umax_val) {
9076 /* Taint dst register if offset had invalid bounds
9077 * derived from e.g. dead branches.
9079 __mark_reg_unknown(env, dst_reg);
9085 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9086 __mark_reg_unknown(env, dst_reg);
9090 if (sanitize_needed(opcode)) {
9091 ret = sanitize_val_alu(env, insn);
9093 return sanitize_err(env, insn, ret, NULL, NULL);
9096 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9097 * There are two classes of instructions: The first class we track both
9098 * alu32 and alu64 sign/unsigned bounds independently this provides the
9099 * greatest amount of precision when alu operations are mixed with jmp32
9100 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9101 * and BPF_OR. This is possible because these ops have fairly easy to
9102 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9103 * See alu32 verifier tests for examples. The second class of
9104 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9105 * with regards to tracking sign/unsigned bounds because the bits may
9106 * cross subreg boundaries in the alu64 case. When this happens we mark
9107 * the reg unbounded in the subreg bound space and use the resulting
9108 * tnum to calculate an approximation of the sign/unsigned bounds.
9112 scalar32_min_max_add(dst_reg, &src_reg);
9113 scalar_min_max_add(dst_reg, &src_reg);
9114 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9117 scalar32_min_max_sub(dst_reg, &src_reg);
9118 scalar_min_max_sub(dst_reg, &src_reg);
9119 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9122 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9123 scalar32_min_max_mul(dst_reg, &src_reg);
9124 scalar_min_max_mul(dst_reg, &src_reg);
9127 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9128 scalar32_min_max_and(dst_reg, &src_reg);
9129 scalar_min_max_and(dst_reg, &src_reg);
9132 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9133 scalar32_min_max_or(dst_reg, &src_reg);
9134 scalar_min_max_or(dst_reg, &src_reg);
9137 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9138 scalar32_min_max_xor(dst_reg, &src_reg);
9139 scalar_min_max_xor(dst_reg, &src_reg);
9142 if (umax_val >= insn_bitness) {
9143 /* Shifts greater than 31 or 63 are undefined.
9144 * This includes shifts by a negative number.
9146 mark_reg_unknown(env, regs, insn->dst_reg);
9150 scalar32_min_max_lsh(dst_reg, &src_reg);
9152 scalar_min_max_lsh(dst_reg, &src_reg);
9155 if (umax_val >= insn_bitness) {
9156 /* Shifts greater than 31 or 63 are undefined.
9157 * This includes shifts by a negative number.
9159 mark_reg_unknown(env, regs, insn->dst_reg);
9163 scalar32_min_max_rsh(dst_reg, &src_reg);
9165 scalar_min_max_rsh(dst_reg, &src_reg);
9168 if (umax_val >= insn_bitness) {
9169 /* Shifts greater than 31 or 63 are undefined.
9170 * This includes shifts by a negative number.
9172 mark_reg_unknown(env, regs, insn->dst_reg);
9176 scalar32_min_max_arsh(dst_reg, &src_reg);
9178 scalar_min_max_arsh(dst_reg, &src_reg);
9181 mark_reg_unknown(env, regs, insn->dst_reg);
9185 /* ALU32 ops are zero extended into 64bit register */
9187 zext_32_to_64(dst_reg);
9188 reg_bounds_sync(dst_reg);
9192 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9195 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9196 struct bpf_insn *insn)
9198 struct bpf_verifier_state *vstate = env->cur_state;
9199 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9200 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9201 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9202 u8 opcode = BPF_OP(insn->code);
9205 dst_reg = ®s[insn->dst_reg];
9207 if (dst_reg->type != SCALAR_VALUE)
9210 /* Make sure ID is cleared otherwise dst_reg min/max could be
9211 * incorrectly propagated into other registers by find_equal_scalars()
9214 if (BPF_SRC(insn->code) == BPF_X) {
9215 src_reg = ®s[insn->src_reg];
9216 if (src_reg->type != SCALAR_VALUE) {
9217 if (dst_reg->type != SCALAR_VALUE) {
9218 /* Combining two pointers by any ALU op yields
9219 * an arbitrary scalar. Disallow all math except
9220 * pointer subtraction
9222 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9223 mark_reg_unknown(env, regs, insn->dst_reg);
9226 verbose(env, "R%d pointer %s pointer prohibited\n",
9228 bpf_alu_string[opcode >> 4]);
9231 /* scalar += pointer
9232 * This is legal, but we have to reverse our
9233 * src/dest handling in computing the range
9235 err = mark_chain_precision(env, insn->dst_reg);
9238 return adjust_ptr_min_max_vals(env, insn,
9241 } else if (ptr_reg) {
9242 /* pointer += scalar */
9243 err = mark_chain_precision(env, insn->src_reg);
9246 return adjust_ptr_min_max_vals(env, insn,
9248 } else if (dst_reg->precise) {
9249 /* if dst_reg is precise, src_reg should be precise as well */
9250 err = mark_chain_precision(env, insn->src_reg);
9255 /* Pretend the src is a reg with a known value, since we only
9256 * need to be able to read from this state.
9258 off_reg.type = SCALAR_VALUE;
9259 __mark_reg_known(&off_reg, insn->imm);
9261 if (ptr_reg) /* pointer += K */
9262 return adjust_ptr_min_max_vals(env, insn,
9266 /* Got here implies adding two SCALAR_VALUEs */
9267 if (WARN_ON_ONCE(ptr_reg)) {
9268 print_verifier_state(env, state, true);
9269 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9272 if (WARN_ON(!src_reg)) {
9273 print_verifier_state(env, state, true);
9274 verbose(env, "verifier internal error: no src_reg\n");
9277 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9280 /* check validity of 32-bit and 64-bit arithmetic operations */
9281 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9283 struct bpf_reg_state *regs = cur_regs(env);
9284 u8 opcode = BPF_OP(insn->code);
9287 if (opcode == BPF_END || opcode == BPF_NEG) {
9288 if (opcode == BPF_NEG) {
9289 if (BPF_SRC(insn->code) != BPF_K ||
9290 insn->src_reg != BPF_REG_0 ||
9291 insn->off != 0 || insn->imm != 0) {
9292 verbose(env, "BPF_NEG uses reserved fields\n");
9296 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9297 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9298 BPF_CLASS(insn->code) == BPF_ALU64) {
9299 verbose(env, "BPF_END uses reserved fields\n");
9304 /* check src operand */
9305 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9309 if (is_pointer_value(env, insn->dst_reg)) {
9310 verbose(env, "R%d pointer arithmetic prohibited\n",
9315 /* check dest operand */
9316 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9320 } else if (opcode == BPF_MOV) {
9322 if (BPF_SRC(insn->code) == BPF_X) {
9323 if (insn->imm != 0 || insn->off != 0) {
9324 verbose(env, "BPF_MOV uses reserved fields\n");
9328 /* check src operand */
9329 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9333 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9334 verbose(env, "BPF_MOV uses reserved fields\n");
9339 /* check dest operand, mark as required later */
9340 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9344 if (BPF_SRC(insn->code) == BPF_X) {
9345 struct bpf_reg_state *src_reg = regs + insn->src_reg;
9346 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9348 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9350 * copy register state to dest reg
9352 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9353 /* Assign src and dst registers the same ID
9354 * that will be used by find_equal_scalars()
9355 * to propagate min/max range.
9357 src_reg->id = ++env->id_gen;
9358 copy_register_state(dst_reg, src_reg);
9359 dst_reg->live |= REG_LIVE_WRITTEN;
9360 dst_reg->subreg_def = DEF_NOT_SUBREG;
9363 if (is_pointer_value(env, insn->src_reg)) {
9365 "R%d partial copy of pointer\n",
9368 } else if (src_reg->type == SCALAR_VALUE) {
9369 copy_register_state(dst_reg, src_reg);
9370 /* Make sure ID is cleared otherwise
9371 * dst_reg min/max could be incorrectly
9372 * propagated into src_reg by find_equal_scalars()
9375 dst_reg->live |= REG_LIVE_WRITTEN;
9376 dst_reg->subreg_def = env->insn_idx + 1;
9378 mark_reg_unknown(env, regs,
9381 zext_32_to_64(dst_reg);
9382 reg_bounds_sync(dst_reg);
9386 * remember the value we stored into this reg
9388 /* clear any state __mark_reg_known doesn't set */
9389 mark_reg_unknown(env, regs, insn->dst_reg);
9390 regs[insn->dst_reg].type = SCALAR_VALUE;
9391 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9392 __mark_reg_known(regs + insn->dst_reg,
9395 __mark_reg_known(regs + insn->dst_reg,
9400 } else if (opcode > BPF_END) {
9401 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9404 } else { /* all other ALU ops: and, sub, xor, add, ... */
9406 if (BPF_SRC(insn->code) == BPF_X) {
9407 if (insn->imm != 0 || insn->off != 0) {
9408 verbose(env, "BPF_ALU uses reserved fields\n");
9411 /* check src1 operand */
9412 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9416 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9417 verbose(env, "BPF_ALU uses reserved fields\n");
9422 /* check src2 operand */
9423 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9427 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9428 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9429 verbose(env, "div by zero\n");
9433 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9434 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9435 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9437 if (insn->imm < 0 || insn->imm >= size) {
9438 verbose(env, "invalid shift %d\n", insn->imm);
9443 /* check dest operand */
9444 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9448 return adjust_reg_min_max_vals(env, insn);
9454 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9455 struct bpf_reg_state *dst_reg,
9456 enum bpf_reg_type type,
9457 bool range_right_open)
9459 struct bpf_func_state *state;
9460 struct bpf_reg_state *reg;
9463 if (dst_reg->off < 0 ||
9464 (dst_reg->off == 0 && range_right_open))
9465 /* This doesn't give us any range */
9468 if (dst_reg->umax_value > MAX_PACKET_OFF ||
9469 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9470 /* Risk of overflow. For instance, ptr + (1<<63) may be less
9471 * than pkt_end, but that's because it's also less than pkt.
9475 new_range = dst_reg->off;
9476 if (range_right_open)
9479 /* Examples for register markings:
9481 * pkt_data in dst register:
9485 * if (r2 > pkt_end) goto <handle exception>
9490 * if (r2 < pkt_end) goto <access okay>
9491 * <handle exception>
9494 * r2 == dst_reg, pkt_end == src_reg
9495 * r2=pkt(id=n,off=8,r=0)
9496 * r3=pkt(id=n,off=0,r=0)
9498 * pkt_data in src register:
9502 * if (pkt_end >= r2) goto <access okay>
9503 * <handle exception>
9507 * if (pkt_end <= r2) goto <handle exception>
9511 * pkt_end == dst_reg, r2 == src_reg
9512 * r2=pkt(id=n,off=8,r=0)
9513 * r3=pkt(id=n,off=0,r=0)
9515 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9516 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9517 * and [r3, r3 + 8-1) respectively is safe to access depending on
9521 /* If our ids match, then we must have the same max_value. And we
9522 * don't care about the other reg's fixed offset, since if it's too big
9523 * the range won't allow anything.
9524 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9526 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9527 if (reg->type == type && reg->id == dst_reg->id)
9528 /* keep the maximum range already checked */
9529 reg->range = max(reg->range, new_range);
9533 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9535 struct tnum subreg = tnum_subreg(reg->var_off);
9536 s32 sval = (s32)val;
9540 if (tnum_is_const(subreg))
9541 return !!tnum_equals_const(subreg, val);
9544 if (tnum_is_const(subreg))
9545 return !tnum_equals_const(subreg, val);
9548 if ((~subreg.mask & subreg.value) & val)
9550 if (!((subreg.mask | subreg.value) & val))
9554 if (reg->u32_min_value > val)
9556 else if (reg->u32_max_value <= val)
9560 if (reg->s32_min_value > sval)
9562 else if (reg->s32_max_value <= sval)
9566 if (reg->u32_max_value < val)
9568 else if (reg->u32_min_value >= val)
9572 if (reg->s32_max_value < sval)
9574 else if (reg->s32_min_value >= sval)
9578 if (reg->u32_min_value >= val)
9580 else if (reg->u32_max_value < val)
9584 if (reg->s32_min_value >= sval)
9586 else if (reg->s32_max_value < sval)
9590 if (reg->u32_max_value <= val)
9592 else if (reg->u32_min_value > val)
9596 if (reg->s32_max_value <= sval)
9598 else if (reg->s32_min_value > sval)
9607 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9609 s64 sval = (s64)val;
9613 if (tnum_is_const(reg->var_off))
9614 return !!tnum_equals_const(reg->var_off, val);
9617 if (tnum_is_const(reg->var_off))
9618 return !tnum_equals_const(reg->var_off, val);
9621 if ((~reg->var_off.mask & reg->var_off.value) & val)
9623 if (!((reg->var_off.mask | reg->var_off.value) & val))
9627 if (reg->umin_value > val)
9629 else if (reg->umax_value <= val)
9633 if (reg->smin_value > sval)
9635 else if (reg->smax_value <= sval)
9639 if (reg->umax_value < val)
9641 else if (reg->umin_value >= val)
9645 if (reg->smax_value < sval)
9647 else if (reg->smin_value >= sval)
9651 if (reg->umin_value >= val)
9653 else if (reg->umax_value < val)
9657 if (reg->smin_value >= sval)
9659 else if (reg->smax_value < sval)
9663 if (reg->umax_value <= val)
9665 else if (reg->umin_value > val)
9669 if (reg->smax_value <= sval)
9671 else if (reg->smin_value > sval)
9679 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9681 * 1 - branch will be taken and "goto target" will be executed
9682 * 0 - branch will not be taken and fall-through to next insn
9683 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9686 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9689 if (__is_pointer_value(false, reg)) {
9690 if (!reg_type_not_null(reg->type))
9693 /* If pointer is valid tests against zero will fail so we can
9694 * use this to direct branch taken.
9710 return is_branch32_taken(reg, val, opcode);
9711 return is_branch64_taken(reg, val, opcode);
9714 static int flip_opcode(u32 opcode)
9716 /* How can we transform "a <op> b" into "b <op> a"? */
9717 static const u8 opcode_flip[16] = {
9718 /* these stay the same */
9719 [BPF_JEQ >> 4] = BPF_JEQ,
9720 [BPF_JNE >> 4] = BPF_JNE,
9721 [BPF_JSET >> 4] = BPF_JSET,
9722 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9723 [BPF_JGE >> 4] = BPF_JLE,
9724 [BPF_JGT >> 4] = BPF_JLT,
9725 [BPF_JLE >> 4] = BPF_JGE,
9726 [BPF_JLT >> 4] = BPF_JGT,
9727 [BPF_JSGE >> 4] = BPF_JSLE,
9728 [BPF_JSGT >> 4] = BPF_JSLT,
9729 [BPF_JSLE >> 4] = BPF_JSGE,
9730 [BPF_JSLT >> 4] = BPF_JSGT
9732 return opcode_flip[opcode >> 4];
9735 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9736 struct bpf_reg_state *src_reg,
9739 struct bpf_reg_state *pkt;
9741 if (src_reg->type == PTR_TO_PACKET_END) {
9743 } else if (dst_reg->type == PTR_TO_PACKET_END) {
9745 opcode = flip_opcode(opcode);
9750 if (pkt->range >= 0)
9755 /* pkt <= pkt_end */
9759 if (pkt->range == BEYOND_PKT_END)
9760 /* pkt has at last one extra byte beyond pkt_end */
9761 return opcode == BPF_JGT;
9767 /* pkt >= pkt_end */
9768 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9769 return opcode == BPF_JGE;
9775 /* Adjusts the register min/max values in the case that the dst_reg is the
9776 * variable register that we are working on, and src_reg is a constant or we're
9777 * simply doing a BPF_K check.
9778 * In JEQ/JNE cases we also adjust the var_off values.
9780 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9781 struct bpf_reg_state *false_reg,
9783 u8 opcode, bool is_jmp32)
9785 struct tnum false_32off = tnum_subreg(false_reg->var_off);
9786 struct tnum false_64off = false_reg->var_off;
9787 struct tnum true_32off = tnum_subreg(true_reg->var_off);
9788 struct tnum true_64off = true_reg->var_off;
9789 s64 sval = (s64)val;
9790 s32 sval32 = (s32)val32;
9792 /* If the dst_reg is a pointer, we can't learn anything about its
9793 * variable offset from the compare (unless src_reg were a pointer into
9794 * the same object, but we don't bother with that.
9795 * Since false_reg and true_reg have the same type by construction, we
9796 * only need to check one of them for pointerness.
9798 if (__is_pointer_value(false, false_reg))
9802 /* JEQ/JNE comparison doesn't change the register equivalence.
9805 * if (r1 == 42) goto label;
9807 * label: // here both r1 and r2 are known to be 42.
9809 * Hence when marking register as known preserve it's ID.
9813 __mark_reg32_known(true_reg, val32);
9814 true_32off = tnum_subreg(true_reg->var_off);
9816 ___mark_reg_known(true_reg, val);
9817 true_64off = true_reg->var_off;
9822 __mark_reg32_known(false_reg, val32);
9823 false_32off = tnum_subreg(false_reg->var_off);
9825 ___mark_reg_known(false_reg, val);
9826 false_64off = false_reg->var_off;
9831 false_32off = tnum_and(false_32off, tnum_const(~val32));
9832 if (is_power_of_2(val32))
9833 true_32off = tnum_or(true_32off,
9836 false_64off = tnum_and(false_64off, tnum_const(~val));
9837 if (is_power_of_2(val))
9838 true_64off = tnum_or(true_64off,
9846 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
9847 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9849 false_reg->u32_max_value = min(false_reg->u32_max_value,
9851 true_reg->u32_min_value = max(true_reg->u32_min_value,
9854 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
9855 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9857 false_reg->umax_value = min(false_reg->umax_value, false_umax);
9858 true_reg->umin_value = max(true_reg->umin_value, true_umin);
9866 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
9867 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9869 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9870 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9872 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
9873 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9875 false_reg->smax_value = min(false_reg->smax_value, false_smax);
9876 true_reg->smin_value = max(true_reg->smin_value, true_smin);
9884 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
9885 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9887 false_reg->u32_min_value = max(false_reg->u32_min_value,
9889 true_reg->u32_max_value = min(true_reg->u32_max_value,
9892 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
9893 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9895 false_reg->umin_value = max(false_reg->umin_value, false_umin);
9896 true_reg->umax_value = min(true_reg->umax_value, true_umax);
9904 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
9905 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9907 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9908 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9910 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
9911 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9913 false_reg->smin_value = max(false_reg->smin_value, false_smin);
9914 true_reg->smax_value = min(true_reg->smax_value, true_smax);
9923 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9924 tnum_subreg(false_32off));
9925 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9926 tnum_subreg(true_32off));
9927 __reg_combine_32_into_64(false_reg);
9928 __reg_combine_32_into_64(true_reg);
9930 false_reg->var_off = false_64off;
9931 true_reg->var_off = true_64off;
9932 __reg_combine_64_into_32(false_reg);
9933 __reg_combine_64_into_32(true_reg);
9937 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9940 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9941 struct bpf_reg_state *false_reg,
9943 u8 opcode, bool is_jmp32)
9945 opcode = flip_opcode(opcode);
9946 /* This uses zero as "not present in table"; luckily the zero opcode,
9947 * BPF_JA, can't get here.
9950 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9953 /* Regs are known to be equal, so intersect their min/max/var_off */
9954 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9955 struct bpf_reg_state *dst_reg)
9957 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9958 dst_reg->umin_value);
9959 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9960 dst_reg->umax_value);
9961 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9962 dst_reg->smin_value);
9963 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9964 dst_reg->smax_value);
9965 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9967 reg_bounds_sync(src_reg);
9968 reg_bounds_sync(dst_reg);
9971 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9972 struct bpf_reg_state *true_dst,
9973 struct bpf_reg_state *false_src,
9974 struct bpf_reg_state *false_dst,
9979 __reg_combine_min_max(true_src, true_dst);
9982 __reg_combine_min_max(false_src, false_dst);
9987 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9988 struct bpf_reg_state *reg, u32 id,
9991 if (type_may_be_null(reg->type) && reg->id == id &&
9992 !WARN_ON_ONCE(!reg->id)) {
9993 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9994 !tnum_equals_const(reg->var_off, 0) ||
9996 /* Old offset (both fixed and variable parts) should
9997 * have been known-zero, because we don't allow pointer
9998 * arithmetic on pointers that might be NULL. If we
9999 * see this happening, don't convert the register.
10004 reg->type = SCALAR_VALUE;
10005 /* We don't need id and ref_obj_id from this point
10006 * onwards anymore, thus we should better reset it,
10007 * so that state pruning has chances to take effect.
10010 reg->ref_obj_id = 0;
10015 mark_ptr_not_null_reg(reg);
10017 if (!reg_may_point_to_spin_lock(reg)) {
10018 /* For not-NULL ptr, reg->ref_obj_id will be reset
10019 * in release_reference().
10021 * reg->id is still used by spin_lock ptr. Other
10022 * than spin_lock ptr type, reg->id can be reset.
10029 /* The logic is similar to find_good_pkt_pointers(), both could eventually
10030 * be folded together at some point.
10032 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
10035 struct bpf_func_state *state = vstate->frame[vstate->curframe];
10036 struct bpf_reg_state *regs = state->regs, *reg;
10037 u32 ref_obj_id = regs[regno].ref_obj_id;
10038 u32 id = regs[regno].id;
10040 if (ref_obj_id && ref_obj_id == id && is_null)
10041 /* regs[regno] is in the " == NULL" branch.
10042 * No one could have freed the reference state before
10043 * doing the NULL check.
10045 WARN_ON_ONCE(release_reference_state(state, id));
10047 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10048 mark_ptr_or_null_reg(state, reg, id, is_null);
10052 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10053 struct bpf_reg_state *dst_reg,
10054 struct bpf_reg_state *src_reg,
10055 struct bpf_verifier_state *this_branch,
10056 struct bpf_verifier_state *other_branch)
10058 if (BPF_SRC(insn->code) != BPF_X)
10061 /* Pointers are always 64-bit. */
10062 if (BPF_CLASS(insn->code) == BPF_JMP32)
10065 switch (BPF_OP(insn->code)) {
10067 if ((dst_reg->type == PTR_TO_PACKET &&
10068 src_reg->type == PTR_TO_PACKET_END) ||
10069 (dst_reg->type == PTR_TO_PACKET_META &&
10070 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10071 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10072 find_good_pkt_pointers(this_branch, dst_reg,
10073 dst_reg->type, false);
10074 mark_pkt_end(other_branch, insn->dst_reg, true);
10075 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10076 src_reg->type == PTR_TO_PACKET) ||
10077 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10078 src_reg->type == PTR_TO_PACKET_META)) {
10079 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
10080 find_good_pkt_pointers(other_branch, src_reg,
10081 src_reg->type, true);
10082 mark_pkt_end(this_branch, insn->src_reg, false);
10088 if ((dst_reg->type == PTR_TO_PACKET &&
10089 src_reg->type == PTR_TO_PACKET_END) ||
10090 (dst_reg->type == PTR_TO_PACKET_META &&
10091 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10092 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10093 find_good_pkt_pointers(other_branch, dst_reg,
10094 dst_reg->type, true);
10095 mark_pkt_end(this_branch, insn->dst_reg, false);
10096 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10097 src_reg->type == PTR_TO_PACKET) ||
10098 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10099 src_reg->type == PTR_TO_PACKET_META)) {
10100 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
10101 find_good_pkt_pointers(this_branch, src_reg,
10102 src_reg->type, false);
10103 mark_pkt_end(other_branch, insn->src_reg, true);
10109 if ((dst_reg->type == PTR_TO_PACKET &&
10110 src_reg->type == PTR_TO_PACKET_END) ||
10111 (dst_reg->type == PTR_TO_PACKET_META &&
10112 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10113 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10114 find_good_pkt_pointers(this_branch, dst_reg,
10115 dst_reg->type, true);
10116 mark_pkt_end(other_branch, insn->dst_reg, false);
10117 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10118 src_reg->type == PTR_TO_PACKET) ||
10119 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10120 src_reg->type == PTR_TO_PACKET_META)) {
10121 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10122 find_good_pkt_pointers(other_branch, src_reg,
10123 src_reg->type, false);
10124 mark_pkt_end(this_branch, insn->src_reg, true);
10130 if ((dst_reg->type == PTR_TO_PACKET &&
10131 src_reg->type == PTR_TO_PACKET_END) ||
10132 (dst_reg->type == PTR_TO_PACKET_META &&
10133 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10134 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10135 find_good_pkt_pointers(other_branch, dst_reg,
10136 dst_reg->type, false);
10137 mark_pkt_end(this_branch, insn->dst_reg, true);
10138 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10139 src_reg->type == PTR_TO_PACKET) ||
10140 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10141 src_reg->type == PTR_TO_PACKET_META)) {
10142 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10143 find_good_pkt_pointers(this_branch, src_reg,
10144 src_reg->type, true);
10145 mark_pkt_end(other_branch, insn->src_reg, false);
10157 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10158 struct bpf_reg_state *known_reg)
10160 struct bpf_func_state *state;
10161 struct bpf_reg_state *reg;
10163 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10164 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10165 copy_register_state(reg, known_reg);
10169 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10170 struct bpf_insn *insn, int *insn_idx)
10172 struct bpf_verifier_state *this_branch = env->cur_state;
10173 struct bpf_verifier_state *other_branch;
10174 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10175 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10176 u8 opcode = BPF_OP(insn->code);
10181 /* Only conditional jumps are expected to reach here. */
10182 if (opcode == BPF_JA || opcode > BPF_JSLE) {
10183 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10187 if (BPF_SRC(insn->code) == BPF_X) {
10188 if (insn->imm != 0) {
10189 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10193 /* check src1 operand */
10194 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10198 if (is_pointer_value(env, insn->src_reg)) {
10199 verbose(env, "R%d pointer comparison prohibited\n",
10203 src_reg = ®s[insn->src_reg];
10205 if (insn->src_reg != BPF_REG_0) {
10206 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10211 /* check src2 operand */
10212 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10216 dst_reg = ®s[insn->dst_reg];
10217 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10219 if (BPF_SRC(insn->code) == BPF_K) {
10220 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10221 } else if (src_reg->type == SCALAR_VALUE &&
10222 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10223 pred = is_branch_taken(dst_reg,
10224 tnum_subreg(src_reg->var_off).value,
10227 } else if (src_reg->type == SCALAR_VALUE &&
10228 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10229 pred = is_branch_taken(dst_reg,
10230 src_reg->var_off.value,
10233 } else if (reg_is_pkt_pointer_any(dst_reg) &&
10234 reg_is_pkt_pointer_any(src_reg) &&
10236 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10240 /* If we get here with a dst_reg pointer type it is because
10241 * above is_branch_taken() special cased the 0 comparison.
10243 if (!__is_pointer_value(false, dst_reg))
10244 err = mark_chain_precision(env, insn->dst_reg);
10245 if (BPF_SRC(insn->code) == BPF_X && !err &&
10246 !__is_pointer_value(false, src_reg))
10247 err = mark_chain_precision(env, insn->src_reg);
10253 /* Only follow the goto, ignore fall-through. If needed, push
10254 * the fall-through branch for simulation under speculative
10257 if (!env->bypass_spec_v1 &&
10258 !sanitize_speculative_path(env, insn, *insn_idx + 1,
10261 *insn_idx += insn->off;
10263 } else if (pred == 0) {
10264 /* Only follow the fall-through branch, since that's where the
10265 * program will go. If needed, push the goto branch for
10266 * simulation under speculative execution.
10268 if (!env->bypass_spec_v1 &&
10269 !sanitize_speculative_path(env, insn,
10270 *insn_idx + insn->off + 1,
10276 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10280 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10282 /* detect if we are comparing against a constant value so we can adjust
10283 * our min/max values for our dst register.
10284 * this is only legit if both are scalars (or pointers to the same
10285 * object, I suppose, but we don't support that right now), because
10286 * otherwise the different base pointers mean the offsets aren't
10289 if (BPF_SRC(insn->code) == BPF_X) {
10290 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
10292 if (dst_reg->type == SCALAR_VALUE &&
10293 src_reg->type == SCALAR_VALUE) {
10294 if (tnum_is_const(src_reg->var_off) ||
10296 tnum_is_const(tnum_subreg(src_reg->var_off))))
10297 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10299 src_reg->var_off.value,
10300 tnum_subreg(src_reg->var_off).value,
10302 else if (tnum_is_const(dst_reg->var_off) ||
10304 tnum_is_const(tnum_subreg(dst_reg->var_off))))
10305 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10307 dst_reg->var_off.value,
10308 tnum_subreg(dst_reg->var_off).value,
10310 else if (!is_jmp32 &&
10311 (opcode == BPF_JEQ || opcode == BPF_JNE))
10312 /* Comparing for equality, we can combine knowledge */
10313 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10314 &other_branch_regs[insn->dst_reg],
10315 src_reg, dst_reg, opcode);
10317 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10318 find_equal_scalars(this_branch, src_reg);
10319 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10323 } else if (dst_reg->type == SCALAR_VALUE) {
10324 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10325 dst_reg, insn->imm, (u32)insn->imm,
10329 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10330 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10331 find_equal_scalars(this_branch, dst_reg);
10332 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10335 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10336 * NOTE: these optimizations below are related with pointer comparison
10337 * which will never be JMP32.
10339 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10340 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10341 type_may_be_null(dst_reg->type)) {
10342 /* Mark all identical registers in each branch as either
10343 * safe or unknown depending R == 0 or R != 0 conditional.
10345 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10346 opcode == BPF_JNE);
10347 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10348 opcode == BPF_JEQ);
10349 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
10350 this_branch, other_branch) &&
10351 is_pointer_value(env, insn->dst_reg)) {
10352 verbose(env, "R%d pointer comparison prohibited\n",
10356 if (env->log.level & BPF_LOG_LEVEL)
10357 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10361 /* verify BPF_LD_IMM64 instruction */
10362 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10364 struct bpf_insn_aux_data *aux = cur_aux(env);
10365 struct bpf_reg_state *regs = cur_regs(env);
10366 struct bpf_reg_state *dst_reg;
10367 struct bpf_map *map;
10370 if (BPF_SIZE(insn->code) != BPF_DW) {
10371 verbose(env, "invalid BPF_LD_IMM insn\n");
10374 if (insn->off != 0) {
10375 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10379 err = check_reg_arg(env, insn->dst_reg, DST_OP);
10383 dst_reg = ®s[insn->dst_reg];
10384 if (insn->src_reg == 0) {
10385 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10387 dst_reg->type = SCALAR_VALUE;
10388 __mark_reg_known(®s[insn->dst_reg], imm);
10392 /* All special src_reg cases are listed below. From this point onwards
10393 * we either succeed and assign a corresponding dst_reg->type after
10394 * zeroing the offset, or fail and reject the program.
10396 mark_reg_known_zero(env, regs, insn->dst_reg);
10398 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10399 dst_reg->type = aux->btf_var.reg_type;
10400 switch (base_type(dst_reg->type)) {
10402 dst_reg->mem_size = aux->btf_var.mem_size;
10404 case PTR_TO_BTF_ID:
10405 dst_reg->btf = aux->btf_var.btf;
10406 dst_reg->btf_id = aux->btf_var.btf_id;
10409 verbose(env, "bpf verifier is misconfigured\n");
10415 if (insn->src_reg == BPF_PSEUDO_FUNC) {
10416 struct bpf_prog_aux *aux = env->prog->aux;
10417 u32 subprogno = find_subprog(env,
10418 env->insn_idx + insn->imm + 1);
10420 if (!aux->func_info) {
10421 verbose(env, "missing btf func_info\n");
10424 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10425 verbose(env, "callback function not static\n");
10429 dst_reg->type = PTR_TO_FUNC;
10430 dst_reg->subprogno = subprogno;
10434 map = env->used_maps[aux->map_index];
10435 dst_reg->map_ptr = map;
10437 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10438 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10439 dst_reg->type = PTR_TO_MAP_VALUE;
10440 dst_reg->off = aux->map_off;
10441 if (map_value_has_spin_lock(map))
10442 dst_reg->id = ++env->id_gen;
10443 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10444 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10445 dst_reg->type = CONST_PTR_TO_MAP;
10447 verbose(env, "bpf verifier is misconfigured\n");
10454 static bool may_access_skb(enum bpf_prog_type type)
10457 case BPF_PROG_TYPE_SOCKET_FILTER:
10458 case BPF_PROG_TYPE_SCHED_CLS:
10459 case BPF_PROG_TYPE_SCHED_ACT:
10466 /* verify safety of LD_ABS|LD_IND instructions:
10467 * - they can only appear in the programs where ctx == skb
10468 * - since they are wrappers of function calls, they scratch R1-R5 registers,
10469 * preserve R6-R9, and store return value into R0
10472 * ctx == skb == R6 == CTX
10475 * SRC == any register
10476 * IMM == 32-bit immediate
10479 * R0 - 8/16/32-bit skb data converted to cpu endianness
10481 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10483 struct bpf_reg_state *regs = cur_regs(env);
10484 static const int ctx_reg = BPF_REG_6;
10485 u8 mode = BPF_MODE(insn->code);
10488 if (!may_access_skb(resolve_prog_type(env->prog))) {
10489 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10493 if (!env->ops->gen_ld_abs) {
10494 verbose(env, "bpf verifier is misconfigured\n");
10498 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10499 BPF_SIZE(insn->code) == BPF_DW ||
10500 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10501 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10505 /* check whether implicit source operand (register R6) is readable */
10506 err = check_reg_arg(env, ctx_reg, SRC_OP);
10510 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10511 * gen_ld_abs() may terminate the program at runtime, leading to
10514 err = check_reference_leak(env);
10516 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10520 if (env->cur_state->active_spin_lock) {
10521 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10525 if (regs[ctx_reg].type != PTR_TO_CTX) {
10527 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10531 if (mode == BPF_IND) {
10532 /* check explicit source operand */
10533 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10538 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
10542 /* reset caller saved regs to unreadable */
10543 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10544 mark_reg_not_init(env, regs, caller_saved[i]);
10545 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10548 /* mark destination R0 register as readable, since it contains
10549 * the value fetched from the packet.
10550 * Already marked as written above.
10552 mark_reg_unknown(env, regs, BPF_REG_0);
10553 /* ld_abs load up to 32-bit skb data. */
10554 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10558 static int check_return_code(struct bpf_verifier_env *env)
10560 struct tnum enforce_attach_type_range = tnum_unknown;
10561 const struct bpf_prog *prog = env->prog;
10562 struct bpf_reg_state *reg;
10563 struct tnum range = tnum_range(0, 1);
10564 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10566 struct bpf_func_state *frame = env->cur_state->frame[0];
10567 const bool is_subprog = frame->subprogno;
10569 /* LSM and struct_ops func-ptr's return type could be "void" */
10571 switch (prog_type) {
10572 case BPF_PROG_TYPE_LSM:
10573 if (prog->expected_attach_type == BPF_LSM_CGROUP)
10574 /* See below, can be 0 or 0-1 depending on hook. */
10577 case BPF_PROG_TYPE_STRUCT_OPS:
10578 if (!prog->aux->attach_func_proto->type)
10586 /* eBPF calling convention is such that R0 is used
10587 * to return the value from eBPF program.
10588 * Make sure that it's readable at this time
10589 * of bpf_exit, which means that program wrote
10590 * something into it earlier
10592 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10596 if (is_pointer_value(env, BPF_REG_0)) {
10597 verbose(env, "R0 leaks addr as return value\n");
10601 reg = cur_regs(env) + BPF_REG_0;
10603 if (frame->in_async_callback_fn) {
10604 /* enforce return zero from async callbacks like timer */
10605 if (reg->type != SCALAR_VALUE) {
10606 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10607 reg_type_str(env, reg->type));
10611 if (!tnum_in(tnum_const(0), reg->var_off)) {
10612 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10619 if (reg->type != SCALAR_VALUE) {
10620 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10621 reg_type_str(env, reg->type));
10627 switch (prog_type) {
10628 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10629 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10630 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10631 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10632 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10633 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10634 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10635 range = tnum_range(1, 1);
10636 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10637 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10638 range = tnum_range(0, 3);
10640 case BPF_PROG_TYPE_CGROUP_SKB:
10641 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10642 range = tnum_range(0, 3);
10643 enforce_attach_type_range = tnum_range(2, 3);
10646 case BPF_PROG_TYPE_CGROUP_SOCK:
10647 case BPF_PROG_TYPE_SOCK_OPS:
10648 case BPF_PROG_TYPE_CGROUP_DEVICE:
10649 case BPF_PROG_TYPE_CGROUP_SYSCTL:
10650 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10652 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10653 if (!env->prog->aux->attach_btf_id)
10655 range = tnum_const(0);
10657 case BPF_PROG_TYPE_TRACING:
10658 switch (env->prog->expected_attach_type) {
10659 case BPF_TRACE_FENTRY:
10660 case BPF_TRACE_FEXIT:
10661 range = tnum_const(0);
10663 case BPF_TRACE_RAW_TP:
10664 case BPF_MODIFY_RETURN:
10666 case BPF_TRACE_ITER:
10672 case BPF_PROG_TYPE_SK_LOOKUP:
10673 range = tnum_range(SK_DROP, SK_PASS);
10676 case BPF_PROG_TYPE_LSM:
10677 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10678 /* Regular BPF_PROG_TYPE_LSM programs can return
10683 if (!env->prog->aux->attach_func_proto->type) {
10684 /* Make sure programs that attach to void
10685 * hooks don't try to modify return value.
10687 range = tnum_range(1, 1);
10691 case BPF_PROG_TYPE_EXT:
10692 /* freplace program can return anything as its return value
10693 * depends on the to-be-replaced kernel func or bpf program.
10699 if (reg->type != SCALAR_VALUE) {
10700 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10701 reg_type_str(env, reg->type));
10705 if (!tnum_in(range, reg->var_off)) {
10706 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10707 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10708 prog_type == BPF_PROG_TYPE_LSM &&
10709 !prog->aux->attach_func_proto->type)
10710 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10714 if (!tnum_is_unknown(enforce_attach_type_range) &&
10715 tnum_in(enforce_attach_type_range, reg->var_off))
10716 env->prog->enforce_expected_attach_type = 1;
10720 /* non-recursive DFS pseudo code
10721 * 1 procedure DFS-iterative(G,v):
10722 * 2 label v as discovered
10723 * 3 let S be a stack
10725 * 5 while S is not empty
10727 * 7 if t is what we're looking for:
10729 * 9 for all edges e in G.adjacentEdges(t) do
10730 * 10 if edge e is already labelled
10731 * 11 continue with the next edge
10732 * 12 w <- G.adjacentVertex(t,e)
10733 * 13 if vertex w is not discovered and not explored
10734 * 14 label e as tree-edge
10735 * 15 label w as discovered
10738 * 18 else if vertex w is discovered
10739 * 19 label e as back-edge
10741 * 21 // vertex w is explored
10742 * 22 label e as forward- or cross-edge
10743 * 23 label t as explored
10747 * 0x10 - discovered
10748 * 0x11 - discovered and fall-through edge labelled
10749 * 0x12 - discovered and fall-through and branch edges labelled
10760 static u32 state_htab_size(struct bpf_verifier_env *env)
10762 return env->prog->len;
10765 static struct bpf_verifier_state_list **explored_state(
10766 struct bpf_verifier_env *env,
10769 struct bpf_verifier_state *cur = env->cur_state;
10770 struct bpf_func_state *state = cur->frame[cur->curframe];
10772 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10775 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10777 env->insn_aux_data[idx].prune_point = true;
10781 DONE_EXPLORING = 0,
10782 KEEP_EXPLORING = 1,
10785 /* t, w, e - match pseudo-code above:
10786 * t - index of current instruction
10787 * w - next instruction
10790 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10793 int *insn_stack = env->cfg.insn_stack;
10794 int *insn_state = env->cfg.insn_state;
10796 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10797 return DONE_EXPLORING;
10799 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10800 return DONE_EXPLORING;
10802 if (w < 0 || w >= env->prog->len) {
10803 verbose_linfo(env, t, "%d: ", t);
10804 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10809 /* mark branch target for state pruning */
10810 init_explored_state(env, w);
10812 if (insn_state[w] == 0) {
10814 insn_state[t] = DISCOVERED | e;
10815 insn_state[w] = DISCOVERED;
10816 if (env->cfg.cur_stack >= env->prog->len)
10818 insn_stack[env->cfg.cur_stack++] = w;
10819 return KEEP_EXPLORING;
10820 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10821 if (loop_ok && env->bpf_capable)
10822 return DONE_EXPLORING;
10823 verbose_linfo(env, t, "%d: ", t);
10824 verbose_linfo(env, w, "%d: ", w);
10825 verbose(env, "back-edge from insn %d to %d\n", t, w);
10827 } else if (insn_state[w] == EXPLORED) {
10828 /* forward- or cross-edge */
10829 insn_state[t] = DISCOVERED | e;
10831 verbose(env, "insn state internal bug\n");
10834 return DONE_EXPLORING;
10837 static int visit_func_call_insn(int t, int insn_cnt,
10838 struct bpf_insn *insns,
10839 struct bpf_verifier_env *env,
10844 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10848 if (t + 1 < insn_cnt)
10849 init_explored_state(env, t + 1);
10850 if (visit_callee) {
10851 init_explored_state(env, t);
10852 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10853 /* It's ok to allow recursion from CFG point of
10854 * view. __check_func_call() will do the actual
10857 bpf_pseudo_func(insns + t));
10862 /* Visits the instruction at index t and returns one of the following:
10863 * < 0 - an error occurred
10864 * DONE_EXPLORING - the instruction was fully explored
10865 * KEEP_EXPLORING - there is still work to be done before it is fully explored
10867 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10869 struct bpf_insn *insns = env->prog->insnsi;
10872 if (bpf_pseudo_func(insns + t))
10873 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10875 /* All non-branch instructions have a single fall-through edge. */
10876 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10877 BPF_CLASS(insns[t].code) != BPF_JMP32)
10878 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10880 switch (BPF_OP(insns[t].code)) {
10882 return DONE_EXPLORING;
10885 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10886 /* Mark this call insn to trigger is_state_visited() check
10887 * before call itself is processed by __check_func_call().
10888 * Otherwise new async state will be pushed for further
10891 init_explored_state(env, t);
10892 return visit_func_call_insn(t, insn_cnt, insns, env,
10893 insns[t].src_reg == BPF_PSEUDO_CALL);
10896 if (BPF_SRC(insns[t].code) != BPF_K)
10899 /* unconditional jump with single edge */
10900 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10905 /* unconditional jmp is not a good pruning point,
10906 * but it's marked, since backtracking needs
10907 * to record jmp history in is_state_visited().
10909 init_explored_state(env, t + insns[t].off + 1);
10910 /* tell verifier to check for equivalent states
10911 * after every call and jump
10913 if (t + 1 < insn_cnt)
10914 init_explored_state(env, t + 1);
10919 /* conditional jump with two edges */
10920 init_explored_state(env, t);
10921 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10925 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10929 /* non-recursive depth-first-search to detect loops in BPF program
10930 * loop == back-edge in directed graph
10932 static int check_cfg(struct bpf_verifier_env *env)
10934 int insn_cnt = env->prog->len;
10935 int *insn_stack, *insn_state;
10939 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10943 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10945 kvfree(insn_state);
10949 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10950 insn_stack[0] = 0; /* 0 is the first instruction */
10951 env->cfg.cur_stack = 1;
10953 while (env->cfg.cur_stack > 0) {
10954 int t = insn_stack[env->cfg.cur_stack - 1];
10956 ret = visit_insn(t, insn_cnt, env);
10958 case DONE_EXPLORING:
10959 insn_state[t] = EXPLORED;
10960 env->cfg.cur_stack--;
10962 case KEEP_EXPLORING:
10966 verbose(env, "visit_insn internal bug\n");
10973 if (env->cfg.cur_stack < 0) {
10974 verbose(env, "pop stack internal bug\n");
10979 for (i = 0; i < insn_cnt; i++) {
10980 if (insn_state[i] != EXPLORED) {
10981 verbose(env, "unreachable insn %d\n", i);
10986 ret = 0; /* cfg looks good */
10989 kvfree(insn_state);
10990 kvfree(insn_stack);
10991 env->cfg.insn_state = env->cfg.insn_stack = NULL;
10995 static int check_abnormal_return(struct bpf_verifier_env *env)
10999 for (i = 1; i < env->subprog_cnt; i++) {
11000 if (env->subprog_info[i].has_ld_abs) {
11001 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
11004 if (env->subprog_info[i].has_tail_call) {
11005 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
11012 /* The minimum supported BTF func info size */
11013 #define MIN_BPF_FUNCINFO_SIZE 8
11014 #define MAX_FUNCINFO_REC_SIZE 252
11016 static int check_btf_func(struct bpf_verifier_env *env,
11017 const union bpf_attr *attr,
11020 const struct btf_type *type, *func_proto, *ret_type;
11021 u32 i, nfuncs, urec_size, min_size;
11022 u32 krec_size = sizeof(struct bpf_func_info);
11023 struct bpf_func_info *krecord;
11024 struct bpf_func_info_aux *info_aux = NULL;
11025 struct bpf_prog *prog;
11026 const struct btf *btf;
11028 u32 prev_offset = 0;
11029 bool scalar_return;
11032 nfuncs = attr->func_info_cnt;
11034 if (check_abnormal_return(env))
11039 if (nfuncs != env->subprog_cnt) {
11040 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11044 urec_size = attr->func_info_rec_size;
11045 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11046 urec_size > MAX_FUNCINFO_REC_SIZE ||
11047 urec_size % sizeof(u32)) {
11048 verbose(env, "invalid func info rec size %u\n", urec_size);
11053 btf = prog->aux->btf;
11055 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11056 min_size = min_t(u32, krec_size, urec_size);
11058 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11061 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11065 for (i = 0; i < nfuncs; i++) {
11066 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11068 if (ret == -E2BIG) {
11069 verbose(env, "nonzero tailing record in func info");
11070 /* set the size kernel expects so loader can zero
11071 * out the rest of the record.
11073 if (copy_to_bpfptr_offset(uattr,
11074 offsetof(union bpf_attr, func_info_rec_size),
11075 &min_size, sizeof(min_size)))
11081 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11086 /* check insn_off */
11089 if (krecord[i].insn_off) {
11091 "nonzero insn_off %u for the first func info record",
11092 krecord[i].insn_off);
11095 } else if (krecord[i].insn_off <= prev_offset) {
11097 "same or smaller insn offset (%u) than previous func info record (%u)",
11098 krecord[i].insn_off, prev_offset);
11102 if (env->subprog_info[i].start != krecord[i].insn_off) {
11103 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11107 /* check type_id */
11108 type = btf_type_by_id(btf, krecord[i].type_id);
11109 if (!type || !btf_type_is_func(type)) {
11110 verbose(env, "invalid type id %d in func info",
11111 krecord[i].type_id);
11114 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11116 func_proto = btf_type_by_id(btf, type->type);
11117 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11118 /* btf_func_check() already verified it during BTF load */
11120 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11122 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11123 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11124 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11127 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11128 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11132 prev_offset = krecord[i].insn_off;
11133 bpfptr_add(&urecord, urec_size);
11136 prog->aux->func_info = krecord;
11137 prog->aux->func_info_cnt = nfuncs;
11138 prog->aux->func_info_aux = info_aux;
11147 static void adjust_btf_func(struct bpf_verifier_env *env)
11149 struct bpf_prog_aux *aux = env->prog->aux;
11152 if (!aux->func_info)
11155 for (i = 0; i < env->subprog_cnt; i++)
11156 aux->func_info[i].insn_off = env->subprog_info[i].start;
11159 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
11160 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
11162 static int check_btf_line(struct bpf_verifier_env *env,
11163 const union bpf_attr *attr,
11166 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11167 struct bpf_subprog_info *sub;
11168 struct bpf_line_info *linfo;
11169 struct bpf_prog *prog;
11170 const struct btf *btf;
11174 nr_linfo = attr->line_info_cnt;
11177 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11180 rec_size = attr->line_info_rec_size;
11181 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11182 rec_size > MAX_LINEINFO_REC_SIZE ||
11183 rec_size & (sizeof(u32) - 1))
11186 /* Need to zero it in case the userspace may
11187 * pass in a smaller bpf_line_info object.
11189 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11190 GFP_KERNEL | __GFP_NOWARN);
11195 btf = prog->aux->btf;
11198 sub = env->subprog_info;
11199 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11200 expected_size = sizeof(struct bpf_line_info);
11201 ncopy = min_t(u32, expected_size, rec_size);
11202 for (i = 0; i < nr_linfo; i++) {
11203 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11205 if (err == -E2BIG) {
11206 verbose(env, "nonzero tailing record in line_info");
11207 if (copy_to_bpfptr_offset(uattr,
11208 offsetof(union bpf_attr, line_info_rec_size),
11209 &expected_size, sizeof(expected_size)))
11215 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11221 * Check insn_off to ensure
11222 * 1) strictly increasing AND
11223 * 2) bounded by prog->len
11225 * The linfo[0].insn_off == 0 check logically falls into
11226 * the later "missing bpf_line_info for func..." case
11227 * because the first linfo[0].insn_off must be the
11228 * first sub also and the first sub must have
11229 * subprog_info[0].start == 0.
11231 if ((i && linfo[i].insn_off <= prev_offset) ||
11232 linfo[i].insn_off >= prog->len) {
11233 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11234 i, linfo[i].insn_off, prev_offset,
11240 if (!prog->insnsi[linfo[i].insn_off].code) {
11242 "Invalid insn code at line_info[%u].insn_off\n",
11248 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11249 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11250 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11255 if (s != env->subprog_cnt) {
11256 if (linfo[i].insn_off == sub[s].start) {
11257 sub[s].linfo_idx = i;
11259 } else if (sub[s].start < linfo[i].insn_off) {
11260 verbose(env, "missing bpf_line_info for func#%u\n", s);
11266 prev_offset = linfo[i].insn_off;
11267 bpfptr_add(&ulinfo, rec_size);
11270 if (s != env->subprog_cnt) {
11271 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11272 env->subprog_cnt - s, s);
11277 prog->aux->linfo = linfo;
11278 prog->aux->nr_linfo = nr_linfo;
11287 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
11288 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
11290 static int check_core_relo(struct bpf_verifier_env *env,
11291 const union bpf_attr *attr,
11294 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11295 struct bpf_core_relo core_relo = {};
11296 struct bpf_prog *prog = env->prog;
11297 const struct btf *btf = prog->aux->btf;
11298 struct bpf_core_ctx ctx = {
11302 bpfptr_t u_core_relo;
11305 nr_core_relo = attr->core_relo_cnt;
11308 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11311 rec_size = attr->core_relo_rec_size;
11312 if (rec_size < MIN_CORE_RELO_SIZE ||
11313 rec_size > MAX_CORE_RELO_SIZE ||
11314 rec_size % sizeof(u32))
11317 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11318 expected_size = sizeof(struct bpf_core_relo);
11319 ncopy = min_t(u32, expected_size, rec_size);
11321 /* Unlike func_info and line_info, copy and apply each CO-RE
11322 * relocation record one at a time.
11324 for (i = 0; i < nr_core_relo; i++) {
11325 /* future proofing when sizeof(bpf_core_relo) changes */
11326 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11328 if (err == -E2BIG) {
11329 verbose(env, "nonzero tailing record in core_relo");
11330 if (copy_to_bpfptr_offset(uattr,
11331 offsetof(union bpf_attr, core_relo_rec_size),
11332 &expected_size, sizeof(expected_size)))
11338 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11343 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11344 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11345 i, core_relo.insn_off, prog->len);
11350 err = bpf_core_apply(&ctx, &core_relo, i,
11351 &prog->insnsi[core_relo.insn_off / 8]);
11354 bpfptr_add(&u_core_relo, rec_size);
11359 static int check_btf_info(struct bpf_verifier_env *env,
11360 const union bpf_attr *attr,
11366 if (!attr->func_info_cnt && !attr->line_info_cnt) {
11367 if (check_abnormal_return(env))
11372 btf = btf_get_by_fd(attr->prog_btf_fd);
11374 return PTR_ERR(btf);
11375 if (btf_is_kernel(btf)) {
11379 env->prog->aux->btf = btf;
11381 err = check_btf_func(env, attr, uattr);
11385 err = check_btf_line(env, attr, uattr);
11389 err = check_core_relo(env, attr, uattr);
11396 /* check %cur's range satisfies %old's */
11397 static bool range_within(struct bpf_reg_state *old,
11398 struct bpf_reg_state *cur)
11400 return old->umin_value <= cur->umin_value &&
11401 old->umax_value >= cur->umax_value &&
11402 old->smin_value <= cur->smin_value &&
11403 old->smax_value >= cur->smax_value &&
11404 old->u32_min_value <= cur->u32_min_value &&
11405 old->u32_max_value >= cur->u32_max_value &&
11406 old->s32_min_value <= cur->s32_min_value &&
11407 old->s32_max_value >= cur->s32_max_value;
11410 /* If in the old state two registers had the same id, then they need to have
11411 * the same id in the new state as well. But that id could be different from
11412 * the old state, so we need to track the mapping from old to new ids.
11413 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11414 * regs with old id 5 must also have new id 9 for the new state to be safe. But
11415 * regs with a different old id could still have new id 9, we don't care about
11417 * So we look through our idmap to see if this old id has been seen before. If
11418 * so, we require the new id to match; otherwise, we add the id pair to the map.
11420 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11424 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11425 if (!idmap[i].old) {
11426 /* Reached an empty slot; haven't seen this id before */
11427 idmap[i].old = old_id;
11428 idmap[i].cur = cur_id;
11431 if (idmap[i].old == old_id)
11432 return idmap[i].cur == cur_id;
11434 /* We ran out of idmap slots, which should be impossible */
11439 static void clean_func_state(struct bpf_verifier_env *env,
11440 struct bpf_func_state *st)
11442 enum bpf_reg_liveness live;
11445 for (i = 0; i < BPF_REG_FP; i++) {
11446 live = st->regs[i].live;
11447 /* liveness must not touch this register anymore */
11448 st->regs[i].live |= REG_LIVE_DONE;
11449 if (!(live & REG_LIVE_READ))
11450 /* since the register is unused, clear its state
11451 * to make further comparison simpler
11453 __mark_reg_not_init(env, &st->regs[i]);
11456 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11457 live = st->stack[i].spilled_ptr.live;
11458 /* liveness must not touch this stack slot anymore */
11459 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11460 if (!(live & REG_LIVE_READ)) {
11461 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11462 for (j = 0; j < BPF_REG_SIZE; j++)
11463 st->stack[i].slot_type[j] = STACK_INVALID;
11468 static void clean_verifier_state(struct bpf_verifier_env *env,
11469 struct bpf_verifier_state *st)
11473 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11474 /* all regs in this state in all frames were already marked */
11477 for (i = 0; i <= st->curframe; i++)
11478 clean_func_state(env, st->frame[i]);
11481 /* the parentage chains form a tree.
11482 * the verifier states are added to state lists at given insn and
11483 * pushed into state stack for future exploration.
11484 * when the verifier reaches bpf_exit insn some of the verifer states
11485 * stored in the state lists have their final liveness state already,
11486 * but a lot of states will get revised from liveness point of view when
11487 * the verifier explores other branches.
11490 * 2: if r1 == 100 goto pc+1
11493 * when the verifier reaches exit insn the register r0 in the state list of
11494 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11495 * of insn 2 and goes exploring further. At the insn 4 it will walk the
11496 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11498 * Since the verifier pushes the branch states as it sees them while exploring
11499 * the program the condition of walking the branch instruction for the second
11500 * time means that all states below this branch were already explored and
11501 * their final liveness marks are already propagated.
11502 * Hence when the verifier completes the search of state list in is_state_visited()
11503 * we can call this clean_live_states() function to mark all liveness states
11504 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11505 * will not be used.
11506 * This function also clears the registers and stack for states that !READ
11507 * to simplify state merging.
11509 * Important note here that walking the same branch instruction in the callee
11510 * doesn't meant that the states are DONE. The verifier has to compare
11513 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11514 struct bpf_verifier_state *cur)
11516 struct bpf_verifier_state_list *sl;
11519 sl = *explored_state(env, insn);
11521 if (sl->state.branches)
11523 if (sl->state.insn_idx != insn ||
11524 sl->state.curframe != cur->curframe)
11526 for (i = 0; i <= cur->curframe; i++)
11527 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11529 clean_verifier_state(env, &sl->state);
11535 /* Returns true if (rold safe implies rcur safe) */
11536 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11537 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11541 if (!(rold->live & REG_LIVE_READ))
11542 /* explored state didn't use this */
11545 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11547 if (rold->type == PTR_TO_STACK)
11548 /* two stack pointers are equal only if they're pointing to
11549 * the same stack frame, since fp-8 in foo != fp-8 in bar
11551 return equal && rold->frameno == rcur->frameno;
11556 if (rold->type == NOT_INIT)
11557 /* explored state can't have used this */
11559 if (rcur->type == NOT_INIT)
11561 switch (base_type(rold->type)) {
11563 if (env->explore_alu_limits)
11565 if (rcur->type == SCALAR_VALUE) {
11566 if (!rold->precise && !rcur->precise)
11568 /* new val must satisfy old val knowledge */
11569 return range_within(rold, rcur) &&
11570 tnum_in(rold->var_off, rcur->var_off);
11572 /* We're trying to use a pointer in place of a scalar.
11573 * Even if the scalar was unbounded, this could lead to
11574 * pointer leaks because scalars are allowed to leak
11575 * while pointers are not. We could make this safe in
11576 * special cases if root is calling us, but it's
11577 * probably not worth the hassle.
11581 case PTR_TO_MAP_KEY:
11582 case PTR_TO_MAP_VALUE:
11583 /* a PTR_TO_MAP_VALUE could be safe to use as a
11584 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11585 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11586 * checked, doing so could have affected others with the same
11587 * id, and we can't check for that because we lost the id when
11588 * we converted to a PTR_TO_MAP_VALUE.
11590 if (type_may_be_null(rold->type)) {
11591 if (!type_may_be_null(rcur->type))
11593 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11595 /* Check our ids match any regs they're supposed to */
11596 return check_ids(rold->id, rcur->id, idmap);
11599 /* If the new min/max/var_off satisfy the old ones and
11600 * everything else matches, we are OK.
11601 * 'id' is not compared, since it's only used for maps with
11602 * bpf_spin_lock inside map element and in such cases if
11603 * the rest of the prog is valid for one map element then
11604 * it's valid for all map elements regardless of the key
11605 * used in bpf_map_lookup()
11607 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11608 range_within(rold, rcur) &&
11609 tnum_in(rold->var_off, rcur->var_off);
11610 case PTR_TO_PACKET_META:
11611 case PTR_TO_PACKET:
11612 if (rcur->type != rold->type)
11614 /* We must have at least as much range as the old ptr
11615 * did, so that any accesses which were safe before are
11616 * still safe. This is true even if old range < old off,
11617 * since someone could have accessed through (ptr - k), or
11618 * even done ptr -= k in a register, to get a safe access.
11620 if (rold->range > rcur->range)
11622 /* If the offsets don't match, we can't trust our alignment;
11623 * nor can we be sure that we won't fall out of range.
11625 if (rold->off != rcur->off)
11627 /* id relations must be preserved */
11628 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11630 /* new val must satisfy old val knowledge */
11631 return range_within(rold, rcur) &&
11632 tnum_in(rold->var_off, rcur->var_off);
11634 case CONST_PTR_TO_MAP:
11635 case PTR_TO_PACKET_END:
11636 case PTR_TO_FLOW_KEYS:
11637 case PTR_TO_SOCKET:
11638 case PTR_TO_SOCK_COMMON:
11639 case PTR_TO_TCP_SOCK:
11640 case PTR_TO_XDP_SOCK:
11641 /* Only valid matches are exact, which memcmp() above
11642 * would have accepted
11645 /* Don't know what's going on, just say it's not safe */
11649 /* Shouldn't get here; if we do, say it's not safe */
11654 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11655 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11659 /* walk slots of the explored stack and ignore any additional
11660 * slots in the current stack, since explored(safe) state
11663 for (i = 0; i < old->allocated_stack; i++) {
11664 spi = i / BPF_REG_SIZE;
11666 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11667 i += BPF_REG_SIZE - 1;
11668 /* explored state didn't use this */
11672 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11675 /* explored stack has more populated slots than current stack
11676 * and these slots were used
11678 if (i >= cur->allocated_stack)
11681 /* if old state was safe with misc data in the stack
11682 * it will be safe with zero-initialized stack.
11683 * The opposite is not true
11685 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11686 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11688 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11689 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11690 /* Ex: old explored (safe) state has STACK_SPILL in
11691 * this stack slot, but current has STACK_MISC ->
11692 * this verifier states are not equivalent,
11693 * return false to continue verification of this path
11696 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11698 if (!is_spilled_reg(&old->stack[spi]))
11700 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11701 &cur->stack[spi].spilled_ptr, idmap))
11702 /* when explored and current stack slot are both storing
11703 * spilled registers, check that stored pointers types
11704 * are the same as well.
11705 * Ex: explored safe path could have stored
11706 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11707 * but current path has stored:
11708 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11709 * such verifier states are not equivalent.
11710 * return false to continue verification of this path
11717 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11719 if (old->acquired_refs != cur->acquired_refs)
11721 return !memcmp(old->refs, cur->refs,
11722 sizeof(*old->refs) * old->acquired_refs);
11725 /* compare two verifier states
11727 * all states stored in state_list are known to be valid, since
11728 * verifier reached 'bpf_exit' instruction through them
11730 * this function is called when verifier exploring different branches of
11731 * execution popped from the state stack. If it sees an old state that has
11732 * more strict register state and more strict stack state then this execution
11733 * branch doesn't need to be explored further, since verifier already
11734 * concluded that more strict state leads to valid finish.
11736 * Therefore two states are equivalent if register state is more conservative
11737 * and explored stack state is more conservative than the current one.
11740 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11741 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11743 * In other words if current stack state (one being explored) has more
11744 * valid slots than old one that already passed validation, it means
11745 * the verifier can stop exploring and conclude that current state is valid too
11747 * Similarly with registers. If explored state has register type as invalid
11748 * whereas register type in current state is meaningful, it means that
11749 * the current state will reach 'bpf_exit' instruction safely
11751 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11752 struct bpf_func_state *cur)
11756 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11757 for (i = 0; i < MAX_BPF_REG; i++)
11758 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11759 env->idmap_scratch))
11762 if (!stacksafe(env, old, cur, env->idmap_scratch))
11765 if (!refsafe(old, cur))
11771 static bool states_equal(struct bpf_verifier_env *env,
11772 struct bpf_verifier_state *old,
11773 struct bpf_verifier_state *cur)
11777 if (old->curframe != cur->curframe)
11780 /* Verification state from speculative execution simulation
11781 * must never prune a non-speculative execution one.
11783 if (old->speculative && !cur->speculative)
11786 if (old->active_spin_lock != cur->active_spin_lock)
11789 /* for states to be equal callsites have to be the same
11790 * and all frame states need to be equivalent
11792 for (i = 0; i <= old->curframe; i++) {
11793 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11795 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11801 /* Return 0 if no propagation happened. Return negative error code if error
11802 * happened. Otherwise, return the propagated bit.
11804 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11805 struct bpf_reg_state *reg,
11806 struct bpf_reg_state *parent_reg)
11808 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11809 u8 flag = reg->live & REG_LIVE_READ;
11812 /* When comes here, read flags of PARENT_REG or REG could be any of
11813 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11814 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11816 if (parent_flag == REG_LIVE_READ64 ||
11817 /* Or if there is no read flag from REG. */
11819 /* Or if the read flag from REG is the same as PARENT_REG. */
11820 parent_flag == flag)
11823 err = mark_reg_read(env, reg, parent_reg, flag);
11830 /* A write screens off any subsequent reads; but write marks come from the
11831 * straight-line code between a state and its parent. When we arrive at an
11832 * equivalent state (jump target or such) we didn't arrive by the straight-line
11833 * code, so read marks in the state must propagate to the parent regardless
11834 * of the state's write marks. That's what 'parent == state->parent' comparison
11835 * in mark_reg_read() is for.
11837 static int propagate_liveness(struct bpf_verifier_env *env,
11838 const struct bpf_verifier_state *vstate,
11839 struct bpf_verifier_state *vparent)
11841 struct bpf_reg_state *state_reg, *parent_reg;
11842 struct bpf_func_state *state, *parent;
11843 int i, frame, err = 0;
11845 if (vparent->curframe != vstate->curframe) {
11846 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11847 vparent->curframe, vstate->curframe);
11850 /* Propagate read liveness of registers... */
11851 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11852 for (frame = 0; frame <= vstate->curframe; frame++) {
11853 parent = vparent->frame[frame];
11854 state = vstate->frame[frame];
11855 parent_reg = parent->regs;
11856 state_reg = state->regs;
11857 /* We don't need to worry about FP liveness, it's read-only */
11858 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11859 err = propagate_liveness_reg(env, &state_reg[i],
11863 if (err == REG_LIVE_READ64)
11864 mark_insn_zext(env, &parent_reg[i]);
11867 /* Propagate stack slots. */
11868 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11869 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11870 parent_reg = &parent->stack[i].spilled_ptr;
11871 state_reg = &state->stack[i].spilled_ptr;
11872 err = propagate_liveness_reg(env, state_reg,
11881 /* find precise scalars in the previous equivalent state and
11882 * propagate them into the current state
11884 static int propagate_precision(struct bpf_verifier_env *env,
11885 const struct bpf_verifier_state *old)
11887 struct bpf_reg_state *state_reg;
11888 struct bpf_func_state *state;
11889 int i, err = 0, fr;
11891 for (fr = old->curframe; fr >= 0; fr--) {
11892 state = old->frame[fr];
11893 state_reg = state->regs;
11894 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11895 if (state_reg->type != SCALAR_VALUE ||
11896 !state_reg->precise)
11898 if (env->log.level & BPF_LOG_LEVEL2)
11899 verbose(env, "frame %d: propagating r%d\n", i, fr);
11900 err = mark_chain_precision_frame(env, fr, i);
11905 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11906 if (!is_spilled_reg(&state->stack[i]))
11908 state_reg = &state->stack[i].spilled_ptr;
11909 if (state_reg->type != SCALAR_VALUE ||
11910 !state_reg->precise)
11912 if (env->log.level & BPF_LOG_LEVEL2)
11913 verbose(env, "frame %d: propagating fp%d\n",
11914 (-i - 1) * BPF_REG_SIZE, fr);
11915 err = mark_chain_precision_stack_frame(env, fr, i);
11923 static bool states_maybe_looping(struct bpf_verifier_state *old,
11924 struct bpf_verifier_state *cur)
11926 struct bpf_func_state *fold, *fcur;
11927 int i, fr = cur->curframe;
11929 if (old->curframe != fr)
11932 fold = old->frame[fr];
11933 fcur = cur->frame[fr];
11934 for (i = 0; i < MAX_BPF_REG; i++)
11935 if (memcmp(&fold->regs[i], &fcur->regs[i],
11936 offsetof(struct bpf_reg_state, parent)))
11942 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11944 struct bpf_verifier_state_list *new_sl;
11945 struct bpf_verifier_state_list *sl, **pprev;
11946 struct bpf_verifier_state *cur = env->cur_state, *new;
11947 int i, j, err, states_cnt = 0;
11948 bool add_new_state = env->test_state_freq ? true : false;
11950 cur->last_insn_idx = env->prev_insn_idx;
11951 if (!env->insn_aux_data[insn_idx].prune_point)
11952 /* this 'insn_idx' instruction wasn't marked, so we will not
11953 * be doing state search here
11957 /* bpf progs typically have pruning point every 4 instructions
11958 * http://vger.kernel.org/bpfconf2019.html#session-1
11959 * Do not add new state for future pruning if the verifier hasn't seen
11960 * at least 2 jumps and at least 8 instructions.
11961 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11962 * In tests that amounts to up to 50% reduction into total verifier
11963 * memory consumption and 20% verifier time speedup.
11965 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11966 env->insn_processed - env->prev_insn_processed >= 8)
11967 add_new_state = true;
11969 pprev = explored_state(env, insn_idx);
11972 clean_live_states(env, insn_idx, cur);
11976 if (sl->state.insn_idx != insn_idx)
11979 if (sl->state.branches) {
11980 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11982 if (frame->in_async_callback_fn &&
11983 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11984 /* Different async_entry_cnt means that the verifier is
11985 * processing another entry into async callback.
11986 * Seeing the same state is not an indication of infinite
11987 * loop or infinite recursion.
11988 * But finding the same state doesn't mean that it's safe
11989 * to stop processing the current state. The previous state
11990 * hasn't yet reached bpf_exit, since state.branches > 0.
11991 * Checking in_async_callback_fn alone is not enough either.
11992 * Since the verifier still needs to catch infinite loops
11993 * inside async callbacks.
11995 } else if (states_maybe_looping(&sl->state, cur) &&
11996 states_equal(env, &sl->state, cur)) {
11997 verbose_linfo(env, insn_idx, "; ");
11998 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
12001 /* if the verifier is processing a loop, avoid adding new state
12002 * too often, since different loop iterations have distinct
12003 * states and may not help future pruning.
12004 * This threshold shouldn't be too low to make sure that
12005 * a loop with large bound will be rejected quickly.
12006 * The most abusive loop will be:
12008 * if r1 < 1000000 goto pc-2
12009 * 1M insn_procssed limit / 100 == 10k peak states.
12010 * This threshold shouldn't be too high either, since states
12011 * at the end of the loop are likely to be useful in pruning.
12013 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
12014 env->insn_processed - env->prev_insn_processed < 100)
12015 add_new_state = false;
12018 if (states_equal(env, &sl->state, cur)) {
12020 /* reached equivalent register/stack state,
12021 * prune the search.
12022 * Registers read by the continuation are read by us.
12023 * If we have any write marks in env->cur_state, they
12024 * will prevent corresponding reads in the continuation
12025 * from reaching our parent (an explored_state). Our
12026 * own state will get the read marks recorded, but
12027 * they'll be immediately forgotten as we're pruning
12028 * this state and will pop a new one.
12030 err = propagate_liveness(env, &sl->state, cur);
12032 /* if previous state reached the exit with precision and
12033 * current state is equivalent to it (except precsion marks)
12034 * the precision needs to be propagated back in
12035 * the current state.
12037 err = err ? : push_jmp_history(env, cur);
12038 err = err ? : propagate_precision(env, &sl->state);
12044 /* when new state is not going to be added do not increase miss count.
12045 * Otherwise several loop iterations will remove the state
12046 * recorded earlier. The goal of these heuristics is to have
12047 * states from some iterations of the loop (some in the beginning
12048 * and some at the end) to help pruning.
12052 /* heuristic to determine whether this state is beneficial
12053 * to keep checking from state equivalence point of view.
12054 * Higher numbers increase max_states_per_insn and verification time,
12055 * but do not meaningfully decrease insn_processed.
12057 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12058 /* the state is unlikely to be useful. Remove it to
12059 * speed up verification
12062 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12063 u32 br = sl->state.branches;
12066 "BUG live_done but branches_to_explore %d\n",
12068 free_verifier_state(&sl->state, false);
12070 env->peak_states--;
12072 /* cannot free this state, since parentage chain may
12073 * walk it later. Add it for free_list instead to
12074 * be freed at the end of verification
12076 sl->next = env->free_list;
12077 env->free_list = sl;
12087 if (env->max_states_per_insn < states_cnt)
12088 env->max_states_per_insn = states_cnt;
12090 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12091 return push_jmp_history(env, cur);
12093 if (!add_new_state)
12094 return push_jmp_history(env, cur);
12096 /* There were no equivalent states, remember the current one.
12097 * Technically the current state is not proven to be safe yet,
12098 * but it will either reach outer most bpf_exit (which means it's safe)
12099 * or it will be rejected. When there are no loops the verifier won't be
12100 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12101 * again on the way to bpf_exit.
12102 * When looping the sl->state.branches will be > 0 and this state
12103 * will not be considered for equivalence until branches == 0.
12105 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12108 env->total_states++;
12109 env->peak_states++;
12110 env->prev_jmps_processed = env->jmps_processed;
12111 env->prev_insn_processed = env->insn_processed;
12113 /* add new state to the head of linked list */
12114 new = &new_sl->state;
12115 err = copy_verifier_state(new, cur);
12117 free_verifier_state(new, false);
12121 new->insn_idx = insn_idx;
12122 WARN_ONCE(new->branches != 1,
12123 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12126 cur->first_insn_idx = insn_idx;
12127 clear_jmp_history(cur);
12128 new_sl->next = *explored_state(env, insn_idx);
12129 *explored_state(env, insn_idx) = new_sl;
12130 /* connect new state to parentage chain. Current frame needs all
12131 * registers connected. Only r6 - r9 of the callers are alive (pushed
12132 * to the stack implicitly by JITs) so in callers' frames connect just
12133 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12134 * the state of the call instruction (with WRITTEN set), and r0 comes
12135 * from callee with its full parentage chain, anyway.
12137 /* clear write marks in current state: the writes we did are not writes
12138 * our child did, so they don't screen off its reads from us.
12139 * (There are no read marks in current state, because reads always mark
12140 * their parent and current state never has children yet. Only
12141 * explored_states can get read marks.)
12143 for (j = 0; j <= cur->curframe; j++) {
12144 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12145 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12146 for (i = 0; i < BPF_REG_FP; i++)
12147 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12150 /* all stack frames are accessible from callee, clear them all */
12151 for (j = 0; j <= cur->curframe; j++) {
12152 struct bpf_func_state *frame = cur->frame[j];
12153 struct bpf_func_state *newframe = new->frame[j];
12155 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12156 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12157 frame->stack[i].spilled_ptr.parent =
12158 &newframe->stack[i].spilled_ptr;
12164 /* Return true if it's OK to have the same insn return a different type. */
12165 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12167 switch (base_type(type)) {
12169 case PTR_TO_SOCKET:
12170 case PTR_TO_SOCK_COMMON:
12171 case PTR_TO_TCP_SOCK:
12172 case PTR_TO_XDP_SOCK:
12173 case PTR_TO_BTF_ID:
12180 /* If an instruction was previously used with particular pointer types, then we
12181 * need to be careful to avoid cases such as the below, where it may be ok
12182 * for one branch accessing the pointer, but not ok for the other branch:
12187 * R1 = some_other_valid_ptr;
12190 * R2 = *(u32 *)(R1 + 0);
12192 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12194 return src != prev && (!reg_type_mismatch_ok(src) ||
12195 !reg_type_mismatch_ok(prev));
12198 static int do_check(struct bpf_verifier_env *env)
12200 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12201 struct bpf_verifier_state *state = env->cur_state;
12202 struct bpf_insn *insns = env->prog->insnsi;
12203 struct bpf_reg_state *regs;
12204 int insn_cnt = env->prog->len;
12205 bool do_print_state = false;
12206 int prev_insn_idx = -1;
12209 struct bpf_insn *insn;
12213 env->prev_insn_idx = prev_insn_idx;
12214 if (env->insn_idx >= insn_cnt) {
12215 verbose(env, "invalid insn idx %d insn_cnt %d\n",
12216 env->insn_idx, insn_cnt);
12220 insn = &insns[env->insn_idx];
12221 class = BPF_CLASS(insn->code);
12223 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12225 "BPF program is too large. Processed %d insn\n",
12226 env->insn_processed);
12230 err = is_state_visited(env, env->insn_idx);
12234 /* found equivalent state, can prune the search */
12235 if (env->log.level & BPF_LOG_LEVEL) {
12236 if (do_print_state)
12237 verbose(env, "\nfrom %d to %d%s: safe\n",
12238 env->prev_insn_idx, env->insn_idx,
12239 env->cur_state->speculative ?
12240 " (speculative execution)" : "");
12242 verbose(env, "%d: safe\n", env->insn_idx);
12244 goto process_bpf_exit;
12247 if (signal_pending(current))
12250 if (need_resched())
12253 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12254 verbose(env, "\nfrom %d to %d%s:",
12255 env->prev_insn_idx, env->insn_idx,
12256 env->cur_state->speculative ?
12257 " (speculative execution)" : "");
12258 print_verifier_state(env, state->frame[state->curframe], true);
12259 do_print_state = false;
12262 if (env->log.level & BPF_LOG_LEVEL) {
12263 const struct bpf_insn_cbs cbs = {
12264 .cb_call = disasm_kfunc_name,
12265 .cb_print = verbose,
12266 .private_data = env,
12269 if (verifier_state_scratched(env))
12270 print_insn_state(env, state->frame[state->curframe]);
12272 verbose_linfo(env, env->insn_idx, "; ");
12273 env->prev_log_len = env->log.len_used;
12274 verbose(env, "%d: ", env->insn_idx);
12275 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12276 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12277 env->prev_log_len = env->log.len_used;
12280 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12281 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12282 env->prev_insn_idx);
12287 regs = cur_regs(env);
12288 sanitize_mark_insn_seen(env);
12289 prev_insn_idx = env->insn_idx;
12291 if (class == BPF_ALU || class == BPF_ALU64) {
12292 err = check_alu_op(env, insn);
12296 } else if (class == BPF_LDX) {
12297 enum bpf_reg_type *prev_src_type, src_reg_type;
12299 /* check for reserved fields is already done */
12301 /* check src operand */
12302 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12306 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12310 src_reg_type = regs[insn->src_reg].type;
12312 /* check that memory (src_reg + off) is readable,
12313 * the state of dst_reg will be updated by this func
12315 err = check_mem_access(env, env->insn_idx, insn->src_reg,
12316 insn->off, BPF_SIZE(insn->code),
12317 BPF_READ, insn->dst_reg, false);
12321 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12323 if (*prev_src_type == NOT_INIT) {
12324 /* saw a valid insn
12325 * dst_reg = *(u32 *)(src_reg + off)
12326 * save type to validate intersecting paths
12328 *prev_src_type = src_reg_type;
12330 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12331 /* ABuser program is trying to use the same insn
12332 * dst_reg = *(u32*) (src_reg + off)
12333 * with different pointer types:
12334 * src_reg == ctx in one branch and
12335 * src_reg == stack|map in some other branch.
12338 verbose(env, "same insn cannot be used with different pointers\n");
12342 } else if (class == BPF_STX) {
12343 enum bpf_reg_type *prev_dst_type, dst_reg_type;
12345 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12346 err = check_atomic(env, env->insn_idx, insn);
12353 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12354 verbose(env, "BPF_STX uses reserved fields\n");
12358 /* check src1 operand */
12359 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12362 /* check src2 operand */
12363 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12367 dst_reg_type = regs[insn->dst_reg].type;
12369 /* check that memory (dst_reg + off) is writeable */
12370 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12371 insn->off, BPF_SIZE(insn->code),
12372 BPF_WRITE, insn->src_reg, false);
12376 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12378 if (*prev_dst_type == NOT_INIT) {
12379 *prev_dst_type = dst_reg_type;
12380 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12381 verbose(env, "same insn cannot be used with different pointers\n");
12385 } else if (class == BPF_ST) {
12386 if (BPF_MODE(insn->code) != BPF_MEM ||
12387 insn->src_reg != BPF_REG_0) {
12388 verbose(env, "BPF_ST uses reserved fields\n");
12391 /* check src operand */
12392 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12396 if (is_ctx_reg(env, insn->dst_reg)) {
12397 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12399 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12403 /* check that memory (dst_reg + off) is writeable */
12404 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12405 insn->off, BPF_SIZE(insn->code),
12406 BPF_WRITE, -1, false);
12410 } else if (class == BPF_JMP || class == BPF_JMP32) {
12411 u8 opcode = BPF_OP(insn->code);
12413 env->jmps_processed++;
12414 if (opcode == BPF_CALL) {
12415 if (BPF_SRC(insn->code) != BPF_K ||
12416 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12417 && insn->off != 0) ||
12418 (insn->src_reg != BPF_REG_0 &&
12419 insn->src_reg != BPF_PSEUDO_CALL &&
12420 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12421 insn->dst_reg != BPF_REG_0 ||
12422 class == BPF_JMP32) {
12423 verbose(env, "BPF_CALL uses reserved fields\n");
12427 if (env->cur_state->active_spin_lock &&
12428 (insn->src_reg == BPF_PSEUDO_CALL ||
12429 insn->imm != BPF_FUNC_spin_unlock)) {
12430 verbose(env, "function calls are not allowed while holding a lock\n");
12433 if (insn->src_reg == BPF_PSEUDO_CALL)
12434 err = check_func_call(env, insn, &env->insn_idx);
12435 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12436 err = check_kfunc_call(env, insn, &env->insn_idx);
12438 err = check_helper_call(env, insn, &env->insn_idx);
12441 } else if (opcode == BPF_JA) {
12442 if (BPF_SRC(insn->code) != BPF_K ||
12444 insn->src_reg != BPF_REG_0 ||
12445 insn->dst_reg != BPF_REG_0 ||
12446 class == BPF_JMP32) {
12447 verbose(env, "BPF_JA uses reserved fields\n");
12451 env->insn_idx += insn->off + 1;
12454 } else if (opcode == BPF_EXIT) {
12455 if (BPF_SRC(insn->code) != BPF_K ||
12457 insn->src_reg != BPF_REG_0 ||
12458 insn->dst_reg != BPF_REG_0 ||
12459 class == BPF_JMP32) {
12460 verbose(env, "BPF_EXIT uses reserved fields\n");
12464 if (env->cur_state->active_spin_lock) {
12465 verbose(env, "bpf_spin_unlock is missing\n");
12469 /* We must do check_reference_leak here before
12470 * prepare_func_exit to handle the case when
12471 * state->curframe > 0, it may be a callback
12472 * function, for which reference_state must
12473 * match caller reference state when it exits.
12475 err = check_reference_leak(env);
12479 if (state->curframe) {
12480 /* exit from nested function */
12481 err = prepare_func_exit(env, &env->insn_idx);
12484 do_print_state = true;
12488 err = check_return_code(env);
12492 mark_verifier_state_scratched(env);
12493 update_branch_counts(env, env->cur_state);
12494 err = pop_stack(env, &prev_insn_idx,
12495 &env->insn_idx, pop_log);
12497 if (err != -ENOENT)
12501 do_print_state = true;
12505 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12509 } else if (class == BPF_LD) {
12510 u8 mode = BPF_MODE(insn->code);
12512 if (mode == BPF_ABS || mode == BPF_IND) {
12513 err = check_ld_abs(env, insn);
12517 } else if (mode == BPF_IMM) {
12518 err = check_ld_imm(env, insn);
12523 sanitize_mark_insn_seen(env);
12525 verbose(env, "invalid BPF_LD mode\n");
12529 verbose(env, "unknown insn class %d\n", class);
12539 static int find_btf_percpu_datasec(struct btf *btf)
12541 const struct btf_type *t;
12546 * Both vmlinux and module each have their own ".data..percpu"
12547 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12548 * types to look at only module's own BTF types.
12550 n = btf_nr_types(btf);
12551 if (btf_is_module(btf))
12552 i = btf_nr_types(btf_vmlinux);
12556 for(; i < n; i++) {
12557 t = btf_type_by_id(btf, i);
12558 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12561 tname = btf_name_by_offset(btf, t->name_off);
12562 if (!strcmp(tname, ".data..percpu"))
12569 /* replace pseudo btf_id with kernel symbol address */
12570 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12571 struct bpf_insn *insn,
12572 struct bpf_insn_aux_data *aux)
12574 const struct btf_var_secinfo *vsi;
12575 const struct btf_type *datasec;
12576 struct btf_mod_pair *btf_mod;
12577 const struct btf_type *t;
12578 const char *sym_name;
12579 bool percpu = false;
12580 u32 type, id = insn->imm;
12584 int i, btf_fd, err;
12586 btf_fd = insn[1].imm;
12588 btf = btf_get_by_fd(btf_fd);
12590 verbose(env, "invalid module BTF object FD specified.\n");
12594 if (!btf_vmlinux) {
12595 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12602 t = btf_type_by_id(btf, id);
12604 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12609 if (!btf_type_is_var(t)) {
12610 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12615 sym_name = btf_name_by_offset(btf, t->name_off);
12616 addr = kallsyms_lookup_name(sym_name);
12618 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12624 datasec_id = find_btf_percpu_datasec(btf);
12625 if (datasec_id > 0) {
12626 datasec = btf_type_by_id(btf, datasec_id);
12627 for_each_vsi(i, datasec, vsi) {
12628 if (vsi->type == id) {
12635 insn[0].imm = (u32)addr;
12636 insn[1].imm = addr >> 32;
12639 t = btf_type_skip_modifiers(btf, type, NULL);
12641 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12642 aux->btf_var.btf = btf;
12643 aux->btf_var.btf_id = type;
12644 } else if (!btf_type_is_struct(t)) {
12645 const struct btf_type *ret;
12649 /* resolve the type size of ksym. */
12650 ret = btf_resolve_size(btf, t, &tsize);
12652 tname = btf_name_by_offset(btf, t->name_off);
12653 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12654 tname, PTR_ERR(ret));
12658 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12659 aux->btf_var.mem_size = tsize;
12661 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12662 aux->btf_var.btf = btf;
12663 aux->btf_var.btf_id = type;
12666 /* check whether we recorded this BTF (and maybe module) already */
12667 for (i = 0; i < env->used_btf_cnt; i++) {
12668 if (env->used_btfs[i].btf == btf) {
12674 if (env->used_btf_cnt >= MAX_USED_BTFS) {
12679 btf_mod = &env->used_btfs[env->used_btf_cnt];
12680 btf_mod->btf = btf;
12681 btf_mod->module = NULL;
12683 /* if we reference variables from kernel module, bump its refcount */
12684 if (btf_is_module(btf)) {
12685 btf_mod->module = btf_try_get_module(btf);
12686 if (!btf_mod->module) {
12692 env->used_btf_cnt++;
12700 static bool is_tracing_prog_type(enum bpf_prog_type type)
12703 case BPF_PROG_TYPE_KPROBE:
12704 case BPF_PROG_TYPE_TRACEPOINT:
12705 case BPF_PROG_TYPE_PERF_EVENT:
12706 case BPF_PROG_TYPE_RAW_TRACEPOINT:
12707 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12714 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12715 struct bpf_map *map,
12716 struct bpf_prog *prog)
12719 enum bpf_prog_type prog_type = resolve_prog_type(prog);
12721 if (map_value_has_spin_lock(map)) {
12722 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12723 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12727 if (is_tracing_prog_type(prog_type)) {
12728 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12732 if (prog->aux->sleepable) {
12733 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12738 if (map_value_has_timer(map)) {
12739 if (is_tracing_prog_type(prog_type)) {
12740 verbose(env, "tracing progs cannot use bpf_timer yet\n");
12745 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12746 !bpf_offload_prog_map_match(prog, map)) {
12747 verbose(env, "offload device mismatch between prog and map\n");
12751 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12752 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12756 if (prog->aux->sleepable)
12757 switch (map->map_type) {
12758 case BPF_MAP_TYPE_HASH:
12759 case BPF_MAP_TYPE_LRU_HASH:
12760 case BPF_MAP_TYPE_ARRAY:
12761 case BPF_MAP_TYPE_PERCPU_HASH:
12762 case BPF_MAP_TYPE_PERCPU_ARRAY:
12763 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12764 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12765 case BPF_MAP_TYPE_HASH_OF_MAPS:
12766 case BPF_MAP_TYPE_RINGBUF:
12767 case BPF_MAP_TYPE_USER_RINGBUF:
12768 case BPF_MAP_TYPE_INODE_STORAGE:
12769 case BPF_MAP_TYPE_SK_STORAGE:
12770 case BPF_MAP_TYPE_TASK_STORAGE:
12774 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12781 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12783 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12784 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12787 /* find and rewrite pseudo imm in ld_imm64 instructions:
12789 * 1. if it accesses map FD, replace it with actual map pointer.
12790 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12792 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12794 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12796 struct bpf_insn *insn = env->prog->insnsi;
12797 int insn_cnt = env->prog->len;
12800 err = bpf_prog_calc_tag(env->prog);
12804 for (i = 0; i < insn_cnt; i++, insn++) {
12805 if (BPF_CLASS(insn->code) == BPF_LDX &&
12806 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12807 verbose(env, "BPF_LDX uses reserved fields\n");
12811 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12812 struct bpf_insn_aux_data *aux;
12813 struct bpf_map *map;
12818 if (i == insn_cnt - 1 || insn[1].code != 0 ||
12819 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12820 insn[1].off != 0) {
12821 verbose(env, "invalid bpf_ld_imm64 insn\n");
12825 if (insn[0].src_reg == 0)
12826 /* valid generic load 64-bit imm */
12829 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12830 aux = &env->insn_aux_data[i];
12831 err = check_pseudo_btf_id(env, insn, aux);
12837 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12838 aux = &env->insn_aux_data[i];
12839 aux->ptr_type = PTR_TO_FUNC;
12843 /* In final convert_pseudo_ld_imm64() step, this is
12844 * converted into regular 64-bit imm load insn.
12846 switch (insn[0].src_reg) {
12847 case BPF_PSEUDO_MAP_VALUE:
12848 case BPF_PSEUDO_MAP_IDX_VALUE:
12850 case BPF_PSEUDO_MAP_FD:
12851 case BPF_PSEUDO_MAP_IDX:
12852 if (insn[1].imm == 0)
12856 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12860 switch (insn[0].src_reg) {
12861 case BPF_PSEUDO_MAP_IDX_VALUE:
12862 case BPF_PSEUDO_MAP_IDX:
12863 if (bpfptr_is_null(env->fd_array)) {
12864 verbose(env, "fd_idx without fd_array is invalid\n");
12867 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12868 insn[0].imm * sizeof(fd),
12878 map = __bpf_map_get(f);
12880 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12882 return PTR_ERR(map);
12885 err = check_map_prog_compatibility(env, map, env->prog);
12891 aux = &env->insn_aux_data[i];
12892 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12893 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12894 addr = (unsigned long)map;
12896 u32 off = insn[1].imm;
12898 if (off >= BPF_MAX_VAR_OFF) {
12899 verbose(env, "direct value offset of %u is not allowed\n", off);
12904 if (!map->ops->map_direct_value_addr) {
12905 verbose(env, "no direct value access support for this map type\n");
12910 err = map->ops->map_direct_value_addr(map, &addr, off);
12912 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12913 map->value_size, off);
12918 aux->map_off = off;
12922 insn[0].imm = (u32)addr;
12923 insn[1].imm = addr >> 32;
12925 /* check whether we recorded this map already */
12926 for (j = 0; j < env->used_map_cnt; j++) {
12927 if (env->used_maps[j] == map) {
12928 aux->map_index = j;
12934 if (env->used_map_cnt >= MAX_USED_MAPS) {
12939 /* hold the map. If the program is rejected by verifier,
12940 * the map will be released by release_maps() or it
12941 * will be used by the valid program until it's unloaded
12942 * and all maps are released in free_used_maps()
12946 aux->map_index = env->used_map_cnt;
12947 env->used_maps[env->used_map_cnt++] = map;
12949 if (bpf_map_is_cgroup_storage(map) &&
12950 bpf_cgroup_storage_assign(env->prog->aux, map)) {
12951 verbose(env, "only one cgroup storage of each type is allowed\n");
12963 /* Basic sanity check before we invest more work here. */
12964 if (!bpf_opcode_in_insntable(insn->code)) {
12965 verbose(env, "unknown opcode %02x\n", insn->code);
12970 /* now all pseudo BPF_LD_IMM64 instructions load valid
12971 * 'struct bpf_map *' into a register instead of user map_fd.
12972 * These pointers will be used later by verifier to validate map access.
12977 /* drop refcnt of maps used by the rejected program */
12978 static void release_maps(struct bpf_verifier_env *env)
12980 __bpf_free_used_maps(env->prog->aux, env->used_maps,
12981 env->used_map_cnt);
12984 /* drop refcnt of maps used by the rejected program */
12985 static void release_btfs(struct bpf_verifier_env *env)
12987 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12988 env->used_btf_cnt);
12991 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12992 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12994 struct bpf_insn *insn = env->prog->insnsi;
12995 int insn_cnt = env->prog->len;
12998 for (i = 0; i < insn_cnt; i++, insn++) {
12999 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
13001 if (insn->src_reg == BPF_PSEUDO_FUNC)
13007 /* single env->prog->insni[off] instruction was replaced with the range
13008 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
13009 * [0, off) and [off, end) to new locations, so the patched range stays zero
13011 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
13012 struct bpf_insn_aux_data *new_data,
13013 struct bpf_prog *new_prog, u32 off, u32 cnt)
13015 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
13016 struct bpf_insn *insn = new_prog->insnsi;
13017 u32 old_seen = old_data[off].seen;
13021 /* aux info at OFF always needs adjustment, no matter fast path
13022 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
13023 * original insn at old prog.
13025 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
13029 prog_len = new_prog->len;
13031 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
13032 memcpy(new_data + off + cnt - 1, old_data + off,
13033 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
13034 for (i = off; i < off + cnt - 1; i++) {
13035 /* Expand insni[off]'s seen count to the patched range. */
13036 new_data[i].seen = old_seen;
13037 new_data[i].zext_dst = insn_has_def32(env, insn + i);
13039 env->insn_aux_data = new_data;
13043 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13049 /* NOTE: fake 'exit' subprog should be updated as well. */
13050 for (i = 0; i <= env->subprog_cnt; i++) {
13051 if (env->subprog_info[i].start <= off)
13053 env->subprog_info[i].start += len - 1;
13057 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13059 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13060 int i, sz = prog->aux->size_poke_tab;
13061 struct bpf_jit_poke_descriptor *desc;
13063 for (i = 0; i < sz; i++) {
13065 if (desc->insn_idx <= off)
13067 desc->insn_idx += len - 1;
13071 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13072 const struct bpf_insn *patch, u32 len)
13074 struct bpf_prog *new_prog;
13075 struct bpf_insn_aux_data *new_data = NULL;
13078 new_data = vzalloc(array_size(env->prog->len + len - 1,
13079 sizeof(struct bpf_insn_aux_data)));
13084 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13085 if (IS_ERR(new_prog)) {
13086 if (PTR_ERR(new_prog) == -ERANGE)
13088 "insn %d cannot be patched due to 16-bit range\n",
13089 env->insn_aux_data[off].orig_idx);
13093 adjust_insn_aux_data(env, new_data, new_prog, off, len);
13094 adjust_subprog_starts(env, off, len);
13095 adjust_poke_descs(new_prog, off, len);
13099 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13104 /* find first prog starting at or after off (first to remove) */
13105 for (i = 0; i < env->subprog_cnt; i++)
13106 if (env->subprog_info[i].start >= off)
13108 /* find first prog starting at or after off + cnt (first to stay) */
13109 for (j = i; j < env->subprog_cnt; j++)
13110 if (env->subprog_info[j].start >= off + cnt)
13112 /* if j doesn't start exactly at off + cnt, we are just removing
13113 * the front of previous prog
13115 if (env->subprog_info[j].start != off + cnt)
13119 struct bpf_prog_aux *aux = env->prog->aux;
13122 /* move fake 'exit' subprog as well */
13123 move = env->subprog_cnt + 1 - j;
13125 memmove(env->subprog_info + i,
13126 env->subprog_info + j,
13127 sizeof(*env->subprog_info) * move);
13128 env->subprog_cnt -= j - i;
13130 /* remove func_info */
13131 if (aux->func_info) {
13132 move = aux->func_info_cnt - j;
13134 memmove(aux->func_info + i,
13135 aux->func_info + j,
13136 sizeof(*aux->func_info) * move);
13137 aux->func_info_cnt -= j - i;
13138 /* func_info->insn_off is set after all code rewrites,
13139 * in adjust_btf_func() - no need to adjust
13143 /* convert i from "first prog to remove" to "first to adjust" */
13144 if (env->subprog_info[i].start == off)
13148 /* update fake 'exit' subprog as well */
13149 for (; i <= env->subprog_cnt; i++)
13150 env->subprog_info[i].start -= cnt;
13155 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13158 struct bpf_prog *prog = env->prog;
13159 u32 i, l_off, l_cnt, nr_linfo;
13160 struct bpf_line_info *linfo;
13162 nr_linfo = prog->aux->nr_linfo;
13166 linfo = prog->aux->linfo;
13168 /* find first line info to remove, count lines to be removed */
13169 for (i = 0; i < nr_linfo; i++)
13170 if (linfo[i].insn_off >= off)
13175 for (; i < nr_linfo; i++)
13176 if (linfo[i].insn_off < off + cnt)
13181 /* First live insn doesn't match first live linfo, it needs to "inherit"
13182 * last removed linfo. prog is already modified, so prog->len == off
13183 * means no live instructions after (tail of the program was removed).
13185 if (prog->len != off && l_cnt &&
13186 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13188 linfo[--i].insn_off = off + cnt;
13191 /* remove the line info which refer to the removed instructions */
13193 memmove(linfo + l_off, linfo + i,
13194 sizeof(*linfo) * (nr_linfo - i));
13196 prog->aux->nr_linfo -= l_cnt;
13197 nr_linfo = prog->aux->nr_linfo;
13200 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13201 for (i = l_off; i < nr_linfo; i++)
13202 linfo[i].insn_off -= cnt;
13204 /* fix up all subprogs (incl. 'exit') which start >= off */
13205 for (i = 0; i <= env->subprog_cnt; i++)
13206 if (env->subprog_info[i].linfo_idx > l_off) {
13207 /* program may have started in the removed region but
13208 * may not be fully removed
13210 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13211 env->subprog_info[i].linfo_idx -= l_cnt;
13213 env->subprog_info[i].linfo_idx = l_off;
13219 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13221 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13222 unsigned int orig_prog_len = env->prog->len;
13225 if (bpf_prog_is_dev_bound(env->prog->aux))
13226 bpf_prog_offload_remove_insns(env, off, cnt);
13228 err = bpf_remove_insns(env->prog, off, cnt);
13232 err = adjust_subprog_starts_after_remove(env, off, cnt);
13236 err = bpf_adj_linfo_after_remove(env, off, cnt);
13240 memmove(aux_data + off, aux_data + off + cnt,
13241 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13246 /* The verifier does more data flow analysis than llvm and will not
13247 * explore branches that are dead at run time. Malicious programs can
13248 * have dead code too. Therefore replace all dead at-run-time code
13251 * Just nops are not optimal, e.g. if they would sit at the end of the
13252 * program and through another bug we would manage to jump there, then
13253 * we'd execute beyond program memory otherwise. Returning exception
13254 * code also wouldn't work since we can have subprogs where the dead
13255 * code could be located.
13257 static void sanitize_dead_code(struct bpf_verifier_env *env)
13259 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13260 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13261 struct bpf_insn *insn = env->prog->insnsi;
13262 const int insn_cnt = env->prog->len;
13265 for (i = 0; i < insn_cnt; i++) {
13266 if (aux_data[i].seen)
13268 memcpy(insn + i, &trap, sizeof(trap));
13269 aux_data[i].zext_dst = false;
13273 static bool insn_is_cond_jump(u8 code)
13277 if (BPF_CLASS(code) == BPF_JMP32)
13280 if (BPF_CLASS(code) != BPF_JMP)
13284 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13287 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13289 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13290 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13291 struct bpf_insn *insn = env->prog->insnsi;
13292 const int insn_cnt = env->prog->len;
13295 for (i = 0; i < insn_cnt; i++, insn++) {
13296 if (!insn_is_cond_jump(insn->code))
13299 if (!aux_data[i + 1].seen)
13300 ja.off = insn->off;
13301 else if (!aux_data[i + 1 + insn->off].seen)
13306 if (bpf_prog_is_dev_bound(env->prog->aux))
13307 bpf_prog_offload_replace_insn(env, i, &ja);
13309 memcpy(insn, &ja, sizeof(ja));
13313 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13315 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13316 int insn_cnt = env->prog->len;
13319 for (i = 0; i < insn_cnt; i++) {
13323 while (i + j < insn_cnt && !aux_data[i + j].seen)
13328 err = verifier_remove_insns(env, i, j);
13331 insn_cnt = env->prog->len;
13337 static int opt_remove_nops(struct bpf_verifier_env *env)
13339 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13340 struct bpf_insn *insn = env->prog->insnsi;
13341 int insn_cnt = env->prog->len;
13344 for (i = 0; i < insn_cnt; i++) {
13345 if (memcmp(&insn[i], &ja, sizeof(ja)))
13348 err = verifier_remove_insns(env, i, 1);
13358 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13359 const union bpf_attr *attr)
13361 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13362 struct bpf_insn_aux_data *aux = env->insn_aux_data;
13363 int i, patch_len, delta = 0, len = env->prog->len;
13364 struct bpf_insn *insns = env->prog->insnsi;
13365 struct bpf_prog *new_prog;
13368 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13369 zext_patch[1] = BPF_ZEXT_REG(0);
13370 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13371 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13372 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13373 for (i = 0; i < len; i++) {
13374 int adj_idx = i + delta;
13375 struct bpf_insn insn;
13378 insn = insns[adj_idx];
13379 load_reg = insn_def_regno(&insn);
13380 if (!aux[adj_idx].zext_dst) {
13388 class = BPF_CLASS(code);
13389 if (load_reg == -1)
13392 /* NOTE: arg "reg" (the fourth one) is only used for
13393 * BPF_STX + SRC_OP, so it is safe to pass NULL
13396 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13397 if (class == BPF_LD &&
13398 BPF_MODE(code) == BPF_IMM)
13403 /* ctx load could be transformed into wider load. */
13404 if (class == BPF_LDX &&
13405 aux[adj_idx].ptr_type == PTR_TO_CTX)
13408 imm_rnd = get_random_u32();
13409 rnd_hi32_patch[0] = insn;
13410 rnd_hi32_patch[1].imm = imm_rnd;
13411 rnd_hi32_patch[3].dst_reg = load_reg;
13412 patch = rnd_hi32_patch;
13414 goto apply_patch_buffer;
13417 /* Add in an zero-extend instruction if a) the JIT has requested
13418 * it or b) it's a CMPXCHG.
13420 * The latter is because: BPF_CMPXCHG always loads a value into
13421 * R0, therefore always zero-extends. However some archs'
13422 * equivalent instruction only does this load when the
13423 * comparison is successful. This detail of CMPXCHG is
13424 * orthogonal to the general zero-extension behaviour of the
13425 * CPU, so it's treated independently of bpf_jit_needs_zext.
13427 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13430 /* Zero-extension is done by the caller. */
13431 if (bpf_pseudo_kfunc_call(&insn))
13434 if (WARN_ON(load_reg == -1)) {
13435 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13439 zext_patch[0] = insn;
13440 zext_patch[1].dst_reg = load_reg;
13441 zext_patch[1].src_reg = load_reg;
13442 patch = zext_patch;
13444 apply_patch_buffer:
13445 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13448 env->prog = new_prog;
13449 insns = new_prog->insnsi;
13450 aux = env->insn_aux_data;
13451 delta += patch_len - 1;
13457 /* convert load instructions that access fields of a context type into a
13458 * sequence of instructions that access fields of the underlying structure:
13459 * struct __sk_buff -> struct sk_buff
13460 * struct bpf_sock_ops -> struct sock
13462 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13464 const struct bpf_verifier_ops *ops = env->ops;
13465 int i, cnt, size, ctx_field_size, delta = 0;
13466 const int insn_cnt = env->prog->len;
13467 struct bpf_insn insn_buf[16], *insn;
13468 u32 target_size, size_default, off;
13469 struct bpf_prog *new_prog;
13470 enum bpf_access_type type;
13471 bool is_narrower_load;
13473 if (ops->gen_prologue || env->seen_direct_write) {
13474 if (!ops->gen_prologue) {
13475 verbose(env, "bpf verifier is misconfigured\n");
13478 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13480 if (cnt >= ARRAY_SIZE(insn_buf)) {
13481 verbose(env, "bpf verifier is misconfigured\n");
13484 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13488 env->prog = new_prog;
13493 if (bpf_prog_is_dev_bound(env->prog->aux))
13496 insn = env->prog->insnsi + delta;
13498 for (i = 0; i < insn_cnt; i++, insn++) {
13499 bpf_convert_ctx_access_t convert_ctx_access;
13502 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13503 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13504 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13505 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13508 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13509 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13510 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13511 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13512 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13513 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13514 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13515 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13517 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13522 if (type == BPF_WRITE &&
13523 env->insn_aux_data[i + delta].sanitize_stack_spill) {
13524 struct bpf_insn patch[] = {
13529 cnt = ARRAY_SIZE(patch);
13530 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13535 env->prog = new_prog;
13536 insn = new_prog->insnsi + i + delta;
13543 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13545 if (!ops->convert_ctx_access)
13547 convert_ctx_access = ops->convert_ctx_access;
13549 case PTR_TO_SOCKET:
13550 case PTR_TO_SOCK_COMMON:
13551 convert_ctx_access = bpf_sock_convert_ctx_access;
13553 case PTR_TO_TCP_SOCK:
13554 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13556 case PTR_TO_XDP_SOCK:
13557 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13559 case PTR_TO_BTF_ID:
13560 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13561 if (type == BPF_READ) {
13562 insn->code = BPF_LDX | BPF_PROBE_MEM |
13563 BPF_SIZE((insn)->code);
13564 env->prog->aux->num_exentries++;
13571 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13572 size = BPF_LDST_BYTES(insn);
13574 /* If the read access is a narrower load of the field,
13575 * convert to a 4/8-byte load, to minimum program type specific
13576 * convert_ctx_access changes. If conversion is successful,
13577 * we will apply proper mask to the result.
13579 is_narrower_load = size < ctx_field_size;
13580 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13582 if (is_narrower_load) {
13585 if (type == BPF_WRITE) {
13586 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13591 if (ctx_field_size == 4)
13593 else if (ctx_field_size == 8)
13594 size_code = BPF_DW;
13596 insn->off = off & ~(size_default - 1);
13597 insn->code = BPF_LDX | BPF_MEM | size_code;
13601 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13603 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13604 (ctx_field_size && !target_size)) {
13605 verbose(env, "bpf verifier is misconfigured\n");
13609 if (is_narrower_load && size < target_size) {
13610 u8 shift = bpf_ctx_narrow_access_offset(
13611 off, size, size_default) * 8;
13612 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13613 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13616 if (ctx_field_size <= 4) {
13618 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13621 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13622 (1 << size * 8) - 1);
13625 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13628 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13629 (1ULL << size * 8) - 1);
13633 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13639 /* keep walking new program and skip insns we just inserted */
13640 env->prog = new_prog;
13641 insn = new_prog->insnsi + i + delta;
13647 static int jit_subprogs(struct bpf_verifier_env *env)
13649 struct bpf_prog *prog = env->prog, **func, *tmp;
13650 int i, j, subprog_start, subprog_end = 0, len, subprog;
13651 struct bpf_map *map_ptr;
13652 struct bpf_insn *insn;
13653 void *old_bpf_func;
13654 int err, num_exentries;
13656 if (env->subprog_cnt <= 1)
13659 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13660 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13663 /* Upon error here we cannot fall back to interpreter but
13664 * need a hard reject of the program. Thus -EFAULT is
13665 * propagated in any case.
13667 subprog = find_subprog(env, i + insn->imm + 1);
13669 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13670 i + insn->imm + 1);
13673 /* temporarily remember subprog id inside insn instead of
13674 * aux_data, since next loop will split up all insns into funcs
13676 insn->off = subprog;
13677 /* remember original imm in case JIT fails and fallback
13678 * to interpreter will be needed
13680 env->insn_aux_data[i].call_imm = insn->imm;
13681 /* point imm to __bpf_call_base+1 from JITs point of view */
13683 if (bpf_pseudo_func(insn))
13684 /* jit (e.g. x86_64) may emit fewer instructions
13685 * if it learns a u32 imm is the same as a u64 imm.
13686 * Force a non zero here.
13691 err = bpf_prog_alloc_jited_linfo(prog);
13693 goto out_undo_insn;
13696 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13698 goto out_undo_insn;
13700 for (i = 0; i < env->subprog_cnt; i++) {
13701 subprog_start = subprog_end;
13702 subprog_end = env->subprog_info[i + 1].start;
13704 len = subprog_end - subprog_start;
13705 /* bpf_prog_run() doesn't call subprogs directly,
13706 * hence main prog stats include the runtime of subprogs.
13707 * subprogs don't have IDs and not reachable via prog_get_next_id
13708 * func[i]->stats will never be accessed and stays NULL
13710 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13713 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13714 len * sizeof(struct bpf_insn));
13715 func[i]->type = prog->type;
13716 func[i]->len = len;
13717 if (bpf_prog_calc_tag(func[i]))
13719 func[i]->is_func = 1;
13720 func[i]->aux->func_idx = i;
13721 /* Below members will be freed only at prog->aux */
13722 func[i]->aux->btf = prog->aux->btf;
13723 func[i]->aux->func_info = prog->aux->func_info;
13724 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13725 func[i]->aux->poke_tab = prog->aux->poke_tab;
13726 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13728 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13729 struct bpf_jit_poke_descriptor *poke;
13731 poke = &prog->aux->poke_tab[j];
13732 if (poke->insn_idx < subprog_end &&
13733 poke->insn_idx >= subprog_start)
13734 poke->aux = func[i]->aux;
13737 func[i]->aux->name[0] = 'F';
13738 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13739 func[i]->jit_requested = 1;
13740 func[i]->blinding_requested = prog->blinding_requested;
13741 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13742 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13743 func[i]->aux->linfo = prog->aux->linfo;
13744 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13745 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13746 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13748 insn = func[i]->insnsi;
13749 for (j = 0; j < func[i]->len; j++, insn++) {
13750 if (BPF_CLASS(insn->code) == BPF_LDX &&
13751 BPF_MODE(insn->code) == BPF_PROBE_MEM)
13754 func[i]->aux->num_exentries = num_exentries;
13755 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13756 func[i] = bpf_int_jit_compile(func[i]);
13757 if (!func[i]->jited) {
13764 /* at this point all bpf functions were successfully JITed
13765 * now populate all bpf_calls with correct addresses and
13766 * run last pass of JIT
13768 for (i = 0; i < env->subprog_cnt; i++) {
13769 insn = func[i]->insnsi;
13770 for (j = 0; j < func[i]->len; j++, insn++) {
13771 if (bpf_pseudo_func(insn)) {
13772 subprog = insn->off;
13773 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13774 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13777 if (!bpf_pseudo_call(insn))
13779 subprog = insn->off;
13780 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13783 /* we use the aux data to keep a list of the start addresses
13784 * of the JITed images for each function in the program
13786 * for some architectures, such as powerpc64, the imm field
13787 * might not be large enough to hold the offset of the start
13788 * address of the callee's JITed image from __bpf_call_base
13790 * in such cases, we can lookup the start address of a callee
13791 * by using its subprog id, available from the off field of
13792 * the call instruction, as an index for this list
13794 func[i]->aux->func = func;
13795 func[i]->aux->func_cnt = env->subprog_cnt;
13797 for (i = 0; i < env->subprog_cnt; i++) {
13798 old_bpf_func = func[i]->bpf_func;
13799 tmp = bpf_int_jit_compile(func[i]);
13800 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13801 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13808 /* finally lock prog and jit images for all functions and
13809 * populate kallsysm
13811 for (i = 0; i < env->subprog_cnt; i++) {
13812 bpf_prog_lock_ro(func[i]);
13813 bpf_prog_kallsyms_add(func[i]);
13816 /* Last step: make now unused interpreter insns from main
13817 * prog consistent for later dump requests, so they can
13818 * later look the same as if they were interpreted only.
13820 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13821 if (bpf_pseudo_func(insn)) {
13822 insn[0].imm = env->insn_aux_data[i].call_imm;
13823 insn[1].imm = insn->off;
13827 if (!bpf_pseudo_call(insn))
13829 insn->off = env->insn_aux_data[i].call_imm;
13830 subprog = find_subprog(env, i + insn->off + 1);
13831 insn->imm = subprog;
13835 prog->bpf_func = func[0]->bpf_func;
13836 prog->jited_len = func[0]->jited_len;
13837 prog->aux->func = func;
13838 prog->aux->func_cnt = env->subprog_cnt;
13839 bpf_prog_jit_attempt_done(prog);
13842 /* We failed JIT'ing, so at this point we need to unregister poke
13843 * descriptors from subprogs, so that kernel is not attempting to
13844 * patch it anymore as we're freeing the subprog JIT memory.
13846 for (i = 0; i < prog->aux->size_poke_tab; i++) {
13847 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13848 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13850 /* At this point we're guaranteed that poke descriptors are not
13851 * live anymore. We can just unlink its descriptor table as it's
13852 * released with the main prog.
13854 for (i = 0; i < env->subprog_cnt; i++) {
13857 func[i]->aux->poke_tab = NULL;
13858 bpf_jit_free(func[i]);
13862 /* cleanup main prog to be interpreted */
13863 prog->jit_requested = 0;
13864 prog->blinding_requested = 0;
13865 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13866 if (!bpf_pseudo_call(insn))
13869 insn->imm = env->insn_aux_data[i].call_imm;
13871 bpf_prog_jit_attempt_done(prog);
13875 static int fixup_call_args(struct bpf_verifier_env *env)
13877 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13878 struct bpf_prog *prog = env->prog;
13879 struct bpf_insn *insn = prog->insnsi;
13880 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13885 if (env->prog->jit_requested &&
13886 !bpf_prog_is_dev_bound(env->prog->aux)) {
13887 err = jit_subprogs(env);
13890 if (err == -EFAULT)
13893 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13894 if (has_kfunc_call) {
13895 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13898 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13899 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13900 * have to be rejected, since interpreter doesn't support them yet.
13902 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13905 for (i = 0; i < prog->len; i++, insn++) {
13906 if (bpf_pseudo_func(insn)) {
13907 /* When JIT fails the progs with callback calls
13908 * have to be rejected, since interpreter doesn't support them yet.
13910 verbose(env, "callbacks are not allowed in non-JITed programs\n");
13914 if (!bpf_pseudo_call(insn))
13916 depth = get_callee_stack_depth(env, insn, i);
13919 bpf_patch_call_args(insn, depth);
13926 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13927 struct bpf_insn *insn)
13929 const struct bpf_kfunc_desc *desc;
13932 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13936 /* insn->imm has the btf func_id. Replace it with
13937 * an address (relative to __bpf_base_call).
13939 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13941 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13946 insn->imm = desc->imm;
13951 /* Do various post-verification rewrites in a single program pass.
13952 * These rewrites simplify JIT and interpreter implementations.
13954 static int do_misc_fixups(struct bpf_verifier_env *env)
13956 struct bpf_prog *prog = env->prog;
13957 enum bpf_attach_type eatype = prog->expected_attach_type;
13958 enum bpf_prog_type prog_type = resolve_prog_type(prog);
13959 struct bpf_insn *insn = prog->insnsi;
13960 const struct bpf_func_proto *fn;
13961 const int insn_cnt = prog->len;
13962 const struct bpf_map_ops *ops;
13963 struct bpf_insn_aux_data *aux;
13964 struct bpf_insn insn_buf[16];
13965 struct bpf_prog *new_prog;
13966 struct bpf_map *map_ptr;
13967 int i, ret, cnt, delta = 0;
13969 for (i = 0; i < insn_cnt; i++, insn++) {
13970 /* Make divide-by-zero exceptions impossible. */
13971 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13972 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13973 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13974 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13975 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13976 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13977 struct bpf_insn *patchlet;
13978 struct bpf_insn chk_and_div[] = {
13979 /* [R,W]x div 0 -> 0 */
13980 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13981 BPF_JNE | BPF_K, insn->src_reg,
13983 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13984 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13987 struct bpf_insn chk_and_mod[] = {
13988 /* [R,W]x mod 0 -> [R,W]x */
13989 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13990 BPF_JEQ | BPF_K, insn->src_reg,
13991 0, 1 + (is64 ? 0 : 1), 0),
13993 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13994 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13997 patchlet = isdiv ? chk_and_div : chk_and_mod;
13998 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13999 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
14001 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
14006 env->prog = prog = new_prog;
14007 insn = new_prog->insnsi + i + delta;
14011 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
14012 if (BPF_CLASS(insn->code) == BPF_LD &&
14013 (BPF_MODE(insn->code) == BPF_ABS ||
14014 BPF_MODE(insn->code) == BPF_IND)) {
14015 cnt = env->ops->gen_ld_abs(insn, insn_buf);
14016 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14017 verbose(env, "bpf verifier is misconfigured\n");
14021 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14026 env->prog = prog = new_prog;
14027 insn = new_prog->insnsi + i + delta;
14031 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
14032 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
14033 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
14034 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
14035 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
14036 struct bpf_insn *patch = &insn_buf[0];
14037 bool issrc, isneg, isimm;
14040 aux = &env->insn_aux_data[i + delta];
14041 if (!aux->alu_state ||
14042 aux->alu_state == BPF_ALU_NON_POINTER)
14045 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14046 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14047 BPF_ALU_SANITIZE_SRC;
14048 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14050 off_reg = issrc ? insn->src_reg : insn->dst_reg;
14052 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14055 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14056 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14057 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14058 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14059 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14060 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14061 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14064 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14065 insn->src_reg = BPF_REG_AX;
14067 insn->code = insn->code == code_add ?
14068 code_sub : code_add;
14070 if (issrc && isneg && !isimm)
14071 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14072 cnt = patch - insn_buf;
14074 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14079 env->prog = prog = new_prog;
14080 insn = new_prog->insnsi + i + delta;
14084 if (insn->code != (BPF_JMP | BPF_CALL))
14086 if (insn->src_reg == BPF_PSEUDO_CALL)
14088 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14089 ret = fixup_kfunc_call(env, insn);
14095 if (insn->imm == BPF_FUNC_get_route_realm)
14096 prog->dst_needed = 1;
14097 if (insn->imm == BPF_FUNC_get_prandom_u32)
14098 bpf_user_rnd_init_once();
14099 if (insn->imm == BPF_FUNC_override_return)
14100 prog->kprobe_override = 1;
14101 if (insn->imm == BPF_FUNC_tail_call) {
14102 /* If we tail call into other programs, we
14103 * cannot make any assumptions since they can
14104 * be replaced dynamically during runtime in
14105 * the program array.
14107 prog->cb_access = 1;
14108 if (!allow_tail_call_in_subprogs(env))
14109 prog->aux->stack_depth = MAX_BPF_STACK;
14110 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14112 /* mark bpf_tail_call as different opcode to avoid
14113 * conditional branch in the interpreter for every normal
14114 * call and to prevent accidental JITing by JIT compiler
14115 * that doesn't support bpf_tail_call yet
14118 insn->code = BPF_JMP | BPF_TAIL_CALL;
14120 aux = &env->insn_aux_data[i + delta];
14121 if (env->bpf_capable && !prog->blinding_requested &&
14122 prog->jit_requested &&
14123 !bpf_map_key_poisoned(aux) &&
14124 !bpf_map_ptr_poisoned(aux) &&
14125 !bpf_map_ptr_unpriv(aux)) {
14126 struct bpf_jit_poke_descriptor desc = {
14127 .reason = BPF_POKE_REASON_TAIL_CALL,
14128 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14129 .tail_call.key = bpf_map_key_immediate(aux),
14130 .insn_idx = i + delta,
14133 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14135 verbose(env, "adding tail call poke descriptor failed\n");
14139 insn->imm = ret + 1;
14143 if (!bpf_map_ptr_unpriv(aux))
14146 /* instead of changing every JIT dealing with tail_call
14147 * emit two extra insns:
14148 * if (index >= max_entries) goto out;
14149 * index &= array->index_mask;
14150 * to avoid out-of-bounds cpu speculation
14152 if (bpf_map_ptr_poisoned(aux)) {
14153 verbose(env, "tail_call abusing map_ptr\n");
14157 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14158 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14159 map_ptr->max_entries, 2);
14160 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14161 container_of(map_ptr,
14164 insn_buf[2] = *insn;
14166 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14171 env->prog = prog = new_prog;
14172 insn = new_prog->insnsi + i + delta;
14176 if (insn->imm == BPF_FUNC_timer_set_callback) {
14177 /* The verifier will process callback_fn as many times as necessary
14178 * with different maps and the register states prepared by
14179 * set_timer_callback_state will be accurate.
14181 * The following use case is valid:
14182 * map1 is shared by prog1, prog2, prog3.
14183 * prog1 calls bpf_timer_init for some map1 elements
14184 * prog2 calls bpf_timer_set_callback for some map1 elements.
14185 * Those that were not bpf_timer_init-ed will return -EINVAL.
14186 * prog3 calls bpf_timer_start for some map1 elements.
14187 * Those that were not both bpf_timer_init-ed and
14188 * bpf_timer_set_callback-ed will return -EINVAL.
14190 struct bpf_insn ld_addrs[2] = {
14191 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14194 insn_buf[0] = ld_addrs[0];
14195 insn_buf[1] = ld_addrs[1];
14196 insn_buf[2] = *insn;
14199 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14204 env->prog = prog = new_prog;
14205 insn = new_prog->insnsi + i + delta;
14206 goto patch_call_imm;
14209 if (insn->imm == BPF_FUNC_task_storage_get ||
14210 insn->imm == BPF_FUNC_sk_storage_get ||
14211 insn->imm == BPF_FUNC_inode_storage_get) {
14212 if (env->prog->aux->sleepable)
14213 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14215 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14216 insn_buf[1] = *insn;
14219 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14224 env->prog = prog = new_prog;
14225 insn = new_prog->insnsi + i + delta;
14226 goto patch_call_imm;
14229 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14230 * and other inlining handlers are currently limited to 64 bit
14233 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14234 (insn->imm == BPF_FUNC_map_lookup_elem ||
14235 insn->imm == BPF_FUNC_map_update_elem ||
14236 insn->imm == BPF_FUNC_map_delete_elem ||
14237 insn->imm == BPF_FUNC_map_push_elem ||
14238 insn->imm == BPF_FUNC_map_pop_elem ||
14239 insn->imm == BPF_FUNC_map_peek_elem ||
14240 insn->imm == BPF_FUNC_redirect_map ||
14241 insn->imm == BPF_FUNC_for_each_map_elem ||
14242 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14243 aux = &env->insn_aux_data[i + delta];
14244 if (bpf_map_ptr_poisoned(aux))
14245 goto patch_call_imm;
14247 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14248 ops = map_ptr->ops;
14249 if (insn->imm == BPF_FUNC_map_lookup_elem &&
14250 ops->map_gen_lookup) {
14251 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14252 if (cnt == -EOPNOTSUPP)
14253 goto patch_map_ops_generic;
14254 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14255 verbose(env, "bpf verifier is misconfigured\n");
14259 new_prog = bpf_patch_insn_data(env, i + delta,
14265 env->prog = prog = new_prog;
14266 insn = new_prog->insnsi + i + delta;
14270 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14271 (void *(*)(struct bpf_map *map, void *key))NULL));
14272 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14273 (int (*)(struct bpf_map *map, void *key))NULL));
14274 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14275 (int (*)(struct bpf_map *map, void *key, void *value,
14277 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14278 (int (*)(struct bpf_map *map, void *value,
14280 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14281 (int (*)(struct bpf_map *map, void *value))NULL));
14282 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14283 (int (*)(struct bpf_map *map, void *value))NULL));
14284 BUILD_BUG_ON(!__same_type(ops->map_redirect,
14285 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14286 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14287 (int (*)(struct bpf_map *map,
14288 bpf_callback_t callback_fn,
14289 void *callback_ctx,
14291 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14292 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14294 patch_map_ops_generic:
14295 switch (insn->imm) {
14296 case BPF_FUNC_map_lookup_elem:
14297 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14299 case BPF_FUNC_map_update_elem:
14300 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14302 case BPF_FUNC_map_delete_elem:
14303 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14305 case BPF_FUNC_map_push_elem:
14306 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14308 case BPF_FUNC_map_pop_elem:
14309 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14311 case BPF_FUNC_map_peek_elem:
14312 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14314 case BPF_FUNC_redirect_map:
14315 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14317 case BPF_FUNC_for_each_map_elem:
14318 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14320 case BPF_FUNC_map_lookup_percpu_elem:
14321 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14325 goto patch_call_imm;
14328 /* Implement bpf_jiffies64 inline. */
14329 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14330 insn->imm == BPF_FUNC_jiffies64) {
14331 struct bpf_insn ld_jiffies_addr[2] = {
14332 BPF_LD_IMM64(BPF_REG_0,
14333 (unsigned long)&jiffies),
14336 insn_buf[0] = ld_jiffies_addr[0];
14337 insn_buf[1] = ld_jiffies_addr[1];
14338 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14342 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14348 env->prog = prog = new_prog;
14349 insn = new_prog->insnsi + i + delta;
14353 /* Implement bpf_get_func_arg inline. */
14354 if (prog_type == BPF_PROG_TYPE_TRACING &&
14355 insn->imm == BPF_FUNC_get_func_arg) {
14356 /* Load nr_args from ctx - 8 */
14357 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14358 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14359 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14360 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14361 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14362 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14363 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14364 insn_buf[7] = BPF_JMP_A(1);
14365 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14368 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14373 env->prog = prog = new_prog;
14374 insn = new_prog->insnsi + i + delta;
14378 /* Implement bpf_get_func_ret inline. */
14379 if (prog_type == BPF_PROG_TYPE_TRACING &&
14380 insn->imm == BPF_FUNC_get_func_ret) {
14381 if (eatype == BPF_TRACE_FEXIT ||
14382 eatype == BPF_MODIFY_RETURN) {
14383 /* Load nr_args from ctx - 8 */
14384 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14385 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14386 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14387 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14388 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14389 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14392 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14396 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14401 env->prog = prog = new_prog;
14402 insn = new_prog->insnsi + i + delta;
14406 /* Implement get_func_arg_cnt inline. */
14407 if (prog_type == BPF_PROG_TYPE_TRACING &&
14408 insn->imm == BPF_FUNC_get_func_arg_cnt) {
14409 /* Load nr_args from ctx - 8 */
14410 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14412 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14416 env->prog = prog = new_prog;
14417 insn = new_prog->insnsi + i + delta;
14421 /* Implement bpf_get_func_ip inline. */
14422 if (prog_type == BPF_PROG_TYPE_TRACING &&
14423 insn->imm == BPF_FUNC_get_func_ip) {
14424 /* Load IP address from ctx - 16 */
14425 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
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;
14437 fn = env->ops->get_func_proto(insn->imm, env->prog);
14438 /* all functions that have prototype and verifier allowed
14439 * programs to call them, must be real in-kernel functions
14443 "kernel subsystem misconfigured func %s#%d\n",
14444 func_id_name(insn->imm), insn->imm);
14447 insn->imm = fn->func - __bpf_call_base;
14450 /* Since poke tab is now finalized, publish aux to tracker. */
14451 for (i = 0; i < prog->aux->size_poke_tab; i++) {
14452 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14453 if (!map_ptr->ops->map_poke_track ||
14454 !map_ptr->ops->map_poke_untrack ||
14455 !map_ptr->ops->map_poke_run) {
14456 verbose(env, "bpf verifier is misconfigured\n");
14460 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14462 verbose(env, "tracking tail call prog failed\n");
14467 sort_kfunc_descs_by_imm(env->prog);
14472 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14475 u32 callback_subprogno,
14478 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14479 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14480 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14481 int reg_loop_max = BPF_REG_6;
14482 int reg_loop_cnt = BPF_REG_7;
14483 int reg_loop_ctx = BPF_REG_8;
14485 struct bpf_prog *new_prog;
14486 u32 callback_start;
14487 u32 call_insn_offset;
14488 s32 callback_offset;
14490 /* This represents an inlined version of bpf_iter.c:bpf_loop,
14491 * be careful to modify this code in sync.
14493 struct bpf_insn insn_buf[] = {
14494 /* Return error and jump to the end of the patch if
14495 * expected number of iterations is too big.
14497 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14498 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14499 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14500 /* spill R6, R7, R8 to use these as loop vars */
14501 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14502 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14503 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14504 /* initialize loop vars */
14505 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14506 BPF_MOV32_IMM(reg_loop_cnt, 0),
14507 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14509 * if reg_loop_cnt >= reg_loop_max skip the loop body
14511 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14513 * correct callback offset would be set after patching
14515 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14516 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14518 /* increment loop counter */
14519 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14520 /* jump to loop header if callback returned 0 */
14521 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14522 /* return value of bpf_loop,
14523 * set R0 to the number of iterations
14525 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14526 /* restore original values of R6, R7, R8 */
14527 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14528 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14529 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14532 *cnt = ARRAY_SIZE(insn_buf);
14533 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14537 /* callback start is known only after patching */
14538 callback_start = env->subprog_info[callback_subprogno].start;
14539 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14540 call_insn_offset = position + 12;
14541 callback_offset = callback_start - call_insn_offset - 1;
14542 new_prog->insnsi[call_insn_offset].imm = callback_offset;
14547 static bool is_bpf_loop_call(struct bpf_insn *insn)
14549 return insn->code == (BPF_JMP | BPF_CALL) &&
14550 insn->src_reg == 0 &&
14551 insn->imm == BPF_FUNC_loop;
14554 /* For all sub-programs in the program (including main) check
14555 * insn_aux_data to see if there are bpf_loop calls that require
14556 * inlining. If such calls are found the calls are replaced with a
14557 * sequence of instructions produced by `inline_bpf_loop` function and
14558 * subprog stack_depth is increased by the size of 3 registers.
14559 * This stack space is used to spill values of the R6, R7, R8. These
14560 * registers are used to store the loop bound, counter and context
14563 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14565 struct bpf_subprog_info *subprogs = env->subprog_info;
14566 int i, cur_subprog = 0, cnt, delta = 0;
14567 struct bpf_insn *insn = env->prog->insnsi;
14568 int insn_cnt = env->prog->len;
14569 u16 stack_depth = subprogs[cur_subprog].stack_depth;
14570 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14571 u16 stack_depth_extra = 0;
14573 for (i = 0; i < insn_cnt; i++, insn++) {
14574 struct bpf_loop_inline_state *inline_state =
14575 &env->insn_aux_data[i + delta].loop_inline_state;
14577 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14578 struct bpf_prog *new_prog;
14580 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14581 new_prog = inline_bpf_loop(env,
14583 -(stack_depth + stack_depth_extra),
14584 inline_state->callback_subprogno,
14590 env->prog = new_prog;
14591 insn = new_prog->insnsi + i + delta;
14594 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14595 subprogs[cur_subprog].stack_depth += stack_depth_extra;
14597 stack_depth = subprogs[cur_subprog].stack_depth;
14598 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14599 stack_depth_extra = 0;
14603 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14608 static void free_states(struct bpf_verifier_env *env)
14610 struct bpf_verifier_state_list *sl, *sln;
14613 sl = env->free_list;
14616 free_verifier_state(&sl->state, false);
14620 env->free_list = NULL;
14622 if (!env->explored_states)
14625 for (i = 0; i < state_htab_size(env); i++) {
14626 sl = env->explored_states[i];
14630 free_verifier_state(&sl->state, false);
14634 env->explored_states[i] = NULL;
14638 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14640 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14641 struct bpf_verifier_state *state;
14642 struct bpf_reg_state *regs;
14645 env->prev_linfo = NULL;
14648 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14651 state->curframe = 0;
14652 state->speculative = false;
14653 state->branches = 1;
14654 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14655 if (!state->frame[0]) {
14659 env->cur_state = state;
14660 init_func_state(env, state->frame[0],
14661 BPF_MAIN_FUNC /* callsite */,
14665 regs = state->frame[state->curframe]->regs;
14666 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14667 ret = btf_prepare_func_args(env, subprog, regs);
14670 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14671 if (regs[i].type == PTR_TO_CTX)
14672 mark_reg_known_zero(env, regs, i);
14673 else if (regs[i].type == SCALAR_VALUE)
14674 mark_reg_unknown(env, regs, i);
14675 else if (base_type(regs[i].type) == PTR_TO_MEM) {
14676 const u32 mem_size = regs[i].mem_size;
14678 mark_reg_known_zero(env, regs, i);
14679 regs[i].mem_size = mem_size;
14680 regs[i].id = ++env->id_gen;
14684 /* 1st arg to a function */
14685 regs[BPF_REG_1].type = PTR_TO_CTX;
14686 mark_reg_known_zero(env, regs, BPF_REG_1);
14687 ret = btf_check_subprog_arg_match(env, subprog, regs);
14688 if (ret == -EFAULT)
14689 /* unlikely verifier bug. abort.
14690 * ret == 0 and ret < 0 are sadly acceptable for
14691 * main() function due to backward compatibility.
14692 * Like socket filter program may be written as:
14693 * int bpf_prog(struct pt_regs *ctx)
14694 * and never dereference that ctx in the program.
14695 * 'struct pt_regs' is a type mismatch for socket
14696 * filter that should be using 'struct __sk_buff'.
14701 ret = do_check(env);
14703 /* check for NULL is necessary, since cur_state can be freed inside
14704 * do_check() under memory pressure.
14706 if (env->cur_state) {
14707 free_verifier_state(env->cur_state, true);
14708 env->cur_state = NULL;
14710 while (!pop_stack(env, NULL, NULL, false));
14711 if (!ret && pop_log)
14712 bpf_vlog_reset(&env->log, 0);
14717 /* Verify all global functions in a BPF program one by one based on their BTF.
14718 * All global functions must pass verification. Otherwise the whole program is rejected.
14729 * foo() will be verified first for R1=any_scalar_value. During verification it
14730 * will be assumed that bar() already verified successfully and call to bar()
14731 * from foo() will be checked for type match only. Later bar() will be verified
14732 * independently to check that it's safe for R1=any_scalar_value.
14734 static int do_check_subprogs(struct bpf_verifier_env *env)
14736 struct bpf_prog_aux *aux = env->prog->aux;
14739 if (!aux->func_info)
14742 for (i = 1; i < env->subprog_cnt; i++) {
14743 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14745 env->insn_idx = env->subprog_info[i].start;
14746 WARN_ON_ONCE(env->insn_idx == 0);
14747 ret = do_check_common(env, i);
14750 } else if (env->log.level & BPF_LOG_LEVEL) {
14752 "Func#%d is safe for any args that match its prototype\n",
14759 static int do_check_main(struct bpf_verifier_env *env)
14764 ret = do_check_common(env, 0);
14766 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14771 static void print_verification_stats(struct bpf_verifier_env *env)
14775 if (env->log.level & BPF_LOG_STATS) {
14776 verbose(env, "verification time %lld usec\n",
14777 div_u64(env->verification_time, 1000));
14778 verbose(env, "stack depth ");
14779 for (i = 0; i < env->subprog_cnt; i++) {
14780 u32 depth = env->subprog_info[i].stack_depth;
14782 verbose(env, "%d", depth);
14783 if (i + 1 < env->subprog_cnt)
14786 verbose(env, "\n");
14788 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14789 "total_states %d peak_states %d mark_read %d\n",
14790 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14791 env->max_states_per_insn, env->total_states,
14792 env->peak_states, env->longest_mark_read_walk);
14795 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14797 const struct btf_type *t, *func_proto;
14798 const struct bpf_struct_ops *st_ops;
14799 const struct btf_member *member;
14800 struct bpf_prog *prog = env->prog;
14801 u32 btf_id, member_idx;
14804 if (!prog->gpl_compatible) {
14805 verbose(env, "struct ops programs must have a GPL compatible license\n");
14809 btf_id = prog->aux->attach_btf_id;
14810 st_ops = bpf_struct_ops_find(btf_id);
14812 verbose(env, "attach_btf_id %u is not a supported struct\n",
14818 member_idx = prog->expected_attach_type;
14819 if (member_idx >= btf_type_vlen(t)) {
14820 verbose(env, "attach to invalid member idx %u of struct %s\n",
14821 member_idx, st_ops->name);
14825 member = &btf_type_member(t)[member_idx];
14826 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14827 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14830 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14831 mname, member_idx, st_ops->name);
14835 if (st_ops->check_member) {
14836 int err = st_ops->check_member(t, member);
14839 verbose(env, "attach to unsupported member %s of struct %s\n",
14840 mname, st_ops->name);
14845 prog->aux->attach_func_proto = func_proto;
14846 prog->aux->attach_func_name = mname;
14847 env->ops = st_ops->verifier_ops;
14851 #define SECURITY_PREFIX "security_"
14853 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14855 if (within_error_injection_list(addr) ||
14856 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14862 /* list of non-sleepable functions that are otherwise on
14863 * ALLOW_ERROR_INJECTION list
14865 BTF_SET_START(btf_non_sleepable_error_inject)
14866 /* Three functions below can be called from sleepable and non-sleepable context.
14867 * Assume non-sleepable from bpf safety point of view.
14869 BTF_ID(func, __filemap_add_folio)
14870 BTF_ID(func, should_fail_alloc_page)
14871 BTF_ID(func, should_failslab)
14872 BTF_SET_END(btf_non_sleepable_error_inject)
14874 static int check_non_sleepable_error_inject(u32 btf_id)
14876 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14879 int bpf_check_attach_target(struct bpf_verifier_log *log,
14880 const struct bpf_prog *prog,
14881 const struct bpf_prog *tgt_prog,
14883 struct bpf_attach_target_info *tgt_info)
14885 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14886 const char prefix[] = "btf_trace_";
14887 int ret = 0, subprog = -1, i;
14888 const struct btf_type *t;
14889 bool conservative = true;
14895 bpf_log(log, "Tracing programs must provide btf_id\n");
14898 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14901 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14904 t = btf_type_by_id(btf, btf_id);
14906 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14909 tname = btf_name_by_offset(btf, t->name_off);
14911 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14915 struct bpf_prog_aux *aux = tgt_prog->aux;
14917 for (i = 0; i < aux->func_info_cnt; i++)
14918 if (aux->func_info[i].type_id == btf_id) {
14922 if (subprog == -1) {
14923 bpf_log(log, "Subprog %s doesn't exist\n", tname);
14926 conservative = aux->func_info_aux[subprog].unreliable;
14927 if (prog_extension) {
14928 if (conservative) {
14930 "Cannot replace static functions\n");
14933 if (!prog->jit_requested) {
14935 "Extension programs should be JITed\n");
14939 if (!tgt_prog->jited) {
14940 bpf_log(log, "Can attach to only JITed progs\n");
14943 if (tgt_prog->type == prog->type) {
14944 /* Cannot fentry/fexit another fentry/fexit program.
14945 * Cannot attach program extension to another extension.
14946 * It's ok to attach fentry/fexit to extension program.
14948 bpf_log(log, "Cannot recursively attach\n");
14951 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14953 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14954 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14955 /* Program extensions can extend all program types
14956 * except fentry/fexit. The reason is the following.
14957 * The fentry/fexit programs are used for performance
14958 * analysis, stats and can be attached to any program
14959 * type except themselves. When extension program is
14960 * replacing XDP function it is necessary to allow
14961 * performance analysis of all functions. Both original
14962 * XDP program and its program extension. Hence
14963 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14964 * allowed. If extending of fentry/fexit was allowed it
14965 * would be possible to create long call chain
14966 * fentry->extension->fentry->extension beyond
14967 * reasonable stack size. Hence extending fentry is not
14970 bpf_log(log, "Cannot extend fentry/fexit\n");
14974 if (prog_extension) {
14975 bpf_log(log, "Cannot replace kernel functions\n");
14980 switch (prog->expected_attach_type) {
14981 case BPF_TRACE_RAW_TP:
14984 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14987 if (!btf_type_is_typedef(t)) {
14988 bpf_log(log, "attach_btf_id %u is not a typedef\n",
14992 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
14993 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
14997 tname += sizeof(prefix) - 1;
14998 t = btf_type_by_id(btf, t->type);
14999 if (!btf_type_is_ptr(t))
15000 /* should never happen in valid vmlinux build */
15002 t = btf_type_by_id(btf, t->type);
15003 if (!btf_type_is_func_proto(t))
15004 /* should never happen in valid vmlinux build */
15008 case BPF_TRACE_ITER:
15009 if (!btf_type_is_func(t)) {
15010 bpf_log(log, "attach_btf_id %u is not a function\n",
15014 t = btf_type_by_id(btf, t->type);
15015 if (!btf_type_is_func_proto(t))
15017 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15022 if (!prog_extension)
15025 case BPF_MODIFY_RETURN:
15027 case BPF_LSM_CGROUP:
15028 case BPF_TRACE_FENTRY:
15029 case BPF_TRACE_FEXIT:
15030 if (!btf_type_is_func(t)) {
15031 bpf_log(log, "attach_btf_id %u is not a function\n",
15035 if (prog_extension &&
15036 btf_check_type_match(log, prog, btf, t))
15038 t = btf_type_by_id(btf, t->type);
15039 if (!btf_type_is_func_proto(t))
15042 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15043 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15044 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15047 if (tgt_prog && conservative)
15050 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15056 addr = (long) tgt_prog->bpf_func;
15058 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15060 addr = kallsyms_lookup_name(tname);
15063 "The address of function %s cannot be found\n",
15069 if (prog->aux->sleepable) {
15071 switch (prog->type) {
15072 case BPF_PROG_TYPE_TRACING:
15073 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
15074 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15076 if (!check_non_sleepable_error_inject(btf_id) &&
15077 within_error_injection_list(addr))
15080 case BPF_PROG_TYPE_LSM:
15081 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
15082 * Only some of them are sleepable.
15084 if (bpf_lsm_is_sleepable_hook(btf_id))
15091 bpf_log(log, "%s is not sleepable\n", tname);
15094 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15096 bpf_log(log, "can't modify return codes of BPF programs\n");
15099 ret = check_attach_modify_return(addr, tname);
15101 bpf_log(log, "%s() is not modifiable\n", tname);
15108 tgt_info->tgt_addr = addr;
15109 tgt_info->tgt_name = tname;
15110 tgt_info->tgt_type = t;
15114 BTF_SET_START(btf_id_deny)
15117 BTF_ID(func, migrate_disable)
15118 BTF_ID(func, migrate_enable)
15120 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15121 BTF_ID(func, rcu_read_unlock_strict)
15123 BTF_SET_END(btf_id_deny)
15125 static int check_attach_btf_id(struct bpf_verifier_env *env)
15127 struct bpf_prog *prog = env->prog;
15128 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15129 struct bpf_attach_target_info tgt_info = {};
15130 u32 btf_id = prog->aux->attach_btf_id;
15131 struct bpf_trampoline *tr;
15135 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15136 if (prog->aux->sleepable)
15137 /* attach_btf_id checked to be zero already */
15139 verbose(env, "Syscall programs can only be sleepable\n");
15143 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15144 prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15145 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15149 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15150 return check_struct_ops_btf_id(env);
15152 if (prog->type != BPF_PROG_TYPE_TRACING &&
15153 prog->type != BPF_PROG_TYPE_LSM &&
15154 prog->type != BPF_PROG_TYPE_EXT)
15157 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15161 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15162 /* to make freplace equivalent to their targets, they need to
15163 * inherit env->ops and expected_attach_type for the rest of the
15166 env->ops = bpf_verifier_ops[tgt_prog->type];
15167 prog->expected_attach_type = tgt_prog->expected_attach_type;
15170 /* store info about the attachment target that will be used later */
15171 prog->aux->attach_func_proto = tgt_info.tgt_type;
15172 prog->aux->attach_func_name = tgt_info.tgt_name;
15175 prog->aux->saved_dst_prog_type = tgt_prog->type;
15176 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15179 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15180 prog->aux->attach_btf_trace = true;
15182 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15183 if (!bpf_iter_prog_supported(prog))
15188 if (prog->type == BPF_PROG_TYPE_LSM) {
15189 ret = bpf_lsm_verify_prog(&env->log, prog);
15192 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15193 btf_id_set_contains(&btf_id_deny, btf_id)) {
15197 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15198 tr = bpf_trampoline_get(key, &tgt_info);
15202 prog->aux->dst_trampoline = tr;
15206 struct btf *bpf_get_btf_vmlinux(void)
15208 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15209 mutex_lock(&bpf_verifier_lock);
15211 btf_vmlinux = btf_parse_vmlinux();
15212 mutex_unlock(&bpf_verifier_lock);
15214 return btf_vmlinux;
15217 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15219 u64 start_time = ktime_get_ns();
15220 struct bpf_verifier_env *env;
15221 struct bpf_verifier_log *log;
15222 int i, len, ret = -EINVAL;
15225 /* no program is valid */
15226 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15229 /* 'struct bpf_verifier_env' can be global, but since it's not small,
15230 * allocate/free it every time bpf_check() is called
15232 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15237 len = (*prog)->len;
15238 env->insn_aux_data =
15239 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15241 if (!env->insn_aux_data)
15243 for (i = 0; i < len; i++)
15244 env->insn_aux_data[i].orig_idx = i;
15246 env->ops = bpf_verifier_ops[env->prog->type];
15247 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15248 is_priv = bpf_capable();
15250 bpf_get_btf_vmlinux();
15252 /* grab the mutex to protect few globals used by verifier */
15254 mutex_lock(&bpf_verifier_lock);
15256 if (attr->log_level || attr->log_buf || attr->log_size) {
15257 /* user requested verbose verifier output
15258 * and supplied buffer to store the verification trace
15260 log->level = attr->log_level;
15261 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15262 log->len_total = attr->log_size;
15264 /* log attributes have to be sane */
15265 if (!bpf_verifier_log_attr_valid(log)) {
15271 mark_verifier_state_clean(env);
15273 if (IS_ERR(btf_vmlinux)) {
15274 /* Either gcc or pahole or kernel are broken. */
15275 verbose(env, "in-kernel BTF is malformed\n");
15276 ret = PTR_ERR(btf_vmlinux);
15277 goto skip_full_check;
15280 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15281 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15282 env->strict_alignment = true;
15283 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15284 env->strict_alignment = false;
15286 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15287 env->allow_uninit_stack = bpf_allow_uninit_stack();
15288 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15289 env->bypass_spec_v1 = bpf_bypass_spec_v1();
15290 env->bypass_spec_v4 = bpf_bypass_spec_v4();
15291 env->bpf_capable = bpf_capable();
15294 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15296 env->explored_states = kvcalloc(state_htab_size(env),
15297 sizeof(struct bpf_verifier_state_list *),
15300 if (!env->explored_states)
15301 goto skip_full_check;
15303 ret = add_subprog_and_kfunc(env);
15305 goto skip_full_check;
15307 ret = check_subprogs(env);
15309 goto skip_full_check;
15311 ret = check_btf_info(env, attr, uattr);
15313 goto skip_full_check;
15315 ret = check_attach_btf_id(env);
15317 goto skip_full_check;
15319 ret = resolve_pseudo_ldimm64(env);
15321 goto skip_full_check;
15323 if (bpf_prog_is_dev_bound(env->prog->aux)) {
15324 ret = bpf_prog_offload_verifier_prep(env->prog);
15326 goto skip_full_check;
15329 ret = check_cfg(env);
15331 goto skip_full_check;
15333 ret = do_check_subprogs(env);
15334 ret = ret ?: do_check_main(env);
15336 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15337 ret = bpf_prog_offload_finalize(env);
15340 kvfree(env->explored_states);
15343 ret = check_max_stack_depth(env);
15345 /* instruction rewrites happen after this point */
15347 ret = optimize_bpf_loop(env);
15351 opt_hard_wire_dead_code_branches(env);
15353 ret = opt_remove_dead_code(env);
15355 ret = opt_remove_nops(env);
15358 sanitize_dead_code(env);
15362 /* program is valid, convert *(u32*)(ctx + off) accesses */
15363 ret = convert_ctx_accesses(env);
15366 ret = do_misc_fixups(env);
15368 /* do 32-bit optimization after insn patching has done so those patched
15369 * insns could be handled correctly.
15371 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15372 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15373 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15378 ret = fixup_call_args(env);
15380 env->verification_time = ktime_get_ns() - start_time;
15381 print_verification_stats(env);
15382 env->prog->aux->verified_insns = env->insn_processed;
15384 if (log->level && bpf_verifier_log_full(log))
15386 if (log->level && !log->ubuf) {
15388 goto err_release_maps;
15392 goto err_release_maps;
15394 if (env->used_map_cnt) {
15395 /* if program passed verifier, update used_maps in bpf_prog_info */
15396 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15397 sizeof(env->used_maps[0]),
15400 if (!env->prog->aux->used_maps) {
15402 goto err_release_maps;
15405 memcpy(env->prog->aux->used_maps, env->used_maps,
15406 sizeof(env->used_maps[0]) * env->used_map_cnt);
15407 env->prog->aux->used_map_cnt = env->used_map_cnt;
15409 if (env->used_btf_cnt) {
15410 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15411 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15412 sizeof(env->used_btfs[0]),
15414 if (!env->prog->aux->used_btfs) {
15416 goto err_release_maps;
15419 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15420 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15421 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15423 if (env->used_map_cnt || env->used_btf_cnt) {
15424 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15425 * bpf_ld_imm64 instructions
15427 convert_pseudo_ld_imm64(env);
15430 adjust_btf_func(env);
15433 if (!env->prog->aux->used_maps)
15434 /* if we didn't copy map pointers into bpf_prog_info, release
15435 * them now. Otherwise free_used_maps() will release them.
15438 if (!env->prog->aux->used_btfs)
15441 /* extension progs temporarily inherit the attach_type of their targets
15442 for verification purposes, so set it back to zero before returning
15444 if (env->prog->type == BPF_PROG_TYPE_EXT)
15445 env->prog->expected_attach_type = 0;
15450 mutex_unlock(&bpf_verifier_lock);
15451 vfree(env->insn_aux_data);