1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3 * Copyright (c) 2016 Facebook
4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32 [_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
41 /* bpf_check() is a static code analyzer that walks eBPF program
42 * instruction by instruction and updates register/stack state.
43 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
45 * The first pass is depth-first-search to check that the program is a DAG.
46 * It rejects the following programs:
47 * - larger than BPF_MAXINSNS insns
48 * - if loop is present (detected via back-edge)
49 * - unreachable insns exist (shouldn't be a forest. program = one function)
50 * - out of bounds or malformed jumps
51 * The second pass is all possible path descent from the 1st insn.
52 * Since it's analyzing all paths through the program, the length of the
53 * analysis is limited to 64k insn, which may be hit even if total number of
54 * insn is less then 4K, but there are too many branches that change stack/regs.
55 * Number of 'branches to be analyzed' is limited to 1k
57 * On entry to each instruction, each register has a type, and the instruction
58 * changes the types of the registers depending on instruction semantics.
59 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
62 * All registers are 64-bit.
63 * R0 - return register
64 * R1-R5 argument passing registers
65 * R6-R9 callee saved registers
66 * R10 - frame pointer read-only
68 * At the start of BPF program the register R1 contains a pointer to bpf_context
69 * and has type PTR_TO_CTX.
71 * Verifier tracks arithmetic operations on pointers in case:
72 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74 * 1st insn copies R10 (which has FRAME_PTR) type into R1
75 * and 2nd arithmetic instruction is pattern matched to recognize
76 * that it wants to construct a pointer to some element within stack.
77 * So after 2nd insn, the register R1 has type PTR_TO_STACK
78 * (and -20 constant is saved for further stack bounds checking).
79 * Meaning that this reg is a pointer to stack plus known immediate constant.
81 * Most of the time the registers have SCALAR_VALUE type, which
82 * means the register has some value, but it's not a valid pointer.
83 * (like pointer plus pointer becomes SCALAR_VALUE type)
85 * When verifier sees load or store instructions the type of base register
86 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87 * four pointer types recognized by check_mem_access() function.
89 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90 * and the range of [ptr, ptr + map's value_size) is accessible.
92 * registers used to pass values to function calls are checked against
93 * function argument constraints.
95 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96 * It means that the register type passed to this function must be
97 * PTR_TO_STACK and it will be used inside the function as
98 * 'pointer to map element key'
100 * For example the argument constraints for bpf_map_lookup_elem():
101 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102 * .arg1_type = ARG_CONST_MAP_PTR,
103 * .arg2_type = ARG_PTR_TO_MAP_KEY,
105 * ret_type says that this function returns 'pointer to map elem value or null'
106 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107 * 2nd argument should be a pointer to stack, which will be used inside
108 * the helper function as a pointer to map element key.
110 * On the kernel side the helper function looks like:
111 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
113 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114 * void *key = (void *) (unsigned long) r2;
117 * here kernel can access 'key' and 'map' pointers safely, knowing that
118 * [key, key + map->key_size) bytes are valid and were initialized on
119 * the stack of eBPF program.
122 * Corresponding eBPF program may look like:
123 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
124 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
126 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127 * here verifier looks at prototype of map_lookup_elem() and sees:
128 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
131 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133 * and were initialized prior to this call.
134 * If it's ok, then verifier allows this BPF_CALL insn and looks at
135 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137 * returns either pointer to map value or NULL.
139 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140 * insn, the register holding that pointer in the true branch changes state to
141 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142 * branch. See check_cond_jmp_op().
144 * After the call R0 is set to return type of the function and registers R1-R5
145 * are set to NOT_INIT to indicate that they are no longer readable.
147 * The following reference types represent a potential reference to a kernel
148 * resource which, after first being allocated, must be checked and freed by
150 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
152 * When the verifier sees a helper call return a reference type, it allocates a
153 * pointer id for the reference and stores it in the current function state.
154 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156 * passes through a NULL-check conditional. For the branch wherein the state is
157 * changed to CONST_IMM, the verifier releases the reference.
159 * For each helper function that allocates a reference, such as
160 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161 * bpf_sk_release(). When a reference type passes into the release function,
162 * the verifier also releases the reference. If any unchecked or unreleased
163 * reference remains at the end of the program, the verifier rejects it.
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168 /* verifer state is 'st'
169 * before processing instruction 'insn_idx'
170 * and after processing instruction 'prev_insn_idx'
172 struct bpf_verifier_state st;
175 struct bpf_verifier_stack_elem *next;
176 /* length of verifier log at the time this state was pushed on stack */
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
181 #define BPF_COMPLEXITY_LIMIT_STATES 64
183 #define BPF_MAP_KEY_POISON (1ULL << 63)
184 #define BPF_MAP_KEY_SEEN (1ULL << 62)
186 #define BPF_MAP_PTR_UNPRIV 1UL
187 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
188 POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
196 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
201 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205 const struct bpf_map *map, bool unpriv)
207 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208 unpriv |= bpf_map_ptr_unpriv(aux);
209 aux->map_ptr_state = (unsigned long)map |
210 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
215 return aux->map_key_state & BPF_MAP_KEY_POISON;
218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
220 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
225 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
230 bool poisoned = bpf_map_key_poisoned(aux);
232 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
236 static bool bpf_pseudo_call(const struct bpf_insn *insn)
238 return insn->code == (BPF_JMP | BPF_CALL) &&
239 insn->src_reg == BPF_PSEUDO_CALL;
242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
244 return insn->code == (BPF_JMP | BPF_CALL) &&
245 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
248 struct bpf_call_arg_meta {
249 struct bpf_map *map_ptr;
265 struct bpf_map_value_off_desc *kptr_off_desc;
266 u8 uninit_dynptr_regno;
269 struct btf *btf_vmlinux;
271 static DEFINE_MUTEX(bpf_verifier_lock);
273 static const struct bpf_line_info *
274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
276 const struct bpf_line_info *linfo;
277 const struct bpf_prog *prog;
281 nr_linfo = prog->aux->nr_linfo;
283 if (!nr_linfo || insn_off >= prog->len)
286 linfo = prog->aux->linfo;
287 for (i = 1; i < nr_linfo; i++)
288 if (insn_off < linfo[i].insn_off)
291 return &linfo[i - 1];
294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
299 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
301 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302 "verifier log line truncated - local buffer too short\n");
304 if (log->level == BPF_LOG_KERNEL) {
305 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
307 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
311 n = min(log->len_total - log->len_used - 1, n);
313 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
323 if (!bpf_verifier_log_needed(log))
326 log->len_used = new_pos;
327 if (put_user(zero, log->ubuf + new_pos))
331 /* log_level controls verbosity level of eBPF verifier.
332 * bpf_verifier_log_write() is used to dump the verification trace to the log,
333 * so the user can figure out what's wrong with the program
335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336 const char *fmt, ...)
340 if (!bpf_verifier_log_needed(&env->log))
344 bpf_verifier_vlog(&env->log, fmt, args);
347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
351 struct bpf_verifier_env *env = private_data;
354 if (!bpf_verifier_log_needed(&env->log))
358 bpf_verifier_vlog(&env->log, fmt, args);
362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363 const char *fmt, ...)
367 if (!bpf_verifier_log_needed(log))
371 bpf_verifier_vlog(log, fmt, args);
374 EXPORT_SYMBOL_GPL(bpf_log);
376 static const char *ltrim(const char *s)
384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
386 const char *prefix_fmt, ...)
388 const struct bpf_line_info *linfo;
390 if (!bpf_verifier_log_needed(&env->log))
393 linfo = find_linfo(env, insn_off);
394 if (!linfo || linfo == env->prev_linfo)
400 va_start(args, prefix_fmt);
401 bpf_verifier_vlog(&env->log, prefix_fmt, args);
406 ltrim(btf_name_by_offset(env->prog->aux->btf,
409 env->prev_linfo = linfo;
412 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413 struct bpf_reg_state *reg,
414 struct tnum *range, const char *ctx,
415 const char *reg_name)
419 verbose(env, "At %s the register %s ", ctx, reg_name);
420 if (!tnum_is_unknown(reg->var_off)) {
421 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422 verbose(env, "has value %s", tn_buf);
424 verbose(env, "has unknown scalar value");
426 tnum_strn(tn_buf, sizeof(tn_buf), *range);
427 verbose(env, " should have been in %s\n", tn_buf);
430 static bool type_is_pkt_pointer(enum bpf_reg_type type)
432 type = base_type(type);
433 return type == PTR_TO_PACKET ||
434 type == PTR_TO_PACKET_META;
437 static bool type_is_sk_pointer(enum bpf_reg_type type)
439 return type == PTR_TO_SOCKET ||
440 type == PTR_TO_SOCK_COMMON ||
441 type == PTR_TO_TCP_SOCK ||
442 type == PTR_TO_XDP_SOCK;
445 static bool reg_type_not_null(enum bpf_reg_type type)
447 return type == PTR_TO_SOCKET ||
448 type == PTR_TO_TCP_SOCK ||
449 type == PTR_TO_MAP_VALUE ||
450 type == PTR_TO_MAP_KEY ||
451 type == PTR_TO_SOCK_COMMON;
454 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
456 return reg->type == PTR_TO_MAP_VALUE &&
457 map_value_has_spin_lock(reg->map_ptr);
460 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
462 type = base_type(type);
463 return type == PTR_TO_SOCKET || type == PTR_TO_TCP_SOCK ||
464 type == PTR_TO_MEM || type == PTR_TO_BTF_ID;
467 static bool type_is_rdonly_mem(u32 type)
469 return type & MEM_RDONLY;
472 static bool type_may_be_null(u32 type)
474 return type & PTR_MAYBE_NULL;
477 static bool is_acquire_function(enum bpf_func_id func_id,
478 const struct bpf_map *map)
480 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
482 if (func_id == BPF_FUNC_sk_lookup_tcp ||
483 func_id == BPF_FUNC_sk_lookup_udp ||
484 func_id == BPF_FUNC_skc_lookup_tcp ||
485 func_id == BPF_FUNC_ringbuf_reserve ||
486 func_id == BPF_FUNC_kptr_xchg)
489 if (func_id == BPF_FUNC_map_lookup_elem &&
490 (map_type == BPF_MAP_TYPE_SOCKMAP ||
491 map_type == BPF_MAP_TYPE_SOCKHASH))
497 static bool is_ptr_cast_function(enum bpf_func_id func_id)
499 return func_id == BPF_FUNC_tcp_sock ||
500 func_id == BPF_FUNC_sk_fullsock ||
501 func_id == BPF_FUNC_skc_to_tcp_sock ||
502 func_id == BPF_FUNC_skc_to_tcp6_sock ||
503 func_id == BPF_FUNC_skc_to_udp6_sock ||
504 func_id == BPF_FUNC_skc_to_mptcp_sock ||
505 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
506 func_id == BPF_FUNC_skc_to_tcp_request_sock;
509 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
511 return func_id == BPF_FUNC_dynptr_data;
514 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
515 const struct bpf_map *map)
517 int ref_obj_uses = 0;
519 if (is_ptr_cast_function(func_id))
521 if (is_acquire_function(func_id, map))
523 if (is_dynptr_ref_function(func_id))
526 return ref_obj_uses > 1;
529 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
531 return BPF_CLASS(insn->code) == BPF_STX &&
532 BPF_MODE(insn->code) == BPF_ATOMIC &&
533 insn->imm == BPF_CMPXCHG;
536 /* string representation of 'enum bpf_reg_type'
538 * Note that reg_type_str() can not appear more than once in a single verbose()
541 static const char *reg_type_str(struct bpf_verifier_env *env,
542 enum bpf_reg_type type)
544 char postfix[16] = {0}, prefix[32] = {0};
545 static const char * const str[] = {
547 [SCALAR_VALUE] = "scalar",
548 [PTR_TO_CTX] = "ctx",
549 [CONST_PTR_TO_MAP] = "map_ptr",
550 [PTR_TO_MAP_VALUE] = "map_value",
551 [PTR_TO_STACK] = "fp",
552 [PTR_TO_PACKET] = "pkt",
553 [PTR_TO_PACKET_META] = "pkt_meta",
554 [PTR_TO_PACKET_END] = "pkt_end",
555 [PTR_TO_FLOW_KEYS] = "flow_keys",
556 [PTR_TO_SOCKET] = "sock",
557 [PTR_TO_SOCK_COMMON] = "sock_common",
558 [PTR_TO_TCP_SOCK] = "tcp_sock",
559 [PTR_TO_TP_BUFFER] = "tp_buffer",
560 [PTR_TO_XDP_SOCK] = "xdp_sock",
561 [PTR_TO_BTF_ID] = "ptr_",
562 [PTR_TO_MEM] = "mem",
563 [PTR_TO_BUF] = "buf",
564 [PTR_TO_FUNC] = "func",
565 [PTR_TO_MAP_KEY] = "map_key",
566 [PTR_TO_DYNPTR] = "dynptr_ptr",
569 if (type & PTR_MAYBE_NULL) {
570 if (base_type(type) == PTR_TO_BTF_ID)
571 strncpy(postfix, "or_null_", 16);
573 strncpy(postfix, "_or_null", 16);
576 if (type & MEM_RDONLY)
577 strncpy(prefix, "rdonly_", 32);
578 if (type & MEM_ALLOC)
579 strncpy(prefix, "alloc_", 32);
581 strncpy(prefix, "user_", 32);
582 if (type & MEM_PERCPU)
583 strncpy(prefix, "percpu_", 32);
584 if (type & PTR_UNTRUSTED)
585 strncpy(prefix, "untrusted_", 32);
587 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
588 prefix, str[base_type(type)], postfix);
589 return env->type_str_buf;
592 static char slot_type_char[] = {
593 [STACK_INVALID] = '?',
597 [STACK_DYNPTR] = 'd',
600 static void print_liveness(struct bpf_verifier_env *env,
601 enum bpf_reg_liveness live)
603 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
605 if (live & REG_LIVE_READ)
607 if (live & REG_LIVE_WRITTEN)
609 if (live & REG_LIVE_DONE)
613 static int get_spi(s32 off)
615 return (-off - 1) / BPF_REG_SIZE;
618 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
620 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
622 /* We need to check that slots between [spi - nr_slots + 1, spi] are
623 * within [0, allocated_stack).
625 * Please note that the spi grows downwards. For example, a dynptr
626 * takes the size of two stack slots; the first slot will be at
627 * spi and the second slot will be at spi - 1.
629 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
632 static struct bpf_func_state *func(struct bpf_verifier_env *env,
633 const struct bpf_reg_state *reg)
635 struct bpf_verifier_state *cur = env->cur_state;
637 return cur->frame[reg->frameno];
640 static const char *kernel_type_name(const struct btf* btf, u32 id)
642 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
645 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
647 env->scratched_regs |= 1U << regno;
650 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
652 env->scratched_stack_slots |= 1ULL << spi;
655 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
657 return (env->scratched_regs >> regno) & 1;
660 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
662 return (env->scratched_stack_slots >> regno) & 1;
665 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
667 return env->scratched_regs || env->scratched_stack_slots;
670 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
672 env->scratched_regs = 0U;
673 env->scratched_stack_slots = 0ULL;
676 /* Used for printing the entire verifier state. */
677 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
679 env->scratched_regs = ~0U;
680 env->scratched_stack_slots = ~0ULL;
683 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
685 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
686 case DYNPTR_TYPE_LOCAL:
687 return BPF_DYNPTR_TYPE_LOCAL;
688 case DYNPTR_TYPE_RINGBUF:
689 return BPF_DYNPTR_TYPE_RINGBUF;
691 return BPF_DYNPTR_TYPE_INVALID;
695 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
697 return type == BPF_DYNPTR_TYPE_RINGBUF;
700 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
701 enum bpf_arg_type arg_type, int insn_idx)
703 struct bpf_func_state *state = func(env, reg);
704 enum bpf_dynptr_type type;
707 spi = get_spi(reg->off);
709 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
712 for (i = 0; i < BPF_REG_SIZE; i++) {
713 state->stack[spi].slot_type[i] = STACK_DYNPTR;
714 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
717 type = arg_to_dynptr_type(arg_type);
718 if (type == BPF_DYNPTR_TYPE_INVALID)
721 state->stack[spi].spilled_ptr.dynptr.first_slot = true;
722 state->stack[spi].spilled_ptr.dynptr.type = type;
723 state->stack[spi - 1].spilled_ptr.dynptr.type = type;
725 if (dynptr_type_refcounted(type)) {
726 /* The id is used to track proper releasing */
727 id = acquire_reference_state(env, insn_idx);
731 state->stack[spi].spilled_ptr.id = id;
732 state->stack[spi - 1].spilled_ptr.id = id;
738 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
740 struct bpf_func_state *state = func(env, reg);
743 spi = get_spi(reg->off);
745 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
748 for (i = 0; i < BPF_REG_SIZE; i++) {
749 state->stack[spi].slot_type[i] = STACK_INVALID;
750 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
753 /* Invalidate any slices associated with this dynptr */
754 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
755 release_reference(env, state->stack[spi].spilled_ptr.id);
756 state->stack[spi].spilled_ptr.id = 0;
757 state->stack[spi - 1].spilled_ptr.id = 0;
760 state->stack[spi].spilled_ptr.dynptr.first_slot = false;
761 state->stack[spi].spilled_ptr.dynptr.type = 0;
762 state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
767 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
769 struct bpf_func_state *state = func(env, reg);
770 int spi = get_spi(reg->off);
773 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
776 for (i = 0; i < BPF_REG_SIZE; i++) {
777 if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
778 state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
785 bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
786 struct bpf_reg_state *reg)
788 struct bpf_func_state *state = func(env, reg);
789 int spi = get_spi(reg->off);
792 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
793 !state->stack[spi].spilled_ptr.dynptr.first_slot)
796 for (i = 0; i < BPF_REG_SIZE; i++) {
797 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
798 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
805 bool is_dynptr_type_expected(struct bpf_verifier_env *env,
806 struct bpf_reg_state *reg,
807 enum bpf_arg_type arg_type)
809 struct bpf_func_state *state = func(env, reg);
810 enum bpf_dynptr_type dynptr_type;
811 int spi = get_spi(reg->off);
813 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
814 if (arg_type == ARG_PTR_TO_DYNPTR)
817 dynptr_type = arg_to_dynptr_type(arg_type);
819 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
822 /* The reg state of a pointer or a bounded scalar was saved when
823 * it was spilled to the stack.
825 static bool is_spilled_reg(const struct bpf_stack_state *stack)
827 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
830 static void scrub_spilled_slot(u8 *stype)
832 if (*stype != STACK_INVALID)
836 static void print_verifier_state(struct bpf_verifier_env *env,
837 const struct bpf_func_state *state,
840 const struct bpf_reg_state *reg;
845 verbose(env, " frame%d:", state->frameno);
846 for (i = 0; i < MAX_BPF_REG; i++) {
847 reg = &state->regs[i];
851 if (!print_all && !reg_scratched(env, i))
853 verbose(env, " R%d", i);
854 print_liveness(env, reg->live);
856 if (t == SCALAR_VALUE && reg->precise)
858 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
859 tnum_is_const(reg->var_off)) {
860 /* reg->off should be 0 for SCALAR_VALUE */
861 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
862 verbose(env, "%lld", reg->var_off.value + reg->off);
864 const char *sep = "";
866 verbose(env, "%s", reg_type_str(env, t));
867 if (base_type(t) == PTR_TO_BTF_ID)
868 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
871 * _a stands for append, was shortened to avoid multiline statements below.
872 * This macro is used to output a comma separated list of attributes.
874 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
877 verbose_a("id=%d", reg->id);
878 if (reg_type_may_be_refcounted_or_null(t) && reg->ref_obj_id)
879 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
880 if (t != SCALAR_VALUE)
881 verbose_a("off=%d", reg->off);
882 if (type_is_pkt_pointer(t))
883 verbose_a("r=%d", reg->range);
884 else if (base_type(t) == CONST_PTR_TO_MAP ||
885 base_type(t) == PTR_TO_MAP_KEY ||
886 base_type(t) == PTR_TO_MAP_VALUE)
887 verbose_a("ks=%d,vs=%d",
888 reg->map_ptr->key_size,
889 reg->map_ptr->value_size);
890 if (tnum_is_const(reg->var_off)) {
891 /* Typically an immediate SCALAR_VALUE, but
892 * could be a pointer whose offset is too big
895 verbose_a("imm=%llx", reg->var_off.value);
897 if (reg->smin_value != reg->umin_value &&
898 reg->smin_value != S64_MIN)
899 verbose_a("smin=%lld", (long long)reg->smin_value);
900 if (reg->smax_value != reg->umax_value &&
901 reg->smax_value != S64_MAX)
902 verbose_a("smax=%lld", (long long)reg->smax_value);
903 if (reg->umin_value != 0)
904 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
905 if (reg->umax_value != U64_MAX)
906 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
907 if (!tnum_is_unknown(reg->var_off)) {
910 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
911 verbose_a("var_off=%s", tn_buf);
913 if (reg->s32_min_value != reg->smin_value &&
914 reg->s32_min_value != S32_MIN)
915 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
916 if (reg->s32_max_value != reg->smax_value &&
917 reg->s32_max_value != S32_MAX)
918 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
919 if (reg->u32_min_value != reg->umin_value &&
920 reg->u32_min_value != U32_MIN)
921 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
922 if (reg->u32_max_value != reg->umax_value &&
923 reg->u32_max_value != U32_MAX)
924 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
931 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
932 char types_buf[BPF_REG_SIZE + 1];
936 for (j = 0; j < BPF_REG_SIZE; j++) {
937 if (state->stack[i].slot_type[j] != STACK_INVALID)
939 types_buf[j] = slot_type_char[
940 state->stack[i].slot_type[j]];
942 types_buf[BPF_REG_SIZE] = 0;
945 if (!print_all && !stack_slot_scratched(env, i))
947 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
948 print_liveness(env, state->stack[i].spilled_ptr.live);
949 if (is_spilled_reg(&state->stack[i])) {
950 reg = &state->stack[i].spilled_ptr;
952 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
953 if (t == SCALAR_VALUE && reg->precise)
955 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
956 verbose(env, "%lld", reg->var_off.value + reg->off);
958 verbose(env, "=%s", types_buf);
961 if (state->acquired_refs && state->refs[0].id) {
962 verbose(env, " refs=%d", state->refs[0].id);
963 for (i = 1; i < state->acquired_refs; i++)
964 if (state->refs[i].id)
965 verbose(env, ",%d", state->refs[i].id);
967 if (state->in_callback_fn)
969 if (state->in_async_callback_fn)
970 verbose(env, " async_cb");
972 mark_verifier_state_clean(env);
975 static inline u32 vlog_alignment(u32 pos)
977 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
978 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
981 static void print_insn_state(struct bpf_verifier_env *env,
982 const struct bpf_func_state *state)
984 if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
985 /* remove new line character */
986 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
987 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
989 verbose(env, "%d:", env->insn_idx);
991 print_verifier_state(env, state, false);
994 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
995 * small to hold src. This is different from krealloc since we don't want to preserve
996 * the contents of dst.
998 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1001 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1007 if (ZERO_OR_NULL_PTR(src))
1010 if (unlikely(check_mul_overflow(n, size, &bytes)))
1013 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1014 dst = krealloc(orig, alloc_bytes, flags);
1020 memcpy(dst, src, bytes);
1022 return dst ? dst : ZERO_SIZE_PTR;
1025 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1026 * small to hold new_n items. new items are zeroed out if the array grows.
1028 * Contrary to krealloc_array, does not free arr if new_n is zero.
1030 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1035 if (!new_n || old_n == new_n)
1038 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1039 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1047 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1050 return arr ? arr : ZERO_SIZE_PTR;
1053 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1055 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1056 sizeof(struct bpf_reference_state), GFP_KERNEL);
1060 dst->acquired_refs = src->acquired_refs;
1064 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1066 size_t n = src->allocated_stack / BPF_REG_SIZE;
1068 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1073 dst->allocated_stack = src->allocated_stack;
1077 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1079 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1080 sizeof(struct bpf_reference_state));
1084 state->acquired_refs = n;
1088 static int grow_stack_state(struct bpf_func_state *state, int size)
1090 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1095 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1099 state->allocated_stack = size;
1103 /* Acquire a pointer id from the env and update the state->refs to include
1104 * this new pointer reference.
1105 * On success, returns a valid pointer id to associate with the register
1106 * On failure, returns a negative errno.
1108 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1110 struct bpf_func_state *state = cur_func(env);
1111 int new_ofs = state->acquired_refs;
1114 err = resize_reference_state(state, state->acquired_refs + 1);
1118 state->refs[new_ofs].id = id;
1119 state->refs[new_ofs].insn_idx = insn_idx;
1120 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1125 /* release function corresponding to acquire_reference_state(). Idempotent. */
1126 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1130 last_idx = state->acquired_refs - 1;
1131 for (i = 0; i < state->acquired_refs; i++) {
1132 if (state->refs[i].id == ptr_id) {
1133 /* Cannot release caller references in callbacks */
1134 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1136 if (last_idx && i != last_idx)
1137 memcpy(&state->refs[i], &state->refs[last_idx],
1138 sizeof(*state->refs));
1139 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1140 state->acquired_refs--;
1147 static void free_func_state(struct bpf_func_state *state)
1152 kfree(state->stack);
1156 static void clear_jmp_history(struct bpf_verifier_state *state)
1158 kfree(state->jmp_history);
1159 state->jmp_history = NULL;
1160 state->jmp_history_cnt = 0;
1163 static void free_verifier_state(struct bpf_verifier_state *state,
1168 for (i = 0; i <= state->curframe; i++) {
1169 free_func_state(state->frame[i]);
1170 state->frame[i] = NULL;
1172 clear_jmp_history(state);
1177 /* copy verifier state from src to dst growing dst stack space
1178 * when necessary to accommodate larger src stack
1180 static int copy_func_state(struct bpf_func_state *dst,
1181 const struct bpf_func_state *src)
1185 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1186 err = copy_reference_state(dst, src);
1189 return copy_stack_state(dst, src);
1192 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1193 const struct bpf_verifier_state *src)
1195 struct bpf_func_state *dst;
1198 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1199 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1201 if (!dst_state->jmp_history)
1203 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1205 /* if dst has more stack frames then src frame, free them */
1206 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1207 free_func_state(dst_state->frame[i]);
1208 dst_state->frame[i] = NULL;
1210 dst_state->speculative = src->speculative;
1211 dst_state->curframe = src->curframe;
1212 dst_state->active_spin_lock = src->active_spin_lock;
1213 dst_state->branches = src->branches;
1214 dst_state->parent = src->parent;
1215 dst_state->first_insn_idx = src->first_insn_idx;
1216 dst_state->last_insn_idx = src->last_insn_idx;
1217 for (i = 0; i <= src->curframe; i++) {
1218 dst = dst_state->frame[i];
1220 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1223 dst_state->frame[i] = dst;
1225 err = copy_func_state(dst, src->frame[i]);
1232 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1235 u32 br = --st->branches;
1237 /* WARN_ON(br > 1) technically makes sense here,
1238 * but see comment in push_stack(), hence:
1240 WARN_ONCE((int)br < 0,
1241 "BUG update_branch_counts:branches_to_explore=%d\n",
1249 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1250 int *insn_idx, bool pop_log)
1252 struct bpf_verifier_state *cur = env->cur_state;
1253 struct bpf_verifier_stack_elem *elem, *head = env->head;
1256 if (env->head == NULL)
1260 err = copy_verifier_state(cur, &head->st);
1265 bpf_vlog_reset(&env->log, head->log_pos);
1267 *insn_idx = head->insn_idx;
1269 *prev_insn_idx = head->prev_insn_idx;
1271 free_verifier_state(&head->st, false);
1278 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1279 int insn_idx, int prev_insn_idx,
1282 struct bpf_verifier_state *cur = env->cur_state;
1283 struct bpf_verifier_stack_elem *elem;
1286 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1290 elem->insn_idx = insn_idx;
1291 elem->prev_insn_idx = prev_insn_idx;
1292 elem->next = env->head;
1293 elem->log_pos = env->log.len_used;
1296 err = copy_verifier_state(&elem->st, cur);
1299 elem->st.speculative |= speculative;
1300 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1301 verbose(env, "The sequence of %d jumps is too complex.\n",
1305 if (elem->st.parent) {
1306 ++elem->st.parent->branches;
1307 /* WARN_ON(branches > 2) technically makes sense here,
1309 * 1. speculative states will bump 'branches' for non-branch
1311 * 2. is_state_visited() heuristics may decide not to create
1312 * a new state for a sequence of branches and all such current
1313 * and cloned states will be pointing to a single parent state
1314 * which might have large 'branches' count.
1319 free_verifier_state(env->cur_state, true);
1320 env->cur_state = NULL;
1321 /* pop all elements and return */
1322 while (!pop_stack(env, NULL, NULL, false));
1326 #define CALLER_SAVED_REGS 6
1327 static const int caller_saved[CALLER_SAVED_REGS] = {
1328 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1331 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1332 struct bpf_reg_state *reg);
1334 /* This helper doesn't clear reg->id */
1335 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1337 reg->var_off = tnum_const(imm);
1338 reg->smin_value = (s64)imm;
1339 reg->smax_value = (s64)imm;
1340 reg->umin_value = imm;
1341 reg->umax_value = imm;
1343 reg->s32_min_value = (s32)imm;
1344 reg->s32_max_value = (s32)imm;
1345 reg->u32_min_value = (u32)imm;
1346 reg->u32_max_value = (u32)imm;
1349 /* Mark the unknown part of a register (variable offset or scalar value) as
1350 * known to have the value @imm.
1352 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1354 /* Clear id, off, and union(map_ptr, range) */
1355 memset(((u8 *)reg) + sizeof(reg->type), 0,
1356 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1357 ___mark_reg_known(reg, imm);
1360 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1362 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1363 reg->s32_min_value = (s32)imm;
1364 reg->s32_max_value = (s32)imm;
1365 reg->u32_min_value = (u32)imm;
1366 reg->u32_max_value = (u32)imm;
1369 /* Mark the 'variable offset' part of a register as zero. This should be
1370 * used only on registers holding a pointer type.
1372 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1374 __mark_reg_known(reg, 0);
1377 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1379 __mark_reg_known(reg, 0);
1380 reg->type = SCALAR_VALUE;
1383 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1384 struct bpf_reg_state *regs, u32 regno)
1386 if (WARN_ON(regno >= MAX_BPF_REG)) {
1387 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1388 /* Something bad happened, let's kill all regs */
1389 for (regno = 0; regno < MAX_BPF_REG; regno++)
1390 __mark_reg_not_init(env, regs + regno);
1393 __mark_reg_known_zero(regs + regno);
1396 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1398 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1399 const struct bpf_map *map = reg->map_ptr;
1401 if (map->inner_map_meta) {
1402 reg->type = CONST_PTR_TO_MAP;
1403 reg->map_ptr = map->inner_map_meta;
1404 /* transfer reg's id which is unique for every map_lookup_elem
1405 * as UID of the inner map.
1407 if (map_value_has_timer(map->inner_map_meta))
1408 reg->map_uid = reg->id;
1409 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1410 reg->type = PTR_TO_XDP_SOCK;
1411 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1412 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1413 reg->type = PTR_TO_SOCKET;
1415 reg->type = PTR_TO_MAP_VALUE;
1420 reg->type &= ~PTR_MAYBE_NULL;
1423 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1425 return type_is_pkt_pointer(reg->type);
1428 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1430 return reg_is_pkt_pointer(reg) ||
1431 reg->type == PTR_TO_PACKET_END;
1434 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1435 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1436 enum bpf_reg_type which)
1438 /* The register can already have a range from prior markings.
1439 * This is fine as long as it hasn't been advanced from its
1442 return reg->type == which &&
1445 tnum_equals_const(reg->var_off, 0);
1448 /* Reset the min/max bounds of a register */
1449 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1451 reg->smin_value = S64_MIN;
1452 reg->smax_value = S64_MAX;
1453 reg->umin_value = 0;
1454 reg->umax_value = U64_MAX;
1456 reg->s32_min_value = S32_MIN;
1457 reg->s32_max_value = S32_MAX;
1458 reg->u32_min_value = 0;
1459 reg->u32_max_value = U32_MAX;
1462 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1464 reg->smin_value = S64_MIN;
1465 reg->smax_value = S64_MAX;
1466 reg->umin_value = 0;
1467 reg->umax_value = U64_MAX;
1470 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1472 reg->s32_min_value = S32_MIN;
1473 reg->s32_max_value = S32_MAX;
1474 reg->u32_min_value = 0;
1475 reg->u32_max_value = U32_MAX;
1478 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1480 struct tnum var32_off = tnum_subreg(reg->var_off);
1482 /* min signed is max(sign bit) | min(other bits) */
1483 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1484 var32_off.value | (var32_off.mask & S32_MIN));
1485 /* max signed is min(sign bit) | max(other bits) */
1486 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1487 var32_off.value | (var32_off.mask & S32_MAX));
1488 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1489 reg->u32_max_value = min(reg->u32_max_value,
1490 (u32)(var32_off.value | var32_off.mask));
1493 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1495 /* min signed is max(sign bit) | min(other bits) */
1496 reg->smin_value = max_t(s64, reg->smin_value,
1497 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1498 /* max signed is min(sign bit) | max(other bits) */
1499 reg->smax_value = min_t(s64, reg->smax_value,
1500 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1501 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1502 reg->umax_value = min(reg->umax_value,
1503 reg->var_off.value | reg->var_off.mask);
1506 static void __update_reg_bounds(struct bpf_reg_state *reg)
1508 __update_reg32_bounds(reg);
1509 __update_reg64_bounds(reg);
1512 /* Uses signed min/max values to inform unsigned, and vice-versa */
1513 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1515 /* Learn sign from signed bounds.
1516 * If we cannot cross the sign boundary, then signed and unsigned bounds
1517 * are the same, so combine. This works even in the negative case, e.g.
1518 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1520 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1521 reg->s32_min_value = reg->u32_min_value =
1522 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1523 reg->s32_max_value = reg->u32_max_value =
1524 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1527 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1528 * boundary, so we must be careful.
1530 if ((s32)reg->u32_max_value >= 0) {
1531 /* Positive. We can't learn anything from the smin, but smax
1532 * is positive, hence safe.
1534 reg->s32_min_value = reg->u32_min_value;
1535 reg->s32_max_value = reg->u32_max_value =
1536 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1537 } else if ((s32)reg->u32_min_value < 0) {
1538 /* Negative. We can't learn anything from the smax, but smin
1539 * is negative, hence safe.
1541 reg->s32_min_value = reg->u32_min_value =
1542 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1543 reg->s32_max_value = reg->u32_max_value;
1547 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1549 /* Learn sign from signed bounds.
1550 * If we cannot cross the sign boundary, then signed and unsigned bounds
1551 * are the same, so combine. This works even in the negative case, e.g.
1552 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1554 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1555 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1557 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1561 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1562 * boundary, so we must be careful.
1564 if ((s64)reg->umax_value >= 0) {
1565 /* Positive. We can't learn anything from the smin, but smax
1566 * is positive, hence safe.
1568 reg->smin_value = reg->umin_value;
1569 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1571 } else if ((s64)reg->umin_value < 0) {
1572 /* Negative. We can't learn anything from the smax, but smin
1573 * is negative, hence safe.
1575 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1577 reg->smax_value = reg->umax_value;
1581 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1583 __reg32_deduce_bounds(reg);
1584 __reg64_deduce_bounds(reg);
1587 /* Attempts to improve var_off based on unsigned min/max information */
1588 static void __reg_bound_offset(struct bpf_reg_state *reg)
1590 struct tnum var64_off = tnum_intersect(reg->var_off,
1591 tnum_range(reg->umin_value,
1593 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
1594 tnum_range(reg->u32_min_value,
1595 reg->u32_max_value));
1597 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1600 static void reg_bounds_sync(struct bpf_reg_state *reg)
1602 /* We might have learned new bounds from the var_off. */
1603 __update_reg_bounds(reg);
1604 /* We might have learned something about the sign bit. */
1605 __reg_deduce_bounds(reg);
1606 /* We might have learned some bits from the bounds. */
1607 __reg_bound_offset(reg);
1608 /* Intersecting with the old var_off might have improved our bounds
1609 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1610 * then new var_off is (0; 0x7f...fc) which improves our umax.
1612 __update_reg_bounds(reg);
1615 static bool __reg32_bound_s64(s32 a)
1617 return a >= 0 && a <= S32_MAX;
1620 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1622 reg->umin_value = reg->u32_min_value;
1623 reg->umax_value = reg->u32_max_value;
1625 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1626 * be positive otherwise set to worse case bounds and refine later
1629 if (__reg32_bound_s64(reg->s32_min_value) &&
1630 __reg32_bound_s64(reg->s32_max_value)) {
1631 reg->smin_value = reg->s32_min_value;
1632 reg->smax_value = reg->s32_max_value;
1634 reg->smin_value = 0;
1635 reg->smax_value = U32_MAX;
1639 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1641 /* special case when 64-bit register has upper 32-bit register
1642 * zeroed. Typically happens after zext or <<32, >>32 sequence
1643 * allowing us to use 32-bit bounds directly,
1645 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1646 __reg_assign_32_into_64(reg);
1648 /* Otherwise the best we can do is push lower 32bit known and
1649 * unknown bits into register (var_off set from jmp logic)
1650 * then learn as much as possible from the 64-bit tnum
1651 * known and unknown bits. The previous smin/smax bounds are
1652 * invalid here because of jmp32 compare so mark them unknown
1653 * so they do not impact tnum bounds calculation.
1655 __mark_reg64_unbounded(reg);
1657 reg_bounds_sync(reg);
1660 static bool __reg64_bound_s32(s64 a)
1662 return a >= S32_MIN && a <= S32_MAX;
1665 static bool __reg64_bound_u32(u64 a)
1667 return a >= U32_MIN && a <= U32_MAX;
1670 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1672 __mark_reg32_unbounded(reg);
1673 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1674 reg->s32_min_value = (s32)reg->smin_value;
1675 reg->s32_max_value = (s32)reg->smax_value;
1677 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1678 reg->u32_min_value = (u32)reg->umin_value;
1679 reg->u32_max_value = (u32)reg->umax_value;
1681 reg_bounds_sync(reg);
1684 /* Mark a register as having a completely unknown (scalar) value. */
1685 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1686 struct bpf_reg_state *reg)
1689 * Clear type, id, off, and union(map_ptr, range) and
1690 * padding between 'type' and union
1692 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1693 reg->type = SCALAR_VALUE;
1694 reg->var_off = tnum_unknown;
1696 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1697 __mark_reg_unbounded(reg);
1700 static void mark_reg_unknown(struct bpf_verifier_env *env,
1701 struct bpf_reg_state *regs, u32 regno)
1703 if (WARN_ON(regno >= MAX_BPF_REG)) {
1704 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1705 /* Something bad happened, let's kill all regs except FP */
1706 for (regno = 0; regno < BPF_REG_FP; regno++)
1707 __mark_reg_not_init(env, regs + regno);
1710 __mark_reg_unknown(env, regs + regno);
1713 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1714 struct bpf_reg_state *reg)
1716 __mark_reg_unknown(env, reg);
1717 reg->type = NOT_INIT;
1720 static void mark_reg_not_init(struct bpf_verifier_env *env,
1721 struct bpf_reg_state *regs, u32 regno)
1723 if (WARN_ON(regno >= MAX_BPF_REG)) {
1724 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1725 /* Something bad happened, let's kill all regs except FP */
1726 for (regno = 0; regno < BPF_REG_FP; regno++)
1727 __mark_reg_not_init(env, regs + regno);
1730 __mark_reg_not_init(env, regs + regno);
1733 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1734 struct bpf_reg_state *regs, u32 regno,
1735 enum bpf_reg_type reg_type,
1736 struct btf *btf, u32 btf_id,
1737 enum bpf_type_flag flag)
1739 if (reg_type == SCALAR_VALUE) {
1740 mark_reg_unknown(env, regs, regno);
1743 mark_reg_known_zero(env, regs, regno);
1744 regs[regno].type = PTR_TO_BTF_ID | flag;
1745 regs[regno].btf = btf;
1746 regs[regno].btf_id = btf_id;
1749 #define DEF_NOT_SUBREG (0)
1750 static void init_reg_state(struct bpf_verifier_env *env,
1751 struct bpf_func_state *state)
1753 struct bpf_reg_state *regs = state->regs;
1756 for (i = 0; i < MAX_BPF_REG; i++) {
1757 mark_reg_not_init(env, regs, i);
1758 regs[i].live = REG_LIVE_NONE;
1759 regs[i].parent = NULL;
1760 regs[i].subreg_def = DEF_NOT_SUBREG;
1764 regs[BPF_REG_FP].type = PTR_TO_STACK;
1765 mark_reg_known_zero(env, regs, BPF_REG_FP);
1766 regs[BPF_REG_FP].frameno = state->frameno;
1769 #define BPF_MAIN_FUNC (-1)
1770 static void init_func_state(struct bpf_verifier_env *env,
1771 struct bpf_func_state *state,
1772 int callsite, int frameno, int subprogno)
1774 state->callsite = callsite;
1775 state->frameno = frameno;
1776 state->subprogno = subprogno;
1777 state->callback_ret_range = tnum_range(0, 0);
1778 init_reg_state(env, state);
1779 mark_verifier_state_scratched(env);
1782 /* Similar to push_stack(), but for async callbacks */
1783 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1784 int insn_idx, int prev_insn_idx,
1787 struct bpf_verifier_stack_elem *elem;
1788 struct bpf_func_state *frame;
1790 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1794 elem->insn_idx = insn_idx;
1795 elem->prev_insn_idx = prev_insn_idx;
1796 elem->next = env->head;
1797 elem->log_pos = env->log.len_used;
1800 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1802 "The sequence of %d jumps is too complex for async cb.\n",
1806 /* Unlike push_stack() do not copy_verifier_state().
1807 * The caller state doesn't matter.
1808 * This is async callback. It starts in a fresh stack.
1809 * Initialize it similar to do_check_common().
1811 elem->st.branches = 1;
1812 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1815 init_func_state(env, frame,
1816 BPF_MAIN_FUNC /* callsite */,
1817 0 /* frameno within this callchain */,
1818 subprog /* subprog number within this prog */);
1819 elem->st.frame[0] = frame;
1822 free_verifier_state(env->cur_state, true);
1823 env->cur_state = NULL;
1824 /* pop all elements and return */
1825 while (!pop_stack(env, NULL, NULL, false));
1831 SRC_OP, /* register is used as source operand */
1832 DST_OP, /* register is used as destination operand */
1833 DST_OP_NO_MARK /* same as above, check only, don't mark */
1836 static int cmp_subprogs(const void *a, const void *b)
1838 return ((struct bpf_subprog_info *)a)->start -
1839 ((struct bpf_subprog_info *)b)->start;
1842 static int find_subprog(struct bpf_verifier_env *env, int off)
1844 struct bpf_subprog_info *p;
1846 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1847 sizeof(env->subprog_info[0]), cmp_subprogs);
1850 return p - env->subprog_info;
1854 static int add_subprog(struct bpf_verifier_env *env, int off)
1856 int insn_cnt = env->prog->len;
1859 if (off >= insn_cnt || off < 0) {
1860 verbose(env, "call to invalid destination\n");
1863 ret = find_subprog(env, off);
1866 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1867 verbose(env, "too many subprograms\n");
1870 /* determine subprog starts. The end is one before the next starts */
1871 env->subprog_info[env->subprog_cnt++].start = off;
1872 sort(env->subprog_info, env->subprog_cnt,
1873 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1874 return env->subprog_cnt - 1;
1877 #define MAX_KFUNC_DESCS 256
1878 #define MAX_KFUNC_BTFS 256
1880 struct bpf_kfunc_desc {
1881 struct btf_func_model func_model;
1887 struct bpf_kfunc_btf {
1889 struct module *module;
1893 struct bpf_kfunc_desc_tab {
1894 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1898 struct bpf_kfunc_btf_tab {
1899 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1903 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1905 const struct bpf_kfunc_desc *d0 = a;
1906 const struct bpf_kfunc_desc *d1 = b;
1908 /* func_id is not greater than BTF_MAX_TYPE */
1909 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1912 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1914 const struct bpf_kfunc_btf *d0 = a;
1915 const struct bpf_kfunc_btf *d1 = b;
1917 return d0->offset - d1->offset;
1920 static const struct bpf_kfunc_desc *
1921 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1923 struct bpf_kfunc_desc desc = {
1927 struct bpf_kfunc_desc_tab *tab;
1929 tab = prog->aux->kfunc_tab;
1930 return bsearch(&desc, tab->descs, tab->nr_descs,
1931 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1934 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1937 struct bpf_kfunc_btf kf_btf = { .offset = offset };
1938 struct bpf_kfunc_btf_tab *tab;
1939 struct bpf_kfunc_btf *b;
1944 tab = env->prog->aux->kfunc_btf_tab;
1945 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1946 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1948 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1949 verbose(env, "too many different module BTFs\n");
1950 return ERR_PTR(-E2BIG);
1953 if (bpfptr_is_null(env->fd_array)) {
1954 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1955 return ERR_PTR(-EPROTO);
1958 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1959 offset * sizeof(btf_fd),
1961 return ERR_PTR(-EFAULT);
1963 btf = btf_get_by_fd(btf_fd);
1965 verbose(env, "invalid module BTF fd specified\n");
1969 if (!btf_is_module(btf)) {
1970 verbose(env, "BTF fd for kfunc is not a module BTF\n");
1972 return ERR_PTR(-EINVAL);
1975 mod = btf_try_get_module(btf);
1978 return ERR_PTR(-ENXIO);
1981 b = &tab->descs[tab->nr_descs++];
1986 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1987 kfunc_btf_cmp_by_off, NULL);
1992 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1997 while (tab->nr_descs--) {
1998 module_put(tab->descs[tab->nr_descs].module);
1999 btf_put(tab->descs[tab->nr_descs].btf);
2004 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2008 /* In the future, this can be allowed to increase limit
2009 * of fd index into fd_array, interpreted as u16.
2011 verbose(env, "negative offset disallowed for kernel module function call\n");
2012 return ERR_PTR(-EINVAL);
2015 return __find_kfunc_desc_btf(env, offset);
2017 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2020 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2022 const struct btf_type *func, *func_proto;
2023 struct bpf_kfunc_btf_tab *btf_tab;
2024 struct bpf_kfunc_desc_tab *tab;
2025 struct bpf_prog_aux *prog_aux;
2026 struct bpf_kfunc_desc *desc;
2027 const char *func_name;
2028 struct btf *desc_btf;
2029 unsigned long call_imm;
2033 prog_aux = env->prog->aux;
2034 tab = prog_aux->kfunc_tab;
2035 btf_tab = prog_aux->kfunc_btf_tab;
2038 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2042 if (!env->prog->jit_requested) {
2043 verbose(env, "JIT is required for calling kernel function\n");
2047 if (!bpf_jit_supports_kfunc_call()) {
2048 verbose(env, "JIT does not support calling kernel function\n");
2052 if (!env->prog->gpl_compatible) {
2053 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2057 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2060 prog_aux->kfunc_tab = tab;
2063 /* func_id == 0 is always invalid, but instead of returning an error, be
2064 * conservative and wait until the code elimination pass before returning
2065 * error, so that invalid calls that get pruned out can be in BPF programs
2066 * loaded from userspace. It is also required that offset be untouched
2069 if (!func_id && !offset)
2072 if (!btf_tab && offset) {
2073 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2076 prog_aux->kfunc_btf_tab = btf_tab;
2079 desc_btf = find_kfunc_desc_btf(env, offset);
2080 if (IS_ERR(desc_btf)) {
2081 verbose(env, "failed to find BTF for kernel function\n");
2082 return PTR_ERR(desc_btf);
2085 if (find_kfunc_desc(env->prog, func_id, offset))
2088 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2089 verbose(env, "too many different kernel function calls\n");
2093 func = btf_type_by_id(desc_btf, func_id);
2094 if (!func || !btf_type_is_func(func)) {
2095 verbose(env, "kernel btf_id %u is not a function\n",
2099 func_proto = btf_type_by_id(desc_btf, func->type);
2100 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2101 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2106 func_name = btf_name_by_offset(desc_btf, func->name_off);
2107 addr = kallsyms_lookup_name(func_name);
2109 verbose(env, "cannot find address for kernel function %s\n",
2114 call_imm = BPF_CALL_IMM(addr);
2115 /* Check whether or not the relative offset overflows desc->imm */
2116 if ((unsigned long)(s32)call_imm != call_imm) {
2117 verbose(env, "address of kernel function %s is out of range\n",
2122 desc = &tab->descs[tab->nr_descs++];
2123 desc->func_id = func_id;
2124 desc->imm = call_imm;
2125 desc->offset = offset;
2126 err = btf_distill_func_proto(&env->log, desc_btf,
2127 func_proto, func_name,
2130 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2131 kfunc_desc_cmp_by_id_off, NULL);
2135 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2137 const struct bpf_kfunc_desc *d0 = a;
2138 const struct bpf_kfunc_desc *d1 = b;
2140 if (d0->imm > d1->imm)
2142 else if (d0->imm < d1->imm)
2147 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2149 struct bpf_kfunc_desc_tab *tab;
2151 tab = prog->aux->kfunc_tab;
2155 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2156 kfunc_desc_cmp_by_imm, NULL);
2159 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2161 return !!prog->aux->kfunc_tab;
2164 const struct btf_func_model *
2165 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2166 const struct bpf_insn *insn)
2168 const struct bpf_kfunc_desc desc = {
2171 const struct bpf_kfunc_desc *res;
2172 struct bpf_kfunc_desc_tab *tab;
2174 tab = prog->aux->kfunc_tab;
2175 res = bsearch(&desc, tab->descs, tab->nr_descs,
2176 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2178 return res ? &res->func_model : NULL;
2181 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2183 struct bpf_subprog_info *subprog = env->subprog_info;
2184 struct bpf_insn *insn = env->prog->insnsi;
2185 int i, ret, insn_cnt = env->prog->len;
2187 /* Add entry function. */
2188 ret = add_subprog(env, 0);
2192 for (i = 0; i < insn_cnt; i++, insn++) {
2193 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2194 !bpf_pseudo_kfunc_call(insn))
2197 if (!env->bpf_capable) {
2198 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2202 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2203 ret = add_subprog(env, i + insn->imm + 1);
2205 ret = add_kfunc_call(env, insn->imm, insn->off);
2211 /* Add a fake 'exit' subprog which could simplify subprog iteration
2212 * logic. 'subprog_cnt' should not be increased.
2214 subprog[env->subprog_cnt].start = insn_cnt;
2216 if (env->log.level & BPF_LOG_LEVEL2)
2217 for (i = 0; i < env->subprog_cnt; i++)
2218 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2223 static int check_subprogs(struct bpf_verifier_env *env)
2225 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2226 struct bpf_subprog_info *subprog = env->subprog_info;
2227 struct bpf_insn *insn = env->prog->insnsi;
2228 int insn_cnt = env->prog->len;
2230 /* now check that all jumps are within the same subprog */
2231 subprog_start = subprog[cur_subprog].start;
2232 subprog_end = subprog[cur_subprog + 1].start;
2233 for (i = 0; i < insn_cnt; i++) {
2234 u8 code = insn[i].code;
2236 if (code == (BPF_JMP | BPF_CALL) &&
2237 insn[i].imm == BPF_FUNC_tail_call &&
2238 insn[i].src_reg != BPF_PSEUDO_CALL)
2239 subprog[cur_subprog].has_tail_call = true;
2240 if (BPF_CLASS(code) == BPF_LD &&
2241 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2242 subprog[cur_subprog].has_ld_abs = true;
2243 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2245 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2247 off = i + insn[i].off + 1;
2248 if (off < subprog_start || off >= subprog_end) {
2249 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2253 if (i == subprog_end - 1) {
2254 /* to avoid fall-through from one subprog into another
2255 * the last insn of the subprog should be either exit
2256 * or unconditional jump back
2258 if (code != (BPF_JMP | BPF_EXIT) &&
2259 code != (BPF_JMP | BPF_JA)) {
2260 verbose(env, "last insn is not an exit or jmp\n");
2263 subprog_start = subprog_end;
2265 if (cur_subprog < env->subprog_cnt)
2266 subprog_end = subprog[cur_subprog + 1].start;
2272 /* Parentage chain of this register (or stack slot) should take care of all
2273 * issues like callee-saved registers, stack slot allocation time, etc.
2275 static int mark_reg_read(struct bpf_verifier_env *env,
2276 const struct bpf_reg_state *state,
2277 struct bpf_reg_state *parent, u8 flag)
2279 bool writes = parent == state->parent; /* Observe write marks */
2283 /* if read wasn't screened by an earlier write ... */
2284 if (writes && state->live & REG_LIVE_WRITTEN)
2286 if (parent->live & REG_LIVE_DONE) {
2287 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2288 reg_type_str(env, parent->type),
2289 parent->var_off.value, parent->off);
2292 /* The first condition is more likely to be true than the
2293 * second, checked it first.
2295 if ((parent->live & REG_LIVE_READ) == flag ||
2296 parent->live & REG_LIVE_READ64)
2297 /* The parentage chain never changes and
2298 * this parent was already marked as LIVE_READ.
2299 * There is no need to keep walking the chain again and
2300 * keep re-marking all parents as LIVE_READ.
2301 * This case happens when the same register is read
2302 * multiple times without writes into it in-between.
2303 * Also, if parent has the stronger REG_LIVE_READ64 set,
2304 * then no need to set the weak REG_LIVE_READ32.
2307 /* ... then we depend on parent's value */
2308 parent->live |= flag;
2309 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2310 if (flag == REG_LIVE_READ64)
2311 parent->live &= ~REG_LIVE_READ32;
2313 parent = state->parent;
2318 if (env->longest_mark_read_walk < cnt)
2319 env->longest_mark_read_walk = cnt;
2323 /* This function is supposed to be used by the following 32-bit optimization
2324 * code only. It returns TRUE if the source or destination register operates
2325 * on 64-bit, otherwise return FALSE.
2327 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2328 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2333 class = BPF_CLASS(code);
2335 if (class == BPF_JMP) {
2336 /* BPF_EXIT for "main" will reach here. Return TRUE
2341 if (op == BPF_CALL) {
2342 /* BPF to BPF call will reach here because of marking
2343 * caller saved clobber with DST_OP_NO_MARK for which we
2344 * don't care the register def because they are anyway
2345 * marked as NOT_INIT already.
2347 if (insn->src_reg == BPF_PSEUDO_CALL)
2349 /* Helper call will reach here because of arg type
2350 * check, conservatively return TRUE.
2359 if (class == BPF_ALU64 || class == BPF_JMP ||
2360 /* BPF_END always use BPF_ALU class. */
2361 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2364 if (class == BPF_ALU || class == BPF_JMP32)
2367 if (class == BPF_LDX) {
2369 return BPF_SIZE(code) == BPF_DW;
2370 /* LDX source must be ptr. */
2374 if (class == BPF_STX) {
2375 /* BPF_STX (including atomic variants) has multiple source
2376 * operands, one of which is a ptr. Check whether the caller is
2379 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2381 return BPF_SIZE(code) == BPF_DW;
2384 if (class == BPF_LD) {
2385 u8 mode = BPF_MODE(code);
2388 if (mode == BPF_IMM)
2391 /* Both LD_IND and LD_ABS return 32-bit data. */
2395 /* Implicit ctx ptr. */
2396 if (regno == BPF_REG_6)
2399 /* Explicit source could be any width. */
2403 if (class == BPF_ST)
2404 /* The only source register for BPF_ST is a ptr. */
2407 /* Conservatively return true at default. */
2411 /* Return the regno defined by the insn, or -1. */
2412 static int insn_def_regno(const struct bpf_insn *insn)
2414 switch (BPF_CLASS(insn->code)) {
2420 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2421 (insn->imm & BPF_FETCH)) {
2422 if (insn->imm == BPF_CMPXCHG)
2425 return insn->src_reg;
2430 return insn->dst_reg;
2434 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2435 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2437 int dst_reg = insn_def_regno(insn);
2442 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2445 static void mark_insn_zext(struct bpf_verifier_env *env,
2446 struct bpf_reg_state *reg)
2448 s32 def_idx = reg->subreg_def;
2450 if (def_idx == DEF_NOT_SUBREG)
2453 env->insn_aux_data[def_idx - 1].zext_dst = true;
2454 /* The dst will be zero extended, so won't be sub-register anymore. */
2455 reg->subreg_def = DEF_NOT_SUBREG;
2458 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2459 enum reg_arg_type t)
2461 struct bpf_verifier_state *vstate = env->cur_state;
2462 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2463 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2464 struct bpf_reg_state *reg, *regs = state->regs;
2467 if (regno >= MAX_BPF_REG) {
2468 verbose(env, "R%d is invalid\n", regno);
2472 mark_reg_scratched(env, regno);
2475 rw64 = is_reg64(env, insn, regno, reg, t);
2477 /* check whether register used as source operand can be read */
2478 if (reg->type == NOT_INIT) {
2479 verbose(env, "R%d !read_ok\n", regno);
2482 /* We don't need to worry about FP liveness because it's read-only */
2483 if (regno == BPF_REG_FP)
2487 mark_insn_zext(env, reg);
2489 return mark_reg_read(env, reg, reg->parent,
2490 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2492 /* check whether register used as dest operand can be written to */
2493 if (regno == BPF_REG_FP) {
2494 verbose(env, "frame pointer is read only\n");
2497 reg->live |= REG_LIVE_WRITTEN;
2498 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2500 mark_reg_unknown(env, regs, regno);
2505 /* for any branch, call, exit record the history of jmps in the given state */
2506 static int push_jmp_history(struct bpf_verifier_env *env,
2507 struct bpf_verifier_state *cur)
2509 u32 cnt = cur->jmp_history_cnt;
2510 struct bpf_idx_pair *p;
2514 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2515 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2518 p[cnt - 1].idx = env->insn_idx;
2519 p[cnt - 1].prev_idx = env->prev_insn_idx;
2520 cur->jmp_history = p;
2521 cur->jmp_history_cnt = cnt;
2525 /* Backtrack one insn at a time. If idx is not at the top of recorded
2526 * history then previous instruction came from straight line execution.
2528 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2533 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2534 i = st->jmp_history[cnt - 1].prev_idx;
2542 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2544 const struct btf_type *func;
2545 struct btf *desc_btf;
2547 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2550 desc_btf = find_kfunc_desc_btf(data, insn->off);
2551 if (IS_ERR(desc_btf))
2554 func = btf_type_by_id(desc_btf, insn->imm);
2555 return btf_name_by_offset(desc_btf, func->name_off);
2558 /* For given verifier state backtrack_insn() is called from the last insn to
2559 * the first insn. Its purpose is to compute a bitmask of registers and
2560 * stack slots that needs precision in the parent verifier state.
2562 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2563 u32 *reg_mask, u64 *stack_mask)
2565 const struct bpf_insn_cbs cbs = {
2566 .cb_call = disasm_kfunc_name,
2567 .cb_print = verbose,
2568 .private_data = env,
2570 struct bpf_insn *insn = env->prog->insnsi + idx;
2571 u8 class = BPF_CLASS(insn->code);
2572 u8 opcode = BPF_OP(insn->code);
2573 u8 mode = BPF_MODE(insn->code);
2574 u32 dreg = 1u << insn->dst_reg;
2575 u32 sreg = 1u << insn->src_reg;
2578 if (insn->code == 0)
2580 if (env->log.level & BPF_LOG_LEVEL2) {
2581 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2582 verbose(env, "%d: ", idx);
2583 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2586 if (class == BPF_ALU || class == BPF_ALU64) {
2587 if (!(*reg_mask & dreg))
2589 if (opcode == BPF_MOV) {
2590 if (BPF_SRC(insn->code) == BPF_X) {
2592 * dreg needs precision after this insn
2593 * sreg needs precision before this insn
2599 * dreg needs precision after this insn.
2600 * Corresponding register is already marked
2601 * as precise=true in this verifier state.
2602 * No further markings in parent are necessary
2607 if (BPF_SRC(insn->code) == BPF_X) {
2609 * both dreg and sreg need precision
2614 * dreg still needs precision before this insn
2617 } else if (class == BPF_LDX) {
2618 if (!(*reg_mask & dreg))
2622 /* scalars can only be spilled into stack w/o losing precision.
2623 * Load from any other memory can be zero extended.
2624 * The desire to keep that precision is already indicated
2625 * by 'precise' mark in corresponding register of this state.
2626 * No further tracking necessary.
2628 if (insn->src_reg != BPF_REG_FP)
2631 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2632 * that [fp - off] slot contains scalar that needs to be
2633 * tracked with precision
2635 spi = (-insn->off - 1) / BPF_REG_SIZE;
2637 verbose(env, "BUG spi %d\n", spi);
2638 WARN_ONCE(1, "verifier backtracking bug");
2641 *stack_mask |= 1ull << spi;
2642 } else if (class == BPF_STX || class == BPF_ST) {
2643 if (*reg_mask & dreg)
2644 /* stx & st shouldn't be using _scalar_ dst_reg
2645 * to access memory. It means backtracking
2646 * encountered a case of pointer subtraction.
2649 /* scalars can only be spilled into stack */
2650 if (insn->dst_reg != BPF_REG_FP)
2652 spi = (-insn->off - 1) / BPF_REG_SIZE;
2654 verbose(env, "BUG spi %d\n", spi);
2655 WARN_ONCE(1, "verifier backtracking bug");
2658 if (!(*stack_mask & (1ull << spi)))
2660 *stack_mask &= ~(1ull << spi);
2661 if (class == BPF_STX)
2663 } else if (class == BPF_JMP || class == BPF_JMP32) {
2664 if (opcode == BPF_CALL) {
2665 if (insn->src_reg == BPF_PSEUDO_CALL)
2667 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
2668 * catch this error later. Make backtracking conservative
2671 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
2673 /* regular helper call sets R0 */
2675 if (*reg_mask & 0x3f) {
2676 /* if backtracing was looking for registers R1-R5
2677 * they should have been found already.
2679 verbose(env, "BUG regs %x\n", *reg_mask);
2680 WARN_ONCE(1, "verifier backtracking bug");
2683 } else if (opcode == BPF_EXIT) {
2685 } else if (BPF_SRC(insn->code) == BPF_X) {
2686 if (!(*reg_mask & (dreg | sreg)))
2689 * Both dreg and sreg need precision before
2690 * this insn. If only sreg was marked precise
2691 * before it would be equally necessary to
2692 * propagate it to dreg.
2694 *reg_mask |= (sreg | dreg);
2695 /* else dreg <cond> K
2696 * Only dreg still needs precision before
2697 * this insn, so for the K-based conditional
2698 * there is nothing new to be marked.
2701 } else if (class == BPF_LD) {
2702 if (!(*reg_mask & dreg))
2705 /* It's ld_imm64 or ld_abs or ld_ind.
2706 * For ld_imm64 no further tracking of precision
2707 * into parent is necessary
2709 if (mode == BPF_IND || mode == BPF_ABS)
2710 /* to be analyzed */
2716 /* the scalar precision tracking algorithm:
2717 * . at the start all registers have precise=false.
2718 * . scalar ranges are tracked as normal through alu and jmp insns.
2719 * . once precise value of the scalar register is used in:
2720 * . ptr + scalar alu
2721 * . if (scalar cond K|scalar)
2722 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2723 * backtrack through the verifier states and mark all registers and
2724 * stack slots with spilled constants that these scalar regisers
2725 * should be precise.
2726 * . during state pruning two registers (or spilled stack slots)
2727 * are equivalent if both are not precise.
2729 * Note the verifier cannot simply walk register parentage chain,
2730 * since many different registers and stack slots could have been
2731 * used to compute single precise scalar.
2733 * The approach of starting with precise=true for all registers and then
2734 * backtrack to mark a register as not precise when the verifier detects
2735 * that program doesn't care about specific value (e.g., when helper
2736 * takes register as ARG_ANYTHING parameter) is not safe.
2738 * It's ok to walk single parentage chain of the verifier states.
2739 * It's possible that this backtracking will go all the way till 1st insn.
2740 * All other branches will be explored for needing precision later.
2742 * The backtracking needs to deal with cases like:
2743 * R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
2746 * if r5 > 0x79f goto pc+7
2747 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2750 * call bpf_perf_event_output#25
2751 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2755 * call foo // uses callee's r6 inside to compute r0
2759 * to track above reg_mask/stack_mask needs to be independent for each frame.
2761 * Also if parent's curframe > frame where backtracking started,
2762 * the verifier need to mark registers in both frames, otherwise callees
2763 * may incorrectly prune callers. This is similar to
2764 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2766 * For now backtracking falls back into conservative marking.
2768 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2769 struct bpf_verifier_state *st)
2771 struct bpf_func_state *func;
2772 struct bpf_reg_state *reg;
2775 /* big hammer: mark all scalars precise in this path.
2776 * pop_stack may still get !precise scalars.
2778 for (; st; st = st->parent)
2779 for (i = 0; i <= st->curframe; i++) {
2780 func = st->frame[i];
2781 for (j = 0; j < BPF_REG_FP; j++) {
2782 reg = &func->regs[j];
2783 if (reg->type != SCALAR_VALUE)
2785 reg->precise = true;
2787 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2788 if (!is_spilled_reg(&func->stack[j]))
2790 reg = &func->stack[j].spilled_ptr;
2791 if (reg->type != SCALAR_VALUE)
2793 reg->precise = true;
2798 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2801 struct bpf_verifier_state *st = env->cur_state;
2802 int first_idx = st->first_insn_idx;
2803 int last_idx = env->insn_idx;
2804 struct bpf_func_state *func;
2805 struct bpf_reg_state *reg;
2806 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2807 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2808 bool skip_first = true;
2809 bool new_marks = false;
2812 if (!env->bpf_capable)
2815 func = st->frame[frame];
2817 reg = &func->regs[regno];
2818 if (reg->type != SCALAR_VALUE) {
2819 WARN_ONCE(1, "backtracing misuse");
2826 reg->precise = true;
2830 if (!is_spilled_reg(&func->stack[spi])) {
2834 reg = &func->stack[spi].spilled_ptr;
2835 if (reg->type != SCALAR_VALUE) {
2843 reg->precise = true;
2849 if (!reg_mask && !stack_mask)
2852 DECLARE_BITMAP(mask, 64);
2853 u32 history = st->jmp_history_cnt;
2855 if (env->log.level & BPF_LOG_LEVEL2)
2856 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2857 for (i = last_idx;;) {
2862 err = backtrack_insn(env, i, ®_mask, &stack_mask);
2864 if (err == -ENOTSUPP) {
2865 mark_all_scalars_precise(env, st);
2870 if (!reg_mask && !stack_mask)
2871 /* Found assignment(s) into tracked register in this state.
2872 * Since this state is already marked, just return.
2873 * Nothing to be tracked further in the parent state.
2878 i = get_prev_insn_idx(st, i, &history);
2879 if (i >= env->prog->len) {
2880 /* This can happen if backtracking reached insn 0
2881 * and there are still reg_mask or stack_mask
2883 * It means the backtracking missed the spot where
2884 * particular register was initialized with a constant.
2886 verbose(env, "BUG backtracking idx %d\n", i);
2887 WARN_ONCE(1, "verifier backtracking bug");
2896 func = st->frame[frame];
2897 bitmap_from_u64(mask, reg_mask);
2898 for_each_set_bit(i, mask, 32) {
2899 reg = &func->regs[i];
2900 if (reg->type != SCALAR_VALUE) {
2901 reg_mask &= ~(1u << i);
2906 reg->precise = true;
2909 bitmap_from_u64(mask, stack_mask);
2910 for_each_set_bit(i, mask, 64) {
2911 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2912 /* the sequence of instructions:
2914 * 3: (7b) *(u64 *)(r3 -8) = r0
2915 * 4: (79) r4 = *(u64 *)(r10 -8)
2916 * doesn't contain jmps. It's backtracked
2917 * as a single block.
2918 * During backtracking insn 3 is not recognized as
2919 * stack access, so at the end of backtracking
2920 * stack slot fp-8 is still marked in stack_mask.
2921 * However the parent state may not have accessed
2922 * fp-8 and it's "unallocated" stack space.
2923 * In such case fallback to conservative.
2925 mark_all_scalars_precise(env, st);
2929 if (!is_spilled_reg(&func->stack[i])) {
2930 stack_mask &= ~(1ull << i);
2933 reg = &func->stack[i].spilled_ptr;
2934 if (reg->type != SCALAR_VALUE) {
2935 stack_mask &= ~(1ull << i);
2940 reg->precise = true;
2942 if (env->log.level & BPF_LOG_LEVEL2) {
2943 verbose(env, "parent %s regs=%x stack=%llx marks:",
2944 new_marks ? "didn't have" : "already had",
2945 reg_mask, stack_mask);
2946 print_verifier_state(env, func, true);
2949 if (!reg_mask && !stack_mask)
2954 last_idx = st->last_insn_idx;
2955 first_idx = st->first_insn_idx;
2960 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2962 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2965 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2967 return __mark_chain_precision(env, frame, regno, -1);
2970 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2972 return __mark_chain_precision(env, frame, -1, spi);
2975 static bool is_spillable_regtype(enum bpf_reg_type type)
2977 switch (base_type(type)) {
2978 case PTR_TO_MAP_VALUE:
2982 case PTR_TO_PACKET_META:
2983 case PTR_TO_PACKET_END:
2984 case PTR_TO_FLOW_KEYS:
2985 case CONST_PTR_TO_MAP:
2987 case PTR_TO_SOCK_COMMON:
2988 case PTR_TO_TCP_SOCK:
2989 case PTR_TO_XDP_SOCK:
2994 case PTR_TO_MAP_KEY:
3001 /* Does this register contain a constant zero? */
3002 static bool register_is_null(struct bpf_reg_state *reg)
3004 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3007 static bool register_is_const(struct bpf_reg_state *reg)
3009 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3012 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3014 return tnum_is_unknown(reg->var_off) &&
3015 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3016 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3017 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3018 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3021 static bool register_is_bounded(struct bpf_reg_state *reg)
3023 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3026 static bool __is_pointer_value(bool allow_ptr_leaks,
3027 const struct bpf_reg_state *reg)
3029 if (allow_ptr_leaks)
3032 return reg->type != SCALAR_VALUE;
3035 /* Copy src state preserving dst->parent and dst->live fields */
3036 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3038 struct bpf_reg_state *parent = dst->parent;
3039 enum bpf_reg_liveness live = dst->live;
3042 dst->parent = parent;
3046 static void save_register_state(struct bpf_func_state *state,
3047 int spi, struct bpf_reg_state *reg,
3052 copy_register_state(&state->stack[spi].spilled_ptr, reg);
3053 if (size == BPF_REG_SIZE)
3054 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3056 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3057 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3059 /* size < 8 bytes spill */
3061 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3064 static bool is_bpf_st_mem(struct bpf_insn *insn)
3066 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3069 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3070 * stack boundary and alignment are checked in check_mem_access()
3072 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3073 /* stack frame we're writing to */
3074 struct bpf_func_state *state,
3075 int off, int size, int value_regno,
3078 struct bpf_func_state *cur; /* state of the current function */
3079 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3080 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3081 struct bpf_reg_state *reg = NULL;
3082 u32 dst_reg = insn->dst_reg;
3084 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3087 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3088 * so it's aligned access and [off, off + size) are within stack limits
3090 if (!env->allow_ptr_leaks &&
3091 state->stack[spi].slot_type[0] == STACK_SPILL &&
3092 size != BPF_REG_SIZE) {
3093 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3097 cur = env->cur_state->frame[env->cur_state->curframe];
3098 if (value_regno >= 0)
3099 reg = &cur->regs[value_regno];
3100 if (!env->bypass_spec_v4) {
3101 bool sanitize = reg && is_spillable_regtype(reg->type);
3103 for (i = 0; i < size; i++) {
3104 u8 type = state->stack[spi].slot_type[i];
3106 if (type != STACK_MISC && type != STACK_ZERO) {
3113 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3116 mark_stack_slot_scratched(env, spi);
3117 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3118 !register_is_null(reg) && env->bpf_capable) {
3119 if (dst_reg != BPF_REG_FP) {
3120 /* The backtracking logic can only recognize explicit
3121 * stack slot address like [fp - 8]. Other spill of
3122 * scalar via different register has to be conservative.
3123 * Backtrack from here and mark all registers as precise
3124 * that contributed into 'reg' being a constant.
3126 err = mark_chain_precision(env, value_regno);
3130 save_register_state(state, spi, reg, size);
3131 /* Break the relation on a narrowing spill. */
3132 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
3133 state->stack[spi].spilled_ptr.id = 0;
3134 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3135 insn->imm != 0 && env->bpf_capable) {
3136 struct bpf_reg_state fake_reg = {};
3138 __mark_reg_known(&fake_reg, (u32)insn->imm);
3139 fake_reg.type = SCALAR_VALUE;
3140 save_register_state(state, spi, &fake_reg, size);
3141 } else if (reg && is_spillable_regtype(reg->type)) {
3142 /* register containing pointer is being spilled into stack */
3143 if (size != BPF_REG_SIZE) {
3144 verbose_linfo(env, insn_idx, "; ");
3145 verbose(env, "invalid size of register spill\n");
3148 if (state != cur && reg->type == PTR_TO_STACK) {
3149 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3152 save_register_state(state, spi, reg, size);
3154 u8 type = STACK_MISC;
3156 /* regular write of data into stack destroys any spilled ptr */
3157 state->stack[spi].spilled_ptr.type = NOT_INIT;
3158 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3159 if (is_spilled_reg(&state->stack[spi]))
3160 for (i = 0; i < BPF_REG_SIZE; i++)
3161 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3163 /* only mark the slot as written if all 8 bytes were written
3164 * otherwise read propagation may incorrectly stop too soon
3165 * when stack slots are partially written.
3166 * This heuristic means that read propagation will be
3167 * conservative, since it will add reg_live_read marks
3168 * to stack slots all the way to first state when programs
3169 * writes+reads less than 8 bytes
3171 if (size == BPF_REG_SIZE)
3172 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3174 /* when we zero initialize stack slots mark them as such */
3175 if ((reg && register_is_null(reg)) ||
3176 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3177 /* backtracking doesn't work for STACK_ZERO yet. */
3178 err = mark_chain_precision(env, value_regno);
3184 /* Mark slots affected by this stack write. */
3185 for (i = 0; i < size; i++)
3186 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3192 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3193 * known to contain a variable offset.
3194 * This function checks whether the write is permitted and conservatively
3195 * tracks the effects of the write, considering that each stack slot in the
3196 * dynamic range is potentially written to.
3198 * 'off' includes 'regno->off'.
3199 * 'value_regno' can be -1, meaning that an unknown value is being written to
3202 * Spilled pointers in range are not marked as written because we don't know
3203 * what's going to be actually written. This means that read propagation for
3204 * future reads cannot be terminated by this write.
3206 * For privileged programs, uninitialized stack slots are considered
3207 * initialized by this write (even though we don't know exactly what offsets
3208 * are going to be written to). The idea is that we don't want the verifier to
3209 * reject future reads that access slots written to through variable offsets.
3211 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3212 /* func where register points to */
3213 struct bpf_func_state *state,
3214 int ptr_regno, int off, int size,
3215 int value_regno, int insn_idx)
3217 struct bpf_func_state *cur; /* state of the current function */
3218 int min_off, max_off;
3220 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3221 bool writing_zero = false;
3222 /* set if the fact that we're writing a zero is used to let any
3223 * stack slots remain STACK_ZERO
3225 bool zero_used = false;
3227 cur = env->cur_state->frame[env->cur_state->curframe];
3228 ptr_reg = &cur->regs[ptr_regno];
3229 min_off = ptr_reg->smin_value + off;
3230 max_off = ptr_reg->smax_value + off + size;
3231 if (value_regno >= 0)
3232 value_reg = &cur->regs[value_regno];
3233 if (value_reg && register_is_null(value_reg))
3234 writing_zero = true;
3236 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3241 /* Variable offset writes destroy any spilled pointers in range. */
3242 for (i = min_off; i < max_off; i++) {
3243 u8 new_type, *stype;
3247 spi = slot / BPF_REG_SIZE;
3248 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3249 mark_stack_slot_scratched(env, spi);
3251 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3252 /* Reject the write if range we may write to has not
3253 * been initialized beforehand. If we didn't reject
3254 * here, the ptr status would be erased below (even
3255 * though not all slots are actually overwritten),
3256 * possibly opening the door to leaks.
3258 * We do however catch STACK_INVALID case below, and
3259 * only allow reading possibly uninitialized memory
3260 * later for CAP_PERFMON, as the write may not happen to
3263 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3268 /* Erase all spilled pointers. */
3269 state->stack[spi].spilled_ptr.type = NOT_INIT;
3271 /* Update the slot type. */
3272 new_type = STACK_MISC;
3273 if (writing_zero && *stype == STACK_ZERO) {
3274 new_type = STACK_ZERO;
3277 /* If the slot is STACK_INVALID, we check whether it's OK to
3278 * pretend that it will be initialized by this write. The slot
3279 * might not actually be written to, and so if we mark it as
3280 * initialized future reads might leak uninitialized memory.
3281 * For privileged programs, we will accept such reads to slots
3282 * that may or may not be written because, if we're reject
3283 * them, the error would be too confusing.
3285 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3286 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3293 /* backtracking doesn't work for STACK_ZERO yet. */
3294 err = mark_chain_precision(env, value_regno);
3301 /* When register 'dst_regno' is assigned some values from stack[min_off,
3302 * max_off), we set the register's type according to the types of the
3303 * respective stack slots. If all the stack values are known to be zeros, then
3304 * so is the destination reg. Otherwise, the register is considered to be
3305 * SCALAR. This function does not deal with register filling; the caller must
3306 * ensure that all spilled registers in the stack range have been marked as
3309 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3310 /* func where src register points to */
3311 struct bpf_func_state *ptr_state,
3312 int min_off, int max_off, int dst_regno)
3314 struct bpf_verifier_state *vstate = env->cur_state;
3315 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3320 for (i = min_off; i < max_off; i++) {
3322 spi = slot / BPF_REG_SIZE;
3323 stype = ptr_state->stack[spi].slot_type;
3324 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3328 if (zeros == max_off - min_off) {
3329 /* any access_size read into register is zero extended,
3330 * so the whole register == const_zero
3332 __mark_reg_const_zero(&state->regs[dst_regno]);
3333 /* backtracking doesn't support STACK_ZERO yet,
3334 * so mark it precise here, so that later
3335 * backtracking can stop here.
3336 * Backtracking may not need this if this register
3337 * doesn't participate in pointer adjustment.
3338 * Forward propagation of precise flag is not
3339 * necessary either. This mark is only to stop
3340 * backtracking. Any register that contributed
3341 * to const 0 was marked precise before spill.
3343 state->regs[dst_regno].precise = true;
3345 /* have read misc data from the stack */
3346 mark_reg_unknown(env, state->regs, dst_regno);
3348 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3351 /* Read the stack at 'off' and put the results into the register indicated by
3352 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3355 * 'dst_regno' can be -1, meaning that the read value is not going to a
3358 * The access is assumed to be within the current stack bounds.
3360 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3361 /* func where src register points to */
3362 struct bpf_func_state *reg_state,
3363 int off, int size, int dst_regno)
3365 struct bpf_verifier_state *vstate = env->cur_state;
3366 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3367 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3368 struct bpf_reg_state *reg;
3371 stype = reg_state->stack[spi].slot_type;
3372 reg = ®_state->stack[spi].spilled_ptr;
3374 if (is_spilled_reg(®_state->stack[spi])) {
3377 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3380 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3381 if (reg->type != SCALAR_VALUE) {
3382 verbose_linfo(env, env->insn_idx, "; ");
3383 verbose(env, "invalid size of register fill\n");
3387 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3391 if (!(off % BPF_REG_SIZE) && size == spill_size) {
3392 /* The earlier check_reg_arg() has decided the
3393 * subreg_def for this insn. Save it first.
3395 s32 subreg_def = state->regs[dst_regno].subreg_def;
3397 copy_register_state(&state->regs[dst_regno], reg);
3398 state->regs[dst_regno].subreg_def = subreg_def;
3400 for (i = 0; i < size; i++) {
3401 type = stype[(slot - i) % BPF_REG_SIZE];
3402 if (type == STACK_SPILL)
3404 if (type == STACK_MISC)
3406 verbose(env, "invalid read from stack off %d+%d size %d\n",
3410 mark_reg_unknown(env, state->regs, dst_regno);
3412 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3416 if (dst_regno >= 0) {
3417 /* restore register state from stack */
3418 copy_register_state(&state->regs[dst_regno], reg);
3419 /* mark reg as written since spilled pointer state likely
3420 * has its liveness marks cleared by is_state_visited()
3421 * which resets stack/reg liveness for state transitions
3423 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3424 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3425 /* If dst_regno==-1, the caller is asking us whether
3426 * it is acceptable to use this value as a SCALAR_VALUE
3428 * We must not allow unprivileged callers to do that
3429 * with spilled pointers.
3431 verbose(env, "leaking pointer from stack off %d\n",
3435 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3437 for (i = 0; i < size; i++) {
3438 type = stype[(slot - i) % BPF_REG_SIZE];
3439 if (type == STACK_MISC)
3441 if (type == STACK_ZERO)
3443 verbose(env, "invalid read from stack off %d+%d size %d\n",
3447 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3449 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3454 enum bpf_access_src {
3455 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
3456 ACCESS_HELPER = 2, /* the access is performed by a helper */
3459 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3460 int regno, int off, int access_size,
3461 bool zero_size_allowed,
3462 enum bpf_access_src type,
3463 struct bpf_call_arg_meta *meta);
3465 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3467 return cur_regs(env) + regno;
3470 /* Read the stack at 'ptr_regno + off' and put the result into the register
3472 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3473 * but not its variable offset.
3474 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3476 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3477 * filling registers (i.e. reads of spilled register cannot be detected when
3478 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3479 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3480 * offset; for a fixed offset check_stack_read_fixed_off should be used
3483 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3484 int ptr_regno, int off, int size, int dst_regno)
3486 /* The state of the source register. */
3487 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3488 struct bpf_func_state *ptr_state = func(env, reg);
3490 int min_off, max_off;
3492 /* Note that we pass a NULL meta, so raw access will not be permitted.
3494 err = check_stack_range_initialized(env, ptr_regno, off, size,
3495 false, ACCESS_DIRECT, NULL);
3499 min_off = reg->smin_value + off;
3500 max_off = reg->smax_value + off;
3501 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3505 /* check_stack_read dispatches to check_stack_read_fixed_off or
3506 * check_stack_read_var_off.
3508 * The caller must ensure that the offset falls within the allocated stack
3511 * 'dst_regno' is a register which will receive the value from the stack. It
3512 * can be -1, meaning that the read value is not going to a register.
3514 static int check_stack_read(struct bpf_verifier_env *env,
3515 int ptr_regno, int off, int size,
3518 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3519 struct bpf_func_state *state = func(env, reg);
3521 /* Some accesses are only permitted with a static offset. */
3522 bool var_off = !tnum_is_const(reg->var_off);
3524 /* The offset is required to be static when reads don't go to a
3525 * register, in order to not leak pointers (see
3526 * check_stack_read_fixed_off).
3528 if (dst_regno < 0 && var_off) {
3531 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3532 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3536 /* Variable offset is prohibited for unprivileged mode for simplicity
3537 * since it requires corresponding support in Spectre masking for stack
3538 * ALU. See also retrieve_ptr_limit(). The check in
3539 * check_stack_access_for_ptr_arithmetic() called by
3540 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
3541 * with variable offsets, therefore no check is required here. Further,
3542 * just checking it here would be insufficient as speculative stack
3543 * writes could still lead to unsafe speculative behaviour.
3546 off += reg->var_off.value;
3547 err = check_stack_read_fixed_off(env, state, off, size,
3550 /* Variable offset stack reads need more conservative handling
3551 * than fixed offset ones. Note that dst_regno >= 0 on this
3554 err = check_stack_read_var_off(env, ptr_regno, off, size,
3561 /* check_stack_write dispatches to check_stack_write_fixed_off or
3562 * check_stack_write_var_off.
3564 * 'ptr_regno' is the register used as a pointer into the stack.
3565 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3566 * 'value_regno' is the register whose value we're writing to the stack. It can
3567 * be -1, meaning that we're not writing from a register.
3569 * The caller must ensure that the offset falls within the maximum stack size.
3571 static int check_stack_write(struct bpf_verifier_env *env,
3572 int ptr_regno, int off, int size,
3573 int value_regno, int insn_idx)
3575 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3576 struct bpf_func_state *state = func(env, reg);
3579 if (tnum_is_const(reg->var_off)) {
3580 off += reg->var_off.value;
3581 err = check_stack_write_fixed_off(env, state, off, size,
3582 value_regno, insn_idx);
3584 /* Variable offset stack reads need more conservative handling
3585 * than fixed offset ones.
3587 err = check_stack_write_var_off(env, state,
3588 ptr_regno, off, size,
3589 value_regno, insn_idx);
3594 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3595 int off, int size, enum bpf_access_type type)
3597 struct bpf_reg_state *regs = cur_regs(env);
3598 struct bpf_map *map = regs[regno].map_ptr;
3599 u32 cap = bpf_map_flags_to_cap(map);
3601 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3602 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3603 map->value_size, off, size);
3607 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3608 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3609 map->value_size, off, size);
3616 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3617 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3618 int off, int size, u32 mem_size,
3619 bool zero_size_allowed)
3621 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3622 struct bpf_reg_state *reg;
3624 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3627 reg = &cur_regs(env)[regno];
3628 switch (reg->type) {
3629 case PTR_TO_MAP_KEY:
3630 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3631 mem_size, off, size);
3633 case PTR_TO_MAP_VALUE:
3634 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3635 mem_size, off, size);
3638 case PTR_TO_PACKET_META:
3639 case PTR_TO_PACKET_END:
3640 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3641 off, size, regno, reg->id, off, mem_size);
3645 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3646 mem_size, off, size);
3652 /* check read/write into a memory region with possible variable offset */
3653 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3654 int off, int size, u32 mem_size,
3655 bool zero_size_allowed)
3657 struct bpf_verifier_state *vstate = env->cur_state;
3658 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3659 struct bpf_reg_state *reg = &state->regs[regno];
3662 /* We may have adjusted the register pointing to memory region, so we
3663 * need to try adding each of min_value and max_value to off
3664 * to make sure our theoretical access will be safe.
3666 * The minimum value is only important with signed
3667 * comparisons where we can't assume the floor of a
3668 * value is 0. If we are using signed variables for our
3669 * index'es we need to make sure that whatever we use
3670 * will have a set floor within our range.
3672 if (reg->smin_value < 0 &&
3673 (reg->smin_value == S64_MIN ||
3674 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3675 reg->smin_value + off < 0)) {
3676 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3680 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3681 mem_size, zero_size_allowed);
3683 verbose(env, "R%d min value is outside of the allowed memory range\n",
3688 /* If we haven't set a max value then we need to bail since we can't be
3689 * sure we won't do bad things.
3690 * If reg->umax_value + off could overflow, treat that as unbounded too.
3692 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3693 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3697 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3698 mem_size, zero_size_allowed);
3700 verbose(env, "R%d max value is outside of the allowed memory range\n",
3708 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3709 const struct bpf_reg_state *reg, int regno,
3712 /* Access to this pointer-typed register or passing it to a helper
3713 * is only allowed in its original, unmodified form.
3717 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3718 reg_type_str(env, reg->type), regno, reg->off);
3722 if (!fixed_off_ok && reg->off) {
3723 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3724 reg_type_str(env, reg->type), regno, reg->off);
3728 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3731 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3732 verbose(env, "variable %s access var_off=%s disallowed\n",
3733 reg_type_str(env, reg->type), tn_buf);
3740 int check_ptr_off_reg(struct bpf_verifier_env *env,
3741 const struct bpf_reg_state *reg, int regno)
3743 return __check_ptr_off_reg(env, reg, regno, false);
3746 static int map_kptr_match_type(struct bpf_verifier_env *env,
3747 struct bpf_map_value_off_desc *off_desc,
3748 struct bpf_reg_state *reg, u32 regno)
3750 const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3751 int perm_flags = PTR_MAYBE_NULL;
3752 const char *reg_name = "";
3754 /* Only unreferenced case accepts untrusted pointers */
3755 if (off_desc->type == BPF_KPTR_UNREF)
3756 perm_flags |= PTR_UNTRUSTED;
3758 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3761 if (!btf_is_kernel(reg->btf)) {
3762 verbose(env, "R%d must point to kernel BTF\n", regno);
3765 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3766 reg_name = kernel_type_name(reg->btf, reg->btf_id);
3768 /* For ref_ptr case, release function check should ensure we get one
3769 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3770 * normal store of unreferenced kptr, we must ensure var_off is zero.
3771 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3772 * reg->off and reg->ref_obj_id are not needed here.
3774 if (__check_ptr_off_reg(env, reg, regno, true))
3777 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3778 * we also need to take into account the reg->off.
3780 * We want to support cases like:
3788 * v = func(); // PTR_TO_BTF_ID
3789 * val->foo = v; // reg->off is zero, btf and btf_id match type
3790 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3791 * // first member type of struct after comparison fails
3792 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3795 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3796 * is zero. We must also ensure that btf_struct_ids_match does not walk
3797 * the struct to match type against first member of struct, i.e. reject
3798 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3799 * strict mode to true for type match.
3801 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3802 off_desc->kptr.btf, off_desc->kptr.btf_id,
3803 off_desc->type == BPF_KPTR_REF))
3807 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3808 reg_type_str(env, reg->type), reg_name);
3809 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3810 if (off_desc->type == BPF_KPTR_UNREF)
3811 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3818 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3819 int value_regno, int insn_idx,
3820 struct bpf_map_value_off_desc *off_desc)
3822 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3823 int class = BPF_CLASS(insn->code);
3824 struct bpf_reg_state *val_reg;
3826 /* Things we already checked for in check_map_access and caller:
3827 * - Reject cases where variable offset may touch kptr
3828 * - size of access (must be BPF_DW)
3829 * - tnum_is_const(reg->var_off)
3830 * - off_desc->offset == off + reg->var_off.value
3832 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3833 if (BPF_MODE(insn->code) != BPF_MEM) {
3834 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3838 /* We only allow loading referenced kptr, since it will be marked as
3839 * untrusted, similar to unreferenced kptr.
3841 if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3842 verbose(env, "store to referenced kptr disallowed\n");
3846 if (class == BPF_LDX) {
3847 val_reg = reg_state(env, value_regno);
3848 /* We can simply mark the value_regno receiving the pointer
3849 * value from map as PTR_TO_BTF_ID, with the correct type.
3851 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3852 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3853 /* For mark_ptr_or_null_reg */
3854 val_reg->id = ++env->id_gen;
3855 } else if (class == BPF_STX) {
3856 val_reg = reg_state(env, value_regno);
3857 if (!register_is_null(val_reg) &&
3858 map_kptr_match_type(env, off_desc, val_reg, value_regno))
3860 } else if (class == BPF_ST) {
3862 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3867 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3873 /* check read/write into a map element with possible variable offset */
3874 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3875 int off, int size, bool zero_size_allowed,
3876 enum bpf_access_src src)
3878 struct bpf_verifier_state *vstate = env->cur_state;
3879 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3880 struct bpf_reg_state *reg = &state->regs[regno];
3881 struct bpf_map *map = reg->map_ptr;
3884 err = check_mem_region_access(env, regno, off, size, map->value_size,
3889 if (map_value_has_spin_lock(map)) {
3890 u32 lock = map->spin_lock_off;
3892 /* if any part of struct bpf_spin_lock can be touched by
3893 * load/store reject this program.
3894 * To check that [x1, x2) overlaps with [y1, y2)
3895 * it is sufficient to check x1 < y2 && y1 < x2.
3897 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3898 lock < reg->umax_value + off + size) {
3899 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3903 if (map_value_has_timer(map)) {
3904 u32 t = map->timer_off;
3906 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3907 t < reg->umax_value + off + size) {
3908 verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3912 if (map_value_has_kptrs(map)) {
3913 struct bpf_map_value_off *tab = map->kptr_off_tab;
3916 for (i = 0; i < tab->nr_off; i++) {
3917 u32 p = tab->off[i].offset;
3919 if (reg->smin_value + off < p + sizeof(u64) &&
3920 p < reg->umax_value + off + size) {
3921 if (src != ACCESS_DIRECT) {
3922 verbose(env, "kptr cannot be accessed indirectly by helper\n");
3925 if (!tnum_is_const(reg->var_off)) {
3926 verbose(env, "kptr access cannot have variable offset\n");
3929 if (p != off + reg->var_off.value) {
3930 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3931 p, off + reg->var_off.value);
3934 if (size != bpf_size_to_bytes(BPF_DW)) {
3935 verbose(env, "kptr access size must be BPF_DW\n");
3945 #define MAX_PACKET_OFF 0xffff
3947 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3948 const struct bpf_call_arg_meta *meta,
3949 enum bpf_access_type t)
3951 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3953 switch (prog_type) {
3954 /* Program types only with direct read access go here! */
3955 case BPF_PROG_TYPE_LWT_IN:
3956 case BPF_PROG_TYPE_LWT_OUT:
3957 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3958 case BPF_PROG_TYPE_SK_REUSEPORT:
3959 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3960 case BPF_PROG_TYPE_CGROUP_SKB:
3965 /* Program types with direct read + write access go here! */
3966 case BPF_PROG_TYPE_SCHED_CLS:
3967 case BPF_PROG_TYPE_SCHED_ACT:
3968 case BPF_PROG_TYPE_XDP:
3969 case BPF_PROG_TYPE_LWT_XMIT:
3970 case BPF_PROG_TYPE_SK_SKB:
3971 case BPF_PROG_TYPE_SK_MSG:
3973 return meta->pkt_access;
3975 env->seen_direct_write = true;
3978 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3980 env->seen_direct_write = true;
3989 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3990 int size, bool zero_size_allowed)
3992 struct bpf_reg_state *regs = cur_regs(env);
3993 struct bpf_reg_state *reg = ®s[regno];
3996 /* We may have added a variable offset to the packet pointer; but any
3997 * reg->range we have comes after that. We are only checking the fixed
4001 /* We don't allow negative numbers, because we aren't tracking enough
4002 * detail to prove they're safe.
4004 if (reg->smin_value < 0) {
4005 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4010 err = reg->range < 0 ? -EINVAL :
4011 __check_mem_access(env, regno, off, size, reg->range,
4014 verbose(env, "R%d offset is outside of the packet\n", regno);
4018 /* __check_mem_access has made sure "off + size - 1" is within u16.
4019 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4020 * otherwise find_good_pkt_pointers would have refused to set range info
4021 * that __check_mem_access would have rejected this pkt access.
4022 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4024 env->prog->aux->max_pkt_offset =
4025 max_t(u32, env->prog->aux->max_pkt_offset,
4026 off + reg->umax_value + size - 1);
4031 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
4032 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4033 enum bpf_access_type t, enum bpf_reg_type *reg_type,
4034 struct btf **btf, u32 *btf_id)
4036 struct bpf_insn_access_aux info = {
4037 .reg_type = *reg_type,
4041 if (env->ops->is_valid_access &&
4042 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4043 /* A non zero info.ctx_field_size indicates that this field is a
4044 * candidate for later verifier transformation to load the whole
4045 * field and then apply a mask when accessed with a narrower
4046 * access than actual ctx access size. A zero info.ctx_field_size
4047 * will only allow for whole field access and rejects any other
4048 * type of narrower access.
4050 *reg_type = info.reg_type;
4052 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4054 *btf_id = info.btf_id;
4056 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4058 /* remember the offset of last byte accessed in ctx */
4059 if (env->prog->aux->max_ctx_offset < off + size)
4060 env->prog->aux->max_ctx_offset = off + size;
4064 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4068 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4071 if (size < 0 || off < 0 ||
4072 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4073 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4080 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4081 u32 regno, int off, int size,
4082 enum bpf_access_type t)
4084 struct bpf_reg_state *regs = cur_regs(env);
4085 struct bpf_reg_state *reg = ®s[regno];
4086 struct bpf_insn_access_aux info = {};
4089 if (reg->smin_value < 0) {
4090 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4095 switch (reg->type) {
4096 case PTR_TO_SOCK_COMMON:
4097 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4100 valid = bpf_sock_is_valid_access(off, size, t, &info);
4102 case PTR_TO_TCP_SOCK:
4103 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4105 case PTR_TO_XDP_SOCK:
4106 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4114 env->insn_aux_data[insn_idx].ctx_field_size =
4115 info.ctx_field_size;
4119 verbose(env, "R%d invalid %s access off=%d size=%d\n",
4120 regno, reg_type_str(env, reg->type), off, size);
4125 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4127 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4130 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4132 const struct bpf_reg_state *reg = reg_state(env, regno);
4134 return reg->type == PTR_TO_CTX;
4137 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4139 const struct bpf_reg_state *reg = reg_state(env, regno);
4141 return type_is_sk_pointer(reg->type);
4144 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4146 const struct bpf_reg_state *reg = reg_state(env, regno);
4148 return type_is_pkt_pointer(reg->type);
4151 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4153 const struct bpf_reg_state *reg = reg_state(env, regno);
4155 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4156 return reg->type == PTR_TO_FLOW_KEYS;
4159 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4160 const struct bpf_reg_state *reg,
4161 int off, int size, bool strict)
4163 struct tnum reg_off;
4166 /* Byte size accesses are always allowed. */
4167 if (!strict || size == 1)
4170 /* For platforms that do not have a Kconfig enabling
4171 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4172 * NET_IP_ALIGN is universally set to '2'. And on platforms
4173 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4174 * to this code only in strict mode where we want to emulate
4175 * the NET_IP_ALIGN==2 checking. Therefore use an
4176 * unconditional IP align value of '2'.
4180 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4181 if (!tnum_is_aligned(reg_off, size)) {
4184 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4186 "misaligned packet access off %d+%s+%d+%d size %d\n",
4187 ip_align, tn_buf, reg->off, off, size);
4194 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4195 const struct bpf_reg_state *reg,
4196 const char *pointer_desc,
4197 int off, int size, bool strict)
4199 struct tnum reg_off;
4201 /* Byte size accesses are always allowed. */
4202 if (!strict || size == 1)
4205 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4206 if (!tnum_is_aligned(reg_off, size)) {
4209 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4210 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4211 pointer_desc, tn_buf, reg->off, off, size);
4218 static int check_ptr_alignment(struct bpf_verifier_env *env,
4219 const struct bpf_reg_state *reg, int off,
4220 int size, bool strict_alignment_once)
4222 bool strict = env->strict_alignment || strict_alignment_once;
4223 const char *pointer_desc = "";
4225 switch (reg->type) {
4227 case PTR_TO_PACKET_META:
4228 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4229 * right in front, treat it the very same way.
4231 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4232 case PTR_TO_FLOW_KEYS:
4233 pointer_desc = "flow keys ";
4235 case PTR_TO_MAP_KEY:
4236 pointer_desc = "key ";
4238 case PTR_TO_MAP_VALUE:
4239 pointer_desc = "value ";
4242 pointer_desc = "context ";
4245 pointer_desc = "stack ";
4246 /* The stack spill tracking logic in check_stack_write_fixed_off()
4247 * and check_stack_read_fixed_off() relies on stack accesses being
4253 pointer_desc = "sock ";
4255 case PTR_TO_SOCK_COMMON:
4256 pointer_desc = "sock_common ";
4258 case PTR_TO_TCP_SOCK:
4259 pointer_desc = "tcp_sock ";
4261 case PTR_TO_XDP_SOCK:
4262 pointer_desc = "xdp_sock ";
4267 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4271 static int update_stack_depth(struct bpf_verifier_env *env,
4272 const struct bpf_func_state *func,
4275 u16 stack = env->subprog_info[func->subprogno].stack_depth;
4280 /* update known max for given subprogram */
4281 env->subprog_info[func->subprogno].stack_depth = -off;
4285 /* starting from main bpf function walk all instructions of the function
4286 * and recursively walk all callees that given function can call.
4287 * Ignore jump and exit insns.
4288 * Since recursion is prevented by check_cfg() this algorithm
4289 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4291 static int check_max_stack_depth(struct bpf_verifier_env *env)
4293 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4294 struct bpf_subprog_info *subprog = env->subprog_info;
4295 struct bpf_insn *insn = env->prog->insnsi;
4296 bool tail_call_reachable = false;
4297 int ret_insn[MAX_CALL_FRAMES];
4298 int ret_prog[MAX_CALL_FRAMES];
4302 /* protect against potential stack overflow that might happen when
4303 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4304 * depth for such case down to 256 so that the worst case scenario
4305 * would result in 8k stack size (32 which is tailcall limit * 256 =
4308 * To get the idea what might happen, see an example:
4309 * func1 -> sub rsp, 128
4310 * subfunc1 -> sub rsp, 256
4311 * tailcall1 -> add rsp, 256
4312 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4313 * subfunc2 -> sub rsp, 64
4314 * subfunc22 -> sub rsp, 128
4315 * tailcall2 -> add rsp, 128
4316 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4318 * tailcall will unwind the current stack frame but it will not get rid
4319 * of caller's stack as shown on the example above.
4321 if (idx && subprog[idx].has_tail_call && depth >= 256) {
4323 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4327 /* round up to 32-bytes, since this is granularity
4328 * of interpreter stack size
4330 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4331 if (depth > MAX_BPF_STACK) {
4332 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4337 subprog_end = subprog[idx + 1].start;
4338 for (; i < subprog_end; i++) {
4341 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4343 /* remember insn and function to return to */
4344 ret_insn[frame] = i + 1;
4345 ret_prog[frame] = idx;
4347 /* find the callee */
4348 next_insn = i + insn[i].imm + 1;
4349 idx = find_subprog(env, next_insn);
4351 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4355 if (subprog[idx].is_async_cb) {
4356 if (subprog[idx].has_tail_call) {
4357 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4360 /* async callbacks don't increase bpf prog stack size */
4365 if (subprog[idx].has_tail_call)
4366 tail_call_reachable = true;
4369 if (frame >= MAX_CALL_FRAMES) {
4370 verbose(env, "the call stack of %d frames is too deep !\n",
4376 /* if tail call got detected across bpf2bpf calls then mark each of the
4377 * currently present subprog frames as tail call reachable subprogs;
4378 * this info will be utilized by JIT so that we will be preserving the
4379 * tail call counter throughout bpf2bpf calls combined with tailcalls
4381 if (tail_call_reachable)
4382 for (j = 0; j < frame; j++)
4383 subprog[ret_prog[j]].tail_call_reachable = true;
4384 if (subprog[0].tail_call_reachable)
4385 env->prog->aux->tail_call_reachable = true;
4387 /* end of for() loop means the last insn of the 'subprog'
4388 * was reached. Doesn't matter whether it was JA or EXIT
4392 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4394 i = ret_insn[frame];
4395 idx = ret_prog[frame];
4399 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4400 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4401 const struct bpf_insn *insn, int idx)
4403 int start = idx + insn->imm + 1, subprog;
4405 subprog = find_subprog(env, start);
4407 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4411 return env->subprog_info[subprog].stack_depth;
4415 static int __check_buffer_access(struct bpf_verifier_env *env,
4416 const char *buf_info,
4417 const struct bpf_reg_state *reg,
4418 int regno, int off, int size)
4422 "R%d invalid %s buffer access: off=%d, size=%d\n",
4423 regno, buf_info, off, size);
4426 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4429 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4431 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4432 regno, off, tn_buf);
4439 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4440 const struct bpf_reg_state *reg,
4441 int regno, int off, int size)
4445 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4449 if (off + size > env->prog->aux->max_tp_access)
4450 env->prog->aux->max_tp_access = off + size;
4455 static int check_buffer_access(struct bpf_verifier_env *env,
4456 const struct bpf_reg_state *reg,
4457 int regno, int off, int size,
4458 bool zero_size_allowed,
4461 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4464 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4468 if (off + size > *max_access)
4469 *max_access = off + size;
4474 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4475 static void zext_32_to_64(struct bpf_reg_state *reg)
4477 reg->var_off = tnum_subreg(reg->var_off);
4478 __reg_assign_32_into_64(reg);
4481 /* truncate register to smaller size (in bytes)
4482 * must be called with size < BPF_REG_SIZE
4484 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4488 /* clear high bits in bit representation */
4489 reg->var_off = tnum_cast(reg->var_off, size);
4491 /* fix arithmetic bounds */
4492 mask = ((u64)1 << (size * 8)) - 1;
4493 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4494 reg->umin_value &= mask;
4495 reg->umax_value &= mask;
4497 reg->umin_value = 0;
4498 reg->umax_value = mask;
4500 reg->smin_value = reg->umin_value;
4501 reg->smax_value = reg->umax_value;
4503 /* If size is smaller than 32bit register the 32bit register
4504 * values are also truncated so we push 64-bit bounds into
4505 * 32-bit bounds. Above were truncated < 32-bits already.
4509 __reg_combine_64_into_32(reg);
4512 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4514 /* A map is considered read-only if the following condition are true:
4516 * 1) BPF program side cannot change any of the map content. The
4517 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4518 * and was set at map creation time.
4519 * 2) The map value(s) have been initialized from user space by a
4520 * loader and then "frozen", such that no new map update/delete
4521 * operations from syscall side are possible for the rest of
4522 * the map's lifetime from that point onwards.
4523 * 3) Any parallel/pending map update/delete operations from syscall
4524 * side have been completed. Only after that point, it's safe to
4525 * assume that map value(s) are immutable.
4527 return (map->map_flags & BPF_F_RDONLY_PROG) &&
4528 READ_ONCE(map->frozen) &&
4529 !bpf_map_write_active(map);
4532 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4538 err = map->ops->map_direct_value_addr(map, &addr, off);
4541 ptr = (void *)(long)addr + off;
4545 *val = (u64)*(u8 *)ptr;
4548 *val = (u64)*(u16 *)ptr;
4551 *val = (u64)*(u32 *)ptr;
4562 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4563 struct bpf_reg_state *regs,
4564 int regno, int off, int size,
4565 enum bpf_access_type atype,
4568 struct bpf_reg_state *reg = regs + regno;
4569 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4570 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4571 enum bpf_type_flag flag = 0;
4577 "R%d is ptr_%s invalid negative access: off=%d\n",
4581 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4584 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4586 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4587 regno, tname, off, tn_buf);
4591 if (reg->type & MEM_USER) {
4593 "R%d is ptr_%s access user memory: off=%d\n",
4598 if (reg->type & MEM_PERCPU) {
4600 "R%d is ptr_%s access percpu memory: off=%d\n",
4605 if (env->ops->btf_struct_access) {
4606 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4607 off, size, atype, &btf_id, &flag);
4609 if (atype != BPF_READ) {
4610 verbose(env, "only read is supported\n");
4614 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4615 atype, &btf_id, &flag);
4621 /* If this is an untrusted pointer, all pointers formed by walking it
4622 * also inherit the untrusted flag.
4624 if (type_flag(reg->type) & PTR_UNTRUSTED)
4625 flag |= PTR_UNTRUSTED;
4627 if (atype == BPF_READ && value_regno >= 0)
4628 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4633 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4634 struct bpf_reg_state *regs,
4635 int regno, int off, int size,
4636 enum bpf_access_type atype,
4639 struct bpf_reg_state *reg = regs + regno;
4640 struct bpf_map *map = reg->map_ptr;
4641 enum bpf_type_flag flag = 0;
4642 const struct btf_type *t;
4648 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4652 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4653 verbose(env, "map_ptr access not supported for map type %d\n",
4658 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4659 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4661 if (!env->allow_ptr_to_map_access) {
4663 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4669 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4674 if (atype != BPF_READ) {
4675 verbose(env, "only read from %s is supported\n", tname);
4679 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4683 if (value_regno >= 0)
4684 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4689 /* Check that the stack access at the given offset is within bounds. The
4690 * maximum valid offset is -1.
4692 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4693 * -state->allocated_stack for reads.
4695 static int check_stack_slot_within_bounds(int off,
4696 struct bpf_func_state *state,
4697 enum bpf_access_type t)
4702 min_valid_off = -MAX_BPF_STACK;
4704 min_valid_off = -state->allocated_stack;
4706 if (off < min_valid_off || off > -1)
4711 /* Check that the stack access at 'regno + off' falls within the maximum stack
4714 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4716 static int check_stack_access_within_bounds(
4717 struct bpf_verifier_env *env,
4718 int regno, int off, int access_size,
4719 enum bpf_access_src src, enum bpf_access_type type)
4721 struct bpf_reg_state *regs = cur_regs(env);
4722 struct bpf_reg_state *reg = regs + regno;
4723 struct bpf_func_state *state = func(env, reg);
4724 int min_off, max_off;
4728 if (src == ACCESS_HELPER)
4729 /* We don't know if helpers are reading or writing (or both). */
4730 err_extra = " indirect access to";
4731 else if (type == BPF_READ)
4732 err_extra = " read from";
4734 err_extra = " write to";
4736 if (tnum_is_const(reg->var_off)) {
4737 min_off = reg->var_off.value + off;
4738 if (access_size > 0)
4739 max_off = min_off + access_size - 1;
4743 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4744 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4745 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4749 min_off = reg->smin_value + off;
4750 if (access_size > 0)
4751 max_off = reg->smax_value + off + access_size - 1;
4756 err = check_stack_slot_within_bounds(min_off, state, type);
4758 err = check_stack_slot_within_bounds(max_off, state, type);
4761 if (tnum_is_const(reg->var_off)) {
4762 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4763 err_extra, regno, off, access_size);
4767 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4768 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4769 err_extra, regno, tn_buf, access_size);
4775 /* check whether memory at (regno + off) is accessible for t = (read | write)
4776 * if t==write, value_regno is a register which value is stored into memory
4777 * if t==read, value_regno is a register which will receive the value from memory
4778 * if t==write && value_regno==-1, some unknown value is stored into memory
4779 * if t==read && value_regno==-1, don't care what we read from memory
4781 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4782 int off, int bpf_size, enum bpf_access_type t,
4783 int value_regno, bool strict_alignment_once)
4785 struct bpf_reg_state *regs = cur_regs(env);
4786 struct bpf_reg_state *reg = regs + regno;
4787 struct bpf_func_state *state;
4790 size = bpf_size_to_bytes(bpf_size);
4794 /* alignment checks will add in reg->off themselves */
4795 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4799 /* for access checks, reg->off is just part of off */
4802 if (reg->type == PTR_TO_MAP_KEY) {
4803 if (t == BPF_WRITE) {
4804 verbose(env, "write to change key R%d not allowed\n", regno);
4808 err = check_mem_region_access(env, regno, off, size,
4809 reg->map_ptr->key_size, false);
4812 if (value_regno >= 0)
4813 mark_reg_unknown(env, regs, value_regno);
4814 } else if (reg->type == PTR_TO_MAP_VALUE) {
4815 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4817 if (t == BPF_WRITE && value_regno >= 0 &&
4818 is_pointer_value(env, value_regno)) {
4819 verbose(env, "R%d leaks addr into map\n", value_regno);
4822 err = check_map_access_type(env, regno, off, size, t);
4825 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4828 if (tnum_is_const(reg->var_off))
4829 kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4830 off + reg->var_off.value);
4831 if (kptr_off_desc) {
4832 err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4834 } else if (t == BPF_READ && value_regno >= 0) {
4835 struct bpf_map *map = reg->map_ptr;
4837 /* if map is read-only, track its contents as scalars */
4838 if (tnum_is_const(reg->var_off) &&
4839 bpf_map_is_rdonly(map) &&
4840 map->ops->map_direct_value_addr) {
4841 int map_off = off + reg->var_off.value;
4844 err = bpf_map_direct_read(map, map_off, size,
4849 regs[value_regno].type = SCALAR_VALUE;
4850 __mark_reg_known(®s[value_regno], val);
4852 mark_reg_unknown(env, regs, value_regno);
4855 } else if (base_type(reg->type) == PTR_TO_MEM) {
4856 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4858 if (type_may_be_null(reg->type)) {
4859 verbose(env, "R%d invalid mem access '%s'\n", regno,
4860 reg_type_str(env, reg->type));
4864 if (t == BPF_WRITE && rdonly_mem) {
4865 verbose(env, "R%d cannot write into %s\n",
4866 regno, reg_type_str(env, reg->type));
4870 if (t == BPF_WRITE && value_regno >= 0 &&
4871 is_pointer_value(env, value_regno)) {
4872 verbose(env, "R%d leaks addr into mem\n", value_regno);
4876 err = check_mem_region_access(env, regno, off, size,
4877 reg->mem_size, false);
4878 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4879 mark_reg_unknown(env, regs, value_regno);
4880 } else if (reg->type == PTR_TO_CTX) {
4881 enum bpf_reg_type reg_type = SCALAR_VALUE;
4882 struct btf *btf = NULL;
4885 if (t == BPF_WRITE && value_regno >= 0 &&
4886 is_pointer_value(env, value_regno)) {
4887 verbose(env, "R%d leaks addr into ctx\n", value_regno);
4891 err = check_ptr_off_reg(env, reg, regno);
4895 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
4898 verbose_linfo(env, insn_idx, "; ");
4899 if (!err && t == BPF_READ && value_regno >= 0) {
4900 /* ctx access returns either a scalar, or a
4901 * PTR_TO_PACKET[_META,_END]. In the latter
4902 * case, we know the offset is zero.
4904 if (reg_type == SCALAR_VALUE) {
4905 mark_reg_unknown(env, regs, value_regno);
4907 mark_reg_known_zero(env, regs,
4909 if (type_may_be_null(reg_type))
4910 regs[value_regno].id = ++env->id_gen;
4911 /* A load of ctx field could have different
4912 * actual load size with the one encoded in the
4913 * insn. When the dst is PTR, it is for sure not
4916 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4917 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4918 regs[value_regno].btf = btf;
4919 regs[value_regno].btf_id = btf_id;
4922 regs[value_regno].type = reg_type;
4925 } else if (reg->type == PTR_TO_STACK) {
4926 /* Basic bounds checks. */
4927 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4931 state = func(env, reg);
4932 err = update_stack_depth(env, state, off);
4937 err = check_stack_read(env, regno, off, size,
4940 err = check_stack_write(env, regno, off, size,
4941 value_regno, insn_idx);
4942 } else if (reg_is_pkt_pointer(reg)) {
4943 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4944 verbose(env, "cannot write into packet\n");
4947 if (t == BPF_WRITE && value_regno >= 0 &&
4948 is_pointer_value(env, value_regno)) {
4949 verbose(env, "R%d leaks addr into packet\n",
4953 err = check_packet_access(env, regno, off, size, false);
4954 if (!err && t == BPF_READ && value_regno >= 0)
4955 mark_reg_unknown(env, regs, value_regno);
4956 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4957 if (t == BPF_WRITE && value_regno >= 0 &&
4958 is_pointer_value(env, value_regno)) {
4959 verbose(env, "R%d leaks addr into flow keys\n",
4964 err = check_flow_keys_access(env, off, size);
4965 if (!err && t == BPF_READ && value_regno >= 0)
4966 mark_reg_unknown(env, regs, value_regno);
4967 } else if (type_is_sk_pointer(reg->type)) {
4968 if (t == BPF_WRITE) {
4969 verbose(env, "R%d cannot write into %s\n",
4970 regno, reg_type_str(env, reg->type));
4973 err = check_sock_access(env, insn_idx, regno, off, size, t);
4974 if (!err && value_regno >= 0)
4975 mark_reg_unknown(env, regs, value_regno);
4976 } else if (reg->type == PTR_TO_TP_BUFFER) {
4977 err = check_tp_buffer_access(env, reg, regno, off, size);
4978 if (!err && t == BPF_READ && value_regno >= 0)
4979 mark_reg_unknown(env, regs, value_regno);
4980 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4981 !type_may_be_null(reg->type)) {
4982 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4984 } else if (reg->type == CONST_PTR_TO_MAP) {
4985 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4987 } else if (base_type(reg->type) == PTR_TO_BUF) {
4988 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4992 if (t == BPF_WRITE) {
4993 verbose(env, "R%d cannot write into %s\n",
4994 regno, reg_type_str(env, reg->type));
4997 max_access = &env->prog->aux->max_rdonly_access;
4999 max_access = &env->prog->aux->max_rdwr_access;
5002 err = check_buffer_access(env, reg, regno, off, size, false,
5005 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5006 mark_reg_unknown(env, regs, value_regno);
5008 verbose(env, "R%d invalid mem access '%s'\n", regno,
5009 reg_type_str(env, reg->type));
5013 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5014 regs[value_regno].type == SCALAR_VALUE) {
5015 /* b/h/w load zero-extends, mark upper bits as known 0 */
5016 coerce_reg_to_size(®s[value_regno], size);
5021 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5026 switch (insn->imm) {
5028 case BPF_ADD | BPF_FETCH:
5030 case BPF_AND | BPF_FETCH:
5032 case BPF_OR | BPF_FETCH:
5034 case BPF_XOR | BPF_FETCH:
5039 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5043 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5044 verbose(env, "invalid atomic operand size\n");
5048 /* check src1 operand */
5049 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5053 /* check src2 operand */
5054 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5058 if (insn->imm == BPF_CMPXCHG) {
5059 /* Check comparison of R0 with memory location */
5060 const u32 aux_reg = BPF_REG_0;
5062 err = check_reg_arg(env, aux_reg, SRC_OP);
5066 if (is_pointer_value(env, aux_reg)) {
5067 verbose(env, "R%d leaks addr into mem\n", aux_reg);
5072 if (is_pointer_value(env, insn->src_reg)) {
5073 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5077 if (is_ctx_reg(env, insn->dst_reg) ||
5078 is_pkt_reg(env, insn->dst_reg) ||
5079 is_flow_key_reg(env, insn->dst_reg) ||
5080 is_sk_reg(env, insn->dst_reg)) {
5081 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5083 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5087 if (insn->imm & BPF_FETCH) {
5088 if (insn->imm == BPF_CMPXCHG)
5089 load_reg = BPF_REG_0;
5091 load_reg = insn->src_reg;
5093 /* check and record load of old value */
5094 err = check_reg_arg(env, load_reg, DST_OP);
5098 /* This instruction accesses a memory location but doesn't
5099 * actually load it into a register.
5104 /* Check whether we can read the memory, with second call for fetch
5105 * case to simulate the register fill.
5107 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5108 BPF_SIZE(insn->code), BPF_READ, -1, true);
5109 if (!err && load_reg >= 0)
5110 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5111 BPF_SIZE(insn->code), BPF_READ, load_reg,
5116 /* Check whether we can write into the same memory. */
5117 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5118 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5125 /* When register 'regno' is used to read the stack (either directly or through
5126 * a helper function) make sure that it's within stack boundary and, depending
5127 * on the access type, that all elements of the stack are initialized.
5129 * 'off' includes 'regno->off', but not its dynamic part (if any).
5131 * All registers that have been spilled on the stack in the slots within the
5132 * read offsets are marked as read.
5134 static int check_stack_range_initialized(
5135 struct bpf_verifier_env *env, int regno, int off,
5136 int access_size, bool zero_size_allowed,
5137 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5139 struct bpf_reg_state *reg = reg_state(env, regno);
5140 struct bpf_func_state *state = func(env, reg);
5141 int err, min_off, max_off, i, j, slot, spi;
5142 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5143 enum bpf_access_type bounds_check_type;
5144 /* Some accesses can write anything into the stack, others are
5147 bool clobber = false;
5149 if (access_size == 0 && !zero_size_allowed) {
5150 verbose(env, "invalid zero-sized read\n");
5154 if (type == ACCESS_HELPER) {
5155 /* The bounds checks for writes are more permissive than for
5156 * reads. However, if raw_mode is not set, we'll do extra
5159 bounds_check_type = BPF_WRITE;
5162 bounds_check_type = BPF_READ;
5164 err = check_stack_access_within_bounds(env, regno, off, access_size,
5165 type, bounds_check_type);
5170 if (tnum_is_const(reg->var_off)) {
5171 min_off = max_off = reg->var_off.value + off;
5173 /* Variable offset is prohibited for unprivileged mode for
5174 * simplicity since it requires corresponding support in
5175 * Spectre masking for stack ALU.
5176 * See also retrieve_ptr_limit().
5178 if (!env->bypass_spec_v1) {
5181 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5182 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5183 regno, err_extra, tn_buf);
5186 /* Only initialized buffer on stack is allowed to be accessed
5187 * with variable offset. With uninitialized buffer it's hard to
5188 * guarantee that whole memory is marked as initialized on
5189 * helper return since specific bounds are unknown what may
5190 * cause uninitialized stack leaking.
5192 if (meta && meta->raw_mode)
5195 min_off = reg->smin_value + off;
5196 max_off = reg->smax_value + off;
5199 if (meta && meta->raw_mode) {
5200 meta->access_size = access_size;
5201 meta->regno = regno;
5205 for (i = min_off; i < max_off + access_size; i++) {
5209 spi = slot / BPF_REG_SIZE;
5210 if (state->allocated_stack <= slot)
5212 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5213 if (*stype == STACK_MISC)
5215 if (*stype == STACK_ZERO) {
5217 /* helper can write anything into the stack */
5218 *stype = STACK_MISC;
5223 if (is_spilled_reg(&state->stack[spi]) &&
5224 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5225 env->allow_ptr_leaks)) {
5227 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5228 for (j = 0; j < BPF_REG_SIZE; j++)
5229 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5235 if (tnum_is_const(reg->var_off)) {
5236 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5237 err_extra, regno, min_off, i - min_off, access_size);
5241 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5242 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5243 err_extra, regno, tn_buf, i - min_off, access_size);
5247 /* reading any byte out of 8-byte 'spill_slot' will cause
5248 * the whole slot to be marked as 'read'
5250 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5251 state->stack[spi].spilled_ptr.parent,
5253 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5254 * be sure that whether stack slot is written to or not. Hence,
5255 * we must still conservatively propagate reads upwards even if
5256 * helper may write to the entire memory range.
5259 return update_stack_depth(env, state, min_off);
5262 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5263 int access_size, bool zero_size_allowed,
5264 struct bpf_call_arg_meta *meta)
5266 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5269 switch (base_type(reg->type)) {
5271 case PTR_TO_PACKET_META:
5272 return check_packet_access(env, regno, reg->off, access_size,
5274 case PTR_TO_MAP_KEY:
5275 if (meta && meta->raw_mode) {
5276 verbose(env, "R%d cannot write into %s\n", regno,
5277 reg_type_str(env, reg->type));
5280 return check_mem_region_access(env, regno, reg->off, access_size,
5281 reg->map_ptr->key_size, false);
5282 case PTR_TO_MAP_VALUE:
5283 if (check_map_access_type(env, regno, reg->off, access_size,
5284 meta && meta->raw_mode ? BPF_WRITE :
5287 return check_map_access(env, regno, reg->off, access_size,
5288 zero_size_allowed, ACCESS_HELPER);
5290 if (type_is_rdonly_mem(reg->type)) {
5291 if (meta && meta->raw_mode) {
5292 verbose(env, "R%d cannot write into %s\n", regno,
5293 reg_type_str(env, reg->type));
5297 return check_mem_region_access(env, regno, reg->off,
5298 access_size, reg->mem_size,
5301 if (type_is_rdonly_mem(reg->type)) {
5302 if (meta && meta->raw_mode) {
5303 verbose(env, "R%d cannot write into %s\n", regno,
5304 reg_type_str(env, reg->type));
5308 max_access = &env->prog->aux->max_rdonly_access;
5310 max_access = &env->prog->aux->max_rdwr_access;
5312 return check_buffer_access(env, reg, regno, reg->off,
5313 access_size, zero_size_allowed,
5316 return check_stack_range_initialized(
5318 regno, reg->off, access_size,
5319 zero_size_allowed, ACCESS_HELPER, meta);
5321 /* in case the function doesn't know how to access the context,
5322 * (because we are in a program of type SYSCALL for example), we
5323 * can not statically check its size.
5324 * Dynamically check it now.
5326 if (!env->ops->convert_ctx_access) {
5327 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5328 int offset = access_size - 1;
5330 /* Allow zero-byte read from PTR_TO_CTX */
5331 if (access_size == 0)
5332 return zero_size_allowed ? 0 : -EACCES;
5334 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5339 default: /* scalar_value or invalid ptr */
5340 /* Allow zero-byte read from NULL, regardless of pointer type */
5341 if (zero_size_allowed && access_size == 0 &&
5342 register_is_null(reg))
5345 verbose(env, "R%d type=%s ", regno,
5346 reg_type_str(env, reg->type));
5347 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5352 static int check_mem_size_reg(struct bpf_verifier_env *env,
5353 struct bpf_reg_state *reg, u32 regno,
5354 bool zero_size_allowed,
5355 struct bpf_call_arg_meta *meta)
5359 /* This is used to refine r0 return value bounds for helpers
5360 * that enforce this value as an upper bound on return values.
5361 * See do_refine_retval_range() for helpers that can refine
5362 * the return value. C type of helper is u32 so we pull register
5363 * bound from umax_value however, if negative verifier errors
5364 * out. Only upper bounds can be learned because retval is an
5365 * int type and negative retvals are allowed.
5367 meta->msize_max_value = reg->umax_value;
5369 /* The register is SCALAR_VALUE; the access check
5370 * happens using its boundaries.
5372 if (!tnum_is_const(reg->var_off))
5373 /* For unprivileged variable accesses, disable raw
5374 * mode so that the program is required to
5375 * initialize all the memory that the helper could
5376 * just partially fill up.
5380 if (reg->smin_value < 0) {
5381 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5386 if (reg->umin_value == 0) {
5387 err = check_helper_mem_access(env, regno - 1, 0,
5394 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5395 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5399 err = check_helper_mem_access(env, regno - 1,
5401 zero_size_allowed, meta);
5403 err = mark_chain_precision(env, regno);
5407 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5408 u32 regno, u32 mem_size)
5410 bool may_be_null = type_may_be_null(reg->type);
5411 struct bpf_reg_state saved_reg;
5412 struct bpf_call_arg_meta meta;
5415 if (register_is_null(reg))
5418 memset(&meta, 0, sizeof(meta));
5419 /* Assuming that the register contains a value check if the memory
5420 * access is safe. Temporarily save and restore the register's state as
5421 * the conversion shouldn't be visible to a caller.
5425 mark_ptr_not_null_reg(reg);
5428 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5429 /* Check access for BPF_WRITE */
5430 meta.raw_mode = true;
5431 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5439 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5442 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5443 bool may_be_null = type_may_be_null(mem_reg->type);
5444 struct bpf_reg_state saved_reg;
5445 struct bpf_call_arg_meta meta;
5448 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5450 memset(&meta, 0, sizeof(meta));
5453 saved_reg = *mem_reg;
5454 mark_ptr_not_null_reg(mem_reg);
5457 err = check_mem_size_reg(env, reg, regno, true, &meta);
5458 /* Check access for BPF_WRITE */
5459 meta.raw_mode = true;
5460 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5463 *mem_reg = saved_reg;
5467 /* Implementation details:
5468 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5469 * Two bpf_map_lookups (even with the same key) will have different reg->id.
5470 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5471 * value_or_null->value transition, since the verifier only cares about
5472 * the range of access to valid map value pointer and doesn't care about actual
5473 * address of the map element.
5474 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5475 * reg->id > 0 after value_or_null->value transition. By doing so
5476 * two bpf_map_lookups will be considered two different pointers that
5477 * point to different bpf_spin_locks.
5478 * The verifier allows taking only one bpf_spin_lock at a time to avoid
5480 * Since only one bpf_spin_lock is allowed the checks are simpler than
5481 * reg_is_refcounted() logic. The verifier needs to remember only
5482 * one spin_lock instead of array of acquired_refs.
5483 * cur_state->active_spin_lock remembers which map value element got locked
5484 * and clears it after bpf_spin_unlock.
5486 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5489 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5490 struct bpf_verifier_state *cur = env->cur_state;
5491 bool is_const = tnum_is_const(reg->var_off);
5492 struct bpf_map *map = reg->map_ptr;
5493 u64 val = reg->var_off.value;
5497 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5503 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5507 if (!map_value_has_spin_lock(map)) {
5508 if (map->spin_lock_off == -E2BIG)
5510 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5512 else if (map->spin_lock_off == -ENOENT)
5514 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5518 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5522 if (map->spin_lock_off != val + reg->off) {
5523 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5528 if (cur->active_spin_lock) {
5530 "Locking two bpf_spin_locks are not allowed\n");
5533 cur->active_spin_lock = reg->id;
5535 if (!cur->active_spin_lock) {
5536 verbose(env, "bpf_spin_unlock without taking a lock\n");
5539 if (cur->active_spin_lock != reg->id) {
5540 verbose(env, "bpf_spin_unlock of different lock\n");
5543 cur->active_spin_lock = 0;
5548 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5549 struct bpf_call_arg_meta *meta)
5551 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5552 bool is_const = tnum_is_const(reg->var_off);
5553 struct bpf_map *map = reg->map_ptr;
5554 u64 val = reg->var_off.value;
5558 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5563 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5567 if (!map_value_has_timer(map)) {
5568 if (map->timer_off == -E2BIG)
5570 "map '%s' has more than one 'struct bpf_timer'\n",
5572 else if (map->timer_off == -ENOENT)
5574 "map '%s' doesn't have 'struct bpf_timer'\n",
5578 "map '%s' is not a struct type or bpf_timer is mangled\n",
5582 if (map->timer_off != val + reg->off) {
5583 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5584 val + reg->off, map->timer_off);
5587 if (meta->map_ptr) {
5588 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5591 meta->map_uid = reg->map_uid;
5592 meta->map_ptr = map;
5596 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5597 struct bpf_call_arg_meta *meta)
5599 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5600 struct bpf_map_value_off_desc *off_desc;
5601 struct bpf_map *map_ptr = reg->map_ptr;
5605 if (!tnum_is_const(reg->var_off)) {
5607 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5611 if (!map_ptr->btf) {
5612 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5616 if (!map_value_has_kptrs(map_ptr)) {
5617 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5619 verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5620 BPF_MAP_VALUE_OFF_MAX);
5621 else if (ret == -EEXIST)
5622 verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5624 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5628 meta->map_ptr = map_ptr;
5629 kptr_off = reg->off + reg->var_off.value;
5630 off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5632 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5635 if (off_desc->type != BPF_KPTR_REF) {
5636 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5639 meta->kptr_off_desc = off_desc;
5643 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5645 return type == ARG_CONST_SIZE ||
5646 type == ARG_CONST_SIZE_OR_ZERO;
5649 static bool arg_type_is_release(enum bpf_arg_type type)
5651 return type & OBJ_RELEASE;
5654 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5656 return base_type(type) == ARG_PTR_TO_DYNPTR;
5659 static int int_ptr_type_to_size(enum bpf_arg_type type)
5661 if (type == ARG_PTR_TO_INT)
5663 else if (type == ARG_PTR_TO_LONG)
5669 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5670 const struct bpf_call_arg_meta *meta,
5671 enum bpf_arg_type *arg_type)
5673 if (!meta->map_ptr) {
5674 /* kernel subsystem misconfigured verifier */
5675 verbose(env, "invalid map_ptr to access map->type\n");
5679 switch (meta->map_ptr->map_type) {
5680 case BPF_MAP_TYPE_SOCKMAP:
5681 case BPF_MAP_TYPE_SOCKHASH:
5682 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5683 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5685 verbose(env, "invalid arg_type for sockmap/sockhash\n");
5689 case BPF_MAP_TYPE_BLOOM_FILTER:
5690 if (meta->func_id == BPF_FUNC_map_peek_elem)
5691 *arg_type = ARG_PTR_TO_MAP_VALUE;
5699 struct bpf_reg_types {
5700 const enum bpf_reg_type types[10];
5704 static const struct bpf_reg_types map_key_value_types = {
5714 static const struct bpf_reg_types sock_types = {
5724 static const struct bpf_reg_types btf_id_sock_common_types = {
5732 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5736 static const struct bpf_reg_types mem_types = {
5744 PTR_TO_MEM | MEM_ALLOC,
5749 static const struct bpf_reg_types int_ptr_types = {
5759 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5760 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5761 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5762 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5763 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5764 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5765 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5766 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5767 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5768 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5769 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5770 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5771 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5772 static const struct bpf_reg_types dynptr_types = {
5775 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5779 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5780 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
5781 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
5782 [ARG_CONST_SIZE] = &scalar_types,
5783 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
5784 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
5785 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
5786 [ARG_PTR_TO_CTX] = &context_types,
5787 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
5789 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5791 [ARG_PTR_TO_SOCKET] = &fullsock_types,
5792 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
5793 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
5794 [ARG_PTR_TO_MEM] = &mem_types,
5795 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
5796 [ARG_PTR_TO_INT] = &int_ptr_types,
5797 [ARG_PTR_TO_LONG] = &int_ptr_types,
5798 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
5799 [ARG_PTR_TO_FUNC] = &func_ptr_types,
5800 [ARG_PTR_TO_STACK] = &stack_ptr_types,
5801 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
5802 [ARG_PTR_TO_TIMER] = &timer_types,
5803 [ARG_PTR_TO_KPTR] = &kptr_types,
5804 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
5807 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5808 enum bpf_arg_type arg_type,
5809 const u32 *arg_btf_id,
5810 struct bpf_call_arg_meta *meta)
5812 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5813 enum bpf_reg_type expected, type = reg->type;
5814 const struct bpf_reg_types *compatible;
5817 compatible = compatible_reg_types[base_type(arg_type)];
5819 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5823 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5824 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5826 * Same for MAYBE_NULL:
5828 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5829 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5831 * Therefore we fold these flags depending on the arg_type before comparison.
5833 if (arg_type & MEM_RDONLY)
5834 type &= ~MEM_RDONLY;
5835 if (arg_type & PTR_MAYBE_NULL)
5836 type &= ~PTR_MAYBE_NULL;
5838 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5839 expected = compatible->types[i];
5840 if (expected == NOT_INIT)
5843 if (type == expected)
5847 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5848 for (j = 0; j + 1 < i; j++)
5849 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5850 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5854 if (reg->type == PTR_TO_BTF_ID) {
5855 /* For bpf_sk_release, it needs to match against first member
5856 * 'struct sock_common', hence make an exception for it. This
5857 * allows bpf_sk_release to work for multiple socket types.
5859 bool strict_type_match = arg_type_is_release(arg_type) &&
5860 meta->func_id != BPF_FUNC_sk_release;
5863 if (!compatible->btf_id) {
5864 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5867 arg_btf_id = compatible->btf_id;
5870 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5871 if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5874 if (arg_btf_id == BPF_PTR_POISON) {
5875 verbose(env, "verifier internal error:");
5876 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5881 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5882 btf_vmlinux, *arg_btf_id,
5883 strict_type_match)) {
5884 verbose(env, "R%d is of type %s but %s is expected\n",
5885 regno, kernel_type_name(reg->btf, reg->btf_id),
5886 kernel_type_name(btf_vmlinux, *arg_btf_id));
5895 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5896 const struct bpf_reg_state *reg, int regno,
5897 enum bpf_arg_type arg_type)
5899 enum bpf_reg_type type = reg->type;
5900 bool fixed_off_ok = false;
5902 switch ((u32)type) {
5903 /* Pointer types where reg offset is explicitly allowed: */
5905 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5906 verbose(env, "cannot pass in dynptr at an offset\n");
5911 case PTR_TO_PACKET_META:
5912 case PTR_TO_MAP_KEY:
5913 case PTR_TO_MAP_VALUE:
5915 case PTR_TO_MEM | MEM_RDONLY:
5916 case PTR_TO_MEM | MEM_ALLOC:
5918 case PTR_TO_BUF | MEM_RDONLY:
5920 /* Some of the argument types nevertheless require a
5921 * zero register offset.
5923 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5926 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5930 /* When referenced PTR_TO_BTF_ID is passed to release function,
5931 * it's fixed offset must be 0. In the other cases, fixed offset
5934 if (arg_type_is_release(arg_type) && reg->off) {
5935 verbose(env, "R%d must have zero offset when passed to release func\n",
5939 /* For arg is release pointer, fixed_off_ok must be false, but
5940 * we already checked and rejected reg->off != 0 above, so set
5941 * to true to allow fixed offset for all other cases.
5943 fixed_off_ok = true;
5948 return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5951 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5953 struct bpf_func_state *state = func(env, reg);
5954 int spi = get_spi(reg->off);
5956 return state->stack[spi].spilled_ptr.id;
5959 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5960 struct bpf_call_arg_meta *meta,
5961 const struct bpf_func_proto *fn)
5963 u32 regno = BPF_REG_1 + arg;
5964 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5965 enum bpf_arg_type arg_type = fn->arg_type[arg];
5966 enum bpf_reg_type type = reg->type;
5967 u32 *arg_btf_id = NULL;
5970 if (arg_type == ARG_DONTCARE)
5973 err = check_reg_arg(env, regno, SRC_OP);
5977 if (arg_type == ARG_ANYTHING) {
5978 if (is_pointer_value(env, regno)) {
5979 verbose(env, "R%d leaks addr into helper function\n",
5986 if (type_is_pkt_pointer(type) &&
5987 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5988 verbose(env, "helper access to the packet is not allowed\n");
5992 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5993 err = resolve_map_arg_type(env, meta, &arg_type);
5998 if (register_is_null(reg) && type_may_be_null(arg_type))
5999 /* A NULL register has a SCALAR_VALUE type, so skip
6002 goto skip_type_check;
6004 /* arg_btf_id and arg_size are in a union. */
6005 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
6006 arg_btf_id = fn->arg_btf_id[arg];
6008 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6012 err = check_func_arg_reg_off(env, reg, regno, arg_type);
6017 if (arg_type_is_release(arg_type)) {
6018 if (arg_type_is_dynptr(arg_type)) {
6019 struct bpf_func_state *state = func(env, reg);
6020 int spi = get_spi(reg->off);
6022 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6023 !state->stack[spi].spilled_ptr.id) {
6024 verbose(env, "arg %d is an unacquired reference\n", regno);
6027 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
6028 verbose(env, "R%d must be referenced when passed to release function\n",
6032 if (meta->release_regno) {
6033 verbose(env, "verifier internal error: more than one release argument\n");
6036 meta->release_regno = regno;
6039 if (reg->ref_obj_id) {
6040 if (meta->ref_obj_id) {
6041 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6042 regno, reg->ref_obj_id,
6046 meta->ref_obj_id = reg->ref_obj_id;
6049 switch (base_type(arg_type)) {
6050 case ARG_CONST_MAP_PTR:
6051 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6052 if (meta->map_ptr) {
6053 /* Use map_uid (which is unique id of inner map) to reject:
6054 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6055 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6056 * if (inner_map1 && inner_map2) {
6057 * timer = bpf_map_lookup_elem(inner_map1);
6059 * // mismatch would have been allowed
6060 * bpf_timer_init(timer, inner_map2);
6063 * Comparing map_ptr is enough to distinguish normal and outer maps.
6065 if (meta->map_ptr != reg->map_ptr ||
6066 meta->map_uid != reg->map_uid) {
6068 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6069 meta->map_uid, reg->map_uid);
6073 meta->map_ptr = reg->map_ptr;
6074 meta->map_uid = reg->map_uid;
6076 case ARG_PTR_TO_MAP_KEY:
6077 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6078 * check that [key, key + map->key_size) are within
6079 * stack limits and initialized
6081 if (!meta->map_ptr) {
6082 /* in function declaration map_ptr must come before
6083 * map_key, so that it's verified and known before
6084 * we have to check map_key here. Otherwise it means
6085 * that kernel subsystem misconfigured verifier
6087 verbose(env, "invalid map_ptr to access map->key\n");
6090 err = check_helper_mem_access(env, regno,
6091 meta->map_ptr->key_size, false,
6094 case ARG_PTR_TO_MAP_VALUE:
6095 if (type_may_be_null(arg_type) && register_is_null(reg))
6098 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6099 * check [value, value + map->value_size) validity
6101 if (!meta->map_ptr) {
6102 /* kernel subsystem misconfigured verifier */
6103 verbose(env, "invalid map_ptr to access map->value\n");
6106 meta->raw_mode = arg_type & MEM_UNINIT;
6107 err = check_helper_mem_access(env, regno,
6108 meta->map_ptr->value_size, false,
6111 case ARG_PTR_TO_PERCPU_BTF_ID:
6113 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6116 meta->ret_btf = reg->btf;
6117 meta->ret_btf_id = reg->btf_id;
6119 case ARG_PTR_TO_SPIN_LOCK:
6120 if (meta->func_id == BPF_FUNC_spin_lock) {
6121 if (process_spin_lock(env, regno, true))
6123 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6124 if (process_spin_lock(env, regno, false))
6127 verbose(env, "verifier internal error\n");
6131 case ARG_PTR_TO_TIMER:
6132 if (process_timer_func(env, regno, meta))
6135 case ARG_PTR_TO_FUNC:
6136 meta->subprogno = reg->subprogno;
6138 case ARG_PTR_TO_MEM:
6139 /* The access to this pointer is only checked when we hit the
6140 * next is_mem_size argument below.
6142 meta->raw_mode = arg_type & MEM_UNINIT;
6143 if (arg_type & MEM_FIXED_SIZE) {
6144 err = check_helper_mem_access(env, regno,
6145 fn->arg_size[arg], false,
6149 case ARG_CONST_SIZE:
6150 err = check_mem_size_reg(env, reg, regno, false, meta);
6152 case ARG_CONST_SIZE_OR_ZERO:
6153 err = check_mem_size_reg(env, reg, regno, true, meta);
6155 case ARG_PTR_TO_DYNPTR:
6156 /* We only need to check for initialized / uninitialized helper
6157 * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6158 * assumption is that if it is, that a helper function
6159 * initialized the dynptr on behalf of the BPF program.
6161 if (base_type(reg->type) == PTR_TO_DYNPTR)
6163 if (arg_type & MEM_UNINIT) {
6164 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6165 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6169 /* We only support one dynptr being uninitialized at the moment,
6170 * which is sufficient for the helper functions we have right now.
6172 if (meta->uninit_dynptr_regno) {
6173 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6177 meta->uninit_dynptr_regno = regno;
6178 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6180 "Expected an initialized dynptr as arg #%d\n",
6183 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6184 const char *err_extra = "";
6186 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6187 case DYNPTR_TYPE_LOCAL:
6188 err_extra = "local";
6190 case DYNPTR_TYPE_RINGBUF:
6191 err_extra = "ringbuf";
6194 err_extra = "<unknown>";
6198 "Expected a dynptr of type %s as arg #%d\n",
6199 err_extra, arg + 1);
6203 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6204 if (!tnum_is_const(reg->var_off)) {
6205 verbose(env, "R%d is not a known constant'\n",
6209 meta->mem_size = reg->var_off.value;
6210 err = mark_chain_precision(env, regno);
6214 case ARG_PTR_TO_INT:
6215 case ARG_PTR_TO_LONG:
6217 int size = int_ptr_type_to_size(arg_type);
6219 err = check_helper_mem_access(env, regno, size, false, meta);
6222 err = check_ptr_alignment(env, reg, 0, size, true);
6225 case ARG_PTR_TO_CONST_STR:
6227 struct bpf_map *map = reg->map_ptr;
6232 if (!bpf_map_is_rdonly(map)) {
6233 verbose(env, "R%d does not point to a readonly map'\n", regno);
6237 if (!tnum_is_const(reg->var_off)) {
6238 verbose(env, "R%d is not a constant address'\n", regno);
6242 if (!map->ops->map_direct_value_addr) {
6243 verbose(env, "no direct value access support for this map type\n");
6247 err = check_map_access(env, regno, reg->off,
6248 map->value_size - reg->off, false,
6253 map_off = reg->off + reg->var_off.value;
6254 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6256 verbose(env, "direct value access on string failed\n");
6260 str_ptr = (char *)(long)(map_addr);
6261 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6262 verbose(env, "string is not zero-terminated\n");
6267 case ARG_PTR_TO_KPTR:
6268 if (process_kptr_func(env, regno, meta))
6276 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6278 enum bpf_attach_type eatype = env->prog->expected_attach_type;
6279 enum bpf_prog_type type = resolve_prog_type(env->prog);
6281 if (func_id != BPF_FUNC_map_update_elem)
6284 /* It's not possible to get access to a locked struct sock in these
6285 * contexts, so updating is safe.
6288 case BPF_PROG_TYPE_TRACING:
6289 if (eatype == BPF_TRACE_ITER)
6292 case BPF_PROG_TYPE_SOCKET_FILTER:
6293 case BPF_PROG_TYPE_SCHED_CLS:
6294 case BPF_PROG_TYPE_SCHED_ACT:
6295 case BPF_PROG_TYPE_XDP:
6296 case BPF_PROG_TYPE_SK_REUSEPORT:
6297 case BPF_PROG_TYPE_FLOW_DISSECTOR:
6298 case BPF_PROG_TYPE_SK_LOOKUP:
6304 verbose(env, "cannot update sockmap in this context\n");
6308 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6310 return env->prog->jit_requested &&
6311 bpf_jit_supports_subprog_tailcalls();
6314 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6315 struct bpf_map *map, int func_id)
6320 /* We need a two way check, first is from map perspective ... */
6321 switch (map->map_type) {
6322 case BPF_MAP_TYPE_PROG_ARRAY:
6323 if (func_id != BPF_FUNC_tail_call)
6326 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6327 if (func_id != BPF_FUNC_perf_event_read &&
6328 func_id != BPF_FUNC_perf_event_output &&
6329 func_id != BPF_FUNC_skb_output &&
6330 func_id != BPF_FUNC_perf_event_read_value &&
6331 func_id != BPF_FUNC_xdp_output)
6334 case BPF_MAP_TYPE_RINGBUF:
6335 if (func_id != BPF_FUNC_ringbuf_output &&
6336 func_id != BPF_FUNC_ringbuf_reserve &&
6337 func_id != BPF_FUNC_ringbuf_query &&
6338 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6339 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6340 func_id != BPF_FUNC_ringbuf_discard_dynptr)
6343 case BPF_MAP_TYPE_USER_RINGBUF:
6344 if (func_id != BPF_FUNC_user_ringbuf_drain)
6347 case BPF_MAP_TYPE_STACK_TRACE:
6348 if (func_id != BPF_FUNC_get_stackid)
6351 case BPF_MAP_TYPE_CGROUP_ARRAY:
6352 if (func_id != BPF_FUNC_skb_under_cgroup &&
6353 func_id != BPF_FUNC_current_task_under_cgroup)
6356 case BPF_MAP_TYPE_CGROUP_STORAGE:
6357 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6358 if (func_id != BPF_FUNC_get_local_storage)
6361 case BPF_MAP_TYPE_DEVMAP:
6362 case BPF_MAP_TYPE_DEVMAP_HASH:
6363 if (func_id != BPF_FUNC_redirect_map &&
6364 func_id != BPF_FUNC_map_lookup_elem)
6367 /* Restrict bpf side of cpumap and xskmap, open when use-cases
6370 case BPF_MAP_TYPE_CPUMAP:
6371 if (func_id != BPF_FUNC_redirect_map)
6374 case BPF_MAP_TYPE_XSKMAP:
6375 if (func_id != BPF_FUNC_redirect_map &&
6376 func_id != BPF_FUNC_map_lookup_elem)
6379 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6380 case BPF_MAP_TYPE_HASH_OF_MAPS:
6381 if (func_id != BPF_FUNC_map_lookup_elem)
6384 case BPF_MAP_TYPE_SOCKMAP:
6385 if (func_id != BPF_FUNC_sk_redirect_map &&
6386 func_id != BPF_FUNC_sock_map_update &&
6387 func_id != BPF_FUNC_map_delete_elem &&
6388 func_id != BPF_FUNC_msg_redirect_map &&
6389 func_id != BPF_FUNC_sk_select_reuseport &&
6390 func_id != BPF_FUNC_map_lookup_elem &&
6391 !may_update_sockmap(env, func_id))
6394 case BPF_MAP_TYPE_SOCKHASH:
6395 if (func_id != BPF_FUNC_sk_redirect_hash &&
6396 func_id != BPF_FUNC_sock_hash_update &&
6397 func_id != BPF_FUNC_map_delete_elem &&
6398 func_id != BPF_FUNC_msg_redirect_hash &&
6399 func_id != BPF_FUNC_sk_select_reuseport &&
6400 func_id != BPF_FUNC_map_lookup_elem &&
6401 !may_update_sockmap(env, func_id))
6404 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6405 if (func_id != BPF_FUNC_sk_select_reuseport)
6408 case BPF_MAP_TYPE_QUEUE:
6409 case BPF_MAP_TYPE_STACK:
6410 if (func_id != BPF_FUNC_map_peek_elem &&
6411 func_id != BPF_FUNC_map_pop_elem &&
6412 func_id != BPF_FUNC_map_push_elem)
6415 case BPF_MAP_TYPE_SK_STORAGE:
6416 if (func_id != BPF_FUNC_sk_storage_get &&
6417 func_id != BPF_FUNC_sk_storage_delete)
6420 case BPF_MAP_TYPE_INODE_STORAGE:
6421 if (func_id != BPF_FUNC_inode_storage_get &&
6422 func_id != BPF_FUNC_inode_storage_delete)
6425 case BPF_MAP_TYPE_TASK_STORAGE:
6426 if (func_id != BPF_FUNC_task_storage_get &&
6427 func_id != BPF_FUNC_task_storage_delete)
6430 case BPF_MAP_TYPE_BLOOM_FILTER:
6431 if (func_id != BPF_FUNC_map_peek_elem &&
6432 func_id != BPF_FUNC_map_push_elem)
6439 /* ... and second from the function itself. */
6441 case BPF_FUNC_tail_call:
6442 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6444 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6445 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6449 case BPF_FUNC_perf_event_read:
6450 case BPF_FUNC_perf_event_output:
6451 case BPF_FUNC_perf_event_read_value:
6452 case BPF_FUNC_skb_output:
6453 case BPF_FUNC_xdp_output:
6454 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6457 case BPF_FUNC_ringbuf_output:
6458 case BPF_FUNC_ringbuf_reserve:
6459 case BPF_FUNC_ringbuf_query:
6460 case BPF_FUNC_ringbuf_reserve_dynptr:
6461 case BPF_FUNC_ringbuf_submit_dynptr:
6462 case BPF_FUNC_ringbuf_discard_dynptr:
6463 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6466 case BPF_FUNC_user_ringbuf_drain:
6467 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6470 case BPF_FUNC_get_stackid:
6471 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6474 case BPF_FUNC_current_task_under_cgroup:
6475 case BPF_FUNC_skb_under_cgroup:
6476 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6479 case BPF_FUNC_redirect_map:
6480 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6481 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6482 map->map_type != BPF_MAP_TYPE_CPUMAP &&
6483 map->map_type != BPF_MAP_TYPE_XSKMAP)
6486 case BPF_FUNC_sk_redirect_map:
6487 case BPF_FUNC_msg_redirect_map:
6488 case BPF_FUNC_sock_map_update:
6489 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6492 case BPF_FUNC_sk_redirect_hash:
6493 case BPF_FUNC_msg_redirect_hash:
6494 case BPF_FUNC_sock_hash_update:
6495 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6498 case BPF_FUNC_get_local_storage:
6499 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6500 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6503 case BPF_FUNC_sk_select_reuseport:
6504 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6505 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6506 map->map_type != BPF_MAP_TYPE_SOCKHASH)
6509 case BPF_FUNC_map_pop_elem:
6510 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6511 map->map_type != BPF_MAP_TYPE_STACK)
6514 case BPF_FUNC_map_peek_elem:
6515 case BPF_FUNC_map_push_elem:
6516 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6517 map->map_type != BPF_MAP_TYPE_STACK &&
6518 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6521 case BPF_FUNC_map_lookup_percpu_elem:
6522 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6523 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6524 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6527 case BPF_FUNC_sk_storage_get:
6528 case BPF_FUNC_sk_storage_delete:
6529 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6532 case BPF_FUNC_inode_storage_get:
6533 case BPF_FUNC_inode_storage_delete:
6534 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6537 case BPF_FUNC_task_storage_get:
6538 case BPF_FUNC_task_storage_delete:
6539 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6548 verbose(env, "cannot pass map_type %d into func %s#%d\n",
6549 map->map_type, func_id_name(func_id), func_id);
6553 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6557 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6559 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6561 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6563 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6565 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6568 /* We only support one arg being in raw mode at the moment,
6569 * which is sufficient for the helper functions we have
6575 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6577 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6578 bool has_size = fn->arg_size[arg] != 0;
6579 bool is_next_size = false;
6581 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6582 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6584 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6585 return is_next_size;
6587 return has_size == is_next_size || is_next_size == is_fixed;
6590 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6592 /* bpf_xxx(..., buf, len) call will access 'len'
6593 * bytes from memory 'buf'. Both arg types need
6594 * to be paired, so make sure there's no buggy
6595 * helper function specification.
6597 if (arg_type_is_mem_size(fn->arg1_type) ||
6598 check_args_pair_invalid(fn, 0) ||
6599 check_args_pair_invalid(fn, 1) ||
6600 check_args_pair_invalid(fn, 2) ||
6601 check_args_pair_invalid(fn, 3) ||
6602 check_args_pair_invalid(fn, 4))
6608 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6612 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6613 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6616 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6617 /* arg_btf_id and arg_size are in a union. */
6618 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6619 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6626 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6628 return check_raw_mode_ok(fn) &&
6629 check_arg_pair_ok(fn) &&
6630 check_btf_id_ok(fn) ? 0 : -EINVAL;
6633 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6634 * are now invalid, so turn them into unknown SCALAR_VALUE.
6636 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6638 struct bpf_func_state *state;
6639 struct bpf_reg_state *reg;
6641 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6642 if (reg_is_pkt_pointer_any(reg))
6643 __mark_reg_unknown(env, reg);
6649 BEYOND_PKT_END = -2,
6652 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6654 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6655 struct bpf_reg_state *reg = &state->regs[regn];
6657 if (reg->type != PTR_TO_PACKET)
6658 /* PTR_TO_PACKET_META is not supported yet */
6661 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6662 * How far beyond pkt_end it goes is unknown.
6663 * if (!range_open) it's the case of pkt >= pkt_end
6664 * if (range_open) it's the case of pkt > pkt_end
6665 * hence this pointer is at least 1 byte bigger than pkt_end
6668 reg->range = BEYOND_PKT_END;
6670 reg->range = AT_PKT_END;
6673 /* The pointer with the specified id has released its reference to kernel
6674 * resources. Identify all copies of the same pointer and clear the reference.
6676 static int release_reference(struct bpf_verifier_env *env,
6679 struct bpf_func_state *state;
6680 struct bpf_reg_state *reg;
6683 err = release_reference_state(cur_func(env), ref_obj_id);
6687 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6688 if (reg->ref_obj_id == ref_obj_id) {
6689 if (!env->allow_ptr_leaks)
6690 __mark_reg_not_init(env, reg);
6692 __mark_reg_unknown(env, reg);
6699 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6700 struct bpf_reg_state *regs)
6704 /* after the call registers r0 - r5 were scratched */
6705 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6706 mark_reg_not_init(env, regs, caller_saved[i]);
6707 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6711 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6712 struct bpf_func_state *caller,
6713 struct bpf_func_state *callee,
6716 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6717 int *insn_idx, int subprog,
6718 set_callee_state_fn set_callee_state_cb)
6720 struct bpf_verifier_state *state = env->cur_state;
6721 struct bpf_func_info_aux *func_info_aux;
6722 struct bpf_func_state *caller, *callee;
6724 bool is_global = false;
6726 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6727 verbose(env, "the call stack of %d frames is too deep\n",
6728 state->curframe + 2);
6732 caller = state->frame[state->curframe];
6733 if (state->frame[state->curframe + 1]) {
6734 verbose(env, "verifier bug. Frame %d already allocated\n",
6735 state->curframe + 1);
6739 func_info_aux = env->prog->aux->func_info_aux;
6741 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6742 err = btf_check_subprog_call(env, subprog, caller->regs);
6747 verbose(env, "Caller passes invalid args into func#%d\n",
6751 if (env->log.level & BPF_LOG_LEVEL)
6753 "Func#%d is global and valid. Skipping.\n",
6755 clear_caller_saved_regs(env, caller->regs);
6757 /* All global functions return a 64-bit SCALAR_VALUE */
6758 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6759 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6761 /* continue with next insn after call */
6766 if (insn->code == (BPF_JMP | BPF_CALL) &&
6767 insn->src_reg == 0 &&
6768 insn->imm == BPF_FUNC_timer_set_callback) {
6769 struct bpf_verifier_state *async_cb;
6771 /* there is no real recursion here. timer callbacks are async */
6772 env->subprog_info[subprog].is_async_cb = true;
6773 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6774 *insn_idx, subprog);
6777 callee = async_cb->frame[0];
6778 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6780 /* Convert bpf_timer_set_callback() args into timer callback args */
6781 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6785 clear_caller_saved_regs(env, caller->regs);
6786 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6787 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6788 /* continue with next insn after call */
6792 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6795 state->frame[state->curframe + 1] = callee;
6797 /* callee cannot access r0, r6 - r9 for reading and has to write
6798 * into its own stack before reading from it.
6799 * callee can read/write into caller's stack
6801 init_func_state(env, callee,
6802 /* remember the callsite, it will be used by bpf_exit */
6803 *insn_idx /* callsite */,
6804 state->curframe + 1 /* frameno within this callchain */,
6805 subprog /* subprog number within this prog */);
6807 /* Transfer references to the callee */
6808 err = copy_reference_state(callee, caller);
6812 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6816 clear_caller_saved_regs(env, caller->regs);
6818 /* only increment it after check_reg_arg() finished */
6821 /* and go analyze first insn of the callee */
6822 *insn_idx = env->subprog_info[subprog].start - 1;
6824 if (env->log.level & BPF_LOG_LEVEL) {
6825 verbose(env, "caller:\n");
6826 print_verifier_state(env, caller, true);
6827 verbose(env, "callee:\n");
6828 print_verifier_state(env, callee, true);
6833 free_func_state(callee);
6834 state->frame[state->curframe + 1] = NULL;
6838 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6839 struct bpf_func_state *caller,
6840 struct bpf_func_state *callee)
6842 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6843 * void *callback_ctx, u64 flags);
6844 * callback_fn(struct bpf_map *map, void *key, void *value,
6845 * void *callback_ctx);
6847 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6849 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6850 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6851 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6853 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6854 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6855 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6857 /* pointer to stack or null */
6858 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6861 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6865 static int set_callee_state(struct bpf_verifier_env *env,
6866 struct bpf_func_state *caller,
6867 struct bpf_func_state *callee, int insn_idx)
6871 /* copy r1 - r5 args that callee can access. The copy includes parent
6872 * pointers, which connects us up to the liveness chain
6874 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6875 callee->regs[i] = caller->regs[i];
6879 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6882 int subprog, target_insn;
6884 target_insn = *insn_idx + insn->imm + 1;
6885 subprog = find_subprog(env, target_insn);
6887 verbose(env, "verifier bug. No program starts at insn %d\n",
6892 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6895 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6896 struct bpf_func_state *caller,
6897 struct bpf_func_state *callee,
6900 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6901 struct bpf_map *map;
6904 if (bpf_map_ptr_poisoned(insn_aux)) {
6905 verbose(env, "tail_call abusing map_ptr\n");
6909 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6910 if (!map->ops->map_set_for_each_callback_args ||
6911 !map->ops->map_for_each_callback) {
6912 verbose(env, "callback function not allowed for map\n");
6916 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6920 callee->in_callback_fn = true;
6921 callee->callback_ret_range = tnum_range(0, 1);
6925 static int set_loop_callback_state(struct bpf_verifier_env *env,
6926 struct bpf_func_state *caller,
6927 struct bpf_func_state *callee,
6930 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6932 * callback_fn(u32 index, void *callback_ctx);
6934 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6935 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6938 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6939 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6940 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6942 callee->in_callback_fn = true;
6943 callee->callback_ret_range = tnum_range(0, 1);
6947 static int set_timer_callback_state(struct bpf_verifier_env *env,
6948 struct bpf_func_state *caller,
6949 struct bpf_func_state *callee,
6952 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6954 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6955 * callback_fn(struct bpf_map *map, void *key, void *value);
6957 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6958 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6959 callee->regs[BPF_REG_1].map_ptr = map_ptr;
6961 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6962 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6963 callee->regs[BPF_REG_2].map_ptr = map_ptr;
6965 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6966 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6967 callee->regs[BPF_REG_3].map_ptr = map_ptr;
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_async_callback_fn = true;
6973 callee->callback_ret_range = tnum_range(0, 1);
6977 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6978 struct bpf_func_state *caller,
6979 struct bpf_func_state *callee,
6982 /* bpf_find_vma(struct task_struct *task, u64 addr,
6983 * void *callback_fn, void *callback_ctx, u64 flags)
6984 * (callback_fn)(struct task_struct *task,
6985 * struct vm_area_struct *vma, void *callback_ctx);
6987 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6989 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6990 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6991 callee->regs[BPF_REG_2].btf = btf_vmlinux;
6992 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6994 /* pointer to stack or null */
6995 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6998 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6999 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7000 callee->in_callback_fn = true;
7001 callee->callback_ret_range = tnum_range(0, 1);
7005 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7006 struct bpf_func_state *caller,
7007 struct bpf_func_state *callee,
7010 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7011 * callback_ctx, u64 flags);
7012 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
7014 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7015 callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
7016 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7017 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7020 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7021 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7022 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7024 callee->in_callback_fn = true;
7025 callee->callback_ret_range = tnum_range(0, 1);
7029 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7031 struct bpf_verifier_state *state = env->cur_state;
7032 struct bpf_func_state *caller, *callee;
7033 struct bpf_reg_state *r0;
7036 callee = state->frame[state->curframe];
7037 r0 = &callee->regs[BPF_REG_0];
7038 if (r0->type == PTR_TO_STACK) {
7039 /* technically it's ok to return caller's stack pointer
7040 * (or caller's caller's pointer) back to the caller,
7041 * since these pointers are valid. Only current stack
7042 * pointer will be invalid as soon as function exits,
7043 * but let's be conservative
7045 verbose(env, "cannot return stack pointer to the caller\n");
7049 caller = state->frame[state->curframe - 1];
7050 if (callee->in_callback_fn) {
7051 /* enforce R0 return value range [0, 1]. */
7052 struct tnum range = callee->callback_ret_range;
7054 if (r0->type != SCALAR_VALUE) {
7055 verbose(env, "R0 not a scalar value\n");
7058 if (!tnum_in(range, r0->var_off)) {
7059 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7063 /* return to the caller whatever r0 had in the callee */
7064 caller->regs[BPF_REG_0] = *r0;
7067 /* callback_fn frame should have released its own additions to parent's
7068 * reference state at this point, or check_reference_leak would
7069 * complain, hence it must be the same as the caller. There is no need
7072 if (!callee->in_callback_fn) {
7073 /* Transfer references to the caller */
7074 err = copy_reference_state(caller, callee);
7079 *insn_idx = callee->callsite + 1;
7080 if (env->log.level & BPF_LOG_LEVEL) {
7081 verbose(env, "returning from callee:\n");
7082 print_verifier_state(env, callee, true);
7083 verbose(env, "to caller at %d:\n", *insn_idx);
7084 print_verifier_state(env, caller, true);
7086 /* clear everything in the callee */
7087 free_func_state(callee);
7088 state->frame[state->curframe--] = NULL;
7092 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7094 struct bpf_call_arg_meta *meta)
7096 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
7098 if (ret_type != RET_INTEGER ||
7099 (func_id != BPF_FUNC_get_stack &&
7100 func_id != BPF_FUNC_get_task_stack &&
7101 func_id != BPF_FUNC_probe_read_str &&
7102 func_id != BPF_FUNC_probe_read_kernel_str &&
7103 func_id != BPF_FUNC_probe_read_user_str))
7106 ret_reg->smax_value = meta->msize_max_value;
7107 ret_reg->s32_max_value = meta->msize_max_value;
7108 ret_reg->smin_value = -MAX_ERRNO;
7109 ret_reg->s32_min_value = -MAX_ERRNO;
7110 reg_bounds_sync(ret_reg);
7114 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7115 int func_id, int insn_idx)
7117 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7118 struct bpf_map *map = meta->map_ptr;
7120 if (func_id != BPF_FUNC_tail_call &&
7121 func_id != BPF_FUNC_map_lookup_elem &&
7122 func_id != BPF_FUNC_map_update_elem &&
7123 func_id != BPF_FUNC_map_delete_elem &&
7124 func_id != BPF_FUNC_map_push_elem &&
7125 func_id != BPF_FUNC_map_pop_elem &&
7126 func_id != BPF_FUNC_map_peek_elem &&
7127 func_id != BPF_FUNC_for_each_map_elem &&
7128 func_id != BPF_FUNC_redirect_map &&
7129 func_id != BPF_FUNC_map_lookup_percpu_elem)
7133 verbose(env, "kernel subsystem misconfigured verifier\n");
7137 /* In case of read-only, some additional restrictions
7138 * need to be applied in order to prevent altering the
7139 * state of the map from program side.
7141 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7142 (func_id == BPF_FUNC_map_delete_elem ||
7143 func_id == BPF_FUNC_map_update_elem ||
7144 func_id == BPF_FUNC_map_push_elem ||
7145 func_id == BPF_FUNC_map_pop_elem)) {
7146 verbose(env, "write into map forbidden\n");
7150 if (!BPF_MAP_PTR(aux->map_ptr_state))
7151 bpf_map_ptr_store(aux, meta->map_ptr,
7152 !meta->map_ptr->bypass_spec_v1);
7153 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7154 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7155 !meta->map_ptr->bypass_spec_v1);
7160 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7161 int func_id, int insn_idx)
7163 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7164 struct bpf_reg_state *regs = cur_regs(env), *reg;
7165 struct bpf_map *map = meta->map_ptr;
7169 if (func_id != BPF_FUNC_tail_call)
7171 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7172 verbose(env, "kernel subsystem misconfigured verifier\n");
7176 reg = ®s[BPF_REG_3];
7177 val = reg->var_off.value;
7178 max = map->max_entries;
7180 if (!(register_is_const(reg) && val < max)) {
7181 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7185 err = mark_chain_precision(env, BPF_REG_3);
7188 if (bpf_map_key_unseen(aux))
7189 bpf_map_key_store(aux, val);
7190 else if (!bpf_map_key_poisoned(aux) &&
7191 bpf_map_key_immediate(aux) != val)
7192 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7196 static int check_reference_leak(struct bpf_verifier_env *env)
7198 struct bpf_func_state *state = cur_func(env);
7199 bool refs_lingering = false;
7202 if (state->frameno && !state->in_callback_fn)
7205 for (i = 0; i < state->acquired_refs; i++) {
7206 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7208 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7209 state->refs[i].id, state->refs[i].insn_idx);
7210 refs_lingering = true;
7212 return refs_lingering ? -EINVAL : 0;
7215 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7216 struct bpf_reg_state *regs)
7218 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
7219 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
7220 struct bpf_map *fmt_map = fmt_reg->map_ptr;
7221 int err, fmt_map_off, num_args;
7225 /* data must be an array of u64 */
7226 if (data_len_reg->var_off.value % 8)
7228 num_args = data_len_reg->var_off.value / 8;
7230 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7231 * and map_direct_value_addr is set.
7233 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7234 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7237 verbose(env, "verifier bug\n");
7240 fmt = (char *)(long)fmt_addr + fmt_map_off;
7242 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7243 * can focus on validating the format specifiers.
7245 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7247 verbose(env, "Invalid format string\n");
7252 static int check_get_func_ip(struct bpf_verifier_env *env)
7254 enum bpf_prog_type type = resolve_prog_type(env->prog);
7255 int func_id = BPF_FUNC_get_func_ip;
7257 if (type == BPF_PROG_TYPE_TRACING) {
7258 if (!bpf_prog_has_trampoline(env->prog)) {
7259 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7260 func_id_name(func_id), func_id);
7264 } else if (type == BPF_PROG_TYPE_KPROBE) {
7268 verbose(env, "func %s#%d not supported for program type %d\n",
7269 func_id_name(func_id), func_id, type);
7273 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7275 return &env->insn_aux_data[env->insn_idx];
7278 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7280 struct bpf_reg_state *regs = cur_regs(env);
7281 struct bpf_reg_state *reg = ®s[BPF_REG_4];
7282 bool reg_is_null = register_is_null(reg);
7285 mark_chain_precision(env, BPF_REG_4);
7290 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7292 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7294 if (!state->initialized) {
7295 state->initialized = 1;
7296 state->fit_for_inline = loop_flag_is_zero(env);
7297 state->callback_subprogno = subprogno;
7301 if (!state->fit_for_inline)
7304 state->fit_for_inline = (loop_flag_is_zero(env) &&
7305 state->callback_subprogno == subprogno);
7308 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7311 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7312 const struct bpf_func_proto *fn = NULL;
7313 enum bpf_return_type ret_type;
7314 enum bpf_type_flag ret_flag;
7315 struct bpf_reg_state *regs;
7316 struct bpf_call_arg_meta meta;
7317 int insn_idx = *insn_idx_p;
7319 int i, err, func_id;
7321 /* find function prototype */
7322 func_id = insn->imm;
7323 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7324 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7329 if (env->ops->get_func_proto)
7330 fn = env->ops->get_func_proto(func_id, env->prog);
7332 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7337 /* eBPF programs must be GPL compatible to use GPL-ed functions */
7338 if (!env->prog->gpl_compatible && fn->gpl_only) {
7339 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7343 if (fn->allowed && !fn->allowed(env->prog)) {
7344 verbose(env, "helper call is not allowed in probe\n");
7348 /* With LD_ABS/IND some JITs save/restore skb from r1. */
7349 changes_data = bpf_helper_changes_pkt_data(fn->func);
7350 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7351 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7352 func_id_name(func_id), func_id);
7356 memset(&meta, 0, sizeof(meta));
7357 meta.pkt_access = fn->pkt_access;
7359 err = check_func_proto(fn, func_id);
7361 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7362 func_id_name(func_id), func_id);
7366 meta.func_id = func_id;
7368 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7369 err = check_func_arg(env, i, &meta, fn);
7374 err = record_func_map(env, &meta, func_id, insn_idx);
7378 err = record_func_key(env, &meta, func_id, insn_idx);
7382 /* Mark slots with STACK_MISC in case of raw mode, stack offset
7383 * is inferred from register state.
7385 for (i = 0; i < meta.access_size; i++) {
7386 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7387 BPF_WRITE, -1, false);
7392 regs = cur_regs(env);
7394 if (meta.uninit_dynptr_regno) {
7395 /* we write BPF_DW bits (8 bytes) at a time */
7396 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7397 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7398 i, BPF_DW, BPF_WRITE, -1, false);
7403 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno],
7404 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7410 if (meta.release_regno) {
7412 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7413 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
7414 else if (meta.ref_obj_id)
7415 err = release_reference(env, meta.ref_obj_id);
7416 /* meta.ref_obj_id can only be 0 if register that is meant to be
7417 * released is NULL, which must be > R0.
7419 else if (register_is_null(®s[meta.release_regno]))
7422 verbose(env, "func %s#%d reference has not been acquired before\n",
7423 func_id_name(func_id), func_id);
7429 case BPF_FUNC_tail_call:
7430 err = check_reference_leak(env);
7432 verbose(env, "tail_call would lead to reference leak\n");
7436 case BPF_FUNC_get_local_storage:
7437 /* check that flags argument in get_local_storage(map, flags) is 0,
7438 * this is required because get_local_storage() can't return an error.
7440 if (!register_is_null(®s[BPF_REG_2])) {
7441 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7445 case BPF_FUNC_for_each_map_elem:
7446 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7447 set_map_elem_callback_state);
7449 case BPF_FUNC_timer_set_callback:
7450 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7451 set_timer_callback_state);
7453 case BPF_FUNC_find_vma:
7454 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7455 set_find_vma_callback_state);
7457 case BPF_FUNC_snprintf:
7458 err = check_bpf_snprintf_call(env, regs);
7461 update_loop_inline_state(env, meta.subprogno);
7462 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7463 set_loop_callback_state);
7465 case BPF_FUNC_dynptr_from_mem:
7466 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7467 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7468 reg_type_str(env, regs[BPF_REG_1].type));
7472 case BPF_FUNC_set_retval:
7473 if (prog_type == BPF_PROG_TYPE_LSM &&
7474 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7475 if (!env->prog->aux->attach_func_proto->type) {
7476 /* Make sure programs that attach to void
7477 * hooks don't try to modify return value.
7479 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7484 case BPF_FUNC_dynptr_data:
7485 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7486 if (arg_type_is_dynptr(fn->arg_type[i])) {
7487 struct bpf_reg_state *reg = ®s[BPF_REG_1 + i];
7489 if (meta.ref_obj_id) {
7490 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7494 if (base_type(reg->type) != PTR_TO_DYNPTR)
7495 /* Find the id of the dynptr we're
7496 * tracking the reference of
7498 meta.ref_obj_id = stack_slot_get_id(env, reg);
7502 if (i == MAX_BPF_FUNC_REG_ARGS) {
7503 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7507 case BPF_FUNC_user_ringbuf_drain:
7508 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7509 set_user_ringbuf_callback_state);
7516 /* reset caller saved regs */
7517 for (i = 0; i < CALLER_SAVED_REGS; i++) {
7518 mark_reg_not_init(env, regs, caller_saved[i]);
7519 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7522 /* helper call returns 64-bit value. */
7523 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7525 /* update return register (already marked as written above) */
7526 ret_type = fn->ret_type;
7527 ret_flag = type_flag(ret_type);
7529 switch (base_type(ret_type)) {
7531 /* sets type to SCALAR_VALUE */
7532 mark_reg_unknown(env, regs, BPF_REG_0);
7535 regs[BPF_REG_0].type = NOT_INIT;
7537 case RET_PTR_TO_MAP_VALUE:
7538 /* There is no offset yet applied, variable or fixed */
7539 mark_reg_known_zero(env, regs, BPF_REG_0);
7540 /* remember map_ptr, so that check_map_access()
7541 * can check 'value_size' boundary of memory access
7542 * to map element returned from bpf_map_lookup_elem()
7544 if (meta.map_ptr == NULL) {
7546 "kernel subsystem misconfigured verifier\n");
7549 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7550 regs[BPF_REG_0].map_uid = meta.map_uid;
7551 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7552 if (!type_may_be_null(ret_type) &&
7553 map_value_has_spin_lock(meta.map_ptr)) {
7554 regs[BPF_REG_0].id = ++env->id_gen;
7557 case RET_PTR_TO_SOCKET:
7558 mark_reg_known_zero(env, regs, BPF_REG_0);
7559 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7561 case RET_PTR_TO_SOCK_COMMON:
7562 mark_reg_known_zero(env, regs, BPF_REG_0);
7563 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7565 case RET_PTR_TO_TCP_SOCK:
7566 mark_reg_known_zero(env, regs, BPF_REG_0);
7567 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7569 case RET_PTR_TO_ALLOC_MEM:
7570 mark_reg_known_zero(env, regs, BPF_REG_0);
7571 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7572 regs[BPF_REG_0].mem_size = meta.mem_size;
7574 case RET_PTR_TO_MEM_OR_BTF_ID:
7576 const struct btf_type *t;
7578 mark_reg_known_zero(env, regs, BPF_REG_0);
7579 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7580 if (!btf_type_is_struct(t)) {
7582 const struct btf_type *ret;
7585 /* resolve the type size of ksym. */
7586 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7588 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7589 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7590 tname, PTR_ERR(ret));
7593 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7594 regs[BPF_REG_0].mem_size = tsize;
7596 /* MEM_RDONLY may be carried from ret_flag, but it
7597 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7598 * it will confuse the check of PTR_TO_BTF_ID in
7599 * check_mem_access().
7601 ret_flag &= ~MEM_RDONLY;
7603 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7604 regs[BPF_REG_0].btf = meta.ret_btf;
7605 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7609 case RET_PTR_TO_BTF_ID:
7611 struct btf *ret_btf;
7614 mark_reg_known_zero(env, regs, BPF_REG_0);
7615 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7616 if (func_id == BPF_FUNC_kptr_xchg) {
7617 ret_btf = meta.kptr_off_desc->kptr.btf;
7618 ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7620 if (fn->ret_btf_id == BPF_PTR_POISON) {
7621 verbose(env, "verifier internal error:");
7622 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7623 func_id_name(func_id));
7626 ret_btf = btf_vmlinux;
7627 ret_btf_id = *fn->ret_btf_id;
7629 if (ret_btf_id == 0) {
7630 verbose(env, "invalid return type %u of func %s#%d\n",
7631 base_type(ret_type), func_id_name(func_id),
7635 regs[BPF_REG_0].btf = ret_btf;
7636 regs[BPF_REG_0].btf_id = ret_btf_id;
7640 verbose(env, "unknown return type %u of func %s#%d\n",
7641 base_type(ret_type), func_id_name(func_id), func_id);
7645 if (type_may_be_null(regs[BPF_REG_0].type))
7646 regs[BPF_REG_0].id = ++env->id_gen;
7648 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7649 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7650 func_id_name(func_id), func_id);
7654 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7655 /* For release_reference() */
7656 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7657 } else if (is_acquire_function(func_id, meta.map_ptr)) {
7658 int id = acquire_reference_state(env, insn_idx);
7662 /* For mark_ptr_or_null_reg() */
7663 regs[BPF_REG_0].id = id;
7664 /* For release_reference() */
7665 regs[BPF_REG_0].ref_obj_id = id;
7668 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7670 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7674 if ((func_id == BPF_FUNC_get_stack ||
7675 func_id == BPF_FUNC_get_task_stack) &&
7676 !env->prog->has_callchain_buf) {
7677 const char *err_str;
7679 #ifdef CONFIG_PERF_EVENTS
7680 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7681 err_str = "cannot get callchain buffer for func %s#%d\n";
7684 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7687 verbose(env, err_str, func_id_name(func_id), func_id);
7691 env->prog->has_callchain_buf = true;
7694 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7695 env->prog->call_get_stack = true;
7697 if (func_id == BPF_FUNC_get_func_ip) {
7698 if (check_get_func_ip(env))
7700 env->prog->call_get_func_ip = true;
7704 clear_all_pkt_pointers(env);
7708 /* mark_btf_func_reg_size() is used when the reg size is determined by
7709 * the BTF func_proto's return value size and argument.
7711 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7714 struct bpf_reg_state *reg = &cur_regs(env)[regno];
7716 if (regno == BPF_REG_0) {
7717 /* Function return value */
7718 reg->live |= REG_LIVE_WRITTEN;
7719 reg->subreg_def = reg_size == sizeof(u64) ?
7720 DEF_NOT_SUBREG : env->insn_idx + 1;
7722 /* Function argument */
7723 if (reg_size == sizeof(u64)) {
7724 mark_insn_zext(env, reg);
7725 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7727 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7732 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7735 const struct btf_type *t, *func, *func_proto, *ptr_type;
7736 struct bpf_reg_state *regs = cur_regs(env);
7737 struct bpf_kfunc_arg_meta meta = { 0 };
7738 const char *func_name, *ptr_type_name;
7739 u32 i, nargs, func_id, ptr_type_id;
7740 int err, insn_idx = *insn_idx_p;
7741 const struct btf_param *args;
7742 struct btf *desc_btf;
7746 /* skip for now, but return error when we find this in fixup_kfunc_call */
7750 desc_btf = find_kfunc_desc_btf(env, insn->off);
7751 if (IS_ERR(desc_btf))
7752 return PTR_ERR(desc_btf);
7754 func_id = insn->imm;
7755 func = btf_type_by_id(desc_btf, func_id);
7756 func_name = btf_name_by_offset(desc_btf, func->name_off);
7757 func_proto = btf_type_by_id(desc_btf, func->type);
7759 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7761 verbose(env, "calling kernel function %s is not allowed\n",
7765 if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7766 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7770 acq = *kfunc_flags & KF_ACQUIRE;
7772 meta.flags = *kfunc_flags;
7774 /* Check the arguments */
7775 err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7778 /* In case of release function, we get register number of refcounted
7779 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7782 err = release_reference(env, regs[err].ref_obj_id);
7784 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7785 func_name, func_id);
7790 for (i = 0; i < CALLER_SAVED_REGS; i++)
7791 mark_reg_not_init(env, regs, caller_saved[i]);
7793 /* Check return type */
7794 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7796 if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7797 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7801 if (btf_type_is_scalar(t)) {
7802 mark_reg_unknown(env, regs, BPF_REG_0);
7803 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7804 } else if (btf_type_is_ptr(t)) {
7805 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7807 if (!btf_type_is_struct(ptr_type)) {
7808 if (!meta.r0_size) {
7809 ptr_type_name = btf_name_by_offset(desc_btf,
7810 ptr_type->name_off);
7812 "kernel function %s returns pointer type %s %s is not supported\n",
7814 btf_type_str(ptr_type),
7819 mark_reg_known_zero(env, regs, BPF_REG_0);
7820 regs[BPF_REG_0].type = PTR_TO_MEM;
7821 regs[BPF_REG_0].mem_size = meta.r0_size;
7824 regs[BPF_REG_0].type |= MEM_RDONLY;
7826 /* Ensures we don't access the memory after a release_reference() */
7827 if (meta.ref_obj_id)
7828 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7830 mark_reg_known_zero(env, regs, BPF_REG_0);
7831 regs[BPF_REG_0].btf = desc_btf;
7832 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7833 regs[BPF_REG_0].btf_id = ptr_type_id;
7835 if (*kfunc_flags & KF_RET_NULL) {
7836 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7837 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7838 regs[BPF_REG_0].id = ++env->id_gen;
7840 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7842 int id = acquire_reference_state(env, insn_idx);
7846 regs[BPF_REG_0].id = id;
7847 regs[BPF_REG_0].ref_obj_id = id;
7849 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7851 nargs = btf_type_vlen(func_proto);
7852 args = (const struct btf_param *)(func_proto + 1);
7853 for (i = 0; i < nargs; i++) {
7856 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7857 if (btf_type_is_ptr(t))
7858 mark_btf_func_reg_size(env, regno, sizeof(void *));
7860 /* scalar. ensured by btf_check_kfunc_arg_match() */
7861 mark_btf_func_reg_size(env, regno, t->size);
7867 static bool signed_add_overflows(s64 a, s64 b)
7869 /* Do the add in u64, where overflow is well-defined */
7870 s64 res = (s64)((u64)a + (u64)b);
7877 static bool signed_add32_overflows(s32 a, s32 b)
7879 /* Do the add in u32, where overflow is well-defined */
7880 s32 res = (s32)((u32)a + (u32)b);
7887 static bool signed_sub_overflows(s64 a, s64 b)
7889 /* Do the sub in u64, where overflow is well-defined */
7890 s64 res = (s64)((u64)a - (u64)b);
7897 static bool signed_sub32_overflows(s32 a, s32 b)
7899 /* Do the sub in u32, where overflow is well-defined */
7900 s32 res = (s32)((u32)a - (u32)b);
7907 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7908 const struct bpf_reg_state *reg,
7909 enum bpf_reg_type type)
7911 bool known = tnum_is_const(reg->var_off);
7912 s64 val = reg->var_off.value;
7913 s64 smin = reg->smin_value;
7915 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7916 verbose(env, "math between %s pointer and %lld is not allowed\n",
7917 reg_type_str(env, type), val);
7921 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7922 verbose(env, "%s pointer offset %d is not allowed\n",
7923 reg_type_str(env, type), reg->off);
7927 if (smin == S64_MIN) {
7928 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7929 reg_type_str(env, type));
7933 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7934 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7935 smin, reg_type_str(env, type));
7950 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7951 u32 *alu_limit, bool mask_to_left)
7953 u32 max = 0, ptr_limit = 0;
7955 switch (ptr_reg->type) {
7957 /* Offset 0 is out-of-bounds, but acceptable start for the
7958 * left direction, see BPF_REG_FP. Also, unknown scalar
7959 * offset where we would need to deal with min/max bounds is
7960 * currently prohibited for unprivileged.
7962 max = MAX_BPF_STACK + mask_to_left;
7963 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7965 case PTR_TO_MAP_VALUE:
7966 max = ptr_reg->map_ptr->value_size;
7967 ptr_limit = (mask_to_left ?
7968 ptr_reg->smin_value :
7969 ptr_reg->umax_value) + ptr_reg->off;
7975 if (ptr_limit >= max)
7976 return REASON_LIMIT;
7977 *alu_limit = ptr_limit;
7981 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7982 const struct bpf_insn *insn)
7984 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7987 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7988 u32 alu_state, u32 alu_limit)
7990 /* If we arrived here from different branches with different
7991 * state or limits to sanitize, then this won't work.
7993 if (aux->alu_state &&
7994 (aux->alu_state != alu_state ||
7995 aux->alu_limit != alu_limit))
7996 return REASON_PATHS;
7998 /* Corresponding fixup done in do_misc_fixups(). */
7999 aux->alu_state = alu_state;
8000 aux->alu_limit = alu_limit;
8004 static int sanitize_val_alu(struct bpf_verifier_env *env,
8005 struct bpf_insn *insn)
8007 struct bpf_insn_aux_data *aux = cur_aux(env);
8009 if (can_skip_alu_sanitation(env, insn))
8012 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
8015 static bool sanitize_needed(u8 opcode)
8017 return opcode == BPF_ADD || opcode == BPF_SUB;
8020 struct bpf_sanitize_info {
8021 struct bpf_insn_aux_data aux;
8025 static struct bpf_verifier_state *
8026 sanitize_speculative_path(struct bpf_verifier_env *env,
8027 const struct bpf_insn *insn,
8028 u32 next_idx, u32 curr_idx)
8030 struct bpf_verifier_state *branch;
8031 struct bpf_reg_state *regs;
8033 branch = push_stack(env, next_idx, curr_idx, true);
8034 if (branch && insn) {
8035 regs = branch->frame[branch->curframe]->regs;
8036 if (BPF_SRC(insn->code) == BPF_K) {
8037 mark_reg_unknown(env, regs, insn->dst_reg);
8038 } else if (BPF_SRC(insn->code) == BPF_X) {
8039 mark_reg_unknown(env, regs, insn->dst_reg);
8040 mark_reg_unknown(env, regs, insn->src_reg);
8046 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
8047 struct bpf_insn *insn,
8048 const struct bpf_reg_state *ptr_reg,
8049 const struct bpf_reg_state *off_reg,
8050 struct bpf_reg_state *dst_reg,
8051 struct bpf_sanitize_info *info,
8052 const bool commit_window)
8054 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
8055 struct bpf_verifier_state *vstate = env->cur_state;
8056 bool off_is_imm = tnum_is_const(off_reg->var_off);
8057 bool off_is_neg = off_reg->smin_value < 0;
8058 bool ptr_is_dst_reg = ptr_reg == dst_reg;
8059 u8 opcode = BPF_OP(insn->code);
8060 u32 alu_state, alu_limit;
8061 struct bpf_reg_state tmp;
8065 if (can_skip_alu_sanitation(env, insn))
8068 /* We already marked aux for masking from non-speculative
8069 * paths, thus we got here in the first place. We only care
8070 * to explore bad access from here.
8072 if (vstate->speculative)
8075 if (!commit_window) {
8076 if (!tnum_is_const(off_reg->var_off) &&
8077 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8078 return REASON_BOUNDS;
8080 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
8081 (opcode == BPF_SUB && !off_is_neg);
8084 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8088 if (commit_window) {
8089 /* In commit phase we narrow the masking window based on
8090 * the observed pointer move after the simulated operation.
8092 alu_state = info->aux.alu_state;
8093 alu_limit = abs(info->aux.alu_limit - alu_limit);
8095 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8096 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8097 alu_state |= ptr_is_dst_reg ?
8098 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8100 /* Limit pruning on unknown scalars to enable deep search for
8101 * potential masking differences from other program paths.
8104 env->explore_alu_limits = true;
8107 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8111 /* If we're in commit phase, we're done here given we already
8112 * pushed the truncated dst_reg into the speculative verification
8115 * Also, when register is a known constant, we rewrite register-based
8116 * operation to immediate-based, and thus do not need masking (and as
8117 * a consequence, do not need to simulate the zero-truncation either).
8119 if (commit_window || off_is_imm)
8122 /* Simulate and find potential out-of-bounds access under
8123 * speculative execution from truncation as a result of
8124 * masking when off was not within expected range. If off
8125 * sits in dst, then we temporarily need to move ptr there
8126 * to simulate dst (== 0) +/-= ptr. Needed, for example,
8127 * for cases where we use K-based arithmetic in one direction
8128 * and truncated reg-based in the other in order to explore
8131 if (!ptr_is_dst_reg) {
8133 copy_register_state(dst_reg, ptr_reg);
8135 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8137 if (!ptr_is_dst_reg && ret)
8139 return !ret ? REASON_STACK : 0;
8142 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8144 struct bpf_verifier_state *vstate = env->cur_state;
8146 /* If we simulate paths under speculation, we don't update the
8147 * insn as 'seen' such that when we verify unreachable paths in
8148 * the non-speculative domain, sanitize_dead_code() can still
8149 * rewrite/sanitize them.
8151 if (!vstate->speculative)
8152 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8155 static int sanitize_err(struct bpf_verifier_env *env,
8156 const struct bpf_insn *insn, int reason,
8157 const struct bpf_reg_state *off_reg,
8158 const struct bpf_reg_state *dst_reg)
8160 static const char *err = "pointer arithmetic with it prohibited for !root";
8161 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8162 u32 dst = insn->dst_reg, src = insn->src_reg;
8166 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8167 off_reg == dst_reg ? dst : src, err);
8170 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8171 off_reg == dst_reg ? src : dst, err);
8174 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8178 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8182 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8186 verbose(env, "verifier internal error: unknown reason (%d)\n",
8194 /* check that stack access falls within stack limits and that 'reg' doesn't
8195 * have a variable offset.
8197 * Variable offset is prohibited for unprivileged mode for simplicity since it
8198 * requires corresponding support in Spectre masking for stack ALU. See also
8199 * retrieve_ptr_limit().
8202 * 'off' includes 'reg->off'.
8204 static int check_stack_access_for_ptr_arithmetic(
8205 struct bpf_verifier_env *env,
8207 const struct bpf_reg_state *reg,
8210 if (!tnum_is_const(reg->var_off)) {
8213 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8214 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8215 regno, tn_buf, off);
8219 if (off >= 0 || off < -MAX_BPF_STACK) {
8220 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8221 "prohibited for !root; off=%d\n", regno, off);
8228 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8229 const struct bpf_insn *insn,
8230 const struct bpf_reg_state *dst_reg)
8232 u32 dst = insn->dst_reg;
8234 /* For unprivileged we require that resulting offset must be in bounds
8235 * in order to be able to sanitize access later on.
8237 if (env->bypass_spec_v1)
8240 switch (dst_reg->type) {
8242 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8243 dst_reg->off + dst_reg->var_off.value))
8246 case PTR_TO_MAP_VALUE:
8247 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8248 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8249 "prohibited for !root\n", dst);
8260 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8261 * Caller should also handle BPF_MOV case separately.
8262 * If we return -EACCES, caller may want to try again treating pointer as a
8263 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
8265 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8266 struct bpf_insn *insn,
8267 const struct bpf_reg_state *ptr_reg,
8268 const struct bpf_reg_state *off_reg)
8270 struct bpf_verifier_state *vstate = env->cur_state;
8271 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8272 struct bpf_reg_state *regs = state->regs, *dst_reg;
8273 bool known = tnum_is_const(off_reg->var_off);
8274 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8275 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8276 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8277 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8278 struct bpf_sanitize_info info = {};
8279 u8 opcode = BPF_OP(insn->code);
8280 u32 dst = insn->dst_reg;
8283 dst_reg = ®s[dst];
8285 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8286 smin_val > smax_val || umin_val > umax_val) {
8287 /* Taint dst register if offset had invalid bounds derived from
8288 * e.g. dead branches.
8290 __mark_reg_unknown(env, dst_reg);
8294 if (BPF_CLASS(insn->code) != BPF_ALU64) {
8295 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8296 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8297 __mark_reg_unknown(env, dst_reg);
8302 "R%d 32-bit pointer arithmetic prohibited\n",
8307 if (ptr_reg->type & PTR_MAYBE_NULL) {
8308 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8309 dst, reg_type_str(env, ptr_reg->type));
8313 switch (base_type(ptr_reg->type)) {
8314 case CONST_PTR_TO_MAP:
8315 /* smin_val represents the known value */
8316 if (known && smin_val == 0 && opcode == BPF_ADD)
8319 case PTR_TO_PACKET_END:
8321 case PTR_TO_SOCK_COMMON:
8322 case PTR_TO_TCP_SOCK:
8323 case PTR_TO_XDP_SOCK:
8324 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8325 dst, reg_type_str(env, ptr_reg->type));
8331 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8332 * The id may be overwritten later if we create a new variable offset.
8334 dst_reg->type = ptr_reg->type;
8335 dst_reg->id = ptr_reg->id;
8337 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8338 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8341 /* pointer types do not carry 32-bit bounds at the moment. */
8342 __mark_reg32_unbounded(dst_reg);
8344 if (sanitize_needed(opcode)) {
8345 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8348 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8353 /* We can take a fixed offset as long as it doesn't overflow
8354 * the s32 'off' field
8356 if (known && (ptr_reg->off + smin_val ==
8357 (s64)(s32)(ptr_reg->off + smin_val))) {
8358 /* pointer += K. Accumulate it into fixed offset */
8359 dst_reg->smin_value = smin_ptr;
8360 dst_reg->smax_value = smax_ptr;
8361 dst_reg->umin_value = umin_ptr;
8362 dst_reg->umax_value = umax_ptr;
8363 dst_reg->var_off = ptr_reg->var_off;
8364 dst_reg->off = ptr_reg->off + smin_val;
8365 dst_reg->raw = ptr_reg->raw;
8368 /* A new variable offset is created. Note that off_reg->off
8369 * == 0, since it's a scalar.
8370 * dst_reg gets the pointer type and since some positive
8371 * integer value was added to the pointer, give it a new 'id'
8372 * if it's a PTR_TO_PACKET.
8373 * this creates a new 'base' pointer, off_reg (variable) gets
8374 * added into the variable offset, and we copy the fixed offset
8377 if (signed_add_overflows(smin_ptr, smin_val) ||
8378 signed_add_overflows(smax_ptr, smax_val)) {
8379 dst_reg->smin_value = S64_MIN;
8380 dst_reg->smax_value = S64_MAX;
8382 dst_reg->smin_value = smin_ptr + smin_val;
8383 dst_reg->smax_value = smax_ptr + smax_val;
8385 if (umin_ptr + umin_val < umin_ptr ||
8386 umax_ptr + umax_val < umax_ptr) {
8387 dst_reg->umin_value = 0;
8388 dst_reg->umax_value = U64_MAX;
8390 dst_reg->umin_value = umin_ptr + umin_val;
8391 dst_reg->umax_value = umax_ptr + umax_val;
8393 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8394 dst_reg->off = ptr_reg->off;
8395 dst_reg->raw = ptr_reg->raw;
8396 if (reg_is_pkt_pointer(ptr_reg)) {
8397 dst_reg->id = ++env->id_gen;
8398 /* something was added to pkt_ptr, set range to zero */
8399 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8403 if (dst_reg == off_reg) {
8404 /* scalar -= pointer. Creates an unknown scalar */
8405 verbose(env, "R%d tried to subtract pointer from scalar\n",
8409 /* We don't allow subtraction from FP, because (according to
8410 * test_verifier.c test "invalid fp arithmetic", JITs might not
8411 * be able to deal with it.
8413 if (ptr_reg->type == PTR_TO_STACK) {
8414 verbose(env, "R%d subtraction from stack pointer prohibited\n",
8418 if (known && (ptr_reg->off - smin_val ==
8419 (s64)(s32)(ptr_reg->off - smin_val))) {
8420 /* pointer -= K. Subtract it from fixed offset */
8421 dst_reg->smin_value = smin_ptr;
8422 dst_reg->smax_value = smax_ptr;
8423 dst_reg->umin_value = umin_ptr;
8424 dst_reg->umax_value = umax_ptr;
8425 dst_reg->var_off = ptr_reg->var_off;
8426 dst_reg->id = ptr_reg->id;
8427 dst_reg->off = ptr_reg->off - smin_val;
8428 dst_reg->raw = ptr_reg->raw;
8431 /* A new variable offset is created. If the subtrahend is known
8432 * nonnegative, then any reg->range we had before is still good.
8434 if (signed_sub_overflows(smin_ptr, smax_val) ||
8435 signed_sub_overflows(smax_ptr, smin_val)) {
8436 /* Overflow possible, we know nothing */
8437 dst_reg->smin_value = S64_MIN;
8438 dst_reg->smax_value = S64_MAX;
8440 dst_reg->smin_value = smin_ptr - smax_val;
8441 dst_reg->smax_value = smax_ptr - smin_val;
8443 if (umin_ptr < umax_val) {
8444 /* Overflow possible, we know nothing */
8445 dst_reg->umin_value = 0;
8446 dst_reg->umax_value = U64_MAX;
8448 /* Cannot overflow (as long as bounds are consistent) */
8449 dst_reg->umin_value = umin_ptr - umax_val;
8450 dst_reg->umax_value = umax_ptr - umin_val;
8452 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8453 dst_reg->off = ptr_reg->off;
8454 dst_reg->raw = ptr_reg->raw;
8455 if (reg_is_pkt_pointer(ptr_reg)) {
8456 dst_reg->id = ++env->id_gen;
8457 /* something was added to pkt_ptr, set range to zero */
8459 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8465 /* bitwise ops on pointers are troublesome, prohibit. */
8466 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8467 dst, bpf_alu_string[opcode >> 4]);
8470 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8471 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8472 dst, bpf_alu_string[opcode >> 4]);
8476 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8478 reg_bounds_sync(dst_reg);
8479 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8481 if (sanitize_needed(opcode)) {
8482 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8485 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8491 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8492 struct bpf_reg_state *src_reg)
8494 s32 smin_val = src_reg->s32_min_value;
8495 s32 smax_val = src_reg->s32_max_value;
8496 u32 umin_val = src_reg->u32_min_value;
8497 u32 umax_val = src_reg->u32_max_value;
8499 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8500 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8501 dst_reg->s32_min_value = S32_MIN;
8502 dst_reg->s32_max_value = S32_MAX;
8504 dst_reg->s32_min_value += smin_val;
8505 dst_reg->s32_max_value += smax_val;
8507 if (dst_reg->u32_min_value + umin_val < umin_val ||
8508 dst_reg->u32_max_value + umax_val < umax_val) {
8509 dst_reg->u32_min_value = 0;
8510 dst_reg->u32_max_value = U32_MAX;
8512 dst_reg->u32_min_value += umin_val;
8513 dst_reg->u32_max_value += umax_val;
8517 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8518 struct bpf_reg_state *src_reg)
8520 s64 smin_val = src_reg->smin_value;
8521 s64 smax_val = src_reg->smax_value;
8522 u64 umin_val = src_reg->umin_value;
8523 u64 umax_val = src_reg->umax_value;
8525 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8526 signed_add_overflows(dst_reg->smax_value, smax_val)) {
8527 dst_reg->smin_value = S64_MIN;
8528 dst_reg->smax_value = S64_MAX;
8530 dst_reg->smin_value += smin_val;
8531 dst_reg->smax_value += smax_val;
8533 if (dst_reg->umin_value + umin_val < umin_val ||
8534 dst_reg->umax_value + umax_val < umax_val) {
8535 dst_reg->umin_value = 0;
8536 dst_reg->umax_value = U64_MAX;
8538 dst_reg->umin_value += umin_val;
8539 dst_reg->umax_value += umax_val;
8543 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8544 struct bpf_reg_state *src_reg)
8546 s32 smin_val = src_reg->s32_min_value;
8547 s32 smax_val = src_reg->s32_max_value;
8548 u32 umin_val = src_reg->u32_min_value;
8549 u32 umax_val = src_reg->u32_max_value;
8551 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8552 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8553 /* Overflow possible, we know nothing */
8554 dst_reg->s32_min_value = S32_MIN;
8555 dst_reg->s32_max_value = S32_MAX;
8557 dst_reg->s32_min_value -= smax_val;
8558 dst_reg->s32_max_value -= smin_val;
8560 if (dst_reg->u32_min_value < umax_val) {
8561 /* Overflow possible, we know nothing */
8562 dst_reg->u32_min_value = 0;
8563 dst_reg->u32_max_value = U32_MAX;
8565 /* Cannot overflow (as long as bounds are consistent) */
8566 dst_reg->u32_min_value -= umax_val;
8567 dst_reg->u32_max_value -= umin_val;
8571 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8572 struct bpf_reg_state *src_reg)
8574 s64 smin_val = src_reg->smin_value;
8575 s64 smax_val = src_reg->smax_value;
8576 u64 umin_val = src_reg->umin_value;
8577 u64 umax_val = src_reg->umax_value;
8579 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8580 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8581 /* Overflow possible, we know nothing */
8582 dst_reg->smin_value = S64_MIN;
8583 dst_reg->smax_value = S64_MAX;
8585 dst_reg->smin_value -= smax_val;
8586 dst_reg->smax_value -= smin_val;
8588 if (dst_reg->umin_value < umax_val) {
8589 /* Overflow possible, we know nothing */
8590 dst_reg->umin_value = 0;
8591 dst_reg->umax_value = U64_MAX;
8593 /* Cannot overflow (as long as bounds are consistent) */
8594 dst_reg->umin_value -= umax_val;
8595 dst_reg->umax_value -= umin_val;
8599 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8600 struct bpf_reg_state *src_reg)
8602 s32 smin_val = src_reg->s32_min_value;
8603 u32 umin_val = src_reg->u32_min_value;
8604 u32 umax_val = src_reg->u32_max_value;
8606 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8607 /* Ain't nobody got time to multiply that sign */
8608 __mark_reg32_unbounded(dst_reg);
8611 /* Both values are positive, so we can work with unsigned and
8612 * copy the result to signed (unless it exceeds S32_MAX).
8614 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8615 /* Potential overflow, we know nothing */
8616 __mark_reg32_unbounded(dst_reg);
8619 dst_reg->u32_min_value *= umin_val;
8620 dst_reg->u32_max_value *= umax_val;
8621 if (dst_reg->u32_max_value > S32_MAX) {
8622 /* Overflow possible, we know nothing */
8623 dst_reg->s32_min_value = S32_MIN;
8624 dst_reg->s32_max_value = S32_MAX;
8626 dst_reg->s32_min_value = dst_reg->u32_min_value;
8627 dst_reg->s32_max_value = dst_reg->u32_max_value;
8631 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8632 struct bpf_reg_state *src_reg)
8634 s64 smin_val = src_reg->smin_value;
8635 u64 umin_val = src_reg->umin_value;
8636 u64 umax_val = src_reg->umax_value;
8638 if (smin_val < 0 || dst_reg->smin_value < 0) {
8639 /* Ain't nobody got time to multiply that sign */
8640 __mark_reg64_unbounded(dst_reg);
8643 /* Both values are positive, so we can work with unsigned and
8644 * copy the result to signed (unless it exceeds S64_MAX).
8646 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8647 /* Potential overflow, we know nothing */
8648 __mark_reg64_unbounded(dst_reg);
8651 dst_reg->umin_value *= umin_val;
8652 dst_reg->umax_value *= umax_val;
8653 if (dst_reg->umax_value > S64_MAX) {
8654 /* Overflow possible, we know nothing */
8655 dst_reg->smin_value = S64_MIN;
8656 dst_reg->smax_value = S64_MAX;
8658 dst_reg->smin_value = dst_reg->umin_value;
8659 dst_reg->smax_value = dst_reg->umax_value;
8663 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8664 struct bpf_reg_state *src_reg)
8666 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8667 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8668 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8669 s32 smin_val = src_reg->s32_min_value;
8670 u32 umax_val = src_reg->u32_max_value;
8672 if (src_known && dst_known) {
8673 __mark_reg32_known(dst_reg, var32_off.value);
8677 /* We get our minimum from the var_off, since that's inherently
8678 * bitwise. Our maximum is the minimum of the operands' maxima.
8680 dst_reg->u32_min_value = var32_off.value;
8681 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8682 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8683 /* Lose signed bounds when ANDing negative numbers,
8684 * ain't nobody got time for that.
8686 dst_reg->s32_min_value = S32_MIN;
8687 dst_reg->s32_max_value = S32_MAX;
8689 /* ANDing two positives gives a positive, so safe to
8690 * cast result into s64.
8692 dst_reg->s32_min_value = dst_reg->u32_min_value;
8693 dst_reg->s32_max_value = dst_reg->u32_max_value;
8697 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8698 struct bpf_reg_state *src_reg)
8700 bool src_known = tnum_is_const(src_reg->var_off);
8701 bool dst_known = tnum_is_const(dst_reg->var_off);
8702 s64 smin_val = src_reg->smin_value;
8703 u64 umax_val = src_reg->umax_value;
8705 if (src_known && dst_known) {
8706 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8710 /* We get our minimum from the var_off, since that's inherently
8711 * bitwise. Our maximum is the minimum of the operands' maxima.
8713 dst_reg->umin_value = dst_reg->var_off.value;
8714 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8715 if (dst_reg->smin_value < 0 || smin_val < 0) {
8716 /* Lose signed bounds when ANDing negative numbers,
8717 * ain't nobody got time for that.
8719 dst_reg->smin_value = S64_MIN;
8720 dst_reg->smax_value = S64_MAX;
8722 /* ANDing two positives gives a positive, so safe to
8723 * cast result into s64.
8725 dst_reg->smin_value = dst_reg->umin_value;
8726 dst_reg->smax_value = dst_reg->umax_value;
8728 /* We may learn something more from the var_off */
8729 __update_reg_bounds(dst_reg);
8732 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8733 struct bpf_reg_state *src_reg)
8735 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8736 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8737 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8738 s32 smin_val = src_reg->s32_min_value;
8739 u32 umin_val = src_reg->u32_min_value;
8741 if (src_known && dst_known) {
8742 __mark_reg32_known(dst_reg, var32_off.value);
8746 /* We get our maximum from the var_off, and our minimum is the
8747 * maximum of the operands' minima
8749 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8750 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8751 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8752 /* Lose signed bounds when ORing negative numbers,
8753 * ain't nobody got time for that.
8755 dst_reg->s32_min_value = S32_MIN;
8756 dst_reg->s32_max_value = S32_MAX;
8758 /* ORing two positives gives a positive, so safe to
8759 * cast result into s64.
8761 dst_reg->s32_min_value = dst_reg->u32_min_value;
8762 dst_reg->s32_max_value = dst_reg->u32_max_value;
8766 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8767 struct bpf_reg_state *src_reg)
8769 bool src_known = tnum_is_const(src_reg->var_off);
8770 bool dst_known = tnum_is_const(dst_reg->var_off);
8771 s64 smin_val = src_reg->smin_value;
8772 u64 umin_val = src_reg->umin_value;
8774 if (src_known && dst_known) {
8775 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8779 /* We get our maximum from the var_off, and our minimum is the
8780 * maximum of the operands' minima
8782 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8783 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8784 if (dst_reg->smin_value < 0 || smin_val < 0) {
8785 /* Lose signed bounds when ORing negative numbers,
8786 * ain't nobody got time for that.
8788 dst_reg->smin_value = S64_MIN;
8789 dst_reg->smax_value = S64_MAX;
8791 /* ORing two positives gives a positive, so safe to
8792 * cast result into s64.
8794 dst_reg->smin_value = dst_reg->umin_value;
8795 dst_reg->smax_value = dst_reg->umax_value;
8797 /* We may learn something more from the var_off */
8798 __update_reg_bounds(dst_reg);
8801 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8802 struct bpf_reg_state *src_reg)
8804 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8805 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8806 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8807 s32 smin_val = src_reg->s32_min_value;
8809 if (src_known && dst_known) {
8810 __mark_reg32_known(dst_reg, var32_off.value);
8814 /* We get both minimum and maximum from the var32_off. */
8815 dst_reg->u32_min_value = var32_off.value;
8816 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8818 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8819 /* XORing two positive sign numbers gives a positive,
8820 * so safe to cast u32 result into s32.
8822 dst_reg->s32_min_value = dst_reg->u32_min_value;
8823 dst_reg->s32_max_value = dst_reg->u32_max_value;
8825 dst_reg->s32_min_value = S32_MIN;
8826 dst_reg->s32_max_value = S32_MAX;
8830 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8831 struct bpf_reg_state *src_reg)
8833 bool src_known = tnum_is_const(src_reg->var_off);
8834 bool dst_known = tnum_is_const(dst_reg->var_off);
8835 s64 smin_val = src_reg->smin_value;
8837 if (src_known && dst_known) {
8838 /* dst_reg->var_off.value has been updated earlier */
8839 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8843 /* We get both minimum and maximum from the var_off. */
8844 dst_reg->umin_value = dst_reg->var_off.value;
8845 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8847 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8848 /* XORing two positive sign numbers gives a positive,
8849 * so safe to cast u64 result into s64.
8851 dst_reg->smin_value = dst_reg->umin_value;
8852 dst_reg->smax_value = dst_reg->umax_value;
8854 dst_reg->smin_value = S64_MIN;
8855 dst_reg->smax_value = S64_MAX;
8858 __update_reg_bounds(dst_reg);
8861 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8862 u64 umin_val, u64 umax_val)
8864 /* We lose all sign bit information (except what we can pick
8867 dst_reg->s32_min_value = S32_MIN;
8868 dst_reg->s32_max_value = S32_MAX;
8869 /* If we might shift our top bit out, then we know nothing */
8870 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8871 dst_reg->u32_min_value = 0;
8872 dst_reg->u32_max_value = U32_MAX;
8874 dst_reg->u32_min_value <<= umin_val;
8875 dst_reg->u32_max_value <<= umax_val;
8879 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8880 struct bpf_reg_state *src_reg)
8882 u32 umax_val = src_reg->u32_max_value;
8883 u32 umin_val = src_reg->u32_min_value;
8884 /* u32 alu operation will zext upper bits */
8885 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8887 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8888 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8889 /* Not required but being careful mark reg64 bounds as unknown so
8890 * that we are forced to pick them up from tnum and zext later and
8891 * if some path skips this step we are still safe.
8893 __mark_reg64_unbounded(dst_reg);
8894 __update_reg32_bounds(dst_reg);
8897 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8898 u64 umin_val, u64 umax_val)
8900 /* Special case <<32 because it is a common compiler pattern to sign
8901 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8902 * positive we know this shift will also be positive so we can track
8903 * bounds correctly. Otherwise we lose all sign bit information except
8904 * what we can pick up from var_off. Perhaps we can generalize this
8905 * later to shifts of any length.
8907 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8908 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8910 dst_reg->smax_value = S64_MAX;
8912 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8913 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8915 dst_reg->smin_value = S64_MIN;
8917 /* If we might shift our top bit out, then we know nothing */
8918 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8919 dst_reg->umin_value = 0;
8920 dst_reg->umax_value = U64_MAX;
8922 dst_reg->umin_value <<= umin_val;
8923 dst_reg->umax_value <<= umax_val;
8927 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8928 struct bpf_reg_state *src_reg)
8930 u64 umax_val = src_reg->umax_value;
8931 u64 umin_val = src_reg->umin_value;
8933 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8934 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8935 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8937 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8938 /* We may learn something more from the var_off */
8939 __update_reg_bounds(dst_reg);
8942 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8943 struct bpf_reg_state *src_reg)
8945 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8946 u32 umax_val = src_reg->u32_max_value;
8947 u32 umin_val = src_reg->u32_min_value;
8949 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8950 * be negative, then either:
8951 * 1) src_reg might be zero, so the sign bit of the result is
8952 * unknown, so we lose our signed bounds
8953 * 2) it's known negative, thus the unsigned bounds capture the
8955 * 3) the signed bounds cross zero, so they tell us nothing
8957 * If the value in dst_reg is known nonnegative, then again the
8958 * unsigned bounds capture the signed bounds.
8959 * Thus, in all cases it suffices to blow away our signed bounds
8960 * and rely on inferring new ones from the unsigned bounds and
8961 * var_off of the result.
8963 dst_reg->s32_min_value = S32_MIN;
8964 dst_reg->s32_max_value = S32_MAX;
8966 dst_reg->var_off = tnum_rshift(subreg, umin_val);
8967 dst_reg->u32_min_value >>= umax_val;
8968 dst_reg->u32_max_value >>= umin_val;
8970 __mark_reg64_unbounded(dst_reg);
8971 __update_reg32_bounds(dst_reg);
8974 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8975 struct bpf_reg_state *src_reg)
8977 u64 umax_val = src_reg->umax_value;
8978 u64 umin_val = src_reg->umin_value;
8980 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8981 * be negative, then either:
8982 * 1) src_reg might be zero, so the sign bit of the result is
8983 * unknown, so we lose our signed bounds
8984 * 2) it's known negative, thus the unsigned bounds capture the
8986 * 3) the signed bounds cross zero, so they tell us nothing
8988 * If the value in dst_reg is known nonnegative, then again the
8989 * unsigned bounds capture the signed bounds.
8990 * Thus, in all cases it suffices to blow away our signed bounds
8991 * and rely on inferring new ones from the unsigned bounds and
8992 * var_off of the result.
8994 dst_reg->smin_value = S64_MIN;
8995 dst_reg->smax_value = S64_MAX;
8996 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8997 dst_reg->umin_value >>= umax_val;
8998 dst_reg->umax_value >>= umin_val;
9000 /* Its not easy to operate on alu32 bounds here because it depends
9001 * on bits being shifted in. Take easy way out and mark unbounded
9002 * so we can recalculate later from tnum.
9004 __mark_reg32_unbounded(dst_reg);
9005 __update_reg_bounds(dst_reg);
9008 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
9009 struct bpf_reg_state *src_reg)
9011 u64 umin_val = src_reg->u32_min_value;
9013 /* Upon reaching here, src_known is true and
9014 * umax_val is equal to umin_val.
9016 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
9017 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
9019 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
9021 /* blow away the dst_reg umin_value/umax_value and rely on
9022 * dst_reg var_off to refine the result.
9024 dst_reg->u32_min_value = 0;
9025 dst_reg->u32_max_value = U32_MAX;
9027 __mark_reg64_unbounded(dst_reg);
9028 __update_reg32_bounds(dst_reg);
9031 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
9032 struct bpf_reg_state *src_reg)
9034 u64 umin_val = src_reg->umin_value;
9036 /* Upon reaching here, src_known is true and umax_val is equal
9039 dst_reg->smin_value >>= umin_val;
9040 dst_reg->smax_value >>= umin_val;
9042 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
9044 /* blow away the dst_reg umin_value/umax_value and rely on
9045 * dst_reg var_off to refine the result.
9047 dst_reg->umin_value = 0;
9048 dst_reg->umax_value = U64_MAX;
9050 /* Its not easy to operate on alu32 bounds here because it depends
9051 * on bits being shifted in from upper 32-bits. Take easy way out
9052 * and mark unbounded so we can recalculate later from tnum.
9054 __mark_reg32_unbounded(dst_reg);
9055 __update_reg_bounds(dst_reg);
9058 /* WARNING: This function does calculations on 64-bit values, but the actual
9059 * execution may occur on 32-bit values. Therefore, things like bitshifts
9060 * need extra checks in the 32-bit case.
9062 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9063 struct bpf_insn *insn,
9064 struct bpf_reg_state *dst_reg,
9065 struct bpf_reg_state src_reg)
9067 struct bpf_reg_state *regs = cur_regs(env);
9068 u8 opcode = BPF_OP(insn->code);
9070 s64 smin_val, smax_val;
9071 u64 umin_val, umax_val;
9072 s32 s32_min_val, s32_max_val;
9073 u32 u32_min_val, u32_max_val;
9074 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9075 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9078 smin_val = src_reg.smin_value;
9079 smax_val = src_reg.smax_value;
9080 umin_val = src_reg.umin_value;
9081 umax_val = src_reg.umax_value;
9083 s32_min_val = src_reg.s32_min_value;
9084 s32_max_val = src_reg.s32_max_value;
9085 u32_min_val = src_reg.u32_min_value;
9086 u32_max_val = src_reg.u32_max_value;
9089 src_known = tnum_subreg_is_const(src_reg.var_off);
9091 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9092 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9093 /* Taint dst register if offset had invalid bounds
9094 * derived from e.g. dead branches.
9096 __mark_reg_unknown(env, dst_reg);
9100 src_known = tnum_is_const(src_reg.var_off);
9102 (smin_val != smax_val || umin_val != umax_val)) ||
9103 smin_val > smax_val || umin_val > umax_val) {
9104 /* Taint dst register if offset had invalid bounds
9105 * derived from e.g. dead branches.
9107 __mark_reg_unknown(env, dst_reg);
9113 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9114 __mark_reg_unknown(env, dst_reg);
9118 if (sanitize_needed(opcode)) {
9119 ret = sanitize_val_alu(env, insn);
9121 return sanitize_err(env, insn, ret, NULL, NULL);
9124 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9125 * There are two classes of instructions: The first class we track both
9126 * alu32 and alu64 sign/unsigned bounds independently this provides the
9127 * greatest amount of precision when alu operations are mixed with jmp32
9128 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9129 * and BPF_OR. This is possible because these ops have fairly easy to
9130 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9131 * See alu32 verifier tests for examples. The second class of
9132 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9133 * with regards to tracking sign/unsigned bounds because the bits may
9134 * cross subreg boundaries in the alu64 case. When this happens we mark
9135 * the reg unbounded in the subreg bound space and use the resulting
9136 * tnum to calculate an approximation of the sign/unsigned bounds.
9140 scalar32_min_max_add(dst_reg, &src_reg);
9141 scalar_min_max_add(dst_reg, &src_reg);
9142 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9145 scalar32_min_max_sub(dst_reg, &src_reg);
9146 scalar_min_max_sub(dst_reg, &src_reg);
9147 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9150 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9151 scalar32_min_max_mul(dst_reg, &src_reg);
9152 scalar_min_max_mul(dst_reg, &src_reg);
9155 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9156 scalar32_min_max_and(dst_reg, &src_reg);
9157 scalar_min_max_and(dst_reg, &src_reg);
9160 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9161 scalar32_min_max_or(dst_reg, &src_reg);
9162 scalar_min_max_or(dst_reg, &src_reg);
9165 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9166 scalar32_min_max_xor(dst_reg, &src_reg);
9167 scalar_min_max_xor(dst_reg, &src_reg);
9170 if (umax_val >= insn_bitness) {
9171 /* Shifts greater than 31 or 63 are undefined.
9172 * This includes shifts by a negative number.
9174 mark_reg_unknown(env, regs, insn->dst_reg);
9178 scalar32_min_max_lsh(dst_reg, &src_reg);
9180 scalar_min_max_lsh(dst_reg, &src_reg);
9183 if (umax_val >= insn_bitness) {
9184 /* Shifts greater than 31 or 63 are undefined.
9185 * This includes shifts by a negative number.
9187 mark_reg_unknown(env, regs, insn->dst_reg);
9191 scalar32_min_max_rsh(dst_reg, &src_reg);
9193 scalar_min_max_rsh(dst_reg, &src_reg);
9196 if (umax_val >= insn_bitness) {
9197 /* Shifts greater than 31 or 63 are undefined.
9198 * This includes shifts by a negative number.
9200 mark_reg_unknown(env, regs, insn->dst_reg);
9204 scalar32_min_max_arsh(dst_reg, &src_reg);
9206 scalar_min_max_arsh(dst_reg, &src_reg);
9209 mark_reg_unknown(env, regs, insn->dst_reg);
9213 /* ALU32 ops are zero extended into 64bit register */
9215 zext_32_to_64(dst_reg);
9216 reg_bounds_sync(dst_reg);
9220 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9223 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9224 struct bpf_insn *insn)
9226 struct bpf_verifier_state *vstate = env->cur_state;
9227 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9228 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9229 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9230 u8 opcode = BPF_OP(insn->code);
9233 dst_reg = ®s[insn->dst_reg];
9235 if (dst_reg->type != SCALAR_VALUE)
9238 /* Make sure ID is cleared otherwise dst_reg min/max could be
9239 * incorrectly propagated into other registers by find_equal_scalars()
9242 if (BPF_SRC(insn->code) == BPF_X) {
9243 src_reg = ®s[insn->src_reg];
9244 if (src_reg->type != SCALAR_VALUE) {
9245 if (dst_reg->type != SCALAR_VALUE) {
9246 /* Combining two pointers by any ALU op yields
9247 * an arbitrary scalar. Disallow all math except
9248 * pointer subtraction
9250 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9251 mark_reg_unknown(env, regs, insn->dst_reg);
9254 verbose(env, "R%d pointer %s pointer prohibited\n",
9256 bpf_alu_string[opcode >> 4]);
9259 /* scalar += pointer
9260 * This is legal, but we have to reverse our
9261 * src/dest handling in computing the range
9263 err = mark_chain_precision(env, insn->dst_reg);
9266 return adjust_ptr_min_max_vals(env, insn,
9269 } else if (ptr_reg) {
9270 /* pointer += scalar */
9271 err = mark_chain_precision(env, insn->src_reg);
9274 return adjust_ptr_min_max_vals(env, insn,
9276 } else if (dst_reg->precise) {
9277 /* if dst_reg is precise, src_reg should be precise as well */
9278 err = mark_chain_precision(env, insn->src_reg);
9283 /* Pretend the src is a reg with a known value, since we only
9284 * need to be able to read from this state.
9286 off_reg.type = SCALAR_VALUE;
9287 __mark_reg_known(&off_reg, insn->imm);
9289 if (ptr_reg) /* pointer += K */
9290 return adjust_ptr_min_max_vals(env, insn,
9294 /* Got here implies adding two SCALAR_VALUEs */
9295 if (WARN_ON_ONCE(ptr_reg)) {
9296 print_verifier_state(env, state, true);
9297 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9300 if (WARN_ON(!src_reg)) {
9301 print_verifier_state(env, state, true);
9302 verbose(env, "verifier internal error: no src_reg\n");
9305 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9308 /* check validity of 32-bit and 64-bit arithmetic operations */
9309 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9311 struct bpf_reg_state *regs = cur_regs(env);
9312 u8 opcode = BPF_OP(insn->code);
9315 if (opcode == BPF_END || opcode == BPF_NEG) {
9316 if (opcode == BPF_NEG) {
9317 if (BPF_SRC(insn->code) != BPF_K ||
9318 insn->src_reg != BPF_REG_0 ||
9319 insn->off != 0 || insn->imm != 0) {
9320 verbose(env, "BPF_NEG uses reserved fields\n");
9324 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9325 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9326 BPF_CLASS(insn->code) == BPF_ALU64) {
9327 verbose(env, "BPF_END uses reserved fields\n");
9332 /* check src operand */
9333 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9337 if (is_pointer_value(env, insn->dst_reg)) {
9338 verbose(env, "R%d pointer arithmetic prohibited\n",
9343 /* check dest operand */
9344 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9348 } else if (opcode == BPF_MOV) {
9350 if (BPF_SRC(insn->code) == BPF_X) {
9351 if (insn->imm != 0 || insn->off != 0) {
9352 verbose(env, "BPF_MOV uses reserved fields\n");
9356 /* check src operand */
9357 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9361 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9362 verbose(env, "BPF_MOV uses reserved fields\n");
9367 /* check dest operand, mark as required later */
9368 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9372 if (BPF_SRC(insn->code) == BPF_X) {
9373 struct bpf_reg_state *src_reg = regs + insn->src_reg;
9374 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9376 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9378 * copy register state to dest reg
9380 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9381 /* Assign src and dst registers the same ID
9382 * that will be used by find_equal_scalars()
9383 * to propagate min/max range.
9385 src_reg->id = ++env->id_gen;
9386 copy_register_state(dst_reg, src_reg);
9387 dst_reg->live |= REG_LIVE_WRITTEN;
9388 dst_reg->subreg_def = DEF_NOT_SUBREG;
9391 if (is_pointer_value(env, insn->src_reg)) {
9393 "R%d partial copy of pointer\n",
9396 } else if (src_reg->type == SCALAR_VALUE) {
9397 copy_register_state(dst_reg, src_reg);
9398 /* Make sure ID is cleared otherwise
9399 * dst_reg min/max could be incorrectly
9400 * propagated into src_reg by find_equal_scalars()
9403 dst_reg->live |= REG_LIVE_WRITTEN;
9404 dst_reg->subreg_def = env->insn_idx + 1;
9406 mark_reg_unknown(env, regs,
9409 zext_32_to_64(dst_reg);
9410 reg_bounds_sync(dst_reg);
9414 * remember the value we stored into this reg
9416 /* clear any state __mark_reg_known doesn't set */
9417 mark_reg_unknown(env, regs, insn->dst_reg);
9418 regs[insn->dst_reg].type = SCALAR_VALUE;
9419 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9420 __mark_reg_known(regs + insn->dst_reg,
9423 __mark_reg_known(regs + insn->dst_reg,
9428 } else if (opcode > BPF_END) {
9429 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9432 } else { /* all other ALU ops: and, sub, xor, add, ... */
9434 if (BPF_SRC(insn->code) == BPF_X) {
9435 if (insn->imm != 0 || insn->off != 0) {
9436 verbose(env, "BPF_ALU uses reserved fields\n");
9439 /* check src1 operand */
9440 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9444 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9445 verbose(env, "BPF_ALU uses reserved fields\n");
9450 /* check src2 operand */
9451 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9455 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9456 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9457 verbose(env, "div by zero\n");
9461 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9462 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9463 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9465 if (insn->imm < 0 || insn->imm >= size) {
9466 verbose(env, "invalid shift %d\n", insn->imm);
9471 /* check dest operand */
9472 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9476 return adjust_reg_min_max_vals(env, insn);
9482 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9483 struct bpf_reg_state *dst_reg,
9484 enum bpf_reg_type type,
9485 bool range_right_open)
9487 struct bpf_func_state *state;
9488 struct bpf_reg_state *reg;
9491 if (dst_reg->off < 0 ||
9492 (dst_reg->off == 0 && range_right_open))
9493 /* This doesn't give us any range */
9496 if (dst_reg->umax_value > MAX_PACKET_OFF ||
9497 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9498 /* Risk of overflow. For instance, ptr + (1<<63) may be less
9499 * than pkt_end, but that's because it's also less than pkt.
9503 new_range = dst_reg->off;
9504 if (range_right_open)
9507 /* Examples for register markings:
9509 * pkt_data in dst register:
9513 * if (r2 > pkt_end) goto <handle exception>
9518 * if (r2 < pkt_end) goto <access okay>
9519 * <handle exception>
9522 * r2 == dst_reg, pkt_end == src_reg
9523 * r2=pkt(id=n,off=8,r=0)
9524 * r3=pkt(id=n,off=0,r=0)
9526 * pkt_data in src register:
9530 * if (pkt_end >= r2) goto <access okay>
9531 * <handle exception>
9535 * if (pkt_end <= r2) goto <handle exception>
9539 * pkt_end == dst_reg, r2 == src_reg
9540 * r2=pkt(id=n,off=8,r=0)
9541 * r3=pkt(id=n,off=0,r=0)
9543 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9544 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9545 * and [r3, r3 + 8-1) respectively is safe to access depending on
9549 /* If our ids match, then we must have the same max_value. And we
9550 * don't care about the other reg's fixed offset, since if it's too big
9551 * the range won't allow anything.
9552 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9554 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9555 if (reg->type == type && reg->id == dst_reg->id)
9556 /* keep the maximum range already checked */
9557 reg->range = max(reg->range, new_range);
9561 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9563 struct tnum subreg = tnum_subreg(reg->var_off);
9564 s32 sval = (s32)val;
9568 if (tnum_is_const(subreg))
9569 return !!tnum_equals_const(subreg, val);
9572 if (tnum_is_const(subreg))
9573 return !tnum_equals_const(subreg, val);
9576 if ((~subreg.mask & subreg.value) & val)
9578 if (!((subreg.mask | subreg.value) & val))
9582 if (reg->u32_min_value > val)
9584 else if (reg->u32_max_value <= val)
9588 if (reg->s32_min_value > sval)
9590 else if (reg->s32_max_value <= sval)
9594 if (reg->u32_max_value < val)
9596 else if (reg->u32_min_value >= val)
9600 if (reg->s32_max_value < sval)
9602 else if (reg->s32_min_value >= sval)
9606 if (reg->u32_min_value >= val)
9608 else if (reg->u32_max_value < val)
9612 if (reg->s32_min_value >= sval)
9614 else if (reg->s32_max_value < sval)
9618 if (reg->u32_max_value <= val)
9620 else if (reg->u32_min_value > val)
9624 if (reg->s32_max_value <= sval)
9626 else if (reg->s32_min_value > sval)
9635 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9637 s64 sval = (s64)val;
9641 if (tnum_is_const(reg->var_off))
9642 return !!tnum_equals_const(reg->var_off, val);
9645 if (tnum_is_const(reg->var_off))
9646 return !tnum_equals_const(reg->var_off, val);
9649 if ((~reg->var_off.mask & reg->var_off.value) & val)
9651 if (!((reg->var_off.mask | reg->var_off.value) & val))
9655 if (reg->umin_value > val)
9657 else if (reg->umax_value <= val)
9661 if (reg->smin_value > sval)
9663 else if (reg->smax_value <= sval)
9667 if (reg->umax_value < val)
9669 else if (reg->umin_value >= val)
9673 if (reg->smax_value < sval)
9675 else if (reg->smin_value >= sval)
9679 if (reg->umin_value >= val)
9681 else if (reg->umax_value < val)
9685 if (reg->smin_value >= sval)
9687 else if (reg->smax_value < sval)
9691 if (reg->umax_value <= val)
9693 else if (reg->umin_value > val)
9697 if (reg->smax_value <= sval)
9699 else if (reg->smin_value > sval)
9707 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9709 * 1 - branch will be taken and "goto target" will be executed
9710 * 0 - branch will not be taken and fall-through to next insn
9711 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9714 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9717 if (__is_pointer_value(false, reg)) {
9718 if (!reg_type_not_null(reg->type))
9721 /* If pointer is valid tests against zero will fail so we can
9722 * use this to direct branch taken.
9738 return is_branch32_taken(reg, val, opcode);
9739 return is_branch64_taken(reg, val, opcode);
9742 static int flip_opcode(u32 opcode)
9744 /* How can we transform "a <op> b" into "b <op> a"? */
9745 static const u8 opcode_flip[16] = {
9746 /* these stay the same */
9747 [BPF_JEQ >> 4] = BPF_JEQ,
9748 [BPF_JNE >> 4] = BPF_JNE,
9749 [BPF_JSET >> 4] = BPF_JSET,
9750 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9751 [BPF_JGE >> 4] = BPF_JLE,
9752 [BPF_JGT >> 4] = BPF_JLT,
9753 [BPF_JLE >> 4] = BPF_JGE,
9754 [BPF_JLT >> 4] = BPF_JGT,
9755 [BPF_JSGE >> 4] = BPF_JSLE,
9756 [BPF_JSGT >> 4] = BPF_JSLT,
9757 [BPF_JSLE >> 4] = BPF_JSGE,
9758 [BPF_JSLT >> 4] = BPF_JSGT
9760 return opcode_flip[opcode >> 4];
9763 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9764 struct bpf_reg_state *src_reg,
9767 struct bpf_reg_state *pkt;
9769 if (src_reg->type == PTR_TO_PACKET_END) {
9771 } else if (dst_reg->type == PTR_TO_PACKET_END) {
9773 opcode = flip_opcode(opcode);
9778 if (pkt->range >= 0)
9783 /* pkt <= pkt_end */
9787 if (pkt->range == BEYOND_PKT_END)
9788 /* pkt has at last one extra byte beyond pkt_end */
9789 return opcode == BPF_JGT;
9795 /* pkt >= pkt_end */
9796 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9797 return opcode == BPF_JGE;
9803 /* Adjusts the register min/max values in the case that the dst_reg is the
9804 * variable register that we are working on, and src_reg is a constant or we're
9805 * simply doing a BPF_K check.
9806 * In JEQ/JNE cases we also adjust the var_off values.
9808 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9809 struct bpf_reg_state *false_reg,
9811 u8 opcode, bool is_jmp32)
9813 struct tnum false_32off = tnum_subreg(false_reg->var_off);
9814 struct tnum false_64off = false_reg->var_off;
9815 struct tnum true_32off = tnum_subreg(true_reg->var_off);
9816 struct tnum true_64off = true_reg->var_off;
9817 s64 sval = (s64)val;
9818 s32 sval32 = (s32)val32;
9820 /* If the dst_reg is a pointer, we can't learn anything about its
9821 * variable offset from the compare (unless src_reg were a pointer into
9822 * the same object, but we don't bother with that.
9823 * Since false_reg and true_reg have the same type by construction, we
9824 * only need to check one of them for pointerness.
9826 if (__is_pointer_value(false, false_reg))
9830 /* JEQ/JNE comparison doesn't change the register equivalence.
9833 * if (r1 == 42) goto label;
9835 * label: // here both r1 and r2 are known to be 42.
9837 * Hence when marking register as known preserve it's ID.
9841 __mark_reg32_known(true_reg, val32);
9842 true_32off = tnum_subreg(true_reg->var_off);
9844 ___mark_reg_known(true_reg, val);
9845 true_64off = true_reg->var_off;
9850 __mark_reg32_known(false_reg, val32);
9851 false_32off = tnum_subreg(false_reg->var_off);
9853 ___mark_reg_known(false_reg, val);
9854 false_64off = false_reg->var_off;
9859 false_32off = tnum_and(false_32off, tnum_const(~val32));
9860 if (is_power_of_2(val32))
9861 true_32off = tnum_or(true_32off,
9864 false_64off = tnum_and(false_64off, tnum_const(~val));
9865 if (is_power_of_2(val))
9866 true_64off = tnum_or(true_64off,
9874 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
9875 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9877 false_reg->u32_max_value = min(false_reg->u32_max_value,
9879 true_reg->u32_min_value = max(true_reg->u32_min_value,
9882 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
9883 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9885 false_reg->umax_value = min(false_reg->umax_value, false_umax);
9886 true_reg->umin_value = max(true_reg->umin_value, true_umin);
9894 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
9895 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9897 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9898 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9900 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
9901 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9903 false_reg->smax_value = min(false_reg->smax_value, false_smax);
9904 true_reg->smin_value = max(true_reg->smin_value, true_smin);
9912 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
9913 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9915 false_reg->u32_min_value = max(false_reg->u32_min_value,
9917 true_reg->u32_max_value = min(true_reg->u32_max_value,
9920 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
9921 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9923 false_reg->umin_value = max(false_reg->umin_value, false_umin);
9924 true_reg->umax_value = min(true_reg->umax_value, true_umax);
9932 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
9933 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9935 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9936 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9938 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
9939 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9941 false_reg->smin_value = max(false_reg->smin_value, false_smin);
9942 true_reg->smax_value = min(true_reg->smax_value, true_smax);
9951 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9952 tnum_subreg(false_32off));
9953 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9954 tnum_subreg(true_32off));
9955 __reg_combine_32_into_64(false_reg);
9956 __reg_combine_32_into_64(true_reg);
9958 false_reg->var_off = false_64off;
9959 true_reg->var_off = true_64off;
9960 __reg_combine_64_into_32(false_reg);
9961 __reg_combine_64_into_32(true_reg);
9965 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9968 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9969 struct bpf_reg_state *false_reg,
9971 u8 opcode, bool is_jmp32)
9973 opcode = flip_opcode(opcode);
9974 /* This uses zero as "not present in table"; luckily the zero opcode,
9975 * BPF_JA, can't get here.
9978 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9981 /* Regs are known to be equal, so intersect their min/max/var_off */
9982 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9983 struct bpf_reg_state *dst_reg)
9985 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9986 dst_reg->umin_value);
9987 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9988 dst_reg->umax_value);
9989 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9990 dst_reg->smin_value);
9991 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9992 dst_reg->smax_value);
9993 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9995 reg_bounds_sync(src_reg);
9996 reg_bounds_sync(dst_reg);
9999 static void reg_combine_min_max(struct bpf_reg_state *true_src,
10000 struct bpf_reg_state *true_dst,
10001 struct bpf_reg_state *false_src,
10002 struct bpf_reg_state *false_dst,
10007 __reg_combine_min_max(true_src, true_dst);
10010 __reg_combine_min_max(false_src, false_dst);
10015 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
10016 struct bpf_reg_state *reg, u32 id,
10019 if (type_may_be_null(reg->type) && reg->id == id &&
10020 !WARN_ON_ONCE(!reg->id)) {
10021 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
10022 !tnum_equals_const(reg->var_off, 0) ||
10024 /* Old offset (both fixed and variable parts) should
10025 * have been known-zero, because we don't allow pointer
10026 * arithmetic on pointers that might be NULL. If we
10027 * see this happening, don't convert the register.
10032 reg->type = SCALAR_VALUE;
10033 /* We don't need id and ref_obj_id from this point
10034 * onwards anymore, thus we should better reset it,
10035 * so that state pruning has chances to take effect.
10038 reg->ref_obj_id = 0;
10043 mark_ptr_not_null_reg(reg);
10045 if (!reg_may_point_to_spin_lock(reg)) {
10046 /* For not-NULL ptr, reg->ref_obj_id will be reset
10047 * in release_reference().
10049 * reg->id is still used by spin_lock ptr. Other
10050 * than spin_lock ptr type, reg->id can be reset.
10057 /* The logic is similar to find_good_pkt_pointers(), both could eventually
10058 * be folded together at some point.
10060 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
10063 struct bpf_func_state *state = vstate->frame[vstate->curframe];
10064 struct bpf_reg_state *regs = state->regs, *reg;
10065 u32 ref_obj_id = regs[regno].ref_obj_id;
10066 u32 id = regs[regno].id;
10068 if (ref_obj_id && ref_obj_id == id && is_null)
10069 /* regs[regno] is in the " == NULL" branch.
10070 * No one could have freed the reference state before
10071 * doing the NULL check.
10073 WARN_ON_ONCE(release_reference_state(state, id));
10075 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10076 mark_ptr_or_null_reg(state, reg, id, is_null);
10080 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10081 struct bpf_reg_state *dst_reg,
10082 struct bpf_reg_state *src_reg,
10083 struct bpf_verifier_state *this_branch,
10084 struct bpf_verifier_state *other_branch)
10086 if (BPF_SRC(insn->code) != BPF_X)
10089 /* Pointers are always 64-bit. */
10090 if (BPF_CLASS(insn->code) == BPF_JMP32)
10093 switch (BPF_OP(insn->code)) {
10095 if ((dst_reg->type == PTR_TO_PACKET &&
10096 src_reg->type == PTR_TO_PACKET_END) ||
10097 (dst_reg->type == PTR_TO_PACKET_META &&
10098 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10099 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10100 find_good_pkt_pointers(this_branch, dst_reg,
10101 dst_reg->type, false);
10102 mark_pkt_end(other_branch, insn->dst_reg, true);
10103 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10104 src_reg->type == PTR_TO_PACKET) ||
10105 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10106 src_reg->type == PTR_TO_PACKET_META)) {
10107 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
10108 find_good_pkt_pointers(other_branch, src_reg,
10109 src_reg->type, true);
10110 mark_pkt_end(this_branch, insn->src_reg, false);
10116 if ((dst_reg->type == PTR_TO_PACKET &&
10117 src_reg->type == PTR_TO_PACKET_END) ||
10118 (dst_reg->type == PTR_TO_PACKET_META &&
10119 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10120 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10121 find_good_pkt_pointers(other_branch, dst_reg,
10122 dst_reg->type, true);
10123 mark_pkt_end(this_branch, insn->dst_reg, false);
10124 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10125 src_reg->type == PTR_TO_PACKET) ||
10126 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10127 src_reg->type == PTR_TO_PACKET_META)) {
10128 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
10129 find_good_pkt_pointers(this_branch, src_reg,
10130 src_reg->type, false);
10131 mark_pkt_end(other_branch, insn->src_reg, true);
10137 if ((dst_reg->type == PTR_TO_PACKET &&
10138 src_reg->type == PTR_TO_PACKET_END) ||
10139 (dst_reg->type == PTR_TO_PACKET_META &&
10140 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10141 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10142 find_good_pkt_pointers(this_branch, dst_reg,
10143 dst_reg->type, true);
10144 mark_pkt_end(other_branch, insn->dst_reg, false);
10145 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10146 src_reg->type == PTR_TO_PACKET) ||
10147 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10148 src_reg->type == PTR_TO_PACKET_META)) {
10149 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10150 find_good_pkt_pointers(other_branch, src_reg,
10151 src_reg->type, false);
10152 mark_pkt_end(this_branch, insn->src_reg, true);
10158 if ((dst_reg->type == PTR_TO_PACKET &&
10159 src_reg->type == PTR_TO_PACKET_END) ||
10160 (dst_reg->type == PTR_TO_PACKET_META &&
10161 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10162 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10163 find_good_pkt_pointers(other_branch, dst_reg,
10164 dst_reg->type, false);
10165 mark_pkt_end(this_branch, insn->dst_reg, true);
10166 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10167 src_reg->type == PTR_TO_PACKET) ||
10168 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10169 src_reg->type == PTR_TO_PACKET_META)) {
10170 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10171 find_good_pkt_pointers(this_branch, src_reg,
10172 src_reg->type, true);
10173 mark_pkt_end(other_branch, insn->src_reg, false);
10185 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10186 struct bpf_reg_state *known_reg)
10188 struct bpf_func_state *state;
10189 struct bpf_reg_state *reg;
10191 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10192 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10193 copy_register_state(reg, known_reg);
10197 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10198 struct bpf_insn *insn, int *insn_idx)
10200 struct bpf_verifier_state *this_branch = env->cur_state;
10201 struct bpf_verifier_state *other_branch;
10202 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10203 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10204 u8 opcode = BPF_OP(insn->code);
10209 /* Only conditional jumps are expected to reach here. */
10210 if (opcode == BPF_JA || opcode > BPF_JSLE) {
10211 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10215 if (BPF_SRC(insn->code) == BPF_X) {
10216 if (insn->imm != 0) {
10217 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10221 /* check src1 operand */
10222 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10226 if (is_pointer_value(env, insn->src_reg)) {
10227 verbose(env, "R%d pointer comparison prohibited\n",
10231 src_reg = ®s[insn->src_reg];
10233 if (insn->src_reg != BPF_REG_0) {
10234 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10239 /* check src2 operand */
10240 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10244 dst_reg = ®s[insn->dst_reg];
10245 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10247 if (BPF_SRC(insn->code) == BPF_K) {
10248 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10249 } else if (src_reg->type == SCALAR_VALUE &&
10250 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10251 pred = is_branch_taken(dst_reg,
10252 tnum_subreg(src_reg->var_off).value,
10255 } else if (src_reg->type == SCALAR_VALUE &&
10256 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10257 pred = is_branch_taken(dst_reg,
10258 src_reg->var_off.value,
10261 } else if (reg_is_pkt_pointer_any(dst_reg) &&
10262 reg_is_pkt_pointer_any(src_reg) &&
10264 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10268 /* If we get here with a dst_reg pointer type it is because
10269 * above is_branch_taken() special cased the 0 comparison.
10271 if (!__is_pointer_value(false, dst_reg))
10272 err = mark_chain_precision(env, insn->dst_reg);
10273 if (BPF_SRC(insn->code) == BPF_X && !err &&
10274 !__is_pointer_value(false, src_reg))
10275 err = mark_chain_precision(env, insn->src_reg);
10281 /* Only follow the goto, ignore fall-through. If needed, push
10282 * the fall-through branch for simulation under speculative
10285 if (!env->bypass_spec_v1 &&
10286 !sanitize_speculative_path(env, insn, *insn_idx + 1,
10289 *insn_idx += insn->off;
10291 } else if (pred == 0) {
10292 /* Only follow the fall-through branch, since that's where the
10293 * program will go. If needed, push the goto branch for
10294 * simulation under speculative execution.
10296 if (!env->bypass_spec_v1 &&
10297 !sanitize_speculative_path(env, insn,
10298 *insn_idx + insn->off + 1,
10304 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10308 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10310 /* detect if we are comparing against a constant value so we can adjust
10311 * our min/max values for our dst register.
10312 * this is only legit if both are scalars (or pointers to the same
10313 * object, I suppose, but we don't support that right now), because
10314 * otherwise the different base pointers mean the offsets aren't
10317 if (BPF_SRC(insn->code) == BPF_X) {
10318 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
10320 if (dst_reg->type == SCALAR_VALUE &&
10321 src_reg->type == SCALAR_VALUE) {
10322 if (tnum_is_const(src_reg->var_off) ||
10324 tnum_is_const(tnum_subreg(src_reg->var_off))))
10325 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10327 src_reg->var_off.value,
10328 tnum_subreg(src_reg->var_off).value,
10330 else if (tnum_is_const(dst_reg->var_off) ||
10332 tnum_is_const(tnum_subreg(dst_reg->var_off))))
10333 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10335 dst_reg->var_off.value,
10336 tnum_subreg(dst_reg->var_off).value,
10338 else if (!is_jmp32 &&
10339 (opcode == BPF_JEQ || opcode == BPF_JNE))
10340 /* Comparing for equality, we can combine knowledge */
10341 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10342 &other_branch_regs[insn->dst_reg],
10343 src_reg, dst_reg, opcode);
10345 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10346 find_equal_scalars(this_branch, src_reg);
10347 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10351 } else if (dst_reg->type == SCALAR_VALUE) {
10352 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10353 dst_reg, insn->imm, (u32)insn->imm,
10357 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10358 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10359 find_equal_scalars(this_branch, dst_reg);
10360 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10363 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10364 * NOTE: these optimizations below are related with pointer comparison
10365 * which will never be JMP32.
10367 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10368 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10369 type_may_be_null(dst_reg->type)) {
10370 /* Mark all identical registers in each branch as either
10371 * safe or unknown depending R == 0 or R != 0 conditional.
10373 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10374 opcode == BPF_JNE);
10375 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10376 opcode == BPF_JEQ);
10377 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
10378 this_branch, other_branch) &&
10379 is_pointer_value(env, insn->dst_reg)) {
10380 verbose(env, "R%d pointer comparison prohibited\n",
10384 if (env->log.level & BPF_LOG_LEVEL)
10385 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10389 /* verify BPF_LD_IMM64 instruction */
10390 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10392 struct bpf_insn_aux_data *aux = cur_aux(env);
10393 struct bpf_reg_state *regs = cur_regs(env);
10394 struct bpf_reg_state *dst_reg;
10395 struct bpf_map *map;
10398 if (BPF_SIZE(insn->code) != BPF_DW) {
10399 verbose(env, "invalid BPF_LD_IMM insn\n");
10402 if (insn->off != 0) {
10403 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10407 err = check_reg_arg(env, insn->dst_reg, DST_OP);
10411 dst_reg = ®s[insn->dst_reg];
10412 if (insn->src_reg == 0) {
10413 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10415 dst_reg->type = SCALAR_VALUE;
10416 __mark_reg_known(®s[insn->dst_reg], imm);
10420 /* All special src_reg cases are listed below. From this point onwards
10421 * we either succeed and assign a corresponding dst_reg->type after
10422 * zeroing the offset, or fail and reject the program.
10424 mark_reg_known_zero(env, regs, insn->dst_reg);
10426 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10427 dst_reg->type = aux->btf_var.reg_type;
10428 switch (base_type(dst_reg->type)) {
10430 dst_reg->mem_size = aux->btf_var.mem_size;
10432 case PTR_TO_BTF_ID:
10433 dst_reg->btf = aux->btf_var.btf;
10434 dst_reg->btf_id = aux->btf_var.btf_id;
10437 verbose(env, "bpf verifier is misconfigured\n");
10443 if (insn->src_reg == BPF_PSEUDO_FUNC) {
10444 struct bpf_prog_aux *aux = env->prog->aux;
10445 u32 subprogno = find_subprog(env,
10446 env->insn_idx + insn->imm + 1);
10448 if (!aux->func_info) {
10449 verbose(env, "missing btf func_info\n");
10452 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10453 verbose(env, "callback function not static\n");
10457 dst_reg->type = PTR_TO_FUNC;
10458 dst_reg->subprogno = subprogno;
10462 map = env->used_maps[aux->map_index];
10463 dst_reg->map_ptr = map;
10465 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10466 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10467 dst_reg->type = PTR_TO_MAP_VALUE;
10468 dst_reg->off = aux->map_off;
10469 if (map_value_has_spin_lock(map))
10470 dst_reg->id = ++env->id_gen;
10471 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10472 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10473 dst_reg->type = CONST_PTR_TO_MAP;
10475 verbose(env, "bpf verifier is misconfigured\n");
10482 static bool may_access_skb(enum bpf_prog_type type)
10485 case BPF_PROG_TYPE_SOCKET_FILTER:
10486 case BPF_PROG_TYPE_SCHED_CLS:
10487 case BPF_PROG_TYPE_SCHED_ACT:
10494 /* verify safety of LD_ABS|LD_IND instructions:
10495 * - they can only appear in the programs where ctx == skb
10496 * - since they are wrappers of function calls, they scratch R1-R5 registers,
10497 * preserve R6-R9, and store return value into R0
10500 * ctx == skb == R6 == CTX
10503 * SRC == any register
10504 * IMM == 32-bit immediate
10507 * R0 - 8/16/32-bit skb data converted to cpu endianness
10509 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10511 struct bpf_reg_state *regs = cur_regs(env);
10512 static const int ctx_reg = BPF_REG_6;
10513 u8 mode = BPF_MODE(insn->code);
10516 if (!may_access_skb(resolve_prog_type(env->prog))) {
10517 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10521 if (!env->ops->gen_ld_abs) {
10522 verbose(env, "bpf verifier is misconfigured\n");
10526 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10527 BPF_SIZE(insn->code) == BPF_DW ||
10528 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10529 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10533 /* check whether implicit source operand (register R6) is readable */
10534 err = check_reg_arg(env, ctx_reg, SRC_OP);
10538 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10539 * gen_ld_abs() may terminate the program at runtime, leading to
10542 err = check_reference_leak(env);
10544 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10548 if (env->cur_state->active_spin_lock) {
10549 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10553 if (regs[ctx_reg].type != PTR_TO_CTX) {
10555 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10559 if (mode == BPF_IND) {
10560 /* check explicit source operand */
10561 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10566 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
10570 /* reset caller saved regs to unreadable */
10571 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10572 mark_reg_not_init(env, regs, caller_saved[i]);
10573 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10576 /* mark destination R0 register as readable, since it contains
10577 * the value fetched from the packet.
10578 * Already marked as written above.
10580 mark_reg_unknown(env, regs, BPF_REG_0);
10581 /* ld_abs load up to 32-bit skb data. */
10582 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10586 static int check_return_code(struct bpf_verifier_env *env)
10588 struct tnum enforce_attach_type_range = tnum_unknown;
10589 const struct bpf_prog *prog = env->prog;
10590 struct bpf_reg_state *reg;
10591 struct tnum range = tnum_range(0, 1);
10592 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10594 struct bpf_func_state *frame = env->cur_state->frame[0];
10595 const bool is_subprog = frame->subprogno;
10597 /* LSM and struct_ops func-ptr's return type could be "void" */
10599 switch (prog_type) {
10600 case BPF_PROG_TYPE_LSM:
10601 if (prog->expected_attach_type == BPF_LSM_CGROUP)
10602 /* See below, can be 0 or 0-1 depending on hook. */
10605 case BPF_PROG_TYPE_STRUCT_OPS:
10606 if (!prog->aux->attach_func_proto->type)
10614 /* eBPF calling convention is such that R0 is used
10615 * to return the value from eBPF program.
10616 * Make sure that it's readable at this time
10617 * of bpf_exit, which means that program wrote
10618 * something into it earlier
10620 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10624 if (is_pointer_value(env, BPF_REG_0)) {
10625 verbose(env, "R0 leaks addr as return value\n");
10629 reg = cur_regs(env) + BPF_REG_0;
10631 if (frame->in_async_callback_fn) {
10632 /* enforce return zero from async callbacks like timer */
10633 if (reg->type != SCALAR_VALUE) {
10634 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10635 reg_type_str(env, reg->type));
10639 if (!tnum_in(tnum_const(0), reg->var_off)) {
10640 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10647 if (reg->type != SCALAR_VALUE) {
10648 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10649 reg_type_str(env, reg->type));
10655 switch (prog_type) {
10656 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10657 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10658 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10659 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10660 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10661 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10662 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10663 range = tnum_range(1, 1);
10664 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10665 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10666 range = tnum_range(0, 3);
10668 case BPF_PROG_TYPE_CGROUP_SKB:
10669 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10670 range = tnum_range(0, 3);
10671 enforce_attach_type_range = tnum_range(2, 3);
10674 case BPF_PROG_TYPE_CGROUP_SOCK:
10675 case BPF_PROG_TYPE_SOCK_OPS:
10676 case BPF_PROG_TYPE_CGROUP_DEVICE:
10677 case BPF_PROG_TYPE_CGROUP_SYSCTL:
10678 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10680 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10681 if (!env->prog->aux->attach_btf_id)
10683 range = tnum_const(0);
10685 case BPF_PROG_TYPE_TRACING:
10686 switch (env->prog->expected_attach_type) {
10687 case BPF_TRACE_FENTRY:
10688 case BPF_TRACE_FEXIT:
10689 range = tnum_const(0);
10691 case BPF_TRACE_RAW_TP:
10692 case BPF_MODIFY_RETURN:
10694 case BPF_TRACE_ITER:
10700 case BPF_PROG_TYPE_SK_LOOKUP:
10701 range = tnum_range(SK_DROP, SK_PASS);
10704 case BPF_PROG_TYPE_LSM:
10705 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10706 /* Regular BPF_PROG_TYPE_LSM programs can return
10711 if (!env->prog->aux->attach_func_proto->type) {
10712 /* Make sure programs that attach to void
10713 * hooks don't try to modify return value.
10715 range = tnum_range(1, 1);
10719 case BPF_PROG_TYPE_EXT:
10720 /* freplace program can return anything as its return value
10721 * depends on the to-be-replaced kernel func or bpf program.
10727 if (reg->type != SCALAR_VALUE) {
10728 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10729 reg_type_str(env, reg->type));
10733 if (!tnum_in(range, reg->var_off)) {
10734 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10735 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10736 prog_type == BPF_PROG_TYPE_LSM &&
10737 !prog->aux->attach_func_proto->type)
10738 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10742 if (!tnum_is_unknown(enforce_attach_type_range) &&
10743 tnum_in(enforce_attach_type_range, reg->var_off))
10744 env->prog->enforce_expected_attach_type = 1;
10748 /* non-recursive DFS pseudo code
10749 * 1 procedure DFS-iterative(G,v):
10750 * 2 label v as discovered
10751 * 3 let S be a stack
10753 * 5 while S is not empty
10755 * 7 if t is what we're looking for:
10757 * 9 for all edges e in G.adjacentEdges(t) do
10758 * 10 if edge e is already labelled
10759 * 11 continue with the next edge
10760 * 12 w <- G.adjacentVertex(t,e)
10761 * 13 if vertex w is not discovered and not explored
10762 * 14 label e as tree-edge
10763 * 15 label w as discovered
10766 * 18 else if vertex w is discovered
10767 * 19 label e as back-edge
10769 * 21 // vertex w is explored
10770 * 22 label e as forward- or cross-edge
10771 * 23 label t as explored
10775 * 0x10 - discovered
10776 * 0x11 - discovered and fall-through edge labelled
10777 * 0x12 - discovered and fall-through and branch edges labelled
10788 static u32 state_htab_size(struct bpf_verifier_env *env)
10790 return env->prog->len;
10793 static struct bpf_verifier_state_list **explored_state(
10794 struct bpf_verifier_env *env,
10797 struct bpf_verifier_state *cur = env->cur_state;
10798 struct bpf_func_state *state = cur->frame[cur->curframe];
10800 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10803 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10805 env->insn_aux_data[idx].prune_point = true;
10809 DONE_EXPLORING = 0,
10810 KEEP_EXPLORING = 1,
10813 /* t, w, e - match pseudo-code above:
10814 * t - index of current instruction
10815 * w - next instruction
10818 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10821 int *insn_stack = env->cfg.insn_stack;
10822 int *insn_state = env->cfg.insn_state;
10824 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10825 return DONE_EXPLORING;
10827 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10828 return DONE_EXPLORING;
10830 if (w < 0 || w >= env->prog->len) {
10831 verbose_linfo(env, t, "%d: ", t);
10832 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10837 /* mark branch target for state pruning */
10838 init_explored_state(env, w);
10840 if (insn_state[w] == 0) {
10842 insn_state[t] = DISCOVERED | e;
10843 insn_state[w] = DISCOVERED;
10844 if (env->cfg.cur_stack >= env->prog->len)
10846 insn_stack[env->cfg.cur_stack++] = w;
10847 return KEEP_EXPLORING;
10848 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10849 if (loop_ok && env->bpf_capable)
10850 return DONE_EXPLORING;
10851 verbose_linfo(env, t, "%d: ", t);
10852 verbose_linfo(env, w, "%d: ", w);
10853 verbose(env, "back-edge from insn %d to %d\n", t, w);
10855 } else if (insn_state[w] == EXPLORED) {
10856 /* forward- or cross-edge */
10857 insn_state[t] = DISCOVERED | e;
10859 verbose(env, "insn state internal bug\n");
10862 return DONE_EXPLORING;
10865 static int visit_func_call_insn(int t, int insn_cnt,
10866 struct bpf_insn *insns,
10867 struct bpf_verifier_env *env,
10872 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10876 if (t + 1 < insn_cnt)
10877 init_explored_state(env, t + 1);
10878 if (visit_callee) {
10879 init_explored_state(env, t);
10880 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10881 /* It's ok to allow recursion from CFG point of
10882 * view. __check_func_call() will do the actual
10885 bpf_pseudo_func(insns + t));
10890 /* Visits the instruction at index t and returns one of the following:
10891 * < 0 - an error occurred
10892 * DONE_EXPLORING - the instruction was fully explored
10893 * KEEP_EXPLORING - there is still work to be done before it is fully explored
10895 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10897 struct bpf_insn *insns = env->prog->insnsi;
10900 if (bpf_pseudo_func(insns + t))
10901 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10903 /* All non-branch instructions have a single fall-through edge. */
10904 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10905 BPF_CLASS(insns[t].code) != BPF_JMP32)
10906 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10908 switch (BPF_OP(insns[t].code)) {
10910 return DONE_EXPLORING;
10913 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10914 /* Mark this call insn to trigger is_state_visited() check
10915 * before call itself is processed by __check_func_call().
10916 * Otherwise new async state will be pushed for further
10919 init_explored_state(env, t);
10920 return visit_func_call_insn(t, insn_cnt, insns, env,
10921 insns[t].src_reg == BPF_PSEUDO_CALL);
10924 if (BPF_SRC(insns[t].code) != BPF_K)
10927 /* unconditional jump with single edge */
10928 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10933 /* unconditional jmp is not a good pruning point,
10934 * but it's marked, since backtracking needs
10935 * to record jmp history in is_state_visited().
10937 init_explored_state(env, t + insns[t].off + 1);
10938 /* tell verifier to check for equivalent states
10939 * after every call and jump
10941 if (t + 1 < insn_cnt)
10942 init_explored_state(env, t + 1);
10947 /* conditional jump with two edges */
10948 init_explored_state(env, t);
10949 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10953 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10957 /* non-recursive depth-first-search to detect loops in BPF program
10958 * loop == back-edge in directed graph
10960 static int check_cfg(struct bpf_verifier_env *env)
10962 int insn_cnt = env->prog->len;
10963 int *insn_stack, *insn_state;
10967 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10971 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10973 kvfree(insn_state);
10977 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10978 insn_stack[0] = 0; /* 0 is the first instruction */
10979 env->cfg.cur_stack = 1;
10981 while (env->cfg.cur_stack > 0) {
10982 int t = insn_stack[env->cfg.cur_stack - 1];
10984 ret = visit_insn(t, insn_cnt, env);
10986 case DONE_EXPLORING:
10987 insn_state[t] = EXPLORED;
10988 env->cfg.cur_stack--;
10990 case KEEP_EXPLORING:
10994 verbose(env, "visit_insn internal bug\n");
11001 if (env->cfg.cur_stack < 0) {
11002 verbose(env, "pop stack internal bug\n");
11007 for (i = 0; i < insn_cnt; i++) {
11008 if (insn_state[i] != EXPLORED) {
11009 verbose(env, "unreachable insn %d\n", i);
11014 ret = 0; /* cfg looks good */
11017 kvfree(insn_state);
11018 kvfree(insn_stack);
11019 env->cfg.insn_state = env->cfg.insn_stack = NULL;
11023 static int check_abnormal_return(struct bpf_verifier_env *env)
11027 for (i = 1; i < env->subprog_cnt; i++) {
11028 if (env->subprog_info[i].has_ld_abs) {
11029 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
11032 if (env->subprog_info[i].has_tail_call) {
11033 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
11040 /* The minimum supported BTF func info size */
11041 #define MIN_BPF_FUNCINFO_SIZE 8
11042 #define MAX_FUNCINFO_REC_SIZE 252
11044 static int check_btf_func(struct bpf_verifier_env *env,
11045 const union bpf_attr *attr,
11048 const struct btf_type *type, *func_proto, *ret_type;
11049 u32 i, nfuncs, urec_size, min_size;
11050 u32 krec_size = sizeof(struct bpf_func_info);
11051 struct bpf_func_info *krecord;
11052 struct bpf_func_info_aux *info_aux = NULL;
11053 struct bpf_prog *prog;
11054 const struct btf *btf;
11056 u32 prev_offset = 0;
11057 bool scalar_return;
11060 nfuncs = attr->func_info_cnt;
11062 if (check_abnormal_return(env))
11067 if (nfuncs != env->subprog_cnt) {
11068 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11072 urec_size = attr->func_info_rec_size;
11073 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11074 urec_size > MAX_FUNCINFO_REC_SIZE ||
11075 urec_size % sizeof(u32)) {
11076 verbose(env, "invalid func info rec size %u\n", urec_size);
11081 btf = prog->aux->btf;
11083 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11084 min_size = min_t(u32, krec_size, urec_size);
11086 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11089 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11093 for (i = 0; i < nfuncs; i++) {
11094 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11096 if (ret == -E2BIG) {
11097 verbose(env, "nonzero tailing record in func info");
11098 /* set the size kernel expects so loader can zero
11099 * out the rest of the record.
11101 if (copy_to_bpfptr_offset(uattr,
11102 offsetof(union bpf_attr, func_info_rec_size),
11103 &min_size, sizeof(min_size)))
11109 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11114 /* check insn_off */
11117 if (krecord[i].insn_off) {
11119 "nonzero insn_off %u for the first func info record",
11120 krecord[i].insn_off);
11123 } else if (krecord[i].insn_off <= prev_offset) {
11125 "same or smaller insn offset (%u) than previous func info record (%u)",
11126 krecord[i].insn_off, prev_offset);
11130 if (env->subprog_info[i].start != krecord[i].insn_off) {
11131 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11135 /* check type_id */
11136 type = btf_type_by_id(btf, krecord[i].type_id);
11137 if (!type || !btf_type_is_func(type)) {
11138 verbose(env, "invalid type id %d in func info",
11139 krecord[i].type_id);
11142 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11144 func_proto = btf_type_by_id(btf, type->type);
11145 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11146 /* btf_func_check() already verified it during BTF load */
11148 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11150 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11151 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11152 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11155 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11156 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11160 prev_offset = krecord[i].insn_off;
11161 bpfptr_add(&urecord, urec_size);
11164 prog->aux->func_info = krecord;
11165 prog->aux->func_info_cnt = nfuncs;
11166 prog->aux->func_info_aux = info_aux;
11175 static void adjust_btf_func(struct bpf_verifier_env *env)
11177 struct bpf_prog_aux *aux = env->prog->aux;
11180 if (!aux->func_info)
11183 for (i = 0; i < env->subprog_cnt; i++)
11184 aux->func_info[i].insn_off = env->subprog_info[i].start;
11187 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
11188 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
11190 static int check_btf_line(struct bpf_verifier_env *env,
11191 const union bpf_attr *attr,
11194 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11195 struct bpf_subprog_info *sub;
11196 struct bpf_line_info *linfo;
11197 struct bpf_prog *prog;
11198 const struct btf *btf;
11202 nr_linfo = attr->line_info_cnt;
11205 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11208 rec_size = attr->line_info_rec_size;
11209 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11210 rec_size > MAX_LINEINFO_REC_SIZE ||
11211 rec_size & (sizeof(u32) - 1))
11214 /* Need to zero it in case the userspace may
11215 * pass in a smaller bpf_line_info object.
11217 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11218 GFP_KERNEL | __GFP_NOWARN);
11223 btf = prog->aux->btf;
11226 sub = env->subprog_info;
11227 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11228 expected_size = sizeof(struct bpf_line_info);
11229 ncopy = min_t(u32, expected_size, rec_size);
11230 for (i = 0; i < nr_linfo; i++) {
11231 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11233 if (err == -E2BIG) {
11234 verbose(env, "nonzero tailing record in line_info");
11235 if (copy_to_bpfptr_offset(uattr,
11236 offsetof(union bpf_attr, line_info_rec_size),
11237 &expected_size, sizeof(expected_size)))
11243 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11249 * Check insn_off to ensure
11250 * 1) strictly increasing AND
11251 * 2) bounded by prog->len
11253 * The linfo[0].insn_off == 0 check logically falls into
11254 * the later "missing bpf_line_info for func..." case
11255 * because the first linfo[0].insn_off must be the
11256 * first sub also and the first sub must have
11257 * subprog_info[0].start == 0.
11259 if ((i && linfo[i].insn_off <= prev_offset) ||
11260 linfo[i].insn_off >= prog->len) {
11261 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11262 i, linfo[i].insn_off, prev_offset,
11268 if (!prog->insnsi[linfo[i].insn_off].code) {
11270 "Invalid insn code at line_info[%u].insn_off\n",
11276 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11277 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11278 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11283 if (s != env->subprog_cnt) {
11284 if (linfo[i].insn_off == sub[s].start) {
11285 sub[s].linfo_idx = i;
11287 } else if (sub[s].start < linfo[i].insn_off) {
11288 verbose(env, "missing bpf_line_info for func#%u\n", s);
11294 prev_offset = linfo[i].insn_off;
11295 bpfptr_add(&ulinfo, rec_size);
11298 if (s != env->subprog_cnt) {
11299 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11300 env->subprog_cnt - s, s);
11305 prog->aux->linfo = linfo;
11306 prog->aux->nr_linfo = nr_linfo;
11315 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
11316 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
11318 static int check_core_relo(struct bpf_verifier_env *env,
11319 const union bpf_attr *attr,
11322 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11323 struct bpf_core_relo core_relo = {};
11324 struct bpf_prog *prog = env->prog;
11325 const struct btf *btf = prog->aux->btf;
11326 struct bpf_core_ctx ctx = {
11330 bpfptr_t u_core_relo;
11333 nr_core_relo = attr->core_relo_cnt;
11336 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11339 rec_size = attr->core_relo_rec_size;
11340 if (rec_size < MIN_CORE_RELO_SIZE ||
11341 rec_size > MAX_CORE_RELO_SIZE ||
11342 rec_size % sizeof(u32))
11345 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11346 expected_size = sizeof(struct bpf_core_relo);
11347 ncopy = min_t(u32, expected_size, rec_size);
11349 /* Unlike func_info and line_info, copy and apply each CO-RE
11350 * relocation record one at a time.
11352 for (i = 0; i < nr_core_relo; i++) {
11353 /* future proofing when sizeof(bpf_core_relo) changes */
11354 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11356 if (err == -E2BIG) {
11357 verbose(env, "nonzero tailing record in core_relo");
11358 if (copy_to_bpfptr_offset(uattr,
11359 offsetof(union bpf_attr, core_relo_rec_size),
11360 &expected_size, sizeof(expected_size)))
11366 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11371 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11372 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11373 i, core_relo.insn_off, prog->len);
11378 err = bpf_core_apply(&ctx, &core_relo, i,
11379 &prog->insnsi[core_relo.insn_off / 8]);
11382 bpfptr_add(&u_core_relo, rec_size);
11387 static int check_btf_info(struct bpf_verifier_env *env,
11388 const union bpf_attr *attr,
11394 if (!attr->func_info_cnt && !attr->line_info_cnt) {
11395 if (check_abnormal_return(env))
11400 btf = btf_get_by_fd(attr->prog_btf_fd);
11402 return PTR_ERR(btf);
11403 if (btf_is_kernel(btf)) {
11407 env->prog->aux->btf = btf;
11409 err = check_btf_func(env, attr, uattr);
11413 err = check_btf_line(env, attr, uattr);
11417 err = check_core_relo(env, attr, uattr);
11424 /* check %cur's range satisfies %old's */
11425 static bool range_within(struct bpf_reg_state *old,
11426 struct bpf_reg_state *cur)
11428 return old->umin_value <= cur->umin_value &&
11429 old->umax_value >= cur->umax_value &&
11430 old->smin_value <= cur->smin_value &&
11431 old->smax_value >= cur->smax_value &&
11432 old->u32_min_value <= cur->u32_min_value &&
11433 old->u32_max_value >= cur->u32_max_value &&
11434 old->s32_min_value <= cur->s32_min_value &&
11435 old->s32_max_value >= cur->s32_max_value;
11438 /* If in the old state two registers had the same id, then they need to have
11439 * the same id in the new state as well. But that id could be different from
11440 * the old state, so we need to track the mapping from old to new ids.
11441 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11442 * regs with old id 5 must also have new id 9 for the new state to be safe. But
11443 * regs with a different old id could still have new id 9, we don't care about
11445 * So we look through our idmap to see if this old id has been seen before. If
11446 * so, we require the new id to match; otherwise, we add the id pair to the map.
11448 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11452 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11453 if (!idmap[i].old) {
11454 /* Reached an empty slot; haven't seen this id before */
11455 idmap[i].old = old_id;
11456 idmap[i].cur = cur_id;
11459 if (idmap[i].old == old_id)
11460 return idmap[i].cur == cur_id;
11462 /* We ran out of idmap slots, which should be impossible */
11467 static void clean_func_state(struct bpf_verifier_env *env,
11468 struct bpf_func_state *st)
11470 enum bpf_reg_liveness live;
11473 for (i = 0; i < BPF_REG_FP; i++) {
11474 live = st->regs[i].live;
11475 /* liveness must not touch this register anymore */
11476 st->regs[i].live |= REG_LIVE_DONE;
11477 if (!(live & REG_LIVE_READ))
11478 /* since the register is unused, clear its state
11479 * to make further comparison simpler
11481 __mark_reg_not_init(env, &st->regs[i]);
11484 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11485 live = st->stack[i].spilled_ptr.live;
11486 /* liveness must not touch this stack slot anymore */
11487 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11488 if (!(live & REG_LIVE_READ)) {
11489 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11490 for (j = 0; j < BPF_REG_SIZE; j++)
11491 st->stack[i].slot_type[j] = STACK_INVALID;
11496 static void clean_verifier_state(struct bpf_verifier_env *env,
11497 struct bpf_verifier_state *st)
11501 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11502 /* all regs in this state in all frames were already marked */
11505 for (i = 0; i <= st->curframe; i++)
11506 clean_func_state(env, st->frame[i]);
11509 /* the parentage chains form a tree.
11510 * the verifier states are added to state lists at given insn and
11511 * pushed into state stack for future exploration.
11512 * when the verifier reaches bpf_exit insn some of the verifer states
11513 * stored in the state lists have their final liveness state already,
11514 * but a lot of states will get revised from liveness point of view when
11515 * the verifier explores other branches.
11518 * 2: if r1 == 100 goto pc+1
11521 * when the verifier reaches exit insn the register r0 in the state list of
11522 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11523 * of insn 2 and goes exploring further. At the insn 4 it will walk the
11524 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11526 * Since the verifier pushes the branch states as it sees them while exploring
11527 * the program the condition of walking the branch instruction for the second
11528 * time means that all states below this branch were already explored and
11529 * their final liveness marks are already propagated.
11530 * Hence when the verifier completes the search of state list in is_state_visited()
11531 * we can call this clean_live_states() function to mark all liveness states
11532 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11533 * will not be used.
11534 * This function also clears the registers and stack for states that !READ
11535 * to simplify state merging.
11537 * Important note here that walking the same branch instruction in the callee
11538 * doesn't meant that the states are DONE. The verifier has to compare
11541 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11542 struct bpf_verifier_state *cur)
11544 struct bpf_verifier_state_list *sl;
11547 sl = *explored_state(env, insn);
11549 if (sl->state.branches)
11551 if (sl->state.insn_idx != insn ||
11552 sl->state.curframe != cur->curframe)
11554 for (i = 0; i <= cur->curframe; i++)
11555 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11557 clean_verifier_state(env, &sl->state);
11563 /* Returns true if (rold safe implies rcur safe) */
11564 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11565 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11569 if (!(rold->live & REG_LIVE_READ))
11570 /* explored state didn't use this */
11573 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11575 if (rold->type == PTR_TO_STACK)
11576 /* two stack pointers are equal only if they're pointing to
11577 * the same stack frame, since fp-8 in foo != fp-8 in bar
11579 return equal && rold->frameno == rcur->frameno;
11584 if (rold->type == NOT_INIT)
11585 /* explored state can't have used this */
11587 if (rcur->type == NOT_INIT)
11589 switch (base_type(rold->type)) {
11591 if (env->explore_alu_limits)
11593 if (rcur->type == SCALAR_VALUE) {
11594 if (!rold->precise && !rcur->precise)
11596 /* new val must satisfy old val knowledge */
11597 return range_within(rold, rcur) &&
11598 tnum_in(rold->var_off, rcur->var_off);
11600 /* We're trying to use a pointer in place of a scalar.
11601 * Even if the scalar was unbounded, this could lead to
11602 * pointer leaks because scalars are allowed to leak
11603 * while pointers are not. We could make this safe in
11604 * special cases if root is calling us, but it's
11605 * probably not worth the hassle.
11609 case PTR_TO_MAP_KEY:
11610 case PTR_TO_MAP_VALUE:
11611 /* a PTR_TO_MAP_VALUE could be safe to use as a
11612 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11613 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11614 * checked, doing so could have affected others with the same
11615 * id, and we can't check for that because we lost the id when
11616 * we converted to a PTR_TO_MAP_VALUE.
11618 if (type_may_be_null(rold->type)) {
11619 if (!type_may_be_null(rcur->type))
11621 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11623 /* Check our ids match any regs they're supposed to */
11624 return check_ids(rold->id, rcur->id, idmap);
11627 /* If the new min/max/var_off satisfy the old ones and
11628 * everything else matches, we are OK.
11629 * 'id' is not compared, since it's only used for maps with
11630 * bpf_spin_lock inside map element and in such cases if
11631 * the rest of the prog is valid for one map element then
11632 * it's valid for all map elements regardless of the key
11633 * used in bpf_map_lookup()
11635 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11636 range_within(rold, rcur) &&
11637 tnum_in(rold->var_off, rcur->var_off);
11638 case PTR_TO_PACKET_META:
11639 case PTR_TO_PACKET:
11640 if (rcur->type != rold->type)
11642 /* We must have at least as much range as the old ptr
11643 * did, so that any accesses which were safe before are
11644 * still safe. This is true even if old range < old off,
11645 * since someone could have accessed through (ptr - k), or
11646 * even done ptr -= k in a register, to get a safe access.
11648 if (rold->range > rcur->range)
11650 /* If the offsets don't match, we can't trust our alignment;
11651 * nor can we be sure that we won't fall out of range.
11653 if (rold->off != rcur->off)
11655 /* id relations must be preserved */
11656 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11658 /* new val must satisfy old val knowledge */
11659 return range_within(rold, rcur) &&
11660 tnum_in(rold->var_off, rcur->var_off);
11662 case CONST_PTR_TO_MAP:
11663 case PTR_TO_PACKET_END:
11664 case PTR_TO_FLOW_KEYS:
11665 case PTR_TO_SOCKET:
11666 case PTR_TO_SOCK_COMMON:
11667 case PTR_TO_TCP_SOCK:
11668 case PTR_TO_XDP_SOCK:
11669 /* Only valid matches are exact, which memcmp() above
11670 * would have accepted
11673 /* Don't know what's going on, just say it's not safe */
11677 /* Shouldn't get here; if we do, say it's not safe */
11682 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11683 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11687 /* walk slots of the explored stack and ignore any additional
11688 * slots in the current stack, since explored(safe) state
11691 for (i = 0; i < old->allocated_stack; i++) {
11692 spi = i / BPF_REG_SIZE;
11694 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11695 i += BPF_REG_SIZE - 1;
11696 /* explored state didn't use this */
11700 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11703 /* explored stack has more populated slots than current stack
11704 * and these slots were used
11706 if (i >= cur->allocated_stack)
11709 /* if old state was safe with misc data in the stack
11710 * it will be safe with zero-initialized stack.
11711 * The opposite is not true
11713 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11714 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11716 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11717 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11718 /* Ex: old explored (safe) state has STACK_SPILL in
11719 * this stack slot, but current has STACK_MISC ->
11720 * this verifier states are not equivalent,
11721 * return false to continue verification of this path
11724 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11726 if (!is_spilled_reg(&old->stack[spi]))
11728 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11729 &cur->stack[spi].spilled_ptr, idmap))
11730 /* when explored and current stack slot are both storing
11731 * spilled registers, check that stored pointers types
11732 * are the same as well.
11733 * Ex: explored safe path could have stored
11734 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11735 * but current path has stored:
11736 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11737 * such verifier states are not equivalent.
11738 * return false to continue verification of this path
11745 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11747 if (old->acquired_refs != cur->acquired_refs)
11749 return !memcmp(old->refs, cur->refs,
11750 sizeof(*old->refs) * old->acquired_refs);
11753 /* compare two verifier states
11755 * all states stored in state_list are known to be valid, since
11756 * verifier reached 'bpf_exit' instruction through them
11758 * this function is called when verifier exploring different branches of
11759 * execution popped from the state stack. If it sees an old state that has
11760 * more strict register state and more strict stack state then this execution
11761 * branch doesn't need to be explored further, since verifier already
11762 * concluded that more strict state leads to valid finish.
11764 * Therefore two states are equivalent if register state is more conservative
11765 * and explored stack state is more conservative than the current one.
11768 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11769 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11771 * In other words if current stack state (one being explored) has more
11772 * valid slots than old one that already passed validation, it means
11773 * the verifier can stop exploring and conclude that current state is valid too
11775 * Similarly with registers. If explored state has register type as invalid
11776 * whereas register type in current state is meaningful, it means that
11777 * the current state will reach 'bpf_exit' instruction safely
11779 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11780 struct bpf_func_state *cur)
11784 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11785 for (i = 0; i < MAX_BPF_REG; i++)
11786 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11787 env->idmap_scratch))
11790 if (!stacksafe(env, old, cur, env->idmap_scratch))
11793 if (!refsafe(old, cur))
11799 static bool states_equal(struct bpf_verifier_env *env,
11800 struct bpf_verifier_state *old,
11801 struct bpf_verifier_state *cur)
11805 if (old->curframe != cur->curframe)
11808 /* Verification state from speculative execution simulation
11809 * must never prune a non-speculative execution one.
11811 if (old->speculative && !cur->speculative)
11814 if (old->active_spin_lock != cur->active_spin_lock)
11817 /* for states to be equal callsites have to be the same
11818 * and all frame states need to be equivalent
11820 for (i = 0; i <= old->curframe; i++) {
11821 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11823 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11829 /* Return 0 if no propagation happened. Return negative error code if error
11830 * happened. Otherwise, return the propagated bit.
11832 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11833 struct bpf_reg_state *reg,
11834 struct bpf_reg_state *parent_reg)
11836 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11837 u8 flag = reg->live & REG_LIVE_READ;
11840 /* When comes here, read flags of PARENT_REG or REG could be any of
11841 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11842 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11844 if (parent_flag == REG_LIVE_READ64 ||
11845 /* Or if there is no read flag from REG. */
11847 /* Or if the read flag from REG is the same as PARENT_REG. */
11848 parent_flag == flag)
11851 err = mark_reg_read(env, reg, parent_reg, flag);
11858 /* A write screens off any subsequent reads; but write marks come from the
11859 * straight-line code between a state and its parent. When we arrive at an
11860 * equivalent state (jump target or such) we didn't arrive by the straight-line
11861 * code, so read marks in the state must propagate to the parent regardless
11862 * of the state's write marks. That's what 'parent == state->parent' comparison
11863 * in mark_reg_read() is for.
11865 static int propagate_liveness(struct bpf_verifier_env *env,
11866 const struct bpf_verifier_state *vstate,
11867 struct bpf_verifier_state *vparent)
11869 struct bpf_reg_state *state_reg, *parent_reg;
11870 struct bpf_func_state *state, *parent;
11871 int i, frame, err = 0;
11873 if (vparent->curframe != vstate->curframe) {
11874 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11875 vparent->curframe, vstate->curframe);
11878 /* Propagate read liveness of registers... */
11879 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11880 for (frame = 0; frame <= vstate->curframe; frame++) {
11881 parent = vparent->frame[frame];
11882 state = vstate->frame[frame];
11883 parent_reg = parent->regs;
11884 state_reg = state->regs;
11885 /* We don't need to worry about FP liveness, it's read-only */
11886 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11887 err = propagate_liveness_reg(env, &state_reg[i],
11891 if (err == REG_LIVE_READ64)
11892 mark_insn_zext(env, &parent_reg[i]);
11895 /* Propagate stack slots. */
11896 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11897 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11898 parent_reg = &parent->stack[i].spilled_ptr;
11899 state_reg = &state->stack[i].spilled_ptr;
11900 err = propagate_liveness_reg(env, state_reg,
11909 /* find precise scalars in the previous equivalent state and
11910 * propagate them into the current state
11912 static int propagate_precision(struct bpf_verifier_env *env,
11913 const struct bpf_verifier_state *old)
11915 struct bpf_reg_state *state_reg;
11916 struct bpf_func_state *state;
11917 int i, err = 0, fr;
11919 for (fr = old->curframe; fr >= 0; fr--) {
11920 state = old->frame[fr];
11921 state_reg = state->regs;
11922 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11923 if (state_reg->type != SCALAR_VALUE ||
11924 !state_reg->precise ||
11925 !(state_reg->live & REG_LIVE_READ))
11927 if (env->log.level & BPF_LOG_LEVEL2)
11928 verbose(env, "frame %d: propagating r%d\n", fr, i);
11929 err = mark_chain_precision_frame(env, fr, i);
11934 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11935 if (!is_spilled_reg(&state->stack[i]))
11937 state_reg = &state->stack[i].spilled_ptr;
11938 if (state_reg->type != SCALAR_VALUE ||
11939 !state_reg->precise ||
11940 !(state_reg->live & REG_LIVE_READ))
11942 if (env->log.level & BPF_LOG_LEVEL2)
11943 verbose(env, "frame %d: propagating fp%d\n",
11944 fr, (-i - 1) * BPF_REG_SIZE);
11945 err = mark_chain_precision_stack_frame(env, fr, i);
11953 static bool states_maybe_looping(struct bpf_verifier_state *old,
11954 struct bpf_verifier_state *cur)
11956 struct bpf_func_state *fold, *fcur;
11957 int i, fr = cur->curframe;
11959 if (old->curframe != fr)
11962 fold = old->frame[fr];
11963 fcur = cur->frame[fr];
11964 for (i = 0; i < MAX_BPF_REG; i++)
11965 if (memcmp(&fold->regs[i], &fcur->regs[i],
11966 offsetof(struct bpf_reg_state, parent)))
11972 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11974 struct bpf_verifier_state_list *new_sl;
11975 struct bpf_verifier_state_list *sl, **pprev;
11976 struct bpf_verifier_state *cur = env->cur_state, *new;
11977 int i, j, err, states_cnt = 0;
11978 bool add_new_state = env->test_state_freq ? true : false;
11980 cur->last_insn_idx = env->prev_insn_idx;
11981 if (!env->insn_aux_data[insn_idx].prune_point)
11982 /* this 'insn_idx' instruction wasn't marked, so we will not
11983 * be doing state search here
11987 /* bpf progs typically have pruning point every 4 instructions
11988 * http://vger.kernel.org/bpfconf2019.html#session-1
11989 * Do not add new state for future pruning if the verifier hasn't seen
11990 * at least 2 jumps and at least 8 instructions.
11991 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11992 * In tests that amounts to up to 50% reduction into total verifier
11993 * memory consumption and 20% verifier time speedup.
11995 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11996 env->insn_processed - env->prev_insn_processed >= 8)
11997 add_new_state = true;
11999 pprev = explored_state(env, insn_idx);
12002 clean_live_states(env, insn_idx, cur);
12006 if (sl->state.insn_idx != insn_idx)
12009 if (sl->state.branches) {
12010 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
12012 if (frame->in_async_callback_fn &&
12013 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
12014 /* Different async_entry_cnt means that the verifier is
12015 * processing another entry into async callback.
12016 * Seeing the same state is not an indication of infinite
12017 * loop or infinite recursion.
12018 * But finding the same state doesn't mean that it's safe
12019 * to stop processing the current state. The previous state
12020 * hasn't yet reached bpf_exit, since state.branches > 0.
12021 * Checking in_async_callback_fn alone is not enough either.
12022 * Since the verifier still needs to catch infinite loops
12023 * inside async callbacks.
12025 } else if (states_maybe_looping(&sl->state, cur) &&
12026 states_equal(env, &sl->state, cur)) {
12027 verbose_linfo(env, insn_idx, "; ");
12028 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
12031 /* if the verifier is processing a loop, avoid adding new state
12032 * too often, since different loop iterations have distinct
12033 * states and may not help future pruning.
12034 * This threshold shouldn't be too low to make sure that
12035 * a loop with large bound will be rejected quickly.
12036 * The most abusive loop will be:
12038 * if r1 < 1000000 goto pc-2
12039 * 1M insn_procssed limit / 100 == 10k peak states.
12040 * This threshold shouldn't be too high either, since states
12041 * at the end of the loop are likely to be useful in pruning.
12043 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
12044 env->insn_processed - env->prev_insn_processed < 100)
12045 add_new_state = false;
12048 if (states_equal(env, &sl->state, cur)) {
12050 /* reached equivalent register/stack state,
12051 * prune the search.
12052 * Registers read by the continuation are read by us.
12053 * If we have any write marks in env->cur_state, they
12054 * will prevent corresponding reads in the continuation
12055 * from reaching our parent (an explored_state). Our
12056 * own state will get the read marks recorded, but
12057 * they'll be immediately forgotten as we're pruning
12058 * this state and will pop a new one.
12060 err = propagate_liveness(env, &sl->state, cur);
12062 /* if previous state reached the exit with precision and
12063 * current state is equivalent to it (except precsion marks)
12064 * the precision needs to be propagated back in
12065 * the current state.
12067 err = err ? : push_jmp_history(env, cur);
12068 err = err ? : propagate_precision(env, &sl->state);
12074 /* when new state is not going to be added do not increase miss count.
12075 * Otherwise several loop iterations will remove the state
12076 * recorded earlier. The goal of these heuristics is to have
12077 * states from some iterations of the loop (some in the beginning
12078 * and some at the end) to help pruning.
12082 /* heuristic to determine whether this state is beneficial
12083 * to keep checking from state equivalence point of view.
12084 * Higher numbers increase max_states_per_insn and verification time,
12085 * but do not meaningfully decrease insn_processed.
12087 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12088 /* the state is unlikely to be useful. Remove it to
12089 * speed up verification
12092 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12093 u32 br = sl->state.branches;
12096 "BUG live_done but branches_to_explore %d\n",
12098 free_verifier_state(&sl->state, false);
12100 env->peak_states--;
12102 /* cannot free this state, since parentage chain may
12103 * walk it later. Add it for free_list instead to
12104 * be freed at the end of verification
12106 sl->next = env->free_list;
12107 env->free_list = sl;
12117 if (env->max_states_per_insn < states_cnt)
12118 env->max_states_per_insn = states_cnt;
12120 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12121 return push_jmp_history(env, cur);
12123 if (!add_new_state)
12124 return push_jmp_history(env, cur);
12126 /* There were no equivalent states, remember the current one.
12127 * Technically the current state is not proven to be safe yet,
12128 * but it will either reach outer most bpf_exit (which means it's safe)
12129 * or it will be rejected. When there are no loops the verifier won't be
12130 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12131 * again on the way to bpf_exit.
12132 * When looping the sl->state.branches will be > 0 and this state
12133 * will not be considered for equivalence until branches == 0.
12135 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12138 env->total_states++;
12139 env->peak_states++;
12140 env->prev_jmps_processed = env->jmps_processed;
12141 env->prev_insn_processed = env->insn_processed;
12143 /* add new state to the head of linked list */
12144 new = &new_sl->state;
12145 err = copy_verifier_state(new, cur);
12147 free_verifier_state(new, false);
12151 new->insn_idx = insn_idx;
12152 WARN_ONCE(new->branches != 1,
12153 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12156 cur->first_insn_idx = insn_idx;
12157 clear_jmp_history(cur);
12158 new_sl->next = *explored_state(env, insn_idx);
12159 *explored_state(env, insn_idx) = new_sl;
12160 /* connect new state to parentage chain. Current frame needs all
12161 * registers connected. Only r6 - r9 of the callers are alive (pushed
12162 * to the stack implicitly by JITs) so in callers' frames connect just
12163 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12164 * the state of the call instruction (with WRITTEN set), and r0 comes
12165 * from callee with its full parentage chain, anyway.
12167 /* clear write marks in current state: the writes we did are not writes
12168 * our child did, so they don't screen off its reads from us.
12169 * (There are no read marks in current state, because reads always mark
12170 * their parent and current state never has children yet. Only
12171 * explored_states can get read marks.)
12173 for (j = 0; j <= cur->curframe; j++) {
12174 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12175 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12176 for (i = 0; i < BPF_REG_FP; i++)
12177 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12180 /* all stack frames are accessible from callee, clear them all */
12181 for (j = 0; j <= cur->curframe; j++) {
12182 struct bpf_func_state *frame = cur->frame[j];
12183 struct bpf_func_state *newframe = new->frame[j];
12185 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12186 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12187 frame->stack[i].spilled_ptr.parent =
12188 &newframe->stack[i].spilled_ptr;
12194 /* Return true if it's OK to have the same insn return a different type. */
12195 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12197 switch (base_type(type)) {
12199 case PTR_TO_SOCKET:
12200 case PTR_TO_SOCK_COMMON:
12201 case PTR_TO_TCP_SOCK:
12202 case PTR_TO_XDP_SOCK:
12203 case PTR_TO_BTF_ID:
12210 /* If an instruction was previously used with particular pointer types, then we
12211 * need to be careful to avoid cases such as the below, where it may be ok
12212 * for one branch accessing the pointer, but not ok for the other branch:
12217 * R1 = some_other_valid_ptr;
12220 * R2 = *(u32 *)(R1 + 0);
12222 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12224 return src != prev && (!reg_type_mismatch_ok(src) ||
12225 !reg_type_mismatch_ok(prev));
12228 static int do_check(struct bpf_verifier_env *env)
12230 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12231 struct bpf_verifier_state *state = env->cur_state;
12232 struct bpf_insn *insns = env->prog->insnsi;
12233 struct bpf_reg_state *regs;
12234 int insn_cnt = env->prog->len;
12235 bool do_print_state = false;
12236 int prev_insn_idx = -1;
12239 struct bpf_insn *insn;
12243 env->prev_insn_idx = prev_insn_idx;
12244 if (env->insn_idx >= insn_cnt) {
12245 verbose(env, "invalid insn idx %d insn_cnt %d\n",
12246 env->insn_idx, insn_cnt);
12250 insn = &insns[env->insn_idx];
12251 class = BPF_CLASS(insn->code);
12253 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12255 "BPF program is too large. Processed %d insn\n",
12256 env->insn_processed);
12260 err = is_state_visited(env, env->insn_idx);
12264 /* found equivalent state, can prune the search */
12265 if (env->log.level & BPF_LOG_LEVEL) {
12266 if (do_print_state)
12267 verbose(env, "\nfrom %d to %d%s: safe\n",
12268 env->prev_insn_idx, env->insn_idx,
12269 env->cur_state->speculative ?
12270 " (speculative execution)" : "");
12272 verbose(env, "%d: safe\n", env->insn_idx);
12274 goto process_bpf_exit;
12277 if (signal_pending(current))
12280 if (need_resched())
12283 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12284 verbose(env, "\nfrom %d to %d%s:",
12285 env->prev_insn_idx, env->insn_idx,
12286 env->cur_state->speculative ?
12287 " (speculative execution)" : "");
12288 print_verifier_state(env, state->frame[state->curframe], true);
12289 do_print_state = false;
12292 if (env->log.level & BPF_LOG_LEVEL) {
12293 const struct bpf_insn_cbs cbs = {
12294 .cb_call = disasm_kfunc_name,
12295 .cb_print = verbose,
12296 .private_data = env,
12299 if (verifier_state_scratched(env))
12300 print_insn_state(env, state->frame[state->curframe]);
12302 verbose_linfo(env, env->insn_idx, "; ");
12303 env->prev_log_len = env->log.len_used;
12304 verbose(env, "%d: ", env->insn_idx);
12305 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12306 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12307 env->prev_log_len = env->log.len_used;
12310 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12311 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12312 env->prev_insn_idx);
12317 regs = cur_regs(env);
12318 sanitize_mark_insn_seen(env);
12319 prev_insn_idx = env->insn_idx;
12321 if (class == BPF_ALU || class == BPF_ALU64) {
12322 err = check_alu_op(env, insn);
12326 } else if (class == BPF_LDX) {
12327 enum bpf_reg_type *prev_src_type, src_reg_type;
12329 /* check for reserved fields is already done */
12331 /* check src operand */
12332 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12336 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12340 src_reg_type = regs[insn->src_reg].type;
12342 /* check that memory (src_reg + off) is readable,
12343 * the state of dst_reg will be updated by this func
12345 err = check_mem_access(env, env->insn_idx, insn->src_reg,
12346 insn->off, BPF_SIZE(insn->code),
12347 BPF_READ, insn->dst_reg, false);
12351 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12353 if (*prev_src_type == NOT_INIT) {
12354 /* saw a valid insn
12355 * dst_reg = *(u32 *)(src_reg + off)
12356 * save type to validate intersecting paths
12358 *prev_src_type = src_reg_type;
12360 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12361 /* ABuser program is trying to use the same insn
12362 * dst_reg = *(u32*) (src_reg + off)
12363 * with different pointer types:
12364 * src_reg == ctx in one branch and
12365 * src_reg == stack|map in some other branch.
12368 verbose(env, "same insn cannot be used with different pointers\n");
12372 } else if (class == BPF_STX) {
12373 enum bpf_reg_type *prev_dst_type, dst_reg_type;
12375 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12376 err = check_atomic(env, env->insn_idx, insn);
12383 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12384 verbose(env, "BPF_STX uses reserved fields\n");
12388 /* check src1 operand */
12389 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12392 /* check src2 operand */
12393 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12397 dst_reg_type = regs[insn->dst_reg].type;
12399 /* check that memory (dst_reg + off) is writeable */
12400 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12401 insn->off, BPF_SIZE(insn->code),
12402 BPF_WRITE, insn->src_reg, false);
12406 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12408 if (*prev_dst_type == NOT_INIT) {
12409 *prev_dst_type = dst_reg_type;
12410 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12411 verbose(env, "same insn cannot be used with different pointers\n");
12415 } else if (class == BPF_ST) {
12416 if (BPF_MODE(insn->code) != BPF_MEM ||
12417 insn->src_reg != BPF_REG_0) {
12418 verbose(env, "BPF_ST uses reserved fields\n");
12421 /* check src operand */
12422 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12426 if (is_ctx_reg(env, insn->dst_reg)) {
12427 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12429 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12433 /* check that memory (dst_reg + off) is writeable */
12434 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12435 insn->off, BPF_SIZE(insn->code),
12436 BPF_WRITE, -1, false);
12440 } else if (class == BPF_JMP || class == BPF_JMP32) {
12441 u8 opcode = BPF_OP(insn->code);
12443 env->jmps_processed++;
12444 if (opcode == BPF_CALL) {
12445 if (BPF_SRC(insn->code) != BPF_K ||
12446 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12447 && insn->off != 0) ||
12448 (insn->src_reg != BPF_REG_0 &&
12449 insn->src_reg != BPF_PSEUDO_CALL &&
12450 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12451 insn->dst_reg != BPF_REG_0 ||
12452 class == BPF_JMP32) {
12453 verbose(env, "BPF_CALL uses reserved fields\n");
12457 if (env->cur_state->active_spin_lock &&
12458 (insn->src_reg == BPF_PSEUDO_CALL ||
12459 insn->imm != BPF_FUNC_spin_unlock)) {
12460 verbose(env, "function calls are not allowed while holding a lock\n");
12463 if (insn->src_reg == BPF_PSEUDO_CALL)
12464 err = check_func_call(env, insn, &env->insn_idx);
12465 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12466 err = check_kfunc_call(env, insn, &env->insn_idx);
12468 err = check_helper_call(env, insn, &env->insn_idx);
12471 } else if (opcode == BPF_JA) {
12472 if (BPF_SRC(insn->code) != BPF_K ||
12474 insn->src_reg != BPF_REG_0 ||
12475 insn->dst_reg != BPF_REG_0 ||
12476 class == BPF_JMP32) {
12477 verbose(env, "BPF_JA uses reserved fields\n");
12481 env->insn_idx += insn->off + 1;
12484 } else if (opcode == BPF_EXIT) {
12485 if (BPF_SRC(insn->code) != BPF_K ||
12487 insn->src_reg != BPF_REG_0 ||
12488 insn->dst_reg != BPF_REG_0 ||
12489 class == BPF_JMP32) {
12490 verbose(env, "BPF_EXIT uses reserved fields\n");
12494 if (env->cur_state->active_spin_lock) {
12495 verbose(env, "bpf_spin_unlock is missing\n");
12499 /* We must do check_reference_leak here before
12500 * prepare_func_exit to handle the case when
12501 * state->curframe > 0, it may be a callback
12502 * function, for which reference_state must
12503 * match caller reference state when it exits.
12505 err = check_reference_leak(env);
12509 if (state->curframe) {
12510 /* exit from nested function */
12511 err = prepare_func_exit(env, &env->insn_idx);
12514 do_print_state = true;
12518 err = check_return_code(env);
12522 mark_verifier_state_scratched(env);
12523 update_branch_counts(env, env->cur_state);
12524 err = pop_stack(env, &prev_insn_idx,
12525 &env->insn_idx, pop_log);
12527 if (err != -ENOENT)
12531 do_print_state = true;
12535 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12539 } else if (class == BPF_LD) {
12540 u8 mode = BPF_MODE(insn->code);
12542 if (mode == BPF_ABS || mode == BPF_IND) {
12543 err = check_ld_abs(env, insn);
12547 } else if (mode == BPF_IMM) {
12548 err = check_ld_imm(env, insn);
12553 sanitize_mark_insn_seen(env);
12555 verbose(env, "invalid BPF_LD mode\n");
12559 verbose(env, "unknown insn class %d\n", class);
12569 static int find_btf_percpu_datasec(struct btf *btf)
12571 const struct btf_type *t;
12576 * Both vmlinux and module each have their own ".data..percpu"
12577 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12578 * types to look at only module's own BTF types.
12580 n = btf_nr_types(btf);
12581 if (btf_is_module(btf))
12582 i = btf_nr_types(btf_vmlinux);
12586 for(; i < n; i++) {
12587 t = btf_type_by_id(btf, i);
12588 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12591 tname = btf_name_by_offset(btf, t->name_off);
12592 if (!strcmp(tname, ".data..percpu"))
12599 /* replace pseudo btf_id with kernel symbol address */
12600 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12601 struct bpf_insn *insn,
12602 struct bpf_insn_aux_data *aux)
12604 const struct btf_var_secinfo *vsi;
12605 const struct btf_type *datasec;
12606 struct btf_mod_pair *btf_mod;
12607 const struct btf_type *t;
12608 const char *sym_name;
12609 bool percpu = false;
12610 u32 type, id = insn->imm;
12614 int i, btf_fd, err;
12616 btf_fd = insn[1].imm;
12618 btf = btf_get_by_fd(btf_fd);
12620 verbose(env, "invalid module BTF object FD specified.\n");
12624 if (!btf_vmlinux) {
12625 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12632 t = btf_type_by_id(btf, id);
12634 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12639 if (!btf_type_is_var(t)) {
12640 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12645 sym_name = btf_name_by_offset(btf, t->name_off);
12646 addr = kallsyms_lookup_name(sym_name);
12648 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12654 datasec_id = find_btf_percpu_datasec(btf);
12655 if (datasec_id > 0) {
12656 datasec = btf_type_by_id(btf, datasec_id);
12657 for_each_vsi(i, datasec, vsi) {
12658 if (vsi->type == id) {
12665 insn[0].imm = (u32)addr;
12666 insn[1].imm = addr >> 32;
12669 t = btf_type_skip_modifiers(btf, type, NULL);
12671 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12672 aux->btf_var.btf = btf;
12673 aux->btf_var.btf_id = type;
12674 } else if (!btf_type_is_struct(t)) {
12675 const struct btf_type *ret;
12679 /* resolve the type size of ksym. */
12680 ret = btf_resolve_size(btf, t, &tsize);
12682 tname = btf_name_by_offset(btf, t->name_off);
12683 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12684 tname, PTR_ERR(ret));
12688 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12689 aux->btf_var.mem_size = tsize;
12691 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12692 aux->btf_var.btf = btf;
12693 aux->btf_var.btf_id = type;
12696 /* check whether we recorded this BTF (and maybe module) already */
12697 for (i = 0; i < env->used_btf_cnt; i++) {
12698 if (env->used_btfs[i].btf == btf) {
12704 if (env->used_btf_cnt >= MAX_USED_BTFS) {
12709 btf_mod = &env->used_btfs[env->used_btf_cnt];
12710 btf_mod->btf = btf;
12711 btf_mod->module = NULL;
12713 /* if we reference variables from kernel module, bump its refcount */
12714 if (btf_is_module(btf)) {
12715 btf_mod->module = btf_try_get_module(btf);
12716 if (!btf_mod->module) {
12722 env->used_btf_cnt++;
12730 static bool is_tracing_prog_type(enum bpf_prog_type type)
12733 case BPF_PROG_TYPE_KPROBE:
12734 case BPF_PROG_TYPE_TRACEPOINT:
12735 case BPF_PROG_TYPE_PERF_EVENT:
12736 case BPF_PROG_TYPE_RAW_TRACEPOINT:
12737 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12744 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12745 struct bpf_map *map,
12746 struct bpf_prog *prog)
12749 enum bpf_prog_type prog_type = resolve_prog_type(prog);
12751 if (map_value_has_spin_lock(map)) {
12752 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12753 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12757 if (is_tracing_prog_type(prog_type)) {
12758 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12762 if (prog->aux->sleepable) {
12763 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12768 if (map_value_has_timer(map)) {
12769 if (is_tracing_prog_type(prog_type)) {
12770 verbose(env, "tracing progs cannot use bpf_timer yet\n");
12775 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12776 !bpf_offload_prog_map_match(prog, map)) {
12777 verbose(env, "offload device mismatch between prog and map\n");
12781 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12782 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12786 if (prog->aux->sleepable)
12787 switch (map->map_type) {
12788 case BPF_MAP_TYPE_HASH:
12789 case BPF_MAP_TYPE_LRU_HASH:
12790 case BPF_MAP_TYPE_ARRAY:
12791 case BPF_MAP_TYPE_PERCPU_HASH:
12792 case BPF_MAP_TYPE_PERCPU_ARRAY:
12793 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12794 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12795 case BPF_MAP_TYPE_HASH_OF_MAPS:
12796 case BPF_MAP_TYPE_RINGBUF:
12797 case BPF_MAP_TYPE_USER_RINGBUF:
12798 case BPF_MAP_TYPE_INODE_STORAGE:
12799 case BPF_MAP_TYPE_SK_STORAGE:
12800 case BPF_MAP_TYPE_TASK_STORAGE:
12804 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12811 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12813 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12814 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12817 /* find and rewrite pseudo imm in ld_imm64 instructions:
12819 * 1. if it accesses map FD, replace it with actual map pointer.
12820 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12822 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12824 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12826 struct bpf_insn *insn = env->prog->insnsi;
12827 int insn_cnt = env->prog->len;
12830 err = bpf_prog_calc_tag(env->prog);
12834 for (i = 0; i < insn_cnt; i++, insn++) {
12835 if (BPF_CLASS(insn->code) == BPF_LDX &&
12836 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12837 verbose(env, "BPF_LDX uses reserved fields\n");
12841 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12842 struct bpf_insn_aux_data *aux;
12843 struct bpf_map *map;
12848 if (i == insn_cnt - 1 || insn[1].code != 0 ||
12849 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12850 insn[1].off != 0) {
12851 verbose(env, "invalid bpf_ld_imm64 insn\n");
12855 if (insn[0].src_reg == 0)
12856 /* valid generic load 64-bit imm */
12859 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12860 aux = &env->insn_aux_data[i];
12861 err = check_pseudo_btf_id(env, insn, aux);
12867 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12868 aux = &env->insn_aux_data[i];
12869 aux->ptr_type = PTR_TO_FUNC;
12873 /* In final convert_pseudo_ld_imm64() step, this is
12874 * converted into regular 64-bit imm load insn.
12876 switch (insn[0].src_reg) {
12877 case BPF_PSEUDO_MAP_VALUE:
12878 case BPF_PSEUDO_MAP_IDX_VALUE:
12880 case BPF_PSEUDO_MAP_FD:
12881 case BPF_PSEUDO_MAP_IDX:
12882 if (insn[1].imm == 0)
12886 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12890 switch (insn[0].src_reg) {
12891 case BPF_PSEUDO_MAP_IDX_VALUE:
12892 case BPF_PSEUDO_MAP_IDX:
12893 if (bpfptr_is_null(env->fd_array)) {
12894 verbose(env, "fd_idx without fd_array is invalid\n");
12897 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12898 insn[0].imm * sizeof(fd),
12908 map = __bpf_map_get(f);
12910 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12912 return PTR_ERR(map);
12915 err = check_map_prog_compatibility(env, map, env->prog);
12921 aux = &env->insn_aux_data[i];
12922 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12923 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12924 addr = (unsigned long)map;
12926 u32 off = insn[1].imm;
12928 if (off >= BPF_MAX_VAR_OFF) {
12929 verbose(env, "direct value offset of %u is not allowed\n", off);
12934 if (!map->ops->map_direct_value_addr) {
12935 verbose(env, "no direct value access support for this map type\n");
12940 err = map->ops->map_direct_value_addr(map, &addr, off);
12942 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12943 map->value_size, off);
12948 aux->map_off = off;
12952 insn[0].imm = (u32)addr;
12953 insn[1].imm = addr >> 32;
12955 /* check whether we recorded this map already */
12956 for (j = 0; j < env->used_map_cnt; j++) {
12957 if (env->used_maps[j] == map) {
12958 aux->map_index = j;
12964 if (env->used_map_cnt >= MAX_USED_MAPS) {
12969 /* hold the map. If the program is rejected by verifier,
12970 * the map will be released by release_maps() or it
12971 * will be used by the valid program until it's unloaded
12972 * and all maps are released in free_used_maps()
12976 aux->map_index = env->used_map_cnt;
12977 env->used_maps[env->used_map_cnt++] = map;
12979 if (bpf_map_is_cgroup_storage(map) &&
12980 bpf_cgroup_storage_assign(env->prog->aux, map)) {
12981 verbose(env, "only one cgroup storage of each type is allowed\n");
12993 /* Basic sanity check before we invest more work here. */
12994 if (!bpf_opcode_in_insntable(insn->code)) {
12995 verbose(env, "unknown opcode %02x\n", insn->code);
13000 /* now all pseudo BPF_LD_IMM64 instructions load valid
13001 * 'struct bpf_map *' into a register instead of user map_fd.
13002 * These pointers will be used later by verifier to validate map access.
13007 /* drop refcnt of maps used by the rejected program */
13008 static void release_maps(struct bpf_verifier_env *env)
13010 __bpf_free_used_maps(env->prog->aux, env->used_maps,
13011 env->used_map_cnt);
13014 /* drop refcnt of maps used by the rejected program */
13015 static void release_btfs(struct bpf_verifier_env *env)
13017 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
13018 env->used_btf_cnt);
13021 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
13022 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
13024 struct bpf_insn *insn = env->prog->insnsi;
13025 int insn_cnt = env->prog->len;
13028 for (i = 0; i < insn_cnt; i++, insn++) {
13029 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
13031 if (insn->src_reg == BPF_PSEUDO_FUNC)
13037 /* single env->prog->insni[off] instruction was replaced with the range
13038 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
13039 * [0, off) and [off, end) to new locations, so the patched range stays zero
13041 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
13042 struct bpf_insn_aux_data *new_data,
13043 struct bpf_prog *new_prog, u32 off, u32 cnt)
13045 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
13046 struct bpf_insn *insn = new_prog->insnsi;
13047 u32 old_seen = old_data[off].seen;
13051 /* aux info at OFF always needs adjustment, no matter fast path
13052 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
13053 * original insn at old prog.
13055 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
13059 prog_len = new_prog->len;
13061 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
13062 memcpy(new_data + off + cnt - 1, old_data + off,
13063 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
13064 for (i = off; i < off + cnt - 1; i++) {
13065 /* Expand insni[off]'s seen count to the patched range. */
13066 new_data[i].seen = old_seen;
13067 new_data[i].zext_dst = insn_has_def32(env, insn + i);
13069 env->insn_aux_data = new_data;
13073 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13079 /* NOTE: fake 'exit' subprog should be updated as well. */
13080 for (i = 0; i <= env->subprog_cnt; i++) {
13081 if (env->subprog_info[i].start <= off)
13083 env->subprog_info[i].start += len - 1;
13087 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13089 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13090 int i, sz = prog->aux->size_poke_tab;
13091 struct bpf_jit_poke_descriptor *desc;
13093 for (i = 0; i < sz; i++) {
13095 if (desc->insn_idx <= off)
13097 desc->insn_idx += len - 1;
13101 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13102 const struct bpf_insn *patch, u32 len)
13104 struct bpf_prog *new_prog;
13105 struct bpf_insn_aux_data *new_data = NULL;
13108 new_data = vzalloc(array_size(env->prog->len + len - 1,
13109 sizeof(struct bpf_insn_aux_data)));
13114 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13115 if (IS_ERR(new_prog)) {
13116 if (PTR_ERR(new_prog) == -ERANGE)
13118 "insn %d cannot be patched due to 16-bit range\n",
13119 env->insn_aux_data[off].orig_idx);
13123 adjust_insn_aux_data(env, new_data, new_prog, off, len);
13124 adjust_subprog_starts(env, off, len);
13125 adjust_poke_descs(new_prog, off, len);
13129 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13134 /* find first prog starting at or after off (first to remove) */
13135 for (i = 0; i < env->subprog_cnt; i++)
13136 if (env->subprog_info[i].start >= off)
13138 /* find first prog starting at or after off + cnt (first to stay) */
13139 for (j = i; j < env->subprog_cnt; j++)
13140 if (env->subprog_info[j].start >= off + cnt)
13142 /* if j doesn't start exactly at off + cnt, we are just removing
13143 * the front of previous prog
13145 if (env->subprog_info[j].start != off + cnt)
13149 struct bpf_prog_aux *aux = env->prog->aux;
13152 /* move fake 'exit' subprog as well */
13153 move = env->subprog_cnt + 1 - j;
13155 memmove(env->subprog_info + i,
13156 env->subprog_info + j,
13157 sizeof(*env->subprog_info) * move);
13158 env->subprog_cnt -= j - i;
13160 /* remove func_info */
13161 if (aux->func_info) {
13162 move = aux->func_info_cnt - j;
13164 memmove(aux->func_info + i,
13165 aux->func_info + j,
13166 sizeof(*aux->func_info) * move);
13167 aux->func_info_cnt -= j - i;
13168 /* func_info->insn_off is set after all code rewrites,
13169 * in adjust_btf_func() - no need to adjust
13173 /* convert i from "first prog to remove" to "first to adjust" */
13174 if (env->subprog_info[i].start == off)
13178 /* update fake 'exit' subprog as well */
13179 for (; i <= env->subprog_cnt; i++)
13180 env->subprog_info[i].start -= cnt;
13185 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13188 struct bpf_prog *prog = env->prog;
13189 u32 i, l_off, l_cnt, nr_linfo;
13190 struct bpf_line_info *linfo;
13192 nr_linfo = prog->aux->nr_linfo;
13196 linfo = prog->aux->linfo;
13198 /* find first line info to remove, count lines to be removed */
13199 for (i = 0; i < nr_linfo; i++)
13200 if (linfo[i].insn_off >= off)
13205 for (; i < nr_linfo; i++)
13206 if (linfo[i].insn_off < off + cnt)
13211 /* First live insn doesn't match first live linfo, it needs to "inherit"
13212 * last removed linfo. prog is already modified, so prog->len == off
13213 * means no live instructions after (tail of the program was removed).
13215 if (prog->len != off && l_cnt &&
13216 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13218 linfo[--i].insn_off = off + cnt;
13221 /* remove the line info which refer to the removed instructions */
13223 memmove(linfo + l_off, linfo + i,
13224 sizeof(*linfo) * (nr_linfo - i));
13226 prog->aux->nr_linfo -= l_cnt;
13227 nr_linfo = prog->aux->nr_linfo;
13230 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13231 for (i = l_off; i < nr_linfo; i++)
13232 linfo[i].insn_off -= cnt;
13234 /* fix up all subprogs (incl. 'exit') which start >= off */
13235 for (i = 0; i <= env->subprog_cnt; i++)
13236 if (env->subprog_info[i].linfo_idx > l_off) {
13237 /* program may have started in the removed region but
13238 * may not be fully removed
13240 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13241 env->subprog_info[i].linfo_idx -= l_cnt;
13243 env->subprog_info[i].linfo_idx = l_off;
13249 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13251 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13252 unsigned int orig_prog_len = env->prog->len;
13255 if (bpf_prog_is_dev_bound(env->prog->aux))
13256 bpf_prog_offload_remove_insns(env, off, cnt);
13258 err = bpf_remove_insns(env->prog, off, cnt);
13262 err = adjust_subprog_starts_after_remove(env, off, cnt);
13266 err = bpf_adj_linfo_after_remove(env, off, cnt);
13270 memmove(aux_data + off, aux_data + off + cnt,
13271 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13276 /* The verifier does more data flow analysis than llvm and will not
13277 * explore branches that are dead at run time. Malicious programs can
13278 * have dead code too. Therefore replace all dead at-run-time code
13281 * Just nops are not optimal, e.g. if they would sit at the end of the
13282 * program and through another bug we would manage to jump there, then
13283 * we'd execute beyond program memory otherwise. Returning exception
13284 * code also wouldn't work since we can have subprogs where the dead
13285 * code could be located.
13287 static void sanitize_dead_code(struct bpf_verifier_env *env)
13289 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13290 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13291 struct bpf_insn *insn = env->prog->insnsi;
13292 const int insn_cnt = env->prog->len;
13295 for (i = 0; i < insn_cnt; i++) {
13296 if (aux_data[i].seen)
13298 memcpy(insn + i, &trap, sizeof(trap));
13299 aux_data[i].zext_dst = false;
13303 static bool insn_is_cond_jump(u8 code)
13307 if (BPF_CLASS(code) == BPF_JMP32)
13310 if (BPF_CLASS(code) != BPF_JMP)
13314 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13317 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13319 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13320 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13321 struct bpf_insn *insn = env->prog->insnsi;
13322 const int insn_cnt = env->prog->len;
13325 for (i = 0; i < insn_cnt; i++, insn++) {
13326 if (!insn_is_cond_jump(insn->code))
13329 if (!aux_data[i + 1].seen)
13330 ja.off = insn->off;
13331 else if (!aux_data[i + 1 + insn->off].seen)
13336 if (bpf_prog_is_dev_bound(env->prog->aux))
13337 bpf_prog_offload_replace_insn(env, i, &ja);
13339 memcpy(insn, &ja, sizeof(ja));
13343 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13345 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13346 int insn_cnt = env->prog->len;
13349 for (i = 0; i < insn_cnt; i++) {
13353 while (i + j < insn_cnt && !aux_data[i + j].seen)
13358 err = verifier_remove_insns(env, i, j);
13361 insn_cnt = env->prog->len;
13367 static int opt_remove_nops(struct bpf_verifier_env *env)
13369 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13370 struct bpf_insn *insn = env->prog->insnsi;
13371 int insn_cnt = env->prog->len;
13374 for (i = 0; i < insn_cnt; i++) {
13375 if (memcmp(&insn[i], &ja, sizeof(ja)))
13378 err = verifier_remove_insns(env, i, 1);
13388 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13389 const union bpf_attr *attr)
13391 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13392 struct bpf_insn_aux_data *aux = env->insn_aux_data;
13393 int i, patch_len, delta = 0, len = env->prog->len;
13394 struct bpf_insn *insns = env->prog->insnsi;
13395 struct bpf_prog *new_prog;
13398 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13399 zext_patch[1] = BPF_ZEXT_REG(0);
13400 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13401 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13402 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13403 for (i = 0; i < len; i++) {
13404 int adj_idx = i + delta;
13405 struct bpf_insn insn;
13408 insn = insns[adj_idx];
13409 load_reg = insn_def_regno(&insn);
13410 if (!aux[adj_idx].zext_dst) {
13418 class = BPF_CLASS(code);
13419 if (load_reg == -1)
13422 /* NOTE: arg "reg" (the fourth one) is only used for
13423 * BPF_STX + SRC_OP, so it is safe to pass NULL
13426 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13427 if (class == BPF_LD &&
13428 BPF_MODE(code) == BPF_IMM)
13433 /* ctx load could be transformed into wider load. */
13434 if (class == BPF_LDX &&
13435 aux[adj_idx].ptr_type == PTR_TO_CTX)
13438 imm_rnd = get_random_u32();
13439 rnd_hi32_patch[0] = insn;
13440 rnd_hi32_patch[1].imm = imm_rnd;
13441 rnd_hi32_patch[3].dst_reg = load_reg;
13442 patch = rnd_hi32_patch;
13444 goto apply_patch_buffer;
13447 /* Add in an zero-extend instruction if a) the JIT has requested
13448 * it or b) it's a CMPXCHG.
13450 * The latter is because: BPF_CMPXCHG always loads a value into
13451 * R0, therefore always zero-extends. However some archs'
13452 * equivalent instruction only does this load when the
13453 * comparison is successful. This detail of CMPXCHG is
13454 * orthogonal to the general zero-extension behaviour of the
13455 * CPU, so it's treated independently of bpf_jit_needs_zext.
13457 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13460 /* Zero-extension is done by the caller. */
13461 if (bpf_pseudo_kfunc_call(&insn))
13464 if (WARN_ON(load_reg == -1)) {
13465 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13469 zext_patch[0] = insn;
13470 zext_patch[1].dst_reg = load_reg;
13471 zext_patch[1].src_reg = load_reg;
13472 patch = zext_patch;
13474 apply_patch_buffer:
13475 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13478 env->prog = new_prog;
13479 insns = new_prog->insnsi;
13480 aux = env->insn_aux_data;
13481 delta += patch_len - 1;
13487 /* convert load instructions that access fields of a context type into a
13488 * sequence of instructions that access fields of the underlying structure:
13489 * struct __sk_buff -> struct sk_buff
13490 * struct bpf_sock_ops -> struct sock
13492 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13494 const struct bpf_verifier_ops *ops = env->ops;
13495 int i, cnt, size, ctx_field_size, delta = 0;
13496 const int insn_cnt = env->prog->len;
13497 struct bpf_insn insn_buf[16], *insn;
13498 u32 target_size, size_default, off;
13499 struct bpf_prog *new_prog;
13500 enum bpf_access_type type;
13501 bool is_narrower_load;
13503 if (ops->gen_prologue || env->seen_direct_write) {
13504 if (!ops->gen_prologue) {
13505 verbose(env, "bpf verifier is misconfigured\n");
13508 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13510 if (cnt >= ARRAY_SIZE(insn_buf)) {
13511 verbose(env, "bpf verifier is misconfigured\n");
13514 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13518 env->prog = new_prog;
13523 if (bpf_prog_is_dev_bound(env->prog->aux))
13526 insn = env->prog->insnsi + delta;
13528 for (i = 0; i < insn_cnt; i++, insn++) {
13529 bpf_convert_ctx_access_t convert_ctx_access;
13532 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13533 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13534 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13535 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13538 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13539 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13540 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13541 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13542 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13543 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13544 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13545 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13547 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13552 if (type == BPF_WRITE &&
13553 env->insn_aux_data[i + delta].sanitize_stack_spill) {
13554 struct bpf_insn patch[] = {
13559 cnt = ARRAY_SIZE(patch);
13560 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13565 env->prog = new_prog;
13566 insn = new_prog->insnsi + i + delta;
13573 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13575 if (!ops->convert_ctx_access)
13577 convert_ctx_access = ops->convert_ctx_access;
13579 case PTR_TO_SOCKET:
13580 case PTR_TO_SOCK_COMMON:
13581 convert_ctx_access = bpf_sock_convert_ctx_access;
13583 case PTR_TO_TCP_SOCK:
13584 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13586 case PTR_TO_XDP_SOCK:
13587 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13589 case PTR_TO_BTF_ID:
13590 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13591 if (type == BPF_READ) {
13592 insn->code = BPF_LDX | BPF_PROBE_MEM |
13593 BPF_SIZE((insn)->code);
13594 env->prog->aux->num_exentries++;
13601 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13602 size = BPF_LDST_BYTES(insn);
13604 /* If the read access is a narrower load of the field,
13605 * convert to a 4/8-byte load, to minimum program type specific
13606 * convert_ctx_access changes. If conversion is successful,
13607 * we will apply proper mask to the result.
13609 is_narrower_load = size < ctx_field_size;
13610 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13612 if (is_narrower_load) {
13615 if (type == BPF_WRITE) {
13616 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13621 if (ctx_field_size == 4)
13623 else if (ctx_field_size == 8)
13624 size_code = BPF_DW;
13626 insn->off = off & ~(size_default - 1);
13627 insn->code = BPF_LDX | BPF_MEM | size_code;
13631 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13633 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13634 (ctx_field_size && !target_size)) {
13635 verbose(env, "bpf verifier is misconfigured\n");
13639 if (is_narrower_load && size < target_size) {
13640 u8 shift = bpf_ctx_narrow_access_offset(
13641 off, size, size_default) * 8;
13642 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13643 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13646 if (ctx_field_size <= 4) {
13648 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13651 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13652 (1 << size * 8) - 1);
13655 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13658 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13659 (1ULL << size * 8) - 1);
13663 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13669 /* keep walking new program and skip insns we just inserted */
13670 env->prog = new_prog;
13671 insn = new_prog->insnsi + i + delta;
13677 static int jit_subprogs(struct bpf_verifier_env *env)
13679 struct bpf_prog *prog = env->prog, **func, *tmp;
13680 int i, j, subprog_start, subprog_end = 0, len, subprog;
13681 struct bpf_map *map_ptr;
13682 struct bpf_insn *insn;
13683 void *old_bpf_func;
13684 int err, num_exentries;
13686 if (env->subprog_cnt <= 1)
13689 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13690 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13693 /* Upon error here we cannot fall back to interpreter but
13694 * need a hard reject of the program. Thus -EFAULT is
13695 * propagated in any case.
13697 subprog = find_subprog(env, i + insn->imm + 1);
13699 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13700 i + insn->imm + 1);
13703 /* temporarily remember subprog id inside insn instead of
13704 * aux_data, since next loop will split up all insns into funcs
13706 insn->off = subprog;
13707 /* remember original imm in case JIT fails and fallback
13708 * to interpreter will be needed
13710 env->insn_aux_data[i].call_imm = insn->imm;
13711 /* point imm to __bpf_call_base+1 from JITs point of view */
13713 if (bpf_pseudo_func(insn))
13714 /* jit (e.g. x86_64) may emit fewer instructions
13715 * if it learns a u32 imm is the same as a u64 imm.
13716 * Force a non zero here.
13721 err = bpf_prog_alloc_jited_linfo(prog);
13723 goto out_undo_insn;
13726 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13728 goto out_undo_insn;
13730 for (i = 0; i < env->subprog_cnt; i++) {
13731 subprog_start = subprog_end;
13732 subprog_end = env->subprog_info[i + 1].start;
13734 len = subprog_end - subprog_start;
13735 /* bpf_prog_run() doesn't call subprogs directly,
13736 * hence main prog stats include the runtime of subprogs.
13737 * subprogs don't have IDs and not reachable via prog_get_next_id
13738 * func[i]->stats will never be accessed and stays NULL
13740 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13743 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13744 len * sizeof(struct bpf_insn));
13745 func[i]->type = prog->type;
13746 func[i]->len = len;
13747 if (bpf_prog_calc_tag(func[i]))
13749 func[i]->is_func = 1;
13750 func[i]->aux->func_idx = i;
13751 /* Below members will be freed only at prog->aux */
13752 func[i]->aux->btf = prog->aux->btf;
13753 func[i]->aux->func_info = prog->aux->func_info;
13754 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13755 func[i]->aux->poke_tab = prog->aux->poke_tab;
13756 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13758 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13759 struct bpf_jit_poke_descriptor *poke;
13761 poke = &prog->aux->poke_tab[j];
13762 if (poke->insn_idx < subprog_end &&
13763 poke->insn_idx >= subprog_start)
13764 poke->aux = func[i]->aux;
13767 func[i]->aux->name[0] = 'F';
13768 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13769 func[i]->jit_requested = 1;
13770 func[i]->blinding_requested = prog->blinding_requested;
13771 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13772 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13773 func[i]->aux->linfo = prog->aux->linfo;
13774 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13775 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13776 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13778 insn = func[i]->insnsi;
13779 for (j = 0; j < func[i]->len; j++, insn++) {
13780 if (BPF_CLASS(insn->code) == BPF_LDX &&
13781 BPF_MODE(insn->code) == BPF_PROBE_MEM)
13784 func[i]->aux->num_exentries = num_exentries;
13785 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13786 func[i] = bpf_int_jit_compile(func[i]);
13787 if (!func[i]->jited) {
13794 /* at this point all bpf functions were successfully JITed
13795 * now populate all bpf_calls with correct addresses and
13796 * run last pass of JIT
13798 for (i = 0; i < env->subprog_cnt; i++) {
13799 insn = func[i]->insnsi;
13800 for (j = 0; j < func[i]->len; j++, insn++) {
13801 if (bpf_pseudo_func(insn)) {
13802 subprog = insn->off;
13803 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13804 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13807 if (!bpf_pseudo_call(insn))
13809 subprog = insn->off;
13810 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13813 /* we use the aux data to keep a list of the start addresses
13814 * of the JITed images for each function in the program
13816 * for some architectures, such as powerpc64, the imm field
13817 * might not be large enough to hold the offset of the start
13818 * address of the callee's JITed image from __bpf_call_base
13820 * in such cases, we can lookup the start address of a callee
13821 * by using its subprog id, available from the off field of
13822 * the call instruction, as an index for this list
13824 func[i]->aux->func = func;
13825 func[i]->aux->func_cnt = env->subprog_cnt;
13827 for (i = 0; i < env->subprog_cnt; i++) {
13828 old_bpf_func = func[i]->bpf_func;
13829 tmp = bpf_int_jit_compile(func[i]);
13830 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13831 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13838 /* finally lock prog and jit images for all functions and
13839 * populate kallsysm. Begin at the first subprogram, since
13840 * bpf_prog_load will add the kallsyms for the main program.
13842 for (i = 1; i < env->subprog_cnt; i++) {
13843 bpf_prog_lock_ro(func[i]);
13844 bpf_prog_kallsyms_add(func[i]);
13847 /* Last step: make now unused interpreter insns from main
13848 * prog consistent for later dump requests, so they can
13849 * later look the same as if they were interpreted only.
13851 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13852 if (bpf_pseudo_func(insn)) {
13853 insn[0].imm = env->insn_aux_data[i].call_imm;
13854 insn[1].imm = insn->off;
13858 if (!bpf_pseudo_call(insn))
13860 insn->off = env->insn_aux_data[i].call_imm;
13861 subprog = find_subprog(env, i + insn->off + 1);
13862 insn->imm = subprog;
13866 prog->bpf_func = func[0]->bpf_func;
13867 prog->jited_len = func[0]->jited_len;
13868 prog->aux->extable = func[0]->aux->extable;
13869 prog->aux->num_exentries = func[0]->aux->num_exentries;
13870 prog->aux->func = func;
13871 prog->aux->func_cnt = env->subprog_cnt;
13872 bpf_prog_jit_attempt_done(prog);
13875 /* We failed JIT'ing, so at this point we need to unregister poke
13876 * descriptors from subprogs, so that kernel is not attempting to
13877 * patch it anymore as we're freeing the subprog JIT memory.
13879 for (i = 0; i < prog->aux->size_poke_tab; i++) {
13880 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13881 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13883 /* At this point we're guaranteed that poke descriptors are not
13884 * live anymore. We can just unlink its descriptor table as it's
13885 * released with the main prog.
13887 for (i = 0; i < env->subprog_cnt; i++) {
13890 func[i]->aux->poke_tab = NULL;
13891 bpf_jit_free(func[i]);
13895 /* cleanup main prog to be interpreted */
13896 prog->jit_requested = 0;
13897 prog->blinding_requested = 0;
13898 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13899 if (!bpf_pseudo_call(insn))
13902 insn->imm = env->insn_aux_data[i].call_imm;
13904 bpf_prog_jit_attempt_done(prog);
13908 static int fixup_call_args(struct bpf_verifier_env *env)
13910 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13911 struct bpf_prog *prog = env->prog;
13912 struct bpf_insn *insn = prog->insnsi;
13913 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13918 if (env->prog->jit_requested &&
13919 !bpf_prog_is_dev_bound(env->prog->aux)) {
13920 err = jit_subprogs(env);
13923 if (err == -EFAULT)
13926 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13927 if (has_kfunc_call) {
13928 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13931 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13932 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13933 * have to be rejected, since interpreter doesn't support them yet.
13935 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13938 for (i = 0; i < prog->len; i++, insn++) {
13939 if (bpf_pseudo_func(insn)) {
13940 /* When JIT fails the progs with callback calls
13941 * have to be rejected, since interpreter doesn't support them yet.
13943 verbose(env, "callbacks are not allowed in non-JITed programs\n");
13947 if (!bpf_pseudo_call(insn))
13949 depth = get_callee_stack_depth(env, insn, i);
13952 bpf_patch_call_args(insn, depth);
13959 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13960 struct bpf_insn *insn)
13962 const struct bpf_kfunc_desc *desc;
13965 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13969 /* insn->imm has the btf func_id. Replace it with
13970 * an address (relative to __bpf_base_call).
13972 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13974 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13979 insn->imm = desc->imm;
13984 /* Do various post-verification rewrites in a single program pass.
13985 * These rewrites simplify JIT and interpreter implementations.
13987 static int do_misc_fixups(struct bpf_verifier_env *env)
13989 struct bpf_prog *prog = env->prog;
13990 enum bpf_attach_type eatype = prog->expected_attach_type;
13991 enum bpf_prog_type prog_type = resolve_prog_type(prog);
13992 struct bpf_insn *insn = prog->insnsi;
13993 const struct bpf_func_proto *fn;
13994 const int insn_cnt = prog->len;
13995 const struct bpf_map_ops *ops;
13996 struct bpf_insn_aux_data *aux;
13997 struct bpf_insn insn_buf[16];
13998 struct bpf_prog *new_prog;
13999 struct bpf_map *map_ptr;
14000 int i, ret, cnt, delta = 0;
14002 for (i = 0; i < insn_cnt; i++, insn++) {
14003 /* Make divide-by-zero exceptions impossible. */
14004 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
14005 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
14006 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
14007 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
14008 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
14009 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
14010 struct bpf_insn *patchlet;
14011 struct bpf_insn chk_and_div[] = {
14012 /* [R,W]x div 0 -> 0 */
14013 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14014 BPF_JNE | BPF_K, insn->src_reg,
14016 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
14017 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14020 struct bpf_insn chk_and_mod[] = {
14021 /* [R,W]x mod 0 -> [R,W]x */
14022 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14023 BPF_JEQ | BPF_K, insn->src_reg,
14024 0, 1 + (is64 ? 0 : 1), 0),
14026 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14027 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
14030 patchlet = isdiv ? chk_and_div : chk_and_mod;
14031 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
14032 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
14034 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
14039 env->prog = prog = new_prog;
14040 insn = new_prog->insnsi + i + delta;
14044 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
14045 if (BPF_CLASS(insn->code) == BPF_LD &&
14046 (BPF_MODE(insn->code) == BPF_ABS ||
14047 BPF_MODE(insn->code) == BPF_IND)) {
14048 cnt = env->ops->gen_ld_abs(insn, insn_buf);
14049 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14050 verbose(env, "bpf verifier is misconfigured\n");
14054 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14059 env->prog = prog = new_prog;
14060 insn = new_prog->insnsi + i + delta;
14064 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
14065 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
14066 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
14067 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
14068 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
14069 struct bpf_insn *patch = &insn_buf[0];
14070 bool issrc, isneg, isimm;
14073 aux = &env->insn_aux_data[i + delta];
14074 if (!aux->alu_state ||
14075 aux->alu_state == BPF_ALU_NON_POINTER)
14078 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14079 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14080 BPF_ALU_SANITIZE_SRC;
14081 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14083 off_reg = issrc ? insn->src_reg : insn->dst_reg;
14085 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14088 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14089 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14090 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14091 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14092 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14093 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14094 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14097 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14098 insn->src_reg = BPF_REG_AX;
14100 insn->code = insn->code == code_add ?
14101 code_sub : code_add;
14103 if (issrc && isneg && !isimm)
14104 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14105 cnt = patch - insn_buf;
14107 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14112 env->prog = prog = new_prog;
14113 insn = new_prog->insnsi + i + delta;
14117 if (insn->code != (BPF_JMP | BPF_CALL))
14119 if (insn->src_reg == BPF_PSEUDO_CALL)
14121 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14122 ret = fixup_kfunc_call(env, insn);
14128 if (insn->imm == BPF_FUNC_get_route_realm)
14129 prog->dst_needed = 1;
14130 if (insn->imm == BPF_FUNC_get_prandom_u32)
14131 bpf_user_rnd_init_once();
14132 if (insn->imm == BPF_FUNC_override_return)
14133 prog->kprobe_override = 1;
14134 if (insn->imm == BPF_FUNC_tail_call) {
14135 /* If we tail call into other programs, we
14136 * cannot make any assumptions since they can
14137 * be replaced dynamically during runtime in
14138 * the program array.
14140 prog->cb_access = 1;
14141 if (!allow_tail_call_in_subprogs(env))
14142 prog->aux->stack_depth = MAX_BPF_STACK;
14143 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14145 /* mark bpf_tail_call as different opcode to avoid
14146 * conditional branch in the interpreter for every normal
14147 * call and to prevent accidental JITing by JIT compiler
14148 * that doesn't support bpf_tail_call yet
14151 insn->code = BPF_JMP | BPF_TAIL_CALL;
14153 aux = &env->insn_aux_data[i + delta];
14154 if (env->bpf_capable && !prog->blinding_requested &&
14155 prog->jit_requested &&
14156 !bpf_map_key_poisoned(aux) &&
14157 !bpf_map_ptr_poisoned(aux) &&
14158 !bpf_map_ptr_unpriv(aux)) {
14159 struct bpf_jit_poke_descriptor desc = {
14160 .reason = BPF_POKE_REASON_TAIL_CALL,
14161 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14162 .tail_call.key = bpf_map_key_immediate(aux),
14163 .insn_idx = i + delta,
14166 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14168 verbose(env, "adding tail call poke descriptor failed\n");
14172 insn->imm = ret + 1;
14176 if (!bpf_map_ptr_unpriv(aux))
14179 /* instead of changing every JIT dealing with tail_call
14180 * emit two extra insns:
14181 * if (index >= max_entries) goto out;
14182 * index &= array->index_mask;
14183 * to avoid out-of-bounds cpu speculation
14185 if (bpf_map_ptr_poisoned(aux)) {
14186 verbose(env, "tail_call abusing map_ptr\n");
14190 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14191 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14192 map_ptr->max_entries, 2);
14193 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14194 container_of(map_ptr,
14197 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;
14209 if (insn->imm == BPF_FUNC_timer_set_callback) {
14210 /* The verifier will process callback_fn as many times as necessary
14211 * with different maps and the register states prepared by
14212 * set_timer_callback_state will be accurate.
14214 * The following use case is valid:
14215 * map1 is shared by prog1, prog2, prog3.
14216 * prog1 calls bpf_timer_init for some map1 elements
14217 * prog2 calls bpf_timer_set_callback for some map1 elements.
14218 * Those that were not bpf_timer_init-ed will return -EINVAL.
14219 * prog3 calls bpf_timer_start for some map1 elements.
14220 * Those that were not both bpf_timer_init-ed and
14221 * bpf_timer_set_callback-ed will return -EINVAL.
14223 struct bpf_insn ld_addrs[2] = {
14224 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14227 insn_buf[0] = ld_addrs[0];
14228 insn_buf[1] = ld_addrs[1];
14229 insn_buf[2] = *insn;
14232 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14237 env->prog = prog = new_prog;
14238 insn = new_prog->insnsi + i + delta;
14239 goto patch_call_imm;
14242 if (insn->imm == BPF_FUNC_task_storage_get ||
14243 insn->imm == BPF_FUNC_sk_storage_get ||
14244 insn->imm == BPF_FUNC_inode_storage_get) {
14245 if (env->prog->aux->sleepable)
14246 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14248 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14249 insn_buf[1] = *insn;
14252 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14257 env->prog = prog = new_prog;
14258 insn = new_prog->insnsi + i + delta;
14259 goto patch_call_imm;
14262 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14263 * and other inlining handlers are currently limited to 64 bit
14266 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14267 (insn->imm == BPF_FUNC_map_lookup_elem ||
14268 insn->imm == BPF_FUNC_map_update_elem ||
14269 insn->imm == BPF_FUNC_map_delete_elem ||
14270 insn->imm == BPF_FUNC_map_push_elem ||
14271 insn->imm == BPF_FUNC_map_pop_elem ||
14272 insn->imm == BPF_FUNC_map_peek_elem ||
14273 insn->imm == BPF_FUNC_redirect_map ||
14274 insn->imm == BPF_FUNC_for_each_map_elem ||
14275 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14276 aux = &env->insn_aux_data[i + delta];
14277 if (bpf_map_ptr_poisoned(aux))
14278 goto patch_call_imm;
14280 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14281 ops = map_ptr->ops;
14282 if (insn->imm == BPF_FUNC_map_lookup_elem &&
14283 ops->map_gen_lookup) {
14284 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14285 if (cnt == -EOPNOTSUPP)
14286 goto patch_map_ops_generic;
14287 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14288 verbose(env, "bpf verifier is misconfigured\n");
14292 new_prog = bpf_patch_insn_data(env, i + delta,
14298 env->prog = prog = new_prog;
14299 insn = new_prog->insnsi + i + delta;
14303 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14304 (void *(*)(struct bpf_map *map, void *key))NULL));
14305 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14306 (int (*)(struct bpf_map *map, void *key))NULL));
14307 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14308 (int (*)(struct bpf_map *map, void *key, void *value,
14310 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14311 (int (*)(struct bpf_map *map, void *value,
14313 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14314 (int (*)(struct bpf_map *map, void *value))NULL));
14315 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14316 (int (*)(struct bpf_map *map, void *value))NULL));
14317 BUILD_BUG_ON(!__same_type(ops->map_redirect,
14318 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14319 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14320 (int (*)(struct bpf_map *map,
14321 bpf_callback_t callback_fn,
14322 void *callback_ctx,
14324 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14325 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14327 patch_map_ops_generic:
14328 switch (insn->imm) {
14329 case BPF_FUNC_map_lookup_elem:
14330 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14332 case BPF_FUNC_map_update_elem:
14333 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14335 case BPF_FUNC_map_delete_elem:
14336 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14338 case BPF_FUNC_map_push_elem:
14339 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14341 case BPF_FUNC_map_pop_elem:
14342 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14344 case BPF_FUNC_map_peek_elem:
14345 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14347 case BPF_FUNC_redirect_map:
14348 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14350 case BPF_FUNC_for_each_map_elem:
14351 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14353 case BPF_FUNC_map_lookup_percpu_elem:
14354 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14358 goto patch_call_imm;
14361 /* Implement bpf_jiffies64 inline. */
14362 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14363 insn->imm == BPF_FUNC_jiffies64) {
14364 struct bpf_insn ld_jiffies_addr[2] = {
14365 BPF_LD_IMM64(BPF_REG_0,
14366 (unsigned long)&jiffies),
14369 insn_buf[0] = ld_jiffies_addr[0];
14370 insn_buf[1] = ld_jiffies_addr[1];
14371 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14375 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14381 env->prog = prog = new_prog;
14382 insn = new_prog->insnsi + i + delta;
14386 /* Implement bpf_get_func_arg inline. */
14387 if (prog_type == BPF_PROG_TYPE_TRACING &&
14388 insn->imm == BPF_FUNC_get_func_arg) {
14389 /* Load nr_args from ctx - 8 */
14390 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14391 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14392 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14393 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14394 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14395 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14396 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14397 insn_buf[7] = BPF_JMP_A(1);
14398 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14401 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14406 env->prog = prog = new_prog;
14407 insn = new_prog->insnsi + i + delta;
14411 /* Implement bpf_get_func_ret inline. */
14412 if (prog_type == BPF_PROG_TYPE_TRACING &&
14413 insn->imm == BPF_FUNC_get_func_ret) {
14414 if (eatype == BPF_TRACE_FEXIT ||
14415 eatype == BPF_MODIFY_RETURN) {
14416 /* Load nr_args from ctx - 8 */
14417 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14418 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14419 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14420 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14421 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14422 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14425 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14429 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14434 env->prog = prog = new_prog;
14435 insn = new_prog->insnsi + i + delta;
14439 /* Implement get_func_arg_cnt inline. */
14440 if (prog_type == BPF_PROG_TYPE_TRACING &&
14441 insn->imm == BPF_FUNC_get_func_arg_cnt) {
14442 /* Load nr_args from ctx - 8 */
14443 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14445 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14449 env->prog = prog = new_prog;
14450 insn = new_prog->insnsi + i + delta;
14454 /* Implement bpf_get_func_ip inline. */
14455 if (prog_type == BPF_PROG_TYPE_TRACING &&
14456 insn->imm == BPF_FUNC_get_func_ip) {
14457 /* Load IP address from ctx - 16 */
14458 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14460 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14464 env->prog = prog = new_prog;
14465 insn = new_prog->insnsi + i + delta;
14470 fn = env->ops->get_func_proto(insn->imm, env->prog);
14471 /* all functions that have prototype and verifier allowed
14472 * programs to call them, must be real in-kernel functions
14476 "kernel subsystem misconfigured func %s#%d\n",
14477 func_id_name(insn->imm), insn->imm);
14480 insn->imm = fn->func - __bpf_call_base;
14483 /* Since poke tab is now finalized, publish aux to tracker. */
14484 for (i = 0; i < prog->aux->size_poke_tab; i++) {
14485 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14486 if (!map_ptr->ops->map_poke_track ||
14487 !map_ptr->ops->map_poke_untrack ||
14488 !map_ptr->ops->map_poke_run) {
14489 verbose(env, "bpf verifier is misconfigured\n");
14493 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14495 verbose(env, "tracking tail call prog failed\n");
14500 sort_kfunc_descs_by_imm(env->prog);
14505 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14508 u32 callback_subprogno,
14511 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14512 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14513 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14514 int reg_loop_max = BPF_REG_6;
14515 int reg_loop_cnt = BPF_REG_7;
14516 int reg_loop_ctx = BPF_REG_8;
14518 struct bpf_prog *new_prog;
14519 u32 callback_start;
14520 u32 call_insn_offset;
14521 s32 callback_offset;
14523 /* This represents an inlined version of bpf_iter.c:bpf_loop,
14524 * be careful to modify this code in sync.
14526 struct bpf_insn insn_buf[] = {
14527 /* Return error and jump to the end of the patch if
14528 * expected number of iterations is too big.
14530 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14531 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14532 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14533 /* spill R6, R7, R8 to use these as loop vars */
14534 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14535 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14536 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14537 /* initialize loop vars */
14538 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14539 BPF_MOV32_IMM(reg_loop_cnt, 0),
14540 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14542 * if reg_loop_cnt >= reg_loop_max skip the loop body
14544 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14546 * correct callback offset would be set after patching
14548 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14549 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14551 /* increment loop counter */
14552 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14553 /* jump to loop header if callback returned 0 */
14554 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14555 /* return value of bpf_loop,
14556 * set R0 to the number of iterations
14558 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14559 /* restore original values of R6, R7, R8 */
14560 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14561 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14562 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14565 *cnt = ARRAY_SIZE(insn_buf);
14566 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14570 /* callback start is known only after patching */
14571 callback_start = env->subprog_info[callback_subprogno].start;
14572 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14573 call_insn_offset = position + 12;
14574 callback_offset = callback_start - call_insn_offset - 1;
14575 new_prog->insnsi[call_insn_offset].imm = callback_offset;
14580 static bool is_bpf_loop_call(struct bpf_insn *insn)
14582 return insn->code == (BPF_JMP | BPF_CALL) &&
14583 insn->src_reg == 0 &&
14584 insn->imm == BPF_FUNC_loop;
14587 /* For all sub-programs in the program (including main) check
14588 * insn_aux_data to see if there are bpf_loop calls that require
14589 * inlining. If such calls are found the calls are replaced with a
14590 * sequence of instructions produced by `inline_bpf_loop` function and
14591 * subprog stack_depth is increased by the size of 3 registers.
14592 * This stack space is used to spill values of the R6, R7, R8. These
14593 * registers are used to store the loop bound, counter and context
14596 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14598 struct bpf_subprog_info *subprogs = env->subprog_info;
14599 int i, cur_subprog = 0, cnt, delta = 0;
14600 struct bpf_insn *insn = env->prog->insnsi;
14601 int insn_cnt = env->prog->len;
14602 u16 stack_depth = subprogs[cur_subprog].stack_depth;
14603 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14604 u16 stack_depth_extra = 0;
14606 for (i = 0; i < insn_cnt; i++, insn++) {
14607 struct bpf_loop_inline_state *inline_state =
14608 &env->insn_aux_data[i + delta].loop_inline_state;
14610 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14611 struct bpf_prog *new_prog;
14613 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14614 new_prog = inline_bpf_loop(env,
14616 -(stack_depth + stack_depth_extra),
14617 inline_state->callback_subprogno,
14623 env->prog = new_prog;
14624 insn = new_prog->insnsi + i + delta;
14627 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14628 subprogs[cur_subprog].stack_depth += stack_depth_extra;
14630 stack_depth = subprogs[cur_subprog].stack_depth;
14631 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14632 stack_depth_extra = 0;
14636 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14641 static void free_states(struct bpf_verifier_env *env)
14643 struct bpf_verifier_state_list *sl, *sln;
14646 sl = env->free_list;
14649 free_verifier_state(&sl->state, false);
14653 env->free_list = NULL;
14655 if (!env->explored_states)
14658 for (i = 0; i < state_htab_size(env); i++) {
14659 sl = env->explored_states[i];
14663 free_verifier_state(&sl->state, false);
14667 env->explored_states[i] = NULL;
14671 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14673 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14674 struct bpf_verifier_state *state;
14675 struct bpf_reg_state *regs;
14678 env->prev_linfo = NULL;
14681 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14684 state->curframe = 0;
14685 state->speculative = false;
14686 state->branches = 1;
14687 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14688 if (!state->frame[0]) {
14692 env->cur_state = state;
14693 init_func_state(env, state->frame[0],
14694 BPF_MAIN_FUNC /* callsite */,
14698 regs = state->frame[state->curframe]->regs;
14699 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14700 ret = btf_prepare_func_args(env, subprog, regs);
14703 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14704 if (regs[i].type == PTR_TO_CTX)
14705 mark_reg_known_zero(env, regs, i);
14706 else if (regs[i].type == SCALAR_VALUE)
14707 mark_reg_unknown(env, regs, i);
14708 else if (base_type(regs[i].type) == PTR_TO_MEM) {
14709 const u32 mem_size = regs[i].mem_size;
14711 mark_reg_known_zero(env, regs, i);
14712 regs[i].mem_size = mem_size;
14713 regs[i].id = ++env->id_gen;
14717 /* 1st arg to a function */
14718 regs[BPF_REG_1].type = PTR_TO_CTX;
14719 mark_reg_known_zero(env, regs, BPF_REG_1);
14720 ret = btf_check_subprog_arg_match(env, subprog, regs);
14721 if (ret == -EFAULT)
14722 /* unlikely verifier bug. abort.
14723 * ret == 0 and ret < 0 are sadly acceptable for
14724 * main() function due to backward compatibility.
14725 * Like socket filter program may be written as:
14726 * int bpf_prog(struct pt_regs *ctx)
14727 * and never dereference that ctx in the program.
14728 * 'struct pt_regs' is a type mismatch for socket
14729 * filter that should be using 'struct __sk_buff'.
14734 ret = do_check(env);
14736 /* check for NULL is necessary, since cur_state can be freed inside
14737 * do_check() under memory pressure.
14739 if (env->cur_state) {
14740 free_verifier_state(env->cur_state, true);
14741 env->cur_state = NULL;
14743 while (!pop_stack(env, NULL, NULL, false));
14744 if (!ret && pop_log)
14745 bpf_vlog_reset(&env->log, 0);
14750 /* Verify all global functions in a BPF program one by one based on their BTF.
14751 * All global functions must pass verification. Otherwise the whole program is rejected.
14762 * foo() will be verified first for R1=any_scalar_value. During verification it
14763 * will be assumed that bar() already verified successfully and call to bar()
14764 * from foo() will be checked for type match only. Later bar() will be verified
14765 * independently to check that it's safe for R1=any_scalar_value.
14767 static int do_check_subprogs(struct bpf_verifier_env *env)
14769 struct bpf_prog_aux *aux = env->prog->aux;
14772 if (!aux->func_info)
14775 for (i = 1; i < env->subprog_cnt; i++) {
14776 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14778 env->insn_idx = env->subprog_info[i].start;
14779 WARN_ON_ONCE(env->insn_idx == 0);
14780 ret = do_check_common(env, i);
14783 } else if (env->log.level & BPF_LOG_LEVEL) {
14785 "Func#%d is safe for any args that match its prototype\n",
14792 static int do_check_main(struct bpf_verifier_env *env)
14797 ret = do_check_common(env, 0);
14799 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14804 static void print_verification_stats(struct bpf_verifier_env *env)
14808 if (env->log.level & BPF_LOG_STATS) {
14809 verbose(env, "verification time %lld usec\n",
14810 div_u64(env->verification_time, 1000));
14811 verbose(env, "stack depth ");
14812 for (i = 0; i < env->subprog_cnt; i++) {
14813 u32 depth = env->subprog_info[i].stack_depth;
14815 verbose(env, "%d", depth);
14816 if (i + 1 < env->subprog_cnt)
14819 verbose(env, "\n");
14821 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14822 "total_states %d peak_states %d mark_read %d\n",
14823 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14824 env->max_states_per_insn, env->total_states,
14825 env->peak_states, env->longest_mark_read_walk);
14828 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14830 const struct btf_type *t, *func_proto;
14831 const struct bpf_struct_ops *st_ops;
14832 const struct btf_member *member;
14833 struct bpf_prog *prog = env->prog;
14834 u32 btf_id, member_idx;
14837 if (!prog->gpl_compatible) {
14838 verbose(env, "struct ops programs must have a GPL compatible license\n");
14842 btf_id = prog->aux->attach_btf_id;
14843 st_ops = bpf_struct_ops_find(btf_id);
14845 verbose(env, "attach_btf_id %u is not a supported struct\n",
14851 member_idx = prog->expected_attach_type;
14852 if (member_idx >= btf_type_vlen(t)) {
14853 verbose(env, "attach to invalid member idx %u of struct %s\n",
14854 member_idx, st_ops->name);
14858 member = &btf_type_member(t)[member_idx];
14859 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14860 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14863 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14864 mname, member_idx, st_ops->name);
14868 if (st_ops->check_member) {
14869 int err = st_ops->check_member(t, member);
14872 verbose(env, "attach to unsupported member %s of struct %s\n",
14873 mname, st_ops->name);
14878 prog->aux->attach_func_proto = func_proto;
14879 prog->aux->attach_func_name = mname;
14880 env->ops = st_ops->verifier_ops;
14884 #define SECURITY_PREFIX "security_"
14886 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14888 if (within_error_injection_list(addr) ||
14889 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14895 /* list of non-sleepable functions that are otherwise on
14896 * ALLOW_ERROR_INJECTION list
14898 BTF_SET_START(btf_non_sleepable_error_inject)
14899 /* Three functions below can be called from sleepable and non-sleepable context.
14900 * Assume non-sleepable from bpf safety point of view.
14902 BTF_ID(func, __filemap_add_folio)
14903 BTF_ID(func, should_fail_alloc_page)
14904 BTF_ID(func, should_failslab)
14905 BTF_SET_END(btf_non_sleepable_error_inject)
14907 static int check_non_sleepable_error_inject(u32 btf_id)
14909 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14912 int bpf_check_attach_target(struct bpf_verifier_log *log,
14913 const struct bpf_prog *prog,
14914 const struct bpf_prog *tgt_prog,
14916 struct bpf_attach_target_info *tgt_info)
14918 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14919 const char prefix[] = "btf_trace_";
14920 int ret = 0, subprog = -1, i;
14921 const struct btf_type *t;
14922 bool conservative = true;
14928 bpf_log(log, "Tracing programs must provide btf_id\n");
14931 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14934 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14937 t = btf_type_by_id(btf, btf_id);
14939 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14942 tname = btf_name_by_offset(btf, t->name_off);
14944 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14948 struct bpf_prog_aux *aux = tgt_prog->aux;
14950 for (i = 0; i < aux->func_info_cnt; i++)
14951 if (aux->func_info[i].type_id == btf_id) {
14955 if (subprog == -1) {
14956 bpf_log(log, "Subprog %s doesn't exist\n", tname);
14959 conservative = aux->func_info_aux[subprog].unreliable;
14960 if (prog_extension) {
14961 if (conservative) {
14963 "Cannot replace static functions\n");
14966 if (!prog->jit_requested) {
14968 "Extension programs should be JITed\n");
14972 if (!tgt_prog->jited) {
14973 bpf_log(log, "Can attach to only JITed progs\n");
14976 if (tgt_prog->type == prog->type) {
14977 /* Cannot fentry/fexit another fentry/fexit program.
14978 * Cannot attach program extension to another extension.
14979 * It's ok to attach fentry/fexit to extension program.
14981 bpf_log(log, "Cannot recursively attach\n");
14984 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14986 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14987 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14988 /* Program extensions can extend all program types
14989 * except fentry/fexit. The reason is the following.
14990 * The fentry/fexit programs are used for performance
14991 * analysis, stats and can be attached to any program
14992 * type except themselves. When extension program is
14993 * replacing XDP function it is necessary to allow
14994 * performance analysis of all functions. Both original
14995 * XDP program and its program extension. Hence
14996 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14997 * allowed. If extending of fentry/fexit was allowed it
14998 * would be possible to create long call chain
14999 * fentry->extension->fentry->extension beyond
15000 * reasonable stack size. Hence extending fentry is not
15003 bpf_log(log, "Cannot extend fentry/fexit\n");
15007 if (prog_extension) {
15008 bpf_log(log, "Cannot replace kernel functions\n");
15013 switch (prog->expected_attach_type) {
15014 case BPF_TRACE_RAW_TP:
15017 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
15020 if (!btf_type_is_typedef(t)) {
15021 bpf_log(log, "attach_btf_id %u is not a typedef\n",
15025 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
15026 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
15030 tname += sizeof(prefix) - 1;
15031 t = btf_type_by_id(btf, t->type);
15032 if (!btf_type_is_ptr(t))
15033 /* should never happen in valid vmlinux build */
15035 t = btf_type_by_id(btf, t->type);
15036 if (!btf_type_is_func_proto(t))
15037 /* should never happen in valid vmlinux build */
15041 case BPF_TRACE_ITER:
15042 if (!btf_type_is_func(t)) {
15043 bpf_log(log, "attach_btf_id %u is not a function\n",
15047 t = btf_type_by_id(btf, t->type);
15048 if (!btf_type_is_func_proto(t))
15050 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15055 if (!prog_extension)
15058 case BPF_MODIFY_RETURN:
15060 case BPF_LSM_CGROUP:
15061 case BPF_TRACE_FENTRY:
15062 case BPF_TRACE_FEXIT:
15063 if (!btf_type_is_func(t)) {
15064 bpf_log(log, "attach_btf_id %u is not a function\n",
15068 if (prog_extension &&
15069 btf_check_type_match(log, prog, btf, t))
15071 t = btf_type_by_id(btf, t->type);
15072 if (!btf_type_is_func_proto(t))
15075 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15076 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15077 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15080 if (tgt_prog && conservative)
15083 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15089 addr = (long) tgt_prog->bpf_func;
15091 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15093 addr = kallsyms_lookup_name(tname);
15096 "The address of function %s cannot be found\n",
15102 if (prog->aux->sleepable) {
15104 switch (prog->type) {
15105 case BPF_PROG_TYPE_TRACING:
15106 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
15107 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15109 if (!check_non_sleepable_error_inject(btf_id) &&
15110 within_error_injection_list(addr))
15113 case BPF_PROG_TYPE_LSM:
15114 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
15115 * Only some of them are sleepable.
15117 if (bpf_lsm_is_sleepable_hook(btf_id))
15124 bpf_log(log, "%s is not sleepable\n", tname);
15127 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15129 bpf_log(log, "can't modify return codes of BPF programs\n");
15132 ret = check_attach_modify_return(addr, tname);
15134 bpf_log(log, "%s() is not modifiable\n", tname);
15141 tgt_info->tgt_addr = addr;
15142 tgt_info->tgt_name = tname;
15143 tgt_info->tgt_type = t;
15147 BTF_SET_START(btf_id_deny)
15150 BTF_ID(func, migrate_disable)
15151 BTF_ID(func, migrate_enable)
15153 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15154 BTF_ID(func, rcu_read_unlock_strict)
15156 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
15157 BTF_ID(func, preempt_count_add)
15158 BTF_ID(func, preempt_count_sub)
15160 BTF_SET_END(btf_id_deny)
15162 static int check_attach_btf_id(struct bpf_verifier_env *env)
15164 struct bpf_prog *prog = env->prog;
15165 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15166 struct bpf_attach_target_info tgt_info = {};
15167 u32 btf_id = prog->aux->attach_btf_id;
15168 struct bpf_trampoline *tr;
15172 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15173 if (prog->aux->sleepable)
15174 /* attach_btf_id checked to be zero already */
15176 verbose(env, "Syscall programs can only be sleepable\n");
15180 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15181 prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15182 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15186 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15187 return check_struct_ops_btf_id(env);
15189 if (prog->type != BPF_PROG_TYPE_TRACING &&
15190 prog->type != BPF_PROG_TYPE_LSM &&
15191 prog->type != BPF_PROG_TYPE_EXT)
15194 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15198 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15199 /* to make freplace equivalent to their targets, they need to
15200 * inherit env->ops and expected_attach_type for the rest of the
15203 env->ops = bpf_verifier_ops[tgt_prog->type];
15204 prog->expected_attach_type = tgt_prog->expected_attach_type;
15207 /* store info about the attachment target that will be used later */
15208 prog->aux->attach_func_proto = tgt_info.tgt_type;
15209 prog->aux->attach_func_name = tgt_info.tgt_name;
15212 prog->aux->saved_dst_prog_type = tgt_prog->type;
15213 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15216 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15217 prog->aux->attach_btf_trace = true;
15219 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15220 if (!bpf_iter_prog_supported(prog))
15225 if (prog->type == BPF_PROG_TYPE_LSM) {
15226 ret = bpf_lsm_verify_prog(&env->log, prog);
15229 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15230 btf_id_set_contains(&btf_id_deny, btf_id)) {
15234 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15235 tr = bpf_trampoline_get(key, &tgt_info);
15239 prog->aux->dst_trampoline = tr;
15243 struct btf *bpf_get_btf_vmlinux(void)
15245 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15246 mutex_lock(&bpf_verifier_lock);
15248 btf_vmlinux = btf_parse_vmlinux();
15249 mutex_unlock(&bpf_verifier_lock);
15251 return btf_vmlinux;
15254 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15256 u64 start_time = ktime_get_ns();
15257 struct bpf_verifier_env *env;
15258 struct bpf_verifier_log *log;
15259 int i, len, ret = -EINVAL;
15262 /* no program is valid */
15263 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15266 /* 'struct bpf_verifier_env' can be global, but since it's not small,
15267 * allocate/free it every time bpf_check() is called
15269 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15274 len = (*prog)->len;
15275 env->insn_aux_data =
15276 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15278 if (!env->insn_aux_data)
15280 for (i = 0; i < len; i++)
15281 env->insn_aux_data[i].orig_idx = i;
15283 env->ops = bpf_verifier_ops[env->prog->type];
15284 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15285 is_priv = bpf_capable();
15287 bpf_get_btf_vmlinux();
15289 /* grab the mutex to protect few globals used by verifier */
15291 mutex_lock(&bpf_verifier_lock);
15293 if (attr->log_level || attr->log_buf || attr->log_size) {
15294 /* user requested verbose verifier output
15295 * and supplied buffer to store the verification trace
15297 log->level = attr->log_level;
15298 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15299 log->len_total = attr->log_size;
15301 /* log attributes have to be sane */
15302 if (!bpf_verifier_log_attr_valid(log)) {
15308 mark_verifier_state_clean(env);
15310 if (IS_ERR(btf_vmlinux)) {
15311 /* Either gcc or pahole or kernel are broken. */
15312 verbose(env, "in-kernel BTF is malformed\n");
15313 ret = PTR_ERR(btf_vmlinux);
15314 goto skip_full_check;
15317 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15318 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15319 env->strict_alignment = true;
15320 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15321 env->strict_alignment = false;
15323 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15324 env->allow_uninit_stack = bpf_allow_uninit_stack();
15325 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15326 env->bypass_spec_v1 = bpf_bypass_spec_v1();
15327 env->bypass_spec_v4 = bpf_bypass_spec_v4();
15328 env->bpf_capable = bpf_capable();
15331 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15333 env->explored_states = kvcalloc(state_htab_size(env),
15334 sizeof(struct bpf_verifier_state_list *),
15337 if (!env->explored_states)
15338 goto skip_full_check;
15340 ret = add_subprog_and_kfunc(env);
15342 goto skip_full_check;
15344 ret = check_subprogs(env);
15346 goto skip_full_check;
15348 ret = check_btf_info(env, attr, uattr);
15350 goto skip_full_check;
15352 ret = check_attach_btf_id(env);
15354 goto skip_full_check;
15356 ret = resolve_pseudo_ldimm64(env);
15358 goto skip_full_check;
15360 if (bpf_prog_is_dev_bound(env->prog->aux)) {
15361 ret = bpf_prog_offload_verifier_prep(env->prog);
15363 goto skip_full_check;
15366 ret = check_cfg(env);
15368 goto skip_full_check;
15370 ret = do_check_subprogs(env);
15371 ret = ret ?: do_check_main(env);
15373 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15374 ret = bpf_prog_offload_finalize(env);
15377 kvfree(env->explored_states);
15380 ret = check_max_stack_depth(env);
15382 /* instruction rewrites happen after this point */
15384 ret = optimize_bpf_loop(env);
15388 opt_hard_wire_dead_code_branches(env);
15390 ret = opt_remove_dead_code(env);
15392 ret = opt_remove_nops(env);
15395 sanitize_dead_code(env);
15399 /* program is valid, convert *(u32*)(ctx + off) accesses */
15400 ret = convert_ctx_accesses(env);
15403 ret = do_misc_fixups(env);
15405 /* do 32-bit optimization after insn patching has done so those patched
15406 * insns could be handled correctly.
15408 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15409 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15410 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15415 ret = fixup_call_args(env);
15417 env->verification_time = ktime_get_ns() - start_time;
15418 print_verification_stats(env);
15419 env->prog->aux->verified_insns = env->insn_processed;
15421 if (log->level && bpf_verifier_log_full(log))
15423 if (log->level && !log->ubuf) {
15425 goto err_release_maps;
15429 goto err_release_maps;
15431 if (env->used_map_cnt) {
15432 /* if program passed verifier, update used_maps in bpf_prog_info */
15433 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15434 sizeof(env->used_maps[0]),
15437 if (!env->prog->aux->used_maps) {
15439 goto err_release_maps;
15442 memcpy(env->prog->aux->used_maps, env->used_maps,
15443 sizeof(env->used_maps[0]) * env->used_map_cnt);
15444 env->prog->aux->used_map_cnt = env->used_map_cnt;
15446 if (env->used_btf_cnt) {
15447 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15448 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15449 sizeof(env->used_btfs[0]),
15451 if (!env->prog->aux->used_btfs) {
15453 goto err_release_maps;
15456 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15457 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15458 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15460 if (env->used_map_cnt || env->used_btf_cnt) {
15461 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15462 * bpf_ld_imm64 instructions
15464 convert_pseudo_ld_imm64(env);
15467 adjust_btf_func(env);
15470 if (!env->prog->aux->used_maps)
15471 /* if we didn't copy map pointers into bpf_prog_info, release
15472 * them now. Otherwise free_used_maps() will release them.
15475 if (!env->prog->aux->used_btfs)
15478 /* extension progs temporarily inherit the attach_type of their targets
15479 for verification purposes, so set it back to zero before returning
15481 if (env->prog->type == BPF_PROG_TYPE_EXT)
15482 env->prog->expected_attach_type = 0;
15487 mutex_unlock(&bpf_verifier_lock);
15488 vfree(env->insn_aux_data);