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)
1005 if (ZERO_OR_NULL_PTR(src))
1008 if (unlikely(check_mul_overflow(n, size, &bytes)))
1011 if (ksize(dst) < bytes) {
1013 dst = kmalloc_track_caller(bytes, flags);
1018 memcpy(dst, src, bytes);
1020 return dst ? dst : ZERO_SIZE_PTR;
1023 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1024 * small to hold new_n items. new items are zeroed out if the array grows.
1026 * Contrary to krealloc_array, does not free arr if new_n is zero.
1028 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1030 if (!new_n || old_n == new_n)
1033 arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
1038 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1041 return arr ? arr : ZERO_SIZE_PTR;
1044 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1046 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1047 sizeof(struct bpf_reference_state), GFP_KERNEL);
1051 dst->acquired_refs = src->acquired_refs;
1055 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1057 size_t n = src->allocated_stack / BPF_REG_SIZE;
1059 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1064 dst->allocated_stack = src->allocated_stack;
1068 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1070 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1071 sizeof(struct bpf_reference_state));
1075 state->acquired_refs = n;
1079 static int grow_stack_state(struct bpf_func_state *state, int size)
1081 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1086 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1090 state->allocated_stack = size;
1094 /* Acquire a pointer id from the env and update the state->refs to include
1095 * this new pointer reference.
1096 * On success, returns a valid pointer id to associate with the register
1097 * On failure, returns a negative errno.
1099 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1101 struct bpf_func_state *state = cur_func(env);
1102 int new_ofs = state->acquired_refs;
1105 err = resize_reference_state(state, state->acquired_refs + 1);
1109 state->refs[new_ofs].id = id;
1110 state->refs[new_ofs].insn_idx = insn_idx;
1111 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1116 /* release function corresponding to acquire_reference_state(). Idempotent. */
1117 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1121 last_idx = state->acquired_refs - 1;
1122 for (i = 0; i < state->acquired_refs; i++) {
1123 if (state->refs[i].id == ptr_id) {
1124 /* Cannot release caller references in callbacks */
1125 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1127 if (last_idx && i != last_idx)
1128 memcpy(&state->refs[i], &state->refs[last_idx],
1129 sizeof(*state->refs));
1130 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1131 state->acquired_refs--;
1138 static void free_func_state(struct bpf_func_state *state)
1143 kfree(state->stack);
1147 static void clear_jmp_history(struct bpf_verifier_state *state)
1149 kfree(state->jmp_history);
1150 state->jmp_history = NULL;
1151 state->jmp_history_cnt = 0;
1154 static void free_verifier_state(struct bpf_verifier_state *state,
1159 for (i = 0; i <= state->curframe; i++) {
1160 free_func_state(state->frame[i]);
1161 state->frame[i] = NULL;
1163 clear_jmp_history(state);
1168 /* copy verifier state from src to dst growing dst stack space
1169 * when necessary to accommodate larger src stack
1171 static int copy_func_state(struct bpf_func_state *dst,
1172 const struct bpf_func_state *src)
1176 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1177 err = copy_reference_state(dst, src);
1180 return copy_stack_state(dst, src);
1183 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1184 const struct bpf_verifier_state *src)
1186 struct bpf_func_state *dst;
1189 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1190 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1192 if (!dst_state->jmp_history)
1194 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1196 /* if dst has more stack frames then src frame, free them */
1197 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1198 free_func_state(dst_state->frame[i]);
1199 dst_state->frame[i] = NULL;
1201 dst_state->speculative = src->speculative;
1202 dst_state->curframe = src->curframe;
1203 dst_state->active_spin_lock = src->active_spin_lock;
1204 dst_state->branches = src->branches;
1205 dst_state->parent = src->parent;
1206 dst_state->first_insn_idx = src->first_insn_idx;
1207 dst_state->last_insn_idx = src->last_insn_idx;
1208 for (i = 0; i <= src->curframe; i++) {
1209 dst = dst_state->frame[i];
1211 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1214 dst_state->frame[i] = dst;
1216 err = copy_func_state(dst, src->frame[i]);
1223 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1226 u32 br = --st->branches;
1228 /* WARN_ON(br > 1) technically makes sense here,
1229 * but see comment in push_stack(), hence:
1231 WARN_ONCE((int)br < 0,
1232 "BUG update_branch_counts:branches_to_explore=%d\n",
1240 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1241 int *insn_idx, bool pop_log)
1243 struct bpf_verifier_state *cur = env->cur_state;
1244 struct bpf_verifier_stack_elem *elem, *head = env->head;
1247 if (env->head == NULL)
1251 err = copy_verifier_state(cur, &head->st);
1256 bpf_vlog_reset(&env->log, head->log_pos);
1258 *insn_idx = head->insn_idx;
1260 *prev_insn_idx = head->prev_insn_idx;
1262 free_verifier_state(&head->st, false);
1269 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1270 int insn_idx, int prev_insn_idx,
1273 struct bpf_verifier_state *cur = env->cur_state;
1274 struct bpf_verifier_stack_elem *elem;
1277 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1281 elem->insn_idx = insn_idx;
1282 elem->prev_insn_idx = prev_insn_idx;
1283 elem->next = env->head;
1284 elem->log_pos = env->log.len_used;
1287 err = copy_verifier_state(&elem->st, cur);
1290 elem->st.speculative |= speculative;
1291 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1292 verbose(env, "The sequence of %d jumps is too complex.\n",
1296 if (elem->st.parent) {
1297 ++elem->st.parent->branches;
1298 /* WARN_ON(branches > 2) technically makes sense here,
1300 * 1. speculative states will bump 'branches' for non-branch
1302 * 2. is_state_visited() heuristics may decide not to create
1303 * a new state for a sequence of branches and all such current
1304 * and cloned states will be pointing to a single parent state
1305 * which might have large 'branches' count.
1310 free_verifier_state(env->cur_state, true);
1311 env->cur_state = NULL;
1312 /* pop all elements and return */
1313 while (!pop_stack(env, NULL, NULL, false));
1317 #define CALLER_SAVED_REGS 6
1318 static const int caller_saved[CALLER_SAVED_REGS] = {
1319 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1322 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1323 struct bpf_reg_state *reg);
1325 /* This helper doesn't clear reg->id */
1326 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1328 reg->var_off = tnum_const(imm);
1329 reg->smin_value = (s64)imm;
1330 reg->smax_value = (s64)imm;
1331 reg->umin_value = imm;
1332 reg->umax_value = imm;
1334 reg->s32_min_value = (s32)imm;
1335 reg->s32_max_value = (s32)imm;
1336 reg->u32_min_value = (u32)imm;
1337 reg->u32_max_value = (u32)imm;
1340 /* Mark the unknown part of a register (variable offset or scalar value) as
1341 * known to have the value @imm.
1343 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1345 /* Clear id, off, and union(map_ptr, range) */
1346 memset(((u8 *)reg) + sizeof(reg->type), 0,
1347 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1348 ___mark_reg_known(reg, imm);
1351 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1353 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1354 reg->s32_min_value = (s32)imm;
1355 reg->s32_max_value = (s32)imm;
1356 reg->u32_min_value = (u32)imm;
1357 reg->u32_max_value = (u32)imm;
1360 /* Mark the 'variable offset' part of a register as zero. This should be
1361 * used only on registers holding a pointer type.
1363 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1365 __mark_reg_known(reg, 0);
1368 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1370 __mark_reg_known(reg, 0);
1371 reg->type = SCALAR_VALUE;
1374 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1375 struct bpf_reg_state *regs, u32 regno)
1377 if (WARN_ON(regno >= MAX_BPF_REG)) {
1378 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1379 /* Something bad happened, let's kill all regs */
1380 for (regno = 0; regno < MAX_BPF_REG; regno++)
1381 __mark_reg_not_init(env, regs + regno);
1384 __mark_reg_known_zero(regs + regno);
1387 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1389 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1390 const struct bpf_map *map = reg->map_ptr;
1392 if (map->inner_map_meta) {
1393 reg->type = CONST_PTR_TO_MAP;
1394 reg->map_ptr = map->inner_map_meta;
1395 /* transfer reg's id which is unique for every map_lookup_elem
1396 * as UID of the inner map.
1398 if (map_value_has_timer(map->inner_map_meta))
1399 reg->map_uid = reg->id;
1400 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1401 reg->type = PTR_TO_XDP_SOCK;
1402 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1403 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1404 reg->type = PTR_TO_SOCKET;
1406 reg->type = PTR_TO_MAP_VALUE;
1411 reg->type &= ~PTR_MAYBE_NULL;
1414 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1416 return type_is_pkt_pointer(reg->type);
1419 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1421 return reg_is_pkt_pointer(reg) ||
1422 reg->type == PTR_TO_PACKET_END;
1425 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1426 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1427 enum bpf_reg_type which)
1429 /* The register can already have a range from prior markings.
1430 * This is fine as long as it hasn't been advanced from its
1433 return reg->type == which &&
1436 tnum_equals_const(reg->var_off, 0);
1439 /* Reset the min/max bounds of a register */
1440 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1442 reg->smin_value = S64_MIN;
1443 reg->smax_value = S64_MAX;
1444 reg->umin_value = 0;
1445 reg->umax_value = U64_MAX;
1447 reg->s32_min_value = S32_MIN;
1448 reg->s32_max_value = S32_MAX;
1449 reg->u32_min_value = 0;
1450 reg->u32_max_value = U32_MAX;
1453 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1455 reg->smin_value = S64_MIN;
1456 reg->smax_value = S64_MAX;
1457 reg->umin_value = 0;
1458 reg->umax_value = U64_MAX;
1461 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1463 reg->s32_min_value = S32_MIN;
1464 reg->s32_max_value = S32_MAX;
1465 reg->u32_min_value = 0;
1466 reg->u32_max_value = U32_MAX;
1469 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1471 struct tnum var32_off = tnum_subreg(reg->var_off);
1473 /* min signed is max(sign bit) | min(other bits) */
1474 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1475 var32_off.value | (var32_off.mask & S32_MIN));
1476 /* max signed is min(sign bit) | max(other bits) */
1477 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1478 var32_off.value | (var32_off.mask & S32_MAX));
1479 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1480 reg->u32_max_value = min(reg->u32_max_value,
1481 (u32)(var32_off.value | var32_off.mask));
1484 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1486 /* min signed is max(sign bit) | min(other bits) */
1487 reg->smin_value = max_t(s64, reg->smin_value,
1488 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1489 /* max signed is min(sign bit) | max(other bits) */
1490 reg->smax_value = min_t(s64, reg->smax_value,
1491 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1492 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1493 reg->umax_value = min(reg->umax_value,
1494 reg->var_off.value | reg->var_off.mask);
1497 static void __update_reg_bounds(struct bpf_reg_state *reg)
1499 __update_reg32_bounds(reg);
1500 __update_reg64_bounds(reg);
1503 /* Uses signed min/max values to inform unsigned, and vice-versa */
1504 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1506 /* Learn sign from signed bounds.
1507 * If we cannot cross the sign boundary, then signed and unsigned bounds
1508 * are the same, so combine. This works even in the negative case, e.g.
1509 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1511 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1512 reg->s32_min_value = reg->u32_min_value =
1513 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1514 reg->s32_max_value = reg->u32_max_value =
1515 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1518 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1519 * boundary, so we must be careful.
1521 if ((s32)reg->u32_max_value >= 0) {
1522 /* Positive. We can't learn anything from the smin, but smax
1523 * is positive, hence safe.
1525 reg->s32_min_value = reg->u32_min_value;
1526 reg->s32_max_value = reg->u32_max_value =
1527 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1528 } else if ((s32)reg->u32_min_value < 0) {
1529 /* Negative. We can't learn anything from the smax, but smin
1530 * is negative, hence safe.
1532 reg->s32_min_value = reg->u32_min_value =
1533 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1534 reg->s32_max_value = reg->u32_max_value;
1538 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1540 /* Learn sign from signed bounds.
1541 * If we cannot cross the sign boundary, then signed and unsigned bounds
1542 * are the same, so combine. This works even in the negative case, e.g.
1543 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1545 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1546 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1548 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1552 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1553 * boundary, so we must be careful.
1555 if ((s64)reg->umax_value >= 0) {
1556 /* Positive. We can't learn anything from the smin, but smax
1557 * is positive, hence safe.
1559 reg->smin_value = reg->umin_value;
1560 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1562 } else if ((s64)reg->umin_value < 0) {
1563 /* Negative. We can't learn anything from the smax, but smin
1564 * is negative, hence safe.
1566 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1568 reg->smax_value = reg->umax_value;
1572 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1574 __reg32_deduce_bounds(reg);
1575 __reg64_deduce_bounds(reg);
1578 /* Attempts to improve var_off based on unsigned min/max information */
1579 static void __reg_bound_offset(struct bpf_reg_state *reg)
1581 struct tnum var64_off = tnum_intersect(reg->var_off,
1582 tnum_range(reg->umin_value,
1584 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1585 tnum_range(reg->u32_min_value,
1586 reg->u32_max_value));
1588 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1591 static void reg_bounds_sync(struct bpf_reg_state *reg)
1593 /* We might have learned new bounds from the var_off. */
1594 __update_reg_bounds(reg);
1595 /* We might have learned something about the sign bit. */
1596 __reg_deduce_bounds(reg);
1597 /* We might have learned some bits from the bounds. */
1598 __reg_bound_offset(reg);
1599 /* Intersecting with the old var_off might have improved our bounds
1600 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1601 * then new var_off is (0; 0x7f...fc) which improves our umax.
1603 __update_reg_bounds(reg);
1606 static bool __reg32_bound_s64(s32 a)
1608 return a >= 0 && a <= S32_MAX;
1611 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1613 reg->umin_value = reg->u32_min_value;
1614 reg->umax_value = reg->u32_max_value;
1616 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1617 * be positive otherwise set to worse case bounds and refine later
1620 if (__reg32_bound_s64(reg->s32_min_value) &&
1621 __reg32_bound_s64(reg->s32_max_value)) {
1622 reg->smin_value = reg->s32_min_value;
1623 reg->smax_value = reg->s32_max_value;
1625 reg->smin_value = 0;
1626 reg->smax_value = U32_MAX;
1630 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1632 /* special case when 64-bit register has upper 32-bit register
1633 * zeroed. Typically happens after zext or <<32, >>32 sequence
1634 * allowing us to use 32-bit bounds directly,
1636 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1637 __reg_assign_32_into_64(reg);
1639 /* Otherwise the best we can do is push lower 32bit known and
1640 * unknown bits into register (var_off set from jmp logic)
1641 * then learn as much as possible from the 64-bit tnum
1642 * known and unknown bits. The previous smin/smax bounds are
1643 * invalid here because of jmp32 compare so mark them unknown
1644 * so they do not impact tnum bounds calculation.
1646 __mark_reg64_unbounded(reg);
1648 reg_bounds_sync(reg);
1651 static bool __reg64_bound_s32(s64 a)
1653 return a >= S32_MIN && a <= S32_MAX;
1656 static bool __reg64_bound_u32(u64 a)
1658 return a >= U32_MIN && a <= U32_MAX;
1661 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1663 __mark_reg32_unbounded(reg);
1664 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1665 reg->s32_min_value = (s32)reg->smin_value;
1666 reg->s32_max_value = (s32)reg->smax_value;
1668 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1669 reg->u32_min_value = (u32)reg->umin_value;
1670 reg->u32_max_value = (u32)reg->umax_value;
1672 reg_bounds_sync(reg);
1675 /* Mark a register as having a completely unknown (scalar) value. */
1676 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1677 struct bpf_reg_state *reg)
1680 * Clear type, id, off, and union(map_ptr, range) and
1681 * padding between 'type' and union
1683 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1684 reg->type = SCALAR_VALUE;
1685 reg->var_off = tnum_unknown;
1687 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1688 __mark_reg_unbounded(reg);
1691 static void mark_reg_unknown(struct bpf_verifier_env *env,
1692 struct bpf_reg_state *regs, u32 regno)
1694 if (WARN_ON(regno >= MAX_BPF_REG)) {
1695 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1696 /* Something bad happened, let's kill all regs except FP */
1697 for (regno = 0; regno < BPF_REG_FP; regno++)
1698 __mark_reg_not_init(env, regs + regno);
1701 __mark_reg_unknown(env, regs + regno);
1704 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1705 struct bpf_reg_state *reg)
1707 __mark_reg_unknown(env, reg);
1708 reg->type = NOT_INIT;
1711 static void mark_reg_not_init(struct bpf_verifier_env *env,
1712 struct bpf_reg_state *regs, u32 regno)
1714 if (WARN_ON(regno >= MAX_BPF_REG)) {
1715 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1716 /* Something bad happened, let's kill all regs except FP */
1717 for (regno = 0; regno < BPF_REG_FP; regno++)
1718 __mark_reg_not_init(env, regs + regno);
1721 __mark_reg_not_init(env, regs + regno);
1724 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1725 struct bpf_reg_state *regs, u32 regno,
1726 enum bpf_reg_type reg_type,
1727 struct btf *btf, u32 btf_id,
1728 enum bpf_type_flag flag)
1730 if (reg_type == SCALAR_VALUE) {
1731 mark_reg_unknown(env, regs, regno);
1734 mark_reg_known_zero(env, regs, regno);
1735 regs[regno].type = PTR_TO_BTF_ID | flag;
1736 regs[regno].btf = btf;
1737 regs[regno].btf_id = btf_id;
1740 #define DEF_NOT_SUBREG (0)
1741 static void init_reg_state(struct bpf_verifier_env *env,
1742 struct bpf_func_state *state)
1744 struct bpf_reg_state *regs = state->regs;
1747 for (i = 0; i < MAX_BPF_REG; i++) {
1748 mark_reg_not_init(env, regs, i);
1749 regs[i].live = REG_LIVE_NONE;
1750 regs[i].parent = NULL;
1751 regs[i].subreg_def = DEF_NOT_SUBREG;
1755 regs[BPF_REG_FP].type = PTR_TO_STACK;
1756 mark_reg_known_zero(env, regs, BPF_REG_FP);
1757 regs[BPF_REG_FP].frameno = state->frameno;
1760 #define BPF_MAIN_FUNC (-1)
1761 static void init_func_state(struct bpf_verifier_env *env,
1762 struct bpf_func_state *state,
1763 int callsite, int frameno, int subprogno)
1765 state->callsite = callsite;
1766 state->frameno = frameno;
1767 state->subprogno = subprogno;
1768 state->callback_ret_range = tnum_range(0, 0);
1769 init_reg_state(env, state);
1770 mark_verifier_state_scratched(env);
1773 /* Similar to push_stack(), but for async callbacks */
1774 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1775 int insn_idx, int prev_insn_idx,
1778 struct bpf_verifier_stack_elem *elem;
1779 struct bpf_func_state *frame;
1781 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1785 elem->insn_idx = insn_idx;
1786 elem->prev_insn_idx = prev_insn_idx;
1787 elem->next = env->head;
1788 elem->log_pos = env->log.len_used;
1791 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1793 "The sequence of %d jumps is too complex for async cb.\n",
1797 /* Unlike push_stack() do not copy_verifier_state().
1798 * The caller state doesn't matter.
1799 * This is async callback. It starts in a fresh stack.
1800 * Initialize it similar to do_check_common().
1802 elem->st.branches = 1;
1803 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1806 init_func_state(env, frame,
1807 BPF_MAIN_FUNC /* callsite */,
1808 0 /* frameno within this callchain */,
1809 subprog /* subprog number within this prog */);
1810 elem->st.frame[0] = frame;
1813 free_verifier_state(env->cur_state, true);
1814 env->cur_state = NULL;
1815 /* pop all elements and return */
1816 while (!pop_stack(env, NULL, NULL, false));
1822 SRC_OP, /* register is used as source operand */
1823 DST_OP, /* register is used as destination operand */
1824 DST_OP_NO_MARK /* same as above, check only, don't mark */
1827 static int cmp_subprogs(const void *a, const void *b)
1829 return ((struct bpf_subprog_info *)a)->start -
1830 ((struct bpf_subprog_info *)b)->start;
1833 static int find_subprog(struct bpf_verifier_env *env, int off)
1835 struct bpf_subprog_info *p;
1837 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1838 sizeof(env->subprog_info[0]), cmp_subprogs);
1841 return p - env->subprog_info;
1845 static int add_subprog(struct bpf_verifier_env *env, int off)
1847 int insn_cnt = env->prog->len;
1850 if (off >= insn_cnt || off < 0) {
1851 verbose(env, "call to invalid destination\n");
1854 ret = find_subprog(env, off);
1857 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1858 verbose(env, "too many subprograms\n");
1861 /* determine subprog starts. The end is one before the next starts */
1862 env->subprog_info[env->subprog_cnt++].start = off;
1863 sort(env->subprog_info, env->subprog_cnt,
1864 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1865 return env->subprog_cnt - 1;
1868 #define MAX_KFUNC_DESCS 256
1869 #define MAX_KFUNC_BTFS 256
1871 struct bpf_kfunc_desc {
1872 struct btf_func_model func_model;
1878 struct bpf_kfunc_btf {
1880 struct module *module;
1884 struct bpf_kfunc_desc_tab {
1885 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1889 struct bpf_kfunc_btf_tab {
1890 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1894 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1896 const struct bpf_kfunc_desc *d0 = a;
1897 const struct bpf_kfunc_desc *d1 = b;
1899 /* func_id is not greater than BTF_MAX_TYPE */
1900 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1903 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1905 const struct bpf_kfunc_btf *d0 = a;
1906 const struct bpf_kfunc_btf *d1 = b;
1908 return d0->offset - d1->offset;
1911 static const struct bpf_kfunc_desc *
1912 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1914 struct bpf_kfunc_desc desc = {
1918 struct bpf_kfunc_desc_tab *tab;
1920 tab = prog->aux->kfunc_tab;
1921 return bsearch(&desc, tab->descs, tab->nr_descs,
1922 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1925 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1928 struct bpf_kfunc_btf kf_btf = { .offset = offset };
1929 struct bpf_kfunc_btf_tab *tab;
1930 struct bpf_kfunc_btf *b;
1935 tab = env->prog->aux->kfunc_btf_tab;
1936 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1937 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1939 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1940 verbose(env, "too many different module BTFs\n");
1941 return ERR_PTR(-E2BIG);
1944 if (bpfptr_is_null(env->fd_array)) {
1945 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1946 return ERR_PTR(-EPROTO);
1949 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1950 offset * sizeof(btf_fd),
1952 return ERR_PTR(-EFAULT);
1954 btf = btf_get_by_fd(btf_fd);
1956 verbose(env, "invalid module BTF fd specified\n");
1960 if (!btf_is_module(btf)) {
1961 verbose(env, "BTF fd for kfunc is not a module BTF\n");
1963 return ERR_PTR(-EINVAL);
1966 mod = btf_try_get_module(btf);
1969 return ERR_PTR(-ENXIO);
1972 b = &tab->descs[tab->nr_descs++];
1977 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1978 kfunc_btf_cmp_by_off, NULL);
1983 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1988 while (tab->nr_descs--) {
1989 module_put(tab->descs[tab->nr_descs].module);
1990 btf_put(tab->descs[tab->nr_descs].btf);
1995 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
1999 /* In the future, this can be allowed to increase limit
2000 * of fd index into fd_array, interpreted as u16.
2002 verbose(env, "negative offset disallowed for kernel module function call\n");
2003 return ERR_PTR(-EINVAL);
2006 return __find_kfunc_desc_btf(env, offset);
2008 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2011 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2013 const struct btf_type *func, *func_proto;
2014 struct bpf_kfunc_btf_tab *btf_tab;
2015 struct bpf_kfunc_desc_tab *tab;
2016 struct bpf_prog_aux *prog_aux;
2017 struct bpf_kfunc_desc *desc;
2018 const char *func_name;
2019 struct btf *desc_btf;
2020 unsigned long call_imm;
2024 prog_aux = env->prog->aux;
2025 tab = prog_aux->kfunc_tab;
2026 btf_tab = prog_aux->kfunc_btf_tab;
2029 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2033 if (!env->prog->jit_requested) {
2034 verbose(env, "JIT is required for calling kernel function\n");
2038 if (!bpf_jit_supports_kfunc_call()) {
2039 verbose(env, "JIT does not support calling kernel function\n");
2043 if (!env->prog->gpl_compatible) {
2044 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2048 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2051 prog_aux->kfunc_tab = tab;
2054 /* func_id == 0 is always invalid, but instead of returning an error, be
2055 * conservative and wait until the code elimination pass before returning
2056 * error, so that invalid calls that get pruned out can be in BPF programs
2057 * loaded from userspace. It is also required that offset be untouched
2060 if (!func_id && !offset)
2063 if (!btf_tab && offset) {
2064 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2067 prog_aux->kfunc_btf_tab = btf_tab;
2070 desc_btf = find_kfunc_desc_btf(env, offset);
2071 if (IS_ERR(desc_btf)) {
2072 verbose(env, "failed to find BTF for kernel function\n");
2073 return PTR_ERR(desc_btf);
2076 if (find_kfunc_desc(env->prog, func_id, offset))
2079 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2080 verbose(env, "too many different kernel function calls\n");
2084 func = btf_type_by_id(desc_btf, func_id);
2085 if (!func || !btf_type_is_func(func)) {
2086 verbose(env, "kernel btf_id %u is not a function\n",
2090 func_proto = btf_type_by_id(desc_btf, func->type);
2091 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2092 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2097 func_name = btf_name_by_offset(desc_btf, func->name_off);
2098 addr = kallsyms_lookup_name(func_name);
2100 verbose(env, "cannot find address for kernel function %s\n",
2105 call_imm = BPF_CALL_IMM(addr);
2106 /* Check whether or not the relative offset overflows desc->imm */
2107 if ((unsigned long)(s32)call_imm != call_imm) {
2108 verbose(env, "address of kernel function %s is out of range\n",
2113 desc = &tab->descs[tab->nr_descs++];
2114 desc->func_id = func_id;
2115 desc->imm = call_imm;
2116 desc->offset = offset;
2117 err = btf_distill_func_proto(&env->log, desc_btf,
2118 func_proto, func_name,
2121 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2122 kfunc_desc_cmp_by_id_off, NULL);
2126 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2128 const struct bpf_kfunc_desc *d0 = a;
2129 const struct bpf_kfunc_desc *d1 = b;
2131 if (d0->imm > d1->imm)
2133 else if (d0->imm < d1->imm)
2138 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2140 struct bpf_kfunc_desc_tab *tab;
2142 tab = prog->aux->kfunc_tab;
2146 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2147 kfunc_desc_cmp_by_imm, NULL);
2150 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2152 return !!prog->aux->kfunc_tab;
2155 const struct btf_func_model *
2156 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2157 const struct bpf_insn *insn)
2159 const struct bpf_kfunc_desc desc = {
2162 const struct bpf_kfunc_desc *res;
2163 struct bpf_kfunc_desc_tab *tab;
2165 tab = prog->aux->kfunc_tab;
2166 res = bsearch(&desc, tab->descs, tab->nr_descs,
2167 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2169 return res ? &res->func_model : NULL;
2172 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2174 struct bpf_subprog_info *subprog = env->subprog_info;
2175 struct bpf_insn *insn = env->prog->insnsi;
2176 int i, ret, insn_cnt = env->prog->len;
2178 /* Add entry function. */
2179 ret = add_subprog(env, 0);
2183 for (i = 0; i < insn_cnt; i++, insn++) {
2184 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2185 !bpf_pseudo_kfunc_call(insn))
2188 if (!env->bpf_capable) {
2189 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2193 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2194 ret = add_subprog(env, i + insn->imm + 1);
2196 ret = add_kfunc_call(env, insn->imm, insn->off);
2202 /* Add a fake 'exit' subprog which could simplify subprog iteration
2203 * logic. 'subprog_cnt' should not be increased.
2205 subprog[env->subprog_cnt].start = insn_cnt;
2207 if (env->log.level & BPF_LOG_LEVEL2)
2208 for (i = 0; i < env->subprog_cnt; i++)
2209 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2214 static int check_subprogs(struct bpf_verifier_env *env)
2216 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2217 struct bpf_subprog_info *subprog = env->subprog_info;
2218 struct bpf_insn *insn = env->prog->insnsi;
2219 int insn_cnt = env->prog->len;
2221 /* now check that all jumps are within the same subprog */
2222 subprog_start = subprog[cur_subprog].start;
2223 subprog_end = subprog[cur_subprog + 1].start;
2224 for (i = 0; i < insn_cnt; i++) {
2225 u8 code = insn[i].code;
2227 if (code == (BPF_JMP | BPF_CALL) &&
2228 insn[i].imm == BPF_FUNC_tail_call &&
2229 insn[i].src_reg != BPF_PSEUDO_CALL)
2230 subprog[cur_subprog].has_tail_call = true;
2231 if (BPF_CLASS(code) == BPF_LD &&
2232 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2233 subprog[cur_subprog].has_ld_abs = true;
2234 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2236 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2238 off = i + insn[i].off + 1;
2239 if (off < subprog_start || off >= subprog_end) {
2240 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2244 if (i == subprog_end - 1) {
2245 /* to avoid fall-through from one subprog into another
2246 * the last insn of the subprog should be either exit
2247 * or unconditional jump back
2249 if (code != (BPF_JMP | BPF_EXIT) &&
2250 code != (BPF_JMP | BPF_JA)) {
2251 verbose(env, "last insn is not an exit or jmp\n");
2254 subprog_start = subprog_end;
2256 if (cur_subprog < env->subprog_cnt)
2257 subprog_end = subprog[cur_subprog + 1].start;
2263 /* Parentage chain of this register (or stack slot) should take care of all
2264 * issues like callee-saved registers, stack slot allocation time, etc.
2266 static int mark_reg_read(struct bpf_verifier_env *env,
2267 const struct bpf_reg_state *state,
2268 struct bpf_reg_state *parent, u8 flag)
2270 bool writes = parent == state->parent; /* Observe write marks */
2274 /* if read wasn't screened by an earlier write ... */
2275 if (writes && state->live & REG_LIVE_WRITTEN)
2277 if (parent->live & REG_LIVE_DONE) {
2278 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2279 reg_type_str(env, parent->type),
2280 parent->var_off.value, parent->off);
2283 /* The first condition is more likely to be true than the
2284 * second, checked it first.
2286 if ((parent->live & REG_LIVE_READ) == flag ||
2287 parent->live & REG_LIVE_READ64)
2288 /* The parentage chain never changes and
2289 * this parent was already marked as LIVE_READ.
2290 * There is no need to keep walking the chain again and
2291 * keep re-marking all parents as LIVE_READ.
2292 * This case happens when the same register is read
2293 * multiple times without writes into it in-between.
2294 * Also, if parent has the stronger REG_LIVE_READ64 set,
2295 * then no need to set the weak REG_LIVE_READ32.
2298 /* ... then we depend on parent's value */
2299 parent->live |= flag;
2300 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2301 if (flag == REG_LIVE_READ64)
2302 parent->live &= ~REG_LIVE_READ32;
2304 parent = state->parent;
2309 if (env->longest_mark_read_walk < cnt)
2310 env->longest_mark_read_walk = cnt;
2314 /* This function is supposed to be used by the following 32-bit optimization
2315 * code only. It returns TRUE if the source or destination register operates
2316 * on 64-bit, otherwise return FALSE.
2318 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2319 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2324 class = BPF_CLASS(code);
2326 if (class == BPF_JMP) {
2327 /* BPF_EXIT for "main" will reach here. Return TRUE
2332 if (op == BPF_CALL) {
2333 /* BPF to BPF call will reach here because of marking
2334 * caller saved clobber with DST_OP_NO_MARK for which we
2335 * don't care the register def because they are anyway
2336 * marked as NOT_INIT already.
2338 if (insn->src_reg == BPF_PSEUDO_CALL)
2340 /* Helper call will reach here because of arg type
2341 * check, conservatively return TRUE.
2350 if (class == BPF_ALU64 || class == BPF_JMP ||
2351 /* BPF_END always use BPF_ALU class. */
2352 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2355 if (class == BPF_ALU || class == BPF_JMP32)
2358 if (class == BPF_LDX) {
2360 return BPF_SIZE(code) == BPF_DW;
2361 /* LDX source must be ptr. */
2365 if (class == BPF_STX) {
2366 /* BPF_STX (including atomic variants) has multiple source
2367 * operands, one of which is a ptr. Check whether the caller is
2370 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2372 return BPF_SIZE(code) == BPF_DW;
2375 if (class == BPF_LD) {
2376 u8 mode = BPF_MODE(code);
2379 if (mode == BPF_IMM)
2382 /* Both LD_IND and LD_ABS return 32-bit data. */
2386 /* Implicit ctx ptr. */
2387 if (regno == BPF_REG_6)
2390 /* Explicit source could be any width. */
2394 if (class == BPF_ST)
2395 /* The only source register for BPF_ST is a ptr. */
2398 /* Conservatively return true at default. */
2402 /* Return the regno defined by the insn, or -1. */
2403 static int insn_def_regno(const struct bpf_insn *insn)
2405 switch (BPF_CLASS(insn->code)) {
2411 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2412 (insn->imm & BPF_FETCH)) {
2413 if (insn->imm == BPF_CMPXCHG)
2416 return insn->src_reg;
2421 return insn->dst_reg;
2425 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2426 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2428 int dst_reg = insn_def_regno(insn);
2433 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2436 static void mark_insn_zext(struct bpf_verifier_env *env,
2437 struct bpf_reg_state *reg)
2439 s32 def_idx = reg->subreg_def;
2441 if (def_idx == DEF_NOT_SUBREG)
2444 env->insn_aux_data[def_idx - 1].zext_dst = true;
2445 /* The dst will be zero extended, so won't be sub-register anymore. */
2446 reg->subreg_def = DEF_NOT_SUBREG;
2449 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2450 enum reg_arg_type t)
2452 struct bpf_verifier_state *vstate = env->cur_state;
2453 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2454 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2455 struct bpf_reg_state *reg, *regs = state->regs;
2458 if (regno >= MAX_BPF_REG) {
2459 verbose(env, "R%d is invalid\n", regno);
2463 mark_reg_scratched(env, regno);
2466 rw64 = is_reg64(env, insn, regno, reg, t);
2468 /* check whether register used as source operand can be read */
2469 if (reg->type == NOT_INIT) {
2470 verbose(env, "R%d !read_ok\n", regno);
2473 /* We don't need to worry about FP liveness because it's read-only */
2474 if (regno == BPF_REG_FP)
2478 mark_insn_zext(env, reg);
2480 return mark_reg_read(env, reg, reg->parent,
2481 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2483 /* check whether register used as dest operand can be written to */
2484 if (regno == BPF_REG_FP) {
2485 verbose(env, "frame pointer is read only\n");
2488 reg->live |= REG_LIVE_WRITTEN;
2489 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2491 mark_reg_unknown(env, regs, regno);
2496 /* for any branch, call, exit record the history of jmps in the given state */
2497 static int push_jmp_history(struct bpf_verifier_env *env,
2498 struct bpf_verifier_state *cur)
2500 u32 cnt = cur->jmp_history_cnt;
2501 struct bpf_idx_pair *p;
2504 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2507 p[cnt - 1].idx = env->insn_idx;
2508 p[cnt - 1].prev_idx = env->prev_insn_idx;
2509 cur->jmp_history = p;
2510 cur->jmp_history_cnt = cnt;
2514 /* Backtrack one insn at a time. If idx is not at the top of recorded
2515 * history then previous instruction came from straight line execution.
2517 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2522 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2523 i = st->jmp_history[cnt - 1].prev_idx;
2531 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2533 const struct btf_type *func;
2534 struct btf *desc_btf;
2536 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2539 desc_btf = find_kfunc_desc_btf(data, insn->off);
2540 if (IS_ERR(desc_btf))
2543 func = btf_type_by_id(desc_btf, insn->imm);
2544 return btf_name_by_offset(desc_btf, func->name_off);
2547 /* For given verifier state backtrack_insn() is called from the last insn to
2548 * the first insn. Its purpose is to compute a bitmask of registers and
2549 * stack slots that needs precision in the parent verifier state.
2551 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2552 u32 *reg_mask, u64 *stack_mask)
2554 const struct bpf_insn_cbs cbs = {
2555 .cb_call = disasm_kfunc_name,
2556 .cb_print = verbose,
2557 .private_data = env,
2559 struct bpf_insn *insn = env->prog->insnsi + idx;
2560 u8 class = BPF_CLASS(insn->code);
2561 u8 opcode = BPF_OP(insn->code);
2562 u8 mode = BPF_MODE(insn->code);
2563 u32 dreg = 1u << insn->dst_reg;
2564 u32 sreg = 1u << insn->src_reg;
2567 if (insn->code == 0)
2569 if (env->log.level & BPF_LOG_LEVEL2) {
2570 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2571 verbose(env, "%d: ", idx);
2572 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2575 if (class == BPF_ALU || class == BPF_ALU64) {
2576 if (!(*reg_mask & dreg))
2578 if (opcode == BPF_MOV) {
2579 if (BPF_SRC(insn->code) == BPF_X) {
2581 * dreg needs precision after this insn
2582 * sreg needs precision before this insn
2588 * dreg needs precision after this insn.
2589 * Corresponding register is already marked
2590 * as precise=true in this verifier state.
2591 * No further markings in parent are necessary
2596 if (BPF_SRC(insn->code) == BPF_X) {
2598 * both dreg and sreg need precision
2603 * dreg still needs precision before this insn
2606 } else if (class == BPF_LDX) {
2607 if (!(*reg_mask & dreg))
2611 /* scalars can only be spilled into stack w/o losing precision.
2612 * Load from any other memory can be zero extended.
2613 * The desire to keep that precision is already indicated
2614 * by 'precise' mark in corresponding register of this state.
2615 * No further tracking necessary.
2617 if (insn->src_reg != BPF_REG_FP)
2620 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2621 * that [fp - off] slot contains scalar that needs to be
2622 * tracked with precision
2624 spi = (-insn->off - 1) / BPF_REG_SIZE;
2626 verbose(env, "BUG spi %d\n", spi);
2627 WARN_ONCE(1, "verifier backtracking bug");
2630 *stack_mask |= 1ull << spi;
2631 } else if (class == BPF_STX || class == BPF_ST) {
2632 if (*reg_mask & dreg)
2633 /* stx & st shouldn't be using _scalar_ dst_reg
2634 * to access memory. It means backtracking
2635 * encountered a case of pointer subtraction.
2638 /* scalars can only be spilled into stack */
2639 if (insn->dst_reg != BPF_REG_FP)
2641 spi = (-insn->off - 1) / BPF_REG_SIZE;
2643 verbose(env, "BUG spi %d\n", spi);
2644 WARN_ONCE(1, "verifier backtracking bug");
2647 if (!(*stack_mask & (1ull << spi)))
2649 *stack_mask &= ~(1ull << spi);
2650 if (class == BPF_STX)
2652 } else if (class == BPF_JMP || class == BPF_JMP32) {
2653 if (opcode == BPF_CALL) {
2654 if (insn->src_reg == BPF_PSEUDO_CALL)
2656 /* regular helper call sets R0 */
2658 if (*reg_mask & 0x3f) {
2659 /* if backtracing was looking for registers R1-R5
2660 * they should have been found already.
2662 verbose(env, "BUG regs %x\n", *reg_mask);
2663 WARN_ONCE(1, "verifier backtracking bug");
2666 } else if (opcode == BPF_EXIT) {
2669 } else if (class == BPF_LD) {
2670 if (!(*reg_mask & dreg))
2673 /* It's ld_imm64 or ld_abs or ld_ind.
2674 * For ld_imm64 no further tracking of precision
2675 * into parent is necessary
2677 if (mode == BPF_IND || mode == BPF_ABS)
2678 /* to be analyzed */
2684 /* the scalar precision tracking algorithm:
2685 * . at the start all registers have precise=false.
2686 * . scalar ranges are tracked as normal through alu and jmp insns.
2687 * . once precise value of the scalar register is used in:
2688 * . ptr + scalar alu
2689 * . if (scalar cond K|scalar)
2690 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2691 * backtrack through the verifier states and mark all registers and
2692 * stack slots with spilled constants that these scalar regisers
2693 * should be precise.
2694 * . during state pruning two registers (or spilled stack slots)
2695 * are equivalent if both are not precise.
2697 * Note the verifier cannot simply walk register parentage chain,
2698 * since many different registers and stack slots could have been
2699 * used to compute single precise scalar.
2701 * The approach of starting with precise=true for all registers and then
2702 * backtrack to mark a register as not precise when the verifier detects
2703 * that program doesn't care about specific value (e.g., when helper
2704 * takes register as ARG_ANYTHING parameter) is not safe.
2706 * It's ok to walk single parentage chain of the verifier states.
2707 * It's possible that this backtracking will go all the way till 1st insn.
2708 * All other branches will be explored for needing precision later.
2710 * The backtracking needs to deal with cases like:
2711 * 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)
2714 * if r5 > 0x79f goto pc+7
2715 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2718 * call bpf_perf_event_output#25
2719 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2723 * call foo // uses callee's r6 inside to compute r0
2727 * to track above reg_mask/stack_mask needs to be independent for each frame.
2729 * Also if parent's curframe > frame where backtracking started,
2730 * the verifier need to mark registers in both frames, otherwise callees
2731 * may incorrectly prune callers. This is similar to
2732 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2734 * For now backtracking falls back into conservative marking.
2736 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2737 struct bpf_verifier_state *st)
2739 struct bpf_func_state *func;
2740 struct bpf_reg_state *reg;
2743 /* big hammer: mark all scalars precise in this path.
2744 * pop_stack may still get !precise scalars.
2746 for (; st; st = st->parent)
2747 for (i = 0; i <= st->curframe; i++) {
2748 func = st->frame[i];
2749 for (j = 0; j < BPF_REG_FP; j++) {
2750 reg = &func->regs[j];
2751 if (reg->type != SCALAR_VALUE)
2753 reg->precise = true;
2755 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2756 if (!is_spilled_reg(&func->stack[j]))
2758 reg = &func->stack[j].spilled_ptr;
2759 if (reg->type != SCALAR_VALUE)
2761 reg->precise = true;
2766 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2769 struct bpf_verifier_state *st = env->cur_state;
2770 int first_idx = st->first_insn_idx;
2771 int last_idx = env->insn_idx;
2772 struct bpf_func_state *func;
2773 struct bpf_reg_state *reg;
2774 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2775 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2776 bool skip_first = true;
2777 bool new_marks = false;
2780 if (!env->bpf_capable)
2783 func = st->frame[st->curframe];
2785 reg = &func->regs[regno];
2786 if (reg->type != SCALAR_VALUE) {
2787 WARN_ONCE(1, "backtracing misuse");
2794 reg->precise = true;
2798 if (!is_spilled_reg(&func->stack[spi])) {
2802 reg = &func->stack[spi].spilled_ptr;
2803 if (reg->type != SCALAR_VALUE) {
2811 reg->precise = true;
2817 if (!reg_mask && !stack_mask)
2820 DECLARE_BITMAP(mask, 64);
2821 u32 history = st->jmp_history_cnt;
2823 if (env->log.level & BPF_LOG_LEVEL2)
2824 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2825 for (i = last_idx;;) {
2830 err = backtrack_insn(env, i, ®_mask, &stack_mask);
2832 if (err == -ENOTSUPP) {
2833 mark_all_scalars_precise(env, st);
2838 if (!reg_mask && !stack_mask)
2839 /* Found assignment(s) into tracked register in this state.
2840 * Since this state is already marked, just return.
2841 * Nothing to be tracked further in the parent state.
2846 i = get_prev_insn_idx(st, i, &history);
2847 if (i >= env->prog->len) {
2848 /* This can happen if backtracking reached insn 0
2849 * and there are still reg_mask or stack_mask
2851 * It means the backtracking missed the spot where
2852 * particular register was initialized with a constant.
2854 verbose(env, "BUG backtracking idx %d\n", i);
2855 WARN_ONCE(1, "verifier backtracking bug");
2864 func = st->frame[st->curframe];
2865 bitmap_from_u64(mask, reg_mask);
2866 for_each_set_bit(i, mask, 32) {
2867 reg = &func->regs[i];
2868 if (reg->type != SCALAR_VALUE) {
2869 reg_mask &= ~(1u << i);
2874 reg->precise = true;
2877 bitmap_from_u64(mask, stack_mask);
2878 for_each_set_bit(i, mask, 64) {
2879 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2880 /* the sequence of instructions:
2882 * 3: (7b) *(u64 *)(r3 -8) = r0
2883 * 4: (79) r4 = *(u64 *)(r10 -8)
2884 * doesn't contain jmps. It's backtracked
2885 * as a single block.
2886 * During backtracking insn 3 is not recognized as
2887 * stack access, so at the end of backtracking
2888 * stack slot fp-8 is still marked in stack_mask.
2889 * However the parent state may not have accessed
2890 * fp-8 and it's "unallocated" stack space.
2891 * In such case fallback to conservative.
2893 mark_all_scalars_precise(env, st);
2897 if (!is_spilled_reg(&func->stack[i])) {
2898 stack_mask &= ~(1ull << i);
2901 reg = &func->stack[i].spilled_ptr;
2902 if (reg->type != SCALAR_VALUE) {
2903 stack_mask &= ~(1ull << i);
2908 reg->precise = true;
2910 if (env->log.level & BPF_LOG_LEVEL2) {
2911 verbose(env, "parent %s regs=%x stack=%llx marks:",
2912 new_marks ? "didn't have" : "already had",
2913 reg_mask, stack_mask);
2914 print_verifier_state(env, func, true);
2917 if (!reg_mask && !stack_mask)
2922 last_idx = st->last_insn_idx;
2923 first_idx = st->first_insn_idx;
2928 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2930 return __mark_chain_precision(env, regno, -1);
2933 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2935 return __mark_chain_precision(env, -1, spi);
2938 static bool is_spillable_regtype(enum bpf_reg_type type)
2940 switch (base_type(type)) {
2941 case PTR_TO_MAP_VALUE:
2945 case PTR_TO_PACKET_META:
2946 case PTR_TO_PACKET_END:
2947 case PTR_TO_FLOW_KEYS:
2948 case CONST_PTR_TO_MAP:
2950 case PTR_TO_SOCK_COMMON:
2951 case PTR_TO_TCP_SOCK:
2952 case PTR_TO_XDP_SOCK:
2957 case PTR_TO_MAP_KEY:
2964 /* Does this register contain a constant zero? */
2965 static bool register_is_null(struct bpf_reg_state *reg)
2967 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2970 static bool register_is_const(struct bpf_reg_state *reg)
2972 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2975 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2977 return tnum_is_unknown(reg->var_off) &&
2978 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2979 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2980 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2981 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2984 static bool register_is_bounded(struct bpf_reg_state *reg)
2986 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2989 static bool __is_pointer_value(bool allow_ptr_leaks,
2990 const struct bpf_reg_state *reg)
2992 if (allow_ptr_leaks)
2995 return reg->type != SCALAR_VALUE;
2998 static void save_register_state(struct bpf_func_state *state,
2999 int spi, struct bpf_reg_state *reg,
3004 state->stack[spi].spilled_ptr = *reg;
3005 if (size == BPF_REG_SIZE)
3006 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3008 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3009 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3011 /* size < 8 bytes spill */
3013 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3016 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3017 * stack boundary and alignment are checked in check_mem_access()
3019 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3020 /* stack frame we're writing to */
3021 struct bpf_func_state *state,
3022 int off, int size, int value_regno,
3025 struct bpf_func_state *cur; /* state of the current function */
3026 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3027 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3028 struct bpf_reg_state *reg = NULL;
3030 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3033 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3034 * so it's aligned access and [off, off + size) are within stack limits
3036 if (!env->allow_ptr_leaks &&
3037 state->stack[spi].slot_type[0] == STACK_SPILL &&
3038 size != BPF_REG_SIZE) {
3039 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3043 cur = env->cur_state->frame[env->cur_state->curframe];
3044 if (value_regno >= 0)
3045 reg = &cur->regs[value_regno];
3046 if (!env->bypass_spec_v4) {
3047 bool sanitize = reg && is_spillable_regtype(reg->type);
3049 for (i = 0; i < size; i++) {
3050 if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3057 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3060 mark_stack_slot_scratched(env, spi);
3061 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3062 !register_is_null(reg) && env->bpf_capable) {
3063 if (dst_reg != BPF_REG_FP) {
3064 /* The backtracking logic can only recognize explicit
3065 * stack slot address like [fp - 8]. Other spill of
3066 * scalar via different register has to be conservative.
3067 * Backtrack from here and mark all registers as precise
3068 * that contributed into 'reg' being a constant.
3070 err = mark_chain_precision(env, value_regno);
3074 save_register_state(state, spi, reg, size);
3075 } else if (reg && is_spillable_regtype(reg->type)) {
3076 /* register containing pointer is being spilled into stack */
3077 if (size != BPF_REG_SIZE) {
3078 verbose_linfo(env, insn_idx, "; ");
3079 verbose(env, "invalid size of register spill\n");
3082 if (state != cur && reg->type == PTR_TO_STACK) {
3083 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3086 save_register_state(state, spi, reg, size);
3088 u8 type = STACK_MISC;
3090 /* regular write of data into stack destroys any spilled ptr */
3091 state->stack[spi].spilled_ptr.type = NOT_INIT;
3092 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3093 if (is_spilled_reg(&state->stack[spi]))
3094 for (i = 0; i < BPF_REG_SIZE; i++)
3095 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3097 /* only mark the slot as written if all 8 bytes were written
3098 * otherwise read propagation may incorrectly stop too soon
3099 * when stack slots are partially written.
3100 * This heuristic means that read propagation will be
3101 * conservative, since it will add reg_live_read marks
3102 * to stack slots all the way to first state when programs
3103 * writes+reads less than 8 bytes
3105 if (size == BPF_REG_SIZE)
3106 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3108 /* when we zero initialize stack slots mark them as such */
3109 if (reg && register_is_null(reg)) {
3110 /* backtracking doesn't work for STACK_ZERO yet. */
3111 err = mark_chain_precision(env, value_regno);
3117 /* Mark slots affected by this stack write. */
3118 for (i = 0; i < size; i++)
3119 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3125 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3126 * known to contain a variable offset.
3127 * This function checks whether the write is permitted and conservatively
3128 * tracks the effects of the write, considering that each stack slot in the
3129 * dynamic range is potentially written to.
3131 * 'off' includes 'regno->off'.
3132 * 'value_regno' can be -1, meaning that an unknown value is being written to
3135 * Spilled pointers in range are not marked as written because we don't know
3136 * what's going to be actually written. This means that read propagation for
3137 * future reads cannot be terminated by this write.
3139 * For privileged programs, uninitialized stack slots are considered
3140 * initialized by this write (even though we don't know exactly what offsets
3141 * are going to be written to). The idea is that we don't want the verifier to
3142 * reject future reads that access slots written to through variable offsets.
3144 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3145 /* func where register points to */
3146 struct bpf_func_state *state,
3147 int ptr_regno, int off, int size,
3148 int value_regno, int insn_idx)
3150 struct bpf_func_state *cur; /* state of the current function */
3151 int min_off, max_off;
3153 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3154 bool writing_zero = false;
3155 /* set if the fact that we're writing a zero is used to let any
3156 * stack slots remain STACK_ZERO
3158 bool zero_used = false;
3160 cur = env->cur_state->frame[env->cur_state->curframe];
3161 ptr_reg = &cur->regs[ptr_regno];
3162 min_off = ptr_reg->smin_value + off;
3163 max_off = ptr_reg->smax_value + off + size;
3164 if (value_regno >= 0)
3165 value_reg = &cur->regs[value_regno];
3166 if (value_reg && register_is_null(value_reg))
3167 writing_zero = true;
3169 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3174 /* Variable offset writes destroy any spilled pointers in range. */
3175 for (i = min_off; i < max_off; i++) {
3176 u8 new_type, *stype;
3180 spi = slot / BPF_REG_SIZE;
3181 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3182 mark_stack_slot_scratched(env, spi);
3184 if (!env->allow_ptr_leaks
3185 && *stype != NOT_INIT
3186 && *stype != SCALAR_VALUE) {
3187 /* Reject the write if there's are spilled pointers in
3188 * range. If we didn't reject here, the ptr status
3189 * would be erased below (even though not all slots are
3190 * actually overwritten), possibly opening the door to
3193 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3198 /* Erase all spilled pointers. */
3199 state->stack[spi].spilled_ptr.type = NOT_INIT;
3201 /* Update the slot type. */
3202 new_type = STACK_MISC;
3203 if (writing_zero && *stype == STACK_ZERO) {
3204 new_type = STACK_ZERO;
3207 /* If the slot is STACK_INVALID, we check whether it's OK to
3208 * pretend that it will be initialized by this write. The slot
3209 * might not actually be written to, and so if we mark it as
3210 * initialized future reads might leak uninitialized memory.
3211 * For privileged programs, we will accept such reads to slots
3212 * that may or may not be written because, if we're reject
3213 * them, the error would be too confusing.
3215 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3216 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3223 /* backtracking doesn't work for STACK_ZERO yet. */
3224 err = mark_chain_precision(env, value_regno);
3231 /* When register 'dst_regno' is assigned some values from stack[min_off,
3232 * max_off), we set the register's type according to the types of the
3233 * respective stack slots. If all the stack values are known to be zeros, then
3234 * so is the destination reg. Otherwise, the register is considered to be
3235 * SCALAR. This function does not deal with register filling; the caller must
3236 * ensure that all spilled registers in the stack range have been marked as
3239 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3240 /* func where src register points to */
3241 struct bpf_func_state *ptr_state,
3242 int min_off, int max_off, int dst_regno)
3244 struct bpf_verifier_state *vstate = env->cur_state;
3245 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3250 for (i = min_off; i < max_off; i++) {
3252 spi = slot / BPF_REG_SIZE;
3253 stype = ptr_state->stack[spi].slot_type;
3254 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3258 if (zeros == max_off - min_off) {
3259 /* any access_size read into register is zero extended,
3260 * so the whole register == const_zero
3262 __mark_reg_const_zero(&state->regs[dst_regno]);
3263 /* backtracking doesn't support STACK_ZERO yet,
3264 * so mark it precise here, so that later
3265 * backtracking can stop here.
3266 * Backtracking may not need this if this register
3267 * doesn't participate in pointer adjustment.
3268 * Forward propagation of precise flag is not
3269 * necessary either. This mark is only to stop
3270 * backtracking. Any register that contributed
3271 * to const 0 was marked precise before spill.
3273 state->regs[dst_regno].precise = true;
3275 /* have read misc data from the stack */
3276 mark_reg_unknown(env, state->regs, dst_regno);
3278 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3281 /* Read the stack at 'off' and put the results into the register indicated by
3282 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3285 * 'dst_regno' can be -1, meaning that the read value is not going to a
3288 * The access is assumed to be within the current stack bounds.
3290 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3291 /* func where src register points to */
3292 struct bpf_func_state *reg_state,
3293 int off, int size, int dst_regno)
3295 struct bpf_verifier_state *vstate = env->cur_state;
3296 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3297 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3298 struct bpf_reg_state *reg;
3301 stype = reg_state->stack[spi].slot_type;
3302 reg = ®_state->stack[spi].spilled_ptr;
3304 if (is_spilled_reg(®_state->stack[spi])) {
3307 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3310 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3311 if (reg->type != SCALAR_VALUE) {
3312 verbose_linfo(env, env->insn_idx, "; ");
3313 verbose(env, "invalid size of register fill\n");
3317 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3321 if (!(off % BPF_REG_SIZE) && size == spill_size) {
3322 /* The earlier check_reg_arg() has decided the
3323 * subreg_def for this insn. Save it first.
3325 s32 subreg_def = state->regs[dst_regno].subreg_def;
3327 state->regs[dst_regno] = *reg;
3328 state->regs[dst_regno].subreg_def = subreg_def;
3330 for (i = 0; i < size; i++) {
3331 type = stype[(slot - i) % BPF_REG_SIZE];
3332 if (type == STACK_SPILL)
3334 if (type == STACK_MISC)
3336 verbose(env, "invalid read from stack off %d+%d size %d\n",
3340 mark_reg_unknown(env, state->regs, dst_regno);
3342 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3346 if (dst_regno >= 0) {
3347 /* restore register state from stack */
3348 state->regs[dst_regno] = *reg;
3349 /* mark reg as written since spilled pointer state likely
3350 * has its liveness marks cleared by is_state_visited()
3351 * which resets stack/reg liveness for state transitions
3353 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3354 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3355 /* If dst_regno==-1, the caller is asking us whether
3356 * it is acceptable to use this value as a SCALAR_VALUE
3358 * We must not allow unprivileged callers to do that
3359 * with spilled pointers.
3361 verbose(env, "leaking pointer from stack off %d\n",
3365 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3367 for (i = 0; i < size; i++) {
3368 type = stype[(slot - i) % BPF_REG_SIZE];
3369 if (type == STACK_MISC)
3371 if (type == STACK_ZERO)
3373 verbose(env, "invalid read from stack off %d+%d size %d\n",
3377 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3379 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3384 enum bpf_access_src {
3385 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
3386 ACCESS_HELPER = 2, /* the access is performed by a helper */
3389 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3390 int regno, int off, int access_size,
3391 bool zero_size_allowed,
3392 enum bpf_access_src type,
3393 struct bpf_call_arg_meta *meta);
3395 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3397 return cur_regs(env) + regno;
3400 /* Read the stack at 'ptr_regno + off' and put the result into the register
3402 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3403 * but not its variable offset.
3404 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3406 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3407 * filling registers (i.e. reads of spilled register cannot be detected when
3408 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3409 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3410 * offset; for a fixed offset check_stack_read_fixed_off should be used
3413 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3414 int ptr_regno, int off, int size, int dst_regno)
3416 /* The state of the source register. */
3417 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3418 struct bpf_func_state *ptr_state = func(env, reg);
3420 int min_off, max_off;
3422 /* Note that we pass a NULL meta, so raw access will not be permitted.
3424 err = check_stack_range_initialized(env, ptr_regno, off, size,
3425 false, ACCESS_DIRECT, NULL);
3429 min_off = reg->smin_value + off;
3430 max_off = reg->smax_value + off;
3431 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3435 /* check_stack_read dispatches to check_stack_read_fixed_off or
3436 * check_stack_read_var_off.
3438 * The caller must ensure that the offset falls within the allocated stack
3441 * 'dst_regno' is a register which will receive the value from the stack. It
3442 * can be -1, meaning that the read value is not going to a register.
3444 static int check_stack_read(struct bpf_verifier_env *env,
3445 int ptr_regno, int off, int size,
3448 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3449 struct bpf_func_state *state = func(env, reg);
3451 /* Some accesses are only permitted with a static offset. */
3452 bool var_off = !tnum_is_const(reg->var_off);
3454 /* The offset is required to be static when reads don't go to a
3455 * register, in order to not leak pointers (see
3456 * check_stack_read_fixed_off).
3458 if (dst_regno < 0 && var_off) {
3461 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3462 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3466 /* Variable offset is prohibited for unprivileged mode for simplicity
3467 * since it requires corresponding support in Spectre masking for stack
3468 * ALU. See also retrieve_ptr_limit().
3470 if (!env->bypass_spec_v1 && var_off) {
3473 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3474 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3480 off += reg->var_off.value;
3481 err = check_stack_read_fixed_off(env, state, off, size,
3484 /* Variable offset stack reads need more conservative handling
3485 * than fixed offset ones. Note that dst_regno >= 0 on this
3488 err = check_stack_read_var_off(env, ptr_regno, off, size,
3495 /* check_stack_write dispatches to check_stack_write_fixed_off or
3496 * check_stack_write_var_off.
3498 * 'ptr_regno' is the register used as a pointer into the stack.
3499 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3500 * 'value_regno' is the register whose value we're writing to the stack. It can
3501 * be -1, meaning that we're not writing from a register.
3503 * The caller must ensure that the offset falls within the maximum stack size.
3505 static int check_stack_write(struct bpf_verifier_env *env,
3506 int ptr_regno, int off, int size,
3507 int value_regno, int insn_idx)
3509 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3510 struct bpf_func_state *state = func(env, reg);
3513 if (tnum_is_const(reg->var_off)) {
3514 off += reg->var_off.value;
3515 err = check_stack_write_fixed_off(env, state, off, size,
3516 value_regno, insn_idx);
3518 /* Variable offset stack reads need more conservative handling
3519 * than fixed offset ones.
3521 err = check_stack_write_var_off(env, state,
3522 ptr_regno, off, size,
3523 value_regno, insn_idx);
3528 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3529 int off, int size, enum bpf_access_type type)
3531 struct bpf_reg_state *regs = cur_regs(env);
3532 struct bpf_map *map = regs[regno].map_ptr;
3533 u32 cap = bpf_map_flags_to_cap(map);
3535 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3536 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3537 map->value_size, off, size);
3541 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3542 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3543 map->value_size, off, size);
3550 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3551 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3552 int off, int size, u32 mem_size,
3553 bool zero_size_allowed)
3555 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3556 struct bpf_reg_state *reg;
3558 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3561 reg = &cur_regs(env)[regno];
3562 switch (reg->type) {
3563 case PTR_TO_MAP_KEY:
3564 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3565 mem_size, off, size);
3567 case PTR_TO_MAP_VALUE:
3568 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3569 mem_size, off, size);
3572 case PTR_TO_PACKET_META:
3573 case PTR_TO_PACKET_END:
3574 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3575 off, size, regno, reg->id, off, mem_size);
3579 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3580 mem_size, off, size);
3586 /* check read/write into a memory region with possible variable offset */
3587 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3588 int off, int size, u32 mem_size,
3589 bool zero_size_allowed)
3591 struct bpf_verifier_state *vstate = env->cur_state;
3592 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3593 struct bpf_reg_state *reg = &state->regs[regno];
3596 /* We may have adjusted the register pointing to memory region, so we
3597 * need to try adding each of min_value and max_value to off
3598 * to make sure our theoretical access will be safe.
3600 * The minimum value is only important with signed
3601 * comparisons where we can't assume the floor of a
3602 * value is 0. If we are using signed variables for our
3603 * index'es we need to make sure that whatever we use
3604 * will have a set floor within our range.
3606 if (reg->smin_value < 0 &&
3607 (reg->smin_value == S64_MIN ||
3608 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3609 reg->smin_value + off < 0)) {
3610 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3614 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3615 mem_size, zero_size_allowed);
3617 verbose(env, "R%d min value is outside of the allowed memory range\n",
3622 /* If we haven't set a max value then we need to bail since we can't be
3623 * sure we won't do bad things.
3624 * If reg->umax_value + off could overflow, treat that as unbounded too.
3626 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3627 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3631 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3632 mem_size, zero_size_allowed);
3634 verbose(env, "R%d max value is outside of the allowed memory range\n",
3642 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3643 const struct bpf_reg_state *reg, int regno,
3646 /* Access to this pointer-typed register or passing it to a helper
3647 * is only allowed in its original, unmodified form.
3651 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3652 reg_type_str(env, reg->type), regno, reg->off);
3656 if (!fixed_off_ok && reg->off) {
3657 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3658 reg_type_str(env, reg->type), regno, reg->off);
3662 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3665 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3666 verbose(env, "variable %s access var_off=%s disallowed\n",
3667 reg_type_str(env, reg->type), tn_buf);
3674 int check_ptr_off_reg(struct bpf_verifier_env *env,
3675 const struct bpf_reg_state *reg, int regno)
3677 return __check_ptr_off_reg(env, reg, regno, false);
3680 static int map_kptr_match_type(struct bpf_verifier_env *env,
3681 struct bpf_map_value_off_desc *off_desc,
3682 struct bpf_reg_state *reg, u32 regno)
3684 const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3685 int perm_flags = PTR_MAYBE_NULL;
3686 const char *reg_name = "";
3688 /* Only unreferenced case accepts untrusted pointers */
3689 if (off_desc->type == BPF_KPTR_UNREF)
3690 perm_flags |= PTR_UNTRUSTED;
3692 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3695 if (!btf_is_kernel(reg->btf)) {
3696 verbose(env, "R%d must point to kernel BTF\n", regno);
3699 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3700 reg_name = kernel_type_name(reg->btf, reg->btf_id);
3702 /* For ref_ptr case, release function check should ensure we get one
3703 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3704 * normal store of unreferenced kptr, we must ensure var_off is zero.
3705 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3706 * reg->off and reg->ref_obj_id are not needed here.
3708 if (__check_ptr_off_reg(env, reg, regno, true))
3711 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3712 * we also need to take into account the reg->off.
3714 * We want to support cases like:
3722 * v = func(); // PTR_TO_BTF_ID
3723 * val->foo = v; // reg->off is zero, btf and btf_id match type
3724 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3725 * // first member type of struct after comparison fails
3726 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3729 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3730 * is zero. We must also ensure that btf_struct_ids_match does not walk
3731 * the struct to match type against first member of struct, i.e. reject
3732 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3733 * strict mode to true for type match.
3735 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3736 off_desc->kptr.btf, off_desc->kptr.btf_id,
3737 off_desc->type == BPF_KPTR_REF))
3741 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3742 reg_type_str(env, reg->type), reg_name);
3743 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3744 if (off_desc->type == BPF_KPTR_UNREF)
3745 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3752 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3753 int value_regno, int insn_idx,
3754 struct bpf_map_value_off_desc *off_desc)
3756 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3757 int class = BPF_CLASS(insn->code);
3758 struct bpf_reg_state *val_reg;
3760 /* Things we already checked for in check_map_access and caller:
3761 * - Reject cases where variable offset may touch kptr
3762 * - size of access (must be BPF_DW)
3763 * - tnum_is_const(reg->var_off)
3764 * - off_desc->offset == off + reg->var_off.value
3766 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3767 if (BPF_MODE(insn->code) != BPF_MEM) {
3768 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3772 /* We only allow loading referenced kptr, since it will be marked as
3773 * untrusted, similar to unreferenced kptr.
3775 if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3776 verbose(env, "store to referenced kptr disallowed\n");
3780 if (class == BPF_LDX) {
3781 val_reg = reg_state(env, value_regno);
3782 /* We can simply mark the value_regno receiving the pointer
3783 * value from map as PTR_TO_BTF_ID, with the correct type.
3785 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3786 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3787 /* For mark_ptr_or_null_reg */
3788 val_reg->id = ++env->id_gen;
3789 } else if (class == BPF_STX) {
3790 val_reg = reg_state(env, value_regno);
3791 if (!register_is_null(val_reg) &&
3792 map_kptr_match_type(env, off_desc, val_reg, value_regno))
3794 } else if (class == BPF_ST) {
3796 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3801 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3807 /* check read/write into a map element with possible variable offset */
3808 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3809 int off, int size, bool zero_size_allowed,
3810 enum bpf_access_src src)
3812 struct bpf_verifier_state *vstate = env->cur_state;
3813 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3814 struct bpf_reg_state *reg = &state->regs[regno];
3815 struct bpf_map *map = reg->map_ptr;
3818 err = check_mem_region_access(env, regno, off, size, map->value_size,
3823 if (map_value_has_spin_lock(map)) {
3824 u32 lock = map->spin_lock_off;
3826 /* if any part of struct bpf_spin_lock can be touched by
3827 * load/store reject this program.
3828 * To check that [x1, x2) overlaps with [y1, y2)
3829 * it is sufficient to check x1 < y2 && y1 < x2.
3831 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3832 lock < reg->umax_value + off + size) {
3833 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3837 if (map_value_has_timer(map)) {
3838 u32 t = map->timer_off;
3840 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3841 t < reg->umax_value + off + size) {
3842 verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3846 if (map_value_has_kptrs(map)) {
3847 struct bpf_map_value_off *tab = map->kptr_off_tab;
3850 for (i = 0; i < tab->nr_off; i++) {
3851 u32 p = tab->off[i].offset;
3853 if (reg->smin_value + off < p + sizeof(u64) &&
3854 p < reg->umax_value + off + size) {
3855 if (src != ACCESS_DIRECT) {
3856 verbose(env, "kptr cannot be accessed indirectly by helper\n");
3859 if (!tnum_is_const(reg->var_off)) {
3860 verbose(env, "kptr access cannot have variable offset\n");
3863 if (p != off + reg->var_off.value) {
3864 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3865 p, off + reg->var_off.value);
3868 if (size != bpf_size_to_bytes(BPF_DW)) {
3869 verbose(env, "kptr access size must be BPF_DW\n");
3879 #define MAX_PACKET_OFF 0xffff
3881 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3882 const struct bpf_call_arg_meta *meta,
3883 enum bpf_access_type t)
3885 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3887 switch (prog_type) {
3888 /* Program types only with direct read access go here! */
3889 case BPF_PROG_TYPE_LWT_IN:
3890 case BPF_PROG_TYPE_LWT_OUT:
3891 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3892 case BPF_PROG_TYPE_SK_REUSEPORT:
3893 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3894 case BPF_PROG_TYPE_CGROUP_SKB:
3899 /* Program types with direct read + write access go here! */
3900 case BPF_PROG_TYPE_SCHED_CLS:
3901 case BPF_PROG_TYPE_SCHED_ACT:
3902 case BPF_PROG_TYPE_XDP:
3903 case BPF_PROG_TYPE_LWT_XMIT:
3904 case BPF_PROG_TYPE_SK_SKB:
3905 case BPF_PROG_TYPE_SK_MSG:
3907 return meta->pkt_access;
3909 env->seen_direct_write = true;
3912 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3914 env->seen_direct_write = true;
3923 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3924 int size, bool zero_size_allowed)
3926 struct bpf_reg_state *regs = cur_regs(env);
3927 struct bpf_reg_state *reg = ®s[regno];
3930 /* We may have added a variable offset to the packet pointer; but any
3931 * reg->range we have comes after that. We are only checking the fixed
3935 /* We don't allow negative numbers, because we aren't tracking enough
3936 * detail to prove they're safe.
3938 if (reg->smin_value < 0) {
3939 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3944 err = reg->range < 0 ? -EINVAL :
3945 __check_mem_access(env, regno, off, size, reg->range,
3948 verbose(env, "R%d offset is outside of the packet\n", regno);
3952 /* __check_mem_access has made sure "off + size - 1" is within u16.
3953 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3954 * otherwise find_good_pkt_pointers would have refused to set range info
3955 * that __check_mem_access would have rejected this pkt access.
3956 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3958 env->prog->aux->max_pkt_offset =
3959 max_t(u32, env->prog->aux->max_pkt_offset,
3960 off + reg->umax_value + size - 1);
3965 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
3966 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3967 enum bpf_access_type t, enum bpf_reg_type *reg_type,
3968 struct btf **btf, u32 *btf_id)
3970 struct bpf_insn_access_aux info = {
3971 .reg_type = *reg_type,
3975 if (env->ops->is_valid_access &&
3976 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3977 /* A non zero info.ctx_field_size indicates that this field is a
3978 * candidate for later verifier transformation to load the whole
3979 * field and then apply a mask when accessed with a narrower
3980 * access than actual ctx access size. A zero info.ctx_field_size
3981 * will only allow for whole field access and rejects any other
3982 * type of narrower access.
3984 *reg_type = info.reg_type;
3986 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3988 *btf_id = info.btf_id;
3990 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3992 /* remember the offset of last byte accessed in ctx */
3993 if (env->prog->aux->max_ctx_offset < off + size)
3994 env->prog->aux->max_ctx_offset = off + size;
3998 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4002 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4005 if (size < 0 || off < 0 ||
4006 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4007 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4014 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4015 u32 regno, int off, int size,
4016 enum bpf_access_type t)
4018 struct bpf_reg_state *regs = cur_regs(env);
4019 struct bpf_reg_state *reg = ®s[regno];
4020 struct bpf_insn_access_aux info = {};
4023 if (reg->smin_value < 0) {
4024 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4029 switch (reg->type) {
4030 case PTR_TO_SOCK_COMMON:
4031 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4034 valid = bpf_sock_is_valid_access(off, size, t, &info);
4036 case PTR_TO_TCP_SOCK:
4037 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4039 case PTR_TO_XDP_SOCK:
4040 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4048 env->insn_aux_data[insn_idx].ctx_field_size =
4049 info.ctx_field_size;
4053 verbose(env, "R%d invalid %s access off=%d size=%d\n",
4054 regno, reg_type_str(env, reg->type), off, size);
4059 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4061 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4064 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4066 const struct bpf_reg_state *reg = reg_state(env, regno);
4068 return reg->type == PTR_TO_CTX;
4071 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4073 const struct bpf_reg_state *reg = reg_state(env, regno);
4075 return type_is_sk_pointer(reg->type);
4078 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4080 const struct bpf_reg_state *reg = reg_state(env, regno);
4082 return type_is_pkt_pointer(reg->type);
4085 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4087 const struct bpf_reg_state *reg = reg_state(env, regno);
4089 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4090 return reg->type == PTR_TO_FLOW_KEYS;
4093 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4094 const struct bpf_reg_state *reg,
4095 int off, int size, bool strict)
4097 struct tnum reg_off;
4100 /* Byte size accesses are always allowed. */
4101 if (!strict || size == 1)
4104 /* For platforms that do not have a Kconfig enabling
4105 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4106 * NET_IP_ALIGN is universally set to '2'. And on platforms
4107 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4108 * to this code only in strict mode where we want to emulate
4109 * the NET_IP_ALIGN==2 checking. Therefore use an
4110 * unconditional IP align value of '2'.
4114 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4115 if (!tnum_is_aligned(reg_off, size)) {
4118 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4120 "misaligned packet access off %d+%s+%d+%d size %d\n",
4121 ip_align, tn_buf, reg->off, off, size);
4128 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4129 const struct bpf_reg_state *reg,
4130 const char *pointer_desc,
4131 int off, int size, bool strict)
4133 struct tnum reg_off;
4135 /* Byte size accesses are always allowed. */
4136 if (!strict || size == 1)
4139 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4140 if (!tnum_is_aligned(reg_off, size)) {
4143 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4144 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4145 pointer_desc, tn_buf, reg->off, off, size);
4152 static int check_ptr_alignment(struct bpf_verifier_env *env,
4153 const struct bpf_reg_state *reg, int off,
4154 int size, bool strict_alignment_once)
4156 bool strict = env->strict_alignment || strict_alignment_once;
4157 const char *pointer_desc = "";
4159 switch (reg->type) {
4161 case PTR_TO_PACKET_META:
4162 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4163 * right in front, treat it the very same way.
4165 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4166 case PTR_TO_FLOW_KEYS:
4167 pointer_desc = "flow keys ";
4169 case PTR_TO_MAP_KEY:
4170 pointer_desc = "key ";
4172 case PTR_TO_MAP_VALUE:
4173 pointer_desc = "value ";
4176 pointer_desc = "context ";
4179 pointer_desc = "stack ";
4180 /* The stack spill tracking logic in check_stack_write_fixed_off()
4181 * and check_stack_read_fixed_off() relies on stack accesses being
4187 pointer_desc = "sock ";
4189 case PTR_TO_SOCK_COMMON:
4190 pointer_desc = "sock_common ";
4192 case PTR_TO_TCP_SOCK:
4193 pointer_desc = "tcp_sock ";
4195 case PTR_TO_XDP_SOCK:
4196 pointer_desc = "xdp_sock ";
4201 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4205 static int update_stack_depth(struct bpf_verifier_env *env,
4206 const struct bpf_func_state *func,
4209 u16 stack = env->subprog_info[func->subprogno].stack_depth;
4214 /* update known max for given subprogram */
4215 env->subprog_info[func->subprogno].stack_depth = -off;
4219 /* starting from main bpf function walk all instructions of the function
4220 * and recursively walk all callees that given function can call.
4221 * Ignore jump and exit insns.
4222 * Since recursion is prevented by check_cfg() this algorithm
4223 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4225 static int check_max_stack_depth(struct bpf_verifier_env *env)
4227 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4228 struct bpf_subprog_info *subprog = env->subprog_info;
4229 struct bpf_insn *insn = env->prog->insnsi;
4230 bool tail_call_reachable = false;
4231 int ret_insn[MAX_CALL_FRAMES];
4232 int ret_prog[MAX_CALL_FRAMES];
4236 /* protect against potential stack overflow that might happen when
4237 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4238 * depth for such case down to 256 so that the worst case scenario
4239 * would result in 8k stack size (32 which is tailcall limit * 256 =
4242 * To get the idea what might happen, see an example:
4243 * func1 -> sub rsp, 128
4244 * subfunc1 -> sub rsp, 256
4245 * tailcall1 -> add rsp, 256
4246 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4247 * subfunc2 -> sub rsp, 64
4248 * subfunc22 -> sub rsp, 128
4249 * tailcall2 -> add rsp, 128
4250 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4252 * tailcall will unwind the current stack frame but it will not get rid
4253 * of caller's stack as shown on the example above.
4255 if (idx && subprog[idx].has_tail_call && depth >= 256) {
4257 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4261 /* round up to 32-bytes, since this is granularity
4262 * of interpreter stack size
4264 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4265 if (depth > MAX_BPF_STACK) {
4266 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4271 subprog_end = subprog[idx + 1].start;
4272 for (; i < subprog_end; i++) {
4275 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4277 /* remember insn and function to return to */
4278 ret_insn[frame] = i + 1;
4279 ret_prog[frame] = idx;
4281 /* find the callee */
4282 next_insn = i + insn[i].imm + 1;
4283 idx = find_subprog(env, next_insn);
4285 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4289 if (subprog[idx].is_async_cb) {
4290 if (subprog[idx].has_tail_call) {
4291 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4294 /* async callbacks don't increase bpf prog stack size */
4299 if (subprog[idx].has_tail_call)
4300 tail_call_reachable = true;
4303 if (frame >= MAX_CALL_FRAMES) {
4304 verbose(env, "the call stack of %d frames is too deep !\n",
4310 /* if tail call got detected across bpf2bpf calls then mark each of the
4311 * currently present subprog frames as tail call reachable subprogs;
4312 * this info will be utilized by JIT so that we will be preserving the
4313 * tail call counter throughout bpf2bpf calls combined with tailcalls
4315 if (tail_call_reachable)
4316 for (j = 0; j < frame; j++)
4317 subprog[ret_prog[j]].tail_call_reachable = true;
4318 if (subprog[0].tail_call_reachable)
4319 env->prog->aux->tail_call_reachable = true;
4321 /* end of for() loop means the last insn of the 'subprog'
4322 * was reached. Doesn't matter whether it was JA or EXIT
4326 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4328 i = ret_insn[frame];
4329 idx = ret_prog[frame];
4333 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4334 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4335 const struct bpf_insn *insn, int idx)
4337 int start = idx + insn->imm + 1, subprog;
4339 subprog = find_subprog(env, start);
4341 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4345 return env->subprog_info[subprog].stack_depth;
4349 static int __check_buffer_access(struct bpf_verifier_env *env,
4350 const char *buf_info,
4351 const struct bpf_reg_state *reg,
4352 int regno, int off, int size)
4356 "R%d invalid %s buffer access: off=%d, size=%d\n",
4357 regno, buf_info, off, size);
4360 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4363 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4365 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4366 regno, off, tn_buf);
4373 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4374 const struct bpf_reg_state *reg,
4375 int regno, int off, int size)
4379 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4383 if (off + size > env->prog->aux->max_tp_access)
4384 env->prog->aux->max_tp_access = off + size;
4389 static int check_buffer_access(struct bpf_verifier_env *env,
4390 const struct bpf_reg_state *reg,
4391 int regno, int off, int size,
4392 bool zero_size_allowed,
4395 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4398 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4402 if (off + size > *max_access)
4403 *max_access = off + size;
4408 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4409 static void zext_32_to_64(struct bpf_reg_state *reg)
4411 reg->var_off = tnum_subreg(reg->var_off);
4412 __reg_assign_32_into_64(reg);
4415 /* truncate register to smaller size (in bytes)
4416 * must be called with size < BPF_REG_SIZE
4418 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4422 /* clear high bits in bit representation */
4423 reg->var_off = tnum_cast(reg->var_off, size);
4425 /* fix arithmetic bounds */
4426 mask = ((u64)1 << (size * 8)) - 1;
4427 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4428 reg->umin_value &= mask;
4429 reg->umax_value &= mask;
4431 reg->umin_value = 0;
4432 reg->umax_value = mask;
4434 reg->smin_value = reg->umin_value;
4435 reg->smax_value = reg->umax_value;
4437 /* If size is smaller than 32bit register the 32bit register
4438 * values are also truncated so we push 64-bit bounds into
4439 * 32-bit bounds. Above were truncated < 32-bits already.
4443 __reg_combine_64_into_32(reg);
4446 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4448 /* A map is considered read-only if the following condition are true:
4450 * 1) BPF program side cannot change any of the map content. The
4451 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4452 * and was set at map creation time.
4453 * 2) The map value(s) have been initialized from user space by a
4454 * loader and then "frozen", such that no new map update/delete
4455 * operations from syscall side are possible for the rest of
4456 * the map's lifetime from that point onwards.
4457 * 3) Any parallel/pending map update/delete operations from syscall
4458 * side have been completed. Only after that point, it's safe to
4459 * assume that map value(s) are immutable.
4461 return (map->map_flags & BPF_F_RDONLY_PROG) &&
4462 READ_ONCE(map->frozen) &&
4463 !bpf_map_write_active(map);
4466 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4472 err = map->ops->map_direct_value_addr(map, &addr, off);
4475 ptr = (void *)(long)addr + off;
4479 *val = (u64)*(u8 *)ptr;
4482 *val = (u64)*(u16 *)ptr;
4485 *val = (u64)*(u32 *)ptr;
4496 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4497 struct bpf_reg_state *regs,
4498 int regno, int off, int size,
4499 enum bpf_access_type atype,
4502 struct bpf_reg_state *reg = regs + regno;
4503 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4504 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4505 enum bpf_type_flag flag = 0;
4511 "R%d is ptr_%s invalid negative access: off=%d\n",
4515 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4518 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4520 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4521 regno, tname, off, tn_buf);
4525 if (reg->type & MEM_USER) {
4527 "R%d is ptr_%s access user memory: off=%d\n",
4532 if (reg->type & MEM_PERCPU) {
4534 "R%d is ptr_%s access percpu memory: off=%d\n",
4539 if (env->ops->btf_struct_access) {
4540 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4541 off, size, atype, &btf_id, &flag);
4543 if (atype != BPF_READ) {
4544 verbose(env, "only read is supported\n");
4548 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4549 atype, &btf_id, &flag);
4555 /* If this is an untrusted pointer, all pointers formed by walking it
4556 * also inherit the untrusted flag.
4558 if (type_flag(reg->type) & PTR_UNTRUSTED)
4559 flag |= PTR_UNTRUSTED;
4561 if (atype == BPF_READ && value_regno >= 0)
4562 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4567 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4568 struct bpf_reg_state *regs,
4569 int regno, int off, int size,
4570 enum bpf_access_type atype,
4573 struct bpf_reg_state *reg = regs + regno;
4574 struct bpf_map *map = reg->map_ptr;
4575 enum bpf_type_flag flag = 0;
4576 const struct btf_type *t;
4582 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4586 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4587 verbose(env, "map_ptr access not supported for map type %d\n",
4592 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4593 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4595 if (!env->allow_ptr_to_map_access) {
4597 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4603 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4608 if (atype != BPF_READ) {
4609 verbose(env, "only read from %s is supported\n", tname);
4613 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4617 if (value_regno >= 0)
4618 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4623 /* Check that the stack access at the given offset is within bounds. The
4624 * maximum valid offset is -1.
4626 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4627 * -state->allocated_stack for reads.
4629 static int check_stack_slot_within_bounds(int off,
4630 struct bpf_func_state *state,
4631 enum bpf_access_type t)
4636 min_valid_off = -MAX_BPF_STACK;
4638 min_valid_off = -state->allocated_stack;
4640 if (off < min_valid_off || off > -1)
4645 /* Check that the stack access at 'regno + off' falls within the maximum stack
4648 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4650 static int check_stack_access_within_bounds(
4651 struct bpf_verifier_env *env,
4652 int regno, int off, int access_size,
4653 enum bpf_access_src src, enum bpf_access_type type)
4655 struct bpf_reg_state *regs = cur_regs(env);
4656 struct bpf_reg_state *reg = regs + regno;
4657 struct bpf_func_state *state = func(env, reg);
4658 int min_off, max_off;
4662 if (src == ACCESS_HELPER)
4663 /* We don't know if helpers are reading or writing (or both). */
4664 err_extra = " indirect access to";
4665 else if (type == BPF_READ)
4666 err_extra = " read from";
4668 err_extra = " write to";
4670 if (tnum_is_const(reg->var_off)) {
4671 min_off = reg->var_off.value + off;
4672 if (access_size > 0)
4673 max_off = min_off + access_size - 1;
4677 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4678 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4679 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4683 min_off = reg->smin_value + off;
4684 if (access_size > 0)
4685 max_off = reg->smax_value + off + access_size - 1;
4690 err = check_stack_slot_within_bounds(min_off, state, type);
4692 err = check_stack_slot_within_bounds(max_off, state, type);
4695 if (tnum_is_const(reg->var_off)) {
4696 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4697 err_extra, regno, off, access_size);
4701 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4702 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4703 err_extra, regno, tn_buf, access_size);
4709 /* check whether memory at (regno + off) is accessible for t = (read | write)
4710 * if t==write, value_regno is a register which value is stored into memory
4711 * if t==read, value_regno is a register which will receive the value from memory
4712 * if t==write && value_regno==-1, some unknown value is stored into memory
4713 * if t==read && value_regno==-1, don't care what we read from memory
4715 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4716 int off, int bpf_size, enum bpf_access_type t,
4717 int value_regno, bool strict_alignment_once)
4719 struct bpf_reg_state *regs = cur_regs(env);
4720 struct bpf_reg_state *reg = regs + regno;
4721 struct bpf_func_state *state;
4724 size = bpf_size_to_bytes(bpf_size);
4728 /* alignment checks will add in reg->off themselves */
4729 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4733 /* for access checks, reg->off is just part of off */
4736 if (reg->type == PTR_TO_MAP_KEY) {
4737 if (t == BPF_WRITE) {
4738 verbose(env, "write to change key R%d not allowed\n", regno);
4742 err = check_mem_region_access(env, regno, off, size,
4743 reg->map_ptr->key_size, false);
4746 if (value_regno >= 0)
4747 mark_reg_unknown(env, regs, value_regno);
4748 } else if (reg->type == PTR_TO_MAP_VALUE) {
4749 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4751 if (t == BPF_WRITE && value_regno >= 0 &&
4752 is_pointer_value(env, value_regno)) {
4753 verbose(env, "R%d leaks addr into map\n", value_regno);
4756 err = check_map_access_type(env, regno, off, size, t);
4759 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4762 if (tnum_is_const(reg->var_off))
4763 kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4764 off + reg->var_off.value);
4765 if (kptr_off_desc) {
4766 err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4768 } else if (t == BPF_READ && value_regno >= 0) {
4769 struct bpf_map *map = reg->map_ptr;
4771 /* if map is read-only, track its contents as scalars */
4772 if (tnum_is_const(reg->var_off) &&
4773 bpf_map_is_rdonly(map) &&
4774 map->ops->map_direct_value_addr) {
4775 int map_off = off + reg->var_off.value;
4778 err = bpf_map_direct_read(map, map_off, size,
4783 regs[value_regno].type = SCALAR_VALUE;
4784 __mark_reg_known(®s[value_regno], val);
4786 mark_reg_unknown(env, regs, value_regno);
4789 } else if (base_type(reg->type) == PTR_TO_MEM) {
4790 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4792 if (type_may_be_null(reg->type)) {
4793 verbose(env, "R%d invalid mem access '%s'\n", regno,
4794 reg_type_str(env, reg->type));
4798 if (t == BPF_WRITE && rdonly_mem) {
4799 verbose(env, "R%d cannot write into %s\n",
4800 regno, reg_type_str(env, reg->type));
4804 if (t == BPF_WRITE && value_regno >= 0 &&
4805 is_pointer_value(env, value_regno)) {
4806 verbose(env, "R%d leaks addr into mem\n", value_regno);
4810 err = check_mem_region_access(env, regno, off, size,
4811 reg->mem_size, false);
4812 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4813 mark_reg_unknown(env, regs, value_regno);
4814 } else if (reg->type == PTR_TO_CTX) {
4815 enum bpf_reg_type reg_type = SCALAR_VALUE;
4816 struct btf *btf = NULL;
4819 if (t == BPF_WRITE && value_regno >= 0 &&
4820 is_pointer_value(env, value_regno)) {
4821 verbose(env, "R%d leaks addr into ctx\n", value_regno);
4825 err = check_ptr_off_reg(env, reg, regno);
4829 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
4832 verbose_linfo(env, insn_idx, "; ");
4833 if (!err && t == BPF_READ && value_regno >= 0) {
4834 /* ctx access returns either a scalar, or a
4835 * PTR_TO_PACKET[_META,_END]. In the latter
4836 * case, we know the offset is zero.
4838 if (reg_type == SCALAR_VALUE) {
4839 mark_reg_unknown(env, regs, value_regno);
4841 mark_reg_known_zero(env, regs,
4843 if (type_may_be_null(reg_type))
4844 regs[value_regno].id = ++env->id_gen;
4845 /* A load of ctx field could have different
4846 * actual load size with the one encoded in the
4847 * insn. When the dst is PTR, it is for sure not
4850 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4851 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4852 regs[value_regno].btf = btf;
4853 regs[value_regno].btf_id = btf_id;
4856 regs[value_regno].type = reg_type;
4859 } else if (reg->type == PTR_TO_STACK) {
4860 /* Basic bounds checks. */
4861 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4865 state = func(env, reg);
4866 err = update_stack_depth(env, state, off);
4871 err = check_stack_read(env, regno, off, size,
4874 err = check_stack_write(env, regno, off, size,
4875 value_regno, insn_idx);
4876 } else if (reg_is_pkt_pointer(reg)) {
4877 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4878 verbose(env, "cannot write into packet\n");
4881 if (t == BPF_WRITE && value_regno >= 0 &&
4882 is_pointer_value(env, value_regno)) {
4883 verbose(env, "R%d leaks addr into packet\n",
4887 err = check_packet_access(env, regno, off, size, false);
4888 if (!err && t == BPF_READ && value_regno >= 0)
4889 mark_reg_unknown(env, regs, value_regno);
4890 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4891 if (t == BPF_WRITE && value_regno >= 0 &&
4892 is_pointer_value(env, value_regno)) {
4893 verbose(env, "R%d leaks addr into flow keys\n",
4898 err = check_flow_keys_access(env, off, size);
4899 if (!err && t == BPF_READ && value_regno >= 0)
4900 mark_reg_unknown(env, regs, value_regno);
4901 } else if (type_is_sk_pointer(reg->type)) {
4902 if (t == BPF_WRITE) {
4903 verbose(env, "R%d cannot write into %s\n",
4904 regno, reg_type_str(env, reg->type));
4907 err = check_sock_access(env, insn_idx, regno, off, size, t);
4908 if (!err && value_regno >= 0)
4909 mark_reg_unknown(env, regs, value_regno);
4910 } else if (reg->type == PTR_TO_TP_BUFFER) {
4911 err = check_tp_buffer_access(env, reg, regno, off, size);
4912 if (!err && t == BPF_READ && value_regno >= 0)
4913 mark_reg_unknown(env, regs, value_regno);
4914 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4915 !type_may_be_null(reg->type)) {
4916 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4918 } else if (reg->type == CONST_PTR_TO_MAP) {
4919 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4921 } else if (base_type(reg->type) == PTR_TO_BUF) {
4922 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4926 if (t == BPF_WRITE) {
4927 verbose(env, "R%d cannot write into %s\n",
4928 regno, reg_type_str(env, reg->type));
4931 max_access = &env->prog->aux->max_rdonly_access;
4933 max_access = &env->prog->aux->max_rdwr_access;
4936 err = check_buffer_access(env, reg, regno, off, size, false,
4939 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4940 mark_reg_unknown(env, regs, value_regno);
4942 verbose(env, "R%d invalid mem access '%s'\n", regno,
4943 reg_type_str(env, reg->type));
4947 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4948 regs[value_regno].type == SCALAR_VALUE) {
4949 /* b/h/w load zero-extends, mark upper bits as known 0 */
4950 coerce_reg_to_size(®s[value_regno], size);
4955 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4960 switch (insn->imm) {
4962 case BPF_ADD | BPF_FETCH:
4964 case BPF_AND | BPF_FETCH:
4966 case BPF_OR | BPF_FETCH:
4968 case BPF_XOR | BPF_FETCH:
4973 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4977 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4978 verbose(env, "invalid atomic operand size\n");
4982 /* check src1 operand */
4983 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4987 /* check src2 operand */
4988 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4992 if (insn->imm == BPF_CMPXCHG) {
4993 /* Check comparison of R0 with memory location */
4994 const u32 aux_reg = BPF_REG_0;
4996 err = check_reg_arg(env, aux_reg, SRC_OP);
5000 if (is_pointer_value(env, aux_reg)) {
5001 verbose(env, "R%d leaks addr into mem\n", aux_reg);
5006 if (is_pointer_value(env, insn->src_reg)) {
5007 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5011 if (is_ctx_reg(env, insn->dst_reg) ||
5012 is_pkt_reg(env, insn->dst_reg) ||
5013 is_flow_key_reg(env, insn->dst_reg) ||
5014 is_sk_reg(env, insn->dst_reg)) {
5015 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5017 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5021 if (insn->imm & BPF_FETCH) {
5022 if (insn->imm == BPF_CMPXCHG)
5023 load_reg = BPF_REG_0;
5025 load_reg = insn->src_reg;
5027 /* check and record load of old value */
5028 err = check_reg_arg(env, load_reg, DST_OP);
5032 /* This instruction accesses a memory location but doesn't
5033 * actually load it into a register.
5038 /* Check whether we can read the memory, with second call for fetch
5039 * case to simulate the register fill.
5041 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5042 BPF_SIZE(insn->code), BPF_READ, -1, true);
5043 if (!err && load_reg >= 0)
5044 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5045 BPF_SIZE(insn->code), BPF_READ, load_reg,
5050 /* Check whether we can write into the same memory. */
5051 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5052 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5059 /* When register 'regno' is used to read the stack (either directly or through
5060 * a helper function) make sure that it's within stack boundary and, depending
5061 * on the access type, that all elements of the stack are initialized.
5063 * 'off' includes 'regno->off', but not its dynamic part (if any).
5065 * All registers that have been spilled on the stack in the slots within the
5066 * read offsets are marked as read.
5068 static int check_stack_range_initialized(
5069 struct bpf_verifier_env *env, int regno, int off,
5070 int access_size, bool zero_size_allowed,
5071 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5073 struct bpf_reg_state *reg = reg_state(env, regno);
5074 struct bpf_func_state *state = func(env, reg);
5075 int err, min_off, max_off, i, j, slot, spi;
5076 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5077 enum bpf_access_type bounds_check_type;
5078 /* Some accesses can write anything into the stack, others are
5081 bool clobber = false;
5083 if (access_size == 0 && !zero_size_allowed) {
5084 verbose(env, "invalid zero-sized read\n");
5088 if (type == ACCESS_HELPER) {
5089 /* The bounds checks for writes are more permissive than for
5090 * reads. However, if raw_mode is not set, we'll do extra
5093 bounds_check_type = BPF_WRITE;
5096 bounds_check_type = BPF_READ;
5098 err = check_stack_access_within_bounds(env, regno, off, access_size,
5099 type, bounds_check_type);
5104 if (tnum_is_const(reg->var_off)) {
5105 min_off = max_off = reg->var_off.value + off;
5107 /* Variable offset is prohibited for unprivileged mode for
5108 * simplicity since it requires corresponding support in
5109 * Spectre masking for stack ALU.
5110 * See also retrieve_ptr_limit().
5112 if (!env->bypass_spec_v1) {
5115 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5116 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5117 regno, err_extra, tn_buf);
5120 /* Only initialized buffer on stack is allowed to be accessed
5121 * with variable offset. With uninitialized buffer it's hard to
5122 * guarantee that whole memory is marked as initialized on
5123 * helper return since specific bounds are unknown what may
5124 * cause uninitialized stack leaking.
5126 if (meta && meta->raw_mode)
5129 min_off = reg->smin_value + off;
5130 max_off = reg->smax_value + off;
5133 if (meta && meta->raw_mode) {
5134 meta->access_size = access_size;
5135 meta->regno = regno;
5139 for (i = min_off; i < max_off + access_size; i++) {
5143 spi = slot / BPF_REG_SIZE;
5144 if (state->allocated_stack <= slot)
5146 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5147 if (*stype == STACK_MISC)
5149 if (*stype == STACK_ZERO) {
5151 /* helper can write anything into the stack */
5152 *stype = STACK_MISC;
5157 if (is_spilled_reg(&state->stack[spi]) &&
5158 base_type(state->stack[spi].spilled_ptr.type) == PTR_TO_BTF_ID)
5161 if (is_spilled_reg(&state->stack[spi]) &&
5162 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5163 env->allow_ptr_leaks)) {
5165 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5166 for (j = 0; j < BPF_REG_SIZE; j++)
5167 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5173 if (tnum_is_const(reg->var_off)) {
5174 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5175 err_extra, regno, min_off, i - min_off, access_size);
5179 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5180 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5181 err_extra, regno, tn_buf, i - min_off, access_size);
5185 /* reading any byte out of 8-byte 'spill_slot' will cause
5186 * the whole slot to be marked as 'read'
5188 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5189 state->stack[spi].spilled_ptr.parent,
5192 return update_stack_depth(env, state, min_off);
5195 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5196 int access_size, bool zero_size_allowed,
5197 struct bpf_call_arg_meta *meta)
5199 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5202 switch (base_type(reg->type)) {
5204 case PTR_TO_PACKET_META:
5205 return check_packet_access(env, regno, reg->off, access_size,
5207 case PTR_TO_MAP_KEY:
5208 if (meta && meta->raw_mode) {
5209 verbose(env, "R%d cannot write into %s\n", regno,
5210 reg_type_str(env, reg->type));
5213 return check_mem_region_access(env, regno, reg->off, access_size,
5214 reg->map_ptr->key_size, false);
5215 case PTR_TO_MAP_VALUE:
5216 if (check_map_access_type(env, regno, reg->off, access_size,
5217 meta && meta->raw_mode ? BPF_WRITE :
5220 return check_map_access(env, regno, reg->off, access_size,
5221 zero_size_allowed, ACCESS_HELPER);
5223 if (type_is_rdonly_mem(reg->type)) {
5224 if (meta && meta->raw_mode) {
5225 verbose(env, "R%d cannot write into %s\n", regno,
5226 reg_type_str(env, reg->type));
5230 return check_mem_region_access(env, regno, reg->off,
5231 access_size, reg->mem_size,
5234 if (type_is_rdonly_mem(reg->type)) {
5235 if (meta && meta->raw_mode) {
5236 verbose(env, "R%d cannot write into %s\n", regno,
5237 reg_type_str(env, reg->type));
5241 max_access = &env->prog->aux->max_rdonly_access;
5243 max_access = &env->prog->aux->max_rdwr_access;
5245 return check_buffer_access(env, reg, regno, reg->off,
5246 access_size, zero_size_allowed,
5249 return check_stack_range_initialized(
5251 regno, reg->off, access_size,
5252 zero_size_allowed, ACCESS_HELPER, meta);
5254 /* in case the function doesn't know how to access the context,
5255 * (because we are in a program of type SYSCALL for example), we
5256 * can not statically check its size.
5257 * Dynamically check it now.
5259 if (!env->ops->convert_ctx_access) {
5260 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5261 int offset = access_size - 1;
5263 /* Allow zero-byte read from PTR_TO_CTX */
5264 if (access_size == 0)
5265 return zero_size_allowed ? 0 : -EACCES;
5267 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5272 default: /* scalar_value or invalid ptr */
5273 /* Allow zero-byte read from NULL, regardless of pointer type */
5274 if (zero_size_allowed && access_size == 0 &&
5275 register_is_null(reg))
5278 verbose(env, "R%d type=%s ", regno,
5279 reg_type_str(env, reg->type));
5280 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5285 static int check_mem_size_reg(struct bpf_verifier_env *env,
5286 struct bpf_reg_state *reg, u32 regno,
5287 bool zero_size_allowed,
5288 struct bpf_call_arg_meta *meta)
5292 /* This is used to refine r0 return value bounds for helpers
5293 * that enforce this value as an upper bound on return values.
5294 * See do_refine_retval_range() for helpers that can refine
5295 * the return value. C type of helper is u32 so we pull register
5296 * bound from umax_value however, if negative verifier errors
5297 * out. Only upper bounds can be learned because retval is an
5298 * int type and negative retvals are allowed.
5300 meta->msize_max_value = reg->umax_value;
5302 /* The register is SCALAR_VALUE; the access check
5303 * happens using its boundaries.
5305 if (!tnum_is_const(reg->var_off))
5306 /* For unprivileged variable accesses, disable raw
5307 * mode so that the program is required to
5308 * initialize all the memory that the helper could
5309 * just partially fill up.
5313 if (reg->smin_value < 0) {
5314 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5319 if (reg->umin_value == 0) {
5320 err = check_helper_mem_access(env, regno - 1, 0,
5327 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5328 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5332 err = check_helper_mem_access(env, regno - 1,
5334 zero_size_allowed, meta);
5336 err = mark_chain_precision(env, regno);
5340 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5341 u32 regno, u32 mem_size)
5343 bool may_be_null = type_may_be_null(reg->type);
5344 struct bpf_reg_state saved_reg;
5345 struct bpf_call_arg_meta meta;
5348 if (register_is_null(reg))
5351 memset(&meta, 0, sizeof(meta));
5352 /* Assuming that the register contains a value check if the memory
5353 * access is safe. Temporarily save and restore the register's state as
5354 * the conversion shouldn't be visible to a caller.
5358 mark_ptr_not_null_reg(reg);
5361 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5362 /* Check access for BPF_WRITE */
5363 meta.raw_mode = true;
5364 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5372 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5375 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5376 bool may_be_null = type_may_be_null(mem_reg->type);
5377 struct bpf_reg_state saved_reg;
5378 struct bpf_call_arg_meta meta;
5381 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5383 memset(&meta, 0, sizeof(meta));
5386 saved_reg = *mem_reg;
5387 mark_ptr_not_null_reg(mem_reg);
5390 err = check_mem_size_reg(env, reg, regno, true, &meta);
5391 /* Check access for BPF_WRITE */
5392 meta.raw_mode = true;
5393 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5396 *mem_reg = saved_reg;
5400 /* Implementation details:
5401 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5402 * Two bpf_map_lookups (even with the same key) will have different reg->id.
5403 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5404 * value_or_null->value transition, since the verifier only cares about
5405 * the range of access to valid map value pointer and doesn't care about actual
5406 * address of the map element.
5407 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5408 * reg->id > 0 after value_or_null->value transition. By doing so
5409 * two bpf_map_lookups will be considered two different pointers that
5410 * point to different bpf_spin_locks.
5411 * The verifier allows taking only one bpf_spin_lock at a time to avoid
5413 * Since only one bpf_spin_lock is allowed the checks are simpler than
5414 * reg_is_refcounted() logic. The verifier needs to remember only
5415 * one spin_lock instead of array of acquired_refs.
5416 * cur_state->active_spin_lock remembers which map value element got locked
5417 * and clears it after bpf_spin_unlock.
5419 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5422 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5423 struct bpf_verifier_state *cur = env->cur_state;
5424 bool is_const = tnum_is_const(reg->var_off);
5425 struct bpf_map *map = reg->map_ptr;
5426 u64 val = reg->var_off.value;
5430 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5436 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5440 if (!map_value_has_spin_lock(map)) {
5441 if (map->spin_lock_off == -E2BIG)
5443 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5445 else if (map->spin_lock_off == -ENOENT)
5447 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5451 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5455 if (map->spin_lock_off != val + reg->off) {
5456 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5461 if (cur->active_spin_lock) {
5463 "Locking two bpf_spin_locks are not allowed\n");
5466 cur->active_spin_lock = reg->id;
5468 if (!cur->active_spin_lock) {
5469 verbose(env, "bpf_spin_unlock without taking a lock\n");
5472 if (cur->active_spin_lock != reg->id) {
5473 verbose(env, "bpf_spin_unlock of different lock\n");
5476 cur->active_spin_lock = 0;
5481 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5482 struct bpf_call_arg_meta *meta)
5484 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5485 bool is_const = tnum_is_const(reg->var_off);
5486 struct bpf_map *map = reg->map_ptr;
5487 u64 val = reg->var_off.value;
5491 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5496 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5500 if (!map_value_has_timer(map)) {
5501 if (map->timer_off == -E2BIG)
5503 "map '%s' has more than one 'struct bpf_timer'\n",
5505 else if (map->timer_off == -ENOENT)
5507 "map '%s' doesn't have 'struct bpf_timer'\n",
5511 "map '%s' is not a struct type or bpf_timer is mangled\n",
5515 if (map->timer_off != val + reg->off) {
5516 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5517 val + reg->off, map->timer_off);
5520 if (meta->map_ptr) {
5521 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5524 meta->map_uid = reg->map_uid;
5525 meta->map_ptr = map;
5529 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5530 struct bpf_call_arg_meta *meta)
5532 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5533 struct bpf_map_value_off_desc *off_desc;
5534 struct bpf_map *map_ptr = reg->map_ptr;
5538 if (!tnum_is_const(reg->var_off)) {
5540 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5544 if (!map_ptr->btf) {
5545 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5549 if (!map_value_has_kptrs(map_ptr)) {
5550 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5552 verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5553 BPF_MAP_VALUE_OFF_MAX);
5554 else if (ret == -EEXIST)
5555 verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5557 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5561 meta->map_ptr = map_ptr;
5562 kptr_off = reg->off + reg->var_off.value;
5563 off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5565 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5568 if (off_desc->type != BPF_KPTR_REF) {
5569 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5572 meta->kptr_off_desc = off_desc;
5576 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5578 return type == ARG_CONST_SIZE ||
5579 type == ARG_CONST_SIZE_OR_ZERO;
5582 static bool arg_type_is_release(enum bpf_arg_type type)
5584 return type & OBJ_RELEASE;
5587 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5589 return base_type(type) == ARG_PTR_TO_DYNPTR;
5592 static int int_ptr_type_to_size(enum bpf_arg_type type)
5594 if (type == ARG_PTR_TO_INT)
5596 else if (type == ARG_PTR_TO_LONG)
5602 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5603 const struct bpf_call_arg_meta *meta,
5604 enum bpf_arg_type *arg_type)
5606 if (!meta->map_ptr) {
5607 /* kernel subsystem misconfigured verifier */
5608 verbose(env, "invalid map_ptr to access map->type\n");
5612 switch (meta->map_ptr->map_type) {
5613 case BPF_MAP_TYPE_SOCKMAP:
5614 case BPF_MAP_TYPE_SOCKHASH:
5615 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5616 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5618 verbose(env, "invalid arg_type for sockmap/sockhash\n");
5622 case BPF_MAP_TYPE_BLOOM_FILTER:
5623 if (meta->func_id == BPF_FUNC_map_peek_elem)
5624 *arg_type = ARG_PTR_TO_MAP_VALUE;
5632 struct bpf_reg_types {
5633 const enum bpf_reg_type types[10];
5637 static const struct bpf_reg_types map_key_value_types = {
5647 static const struct bpf_reg_types sock_types = {
5657 static const struct bpf_reg_types btf_id_sock_common_types = {
5665 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5669 static const struct bpf_reg_types mem_types = {
5677 PTR_TO_MEM | MEM_ALLOC,
5682 static const struct bpf_reg_types int_ptr_types = {
5692 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5693 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5694 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5695 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5696 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5697 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5698 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5699 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5700 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5701 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5702 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5703 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5704 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5705 static const struct bpf_reg_types dynptr_types = {
5708 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5712 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5713 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
5714 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
5715 [ARG_CONST_SIZE] = &scalar_types,
5716 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
5717 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
5718 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
5719 [ARG_PTR_TO_CTX] = &context_types,
5720 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
5722 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5724 [ARG_PTR_TO_SOCKET] = &fullsock_types,
5725 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
5726 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
5727 [ARG_PTR_TO_MEM] = &mem_types,
5728 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
5729 [ARG_PTR_TO_INT] = &int_ptr_types,
5730 [ARG_PTR_TO_LONG] = &int_ptr_types,
5731 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
5732 [ARG_PTR_TO_FUNC] = &func_ptr_types,
5733 [ARG_PTR_TO_STACK] = &stack_ptr_types,
5734 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
5735 [ARG_PTR_TO_TIMER] = &timer_types,
5736 [ARG_PTR_TO_KPTR] = &kptr_types,
5737 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
5740 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5741 enum bpf_arg_type arg_type,
5742 const u32 *arg_btf_id,
5743 struct bpf_call_arg_meta *meta)
5745 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5746 enum bpf_reg_type expected, type = reg->type;
5747 const struct bpf_reg_types *compatible;
5750 compatible = compatible_reg_types[base_type(arg_type)];
5752 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5756 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5757 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5759 * Same for MAYBE_NULL:
5761 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5762 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5764 * Therefore we fold these flags depending on the arg_type before comparison.
5766 if (arg_type & MEM_RDONLY)
5767 type &= ~MEM_RDONLY;
5768 if (arg_type & PTR_MAYBE_NULL)
5769 type &= ~PTR_MAYBE_NULL;
5771 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5772 expected = compatible->types[i];
5773 if (expected == NOT_INIT)
5776 if (type == expected)
5780 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5781 for (j = 0; j + 1 < i; j++)
5782 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5783 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5787 if (reg->type == PTR_TO_BTF_ID) {
5788 /* For bpf_sk_release, it needs to match against first member
5789 * 'struct sock_common', hence make an exception for it. This
5790 * allows bpf_sk_release to work for multiple socket types.
5792 bool strict_type_match = arg_type_is_release(arg_type) &&
5793 meta->func_id != BPF_FUNC_sk_release;
5796 if (!compatible->btf_id) {
5797 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5800 arg_btf_id = compatible->btf_id;
5803 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5804 if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5807 if (arg_btf_id == BPF_PTR_POISON) {
5808 verbose(env, "verifier internal error:");
5809 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5814 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5815 btf_vmlinux, *arg_btf_id,
5816 strict_type_match)) {
5817 verbose(env, "R%d is of type %s but %s is expected\n",
5818 regno, kernel_type_name(reg->btf, reg->btf_id),
5819 kernel_type_name(btf_vmlinux, *arg_btf_id));
5828 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5829 const struct bpf_reg_state *reg, int regno,
5830 enum bpf_arg_type arg_type)
5832 enum bpf_reg_type type = reg->type;
5833 bool fixed_off_ok = false;
5835 switch ((u32)type) {
5836 /* Pointer types where reg offset is explicitly allowed: */
5838 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5839 verbose(env, "cannot pass in dynptr at an offset\n");
5844 case PTR_TO_PACKET_META:
5845 case PTR_TO_MAP_KEY:
5846 case PTR_TO_MAP_VALUE:
5848 case PTR_TO_MEM | MEM_RDONLY:
5849 case PTR_TO_MEM | MEM_ALLOC:
5851 case PTR_TO_BUF | MEM_RDONLY:
5853 /* Some of the argument types nevertheless require a
5854 * zero register offset.
5856 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5859 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5863 /* When referenced PTR_TO_BTF_ID is passed to release function,
5864 * it's fixed offset must be 0. In the other cases, fixed offset
5867 if (arg_type_is_release(arg_type) && reg->off) {
5868 verbose(env, "R%d must have zero offset when passed to release func\n",
5872 /* For arg is release pointer, fixed_off_ok must be false, but
5873 * we already checked and rejected reg->off != 0 above, so set
5874 * to true to allow fixed offset for all other cases.
5876 fixed_off_ok = true;
5881 return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5884 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5886 struct bpf_func_state *state = func(env, reg);
5887 int spi = get_spi(reg->off);
5889 return state->stack[spi].spilled_ptr.id;
5892 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5893 struct bpf_call_arg_meta *meta,
5894 const struct bpf_func_proto *fn)
5896 u32 regno = BPF_REG_1 + arg;
5897 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5898 enum bpf_arg_type arg_type = fn->arg_type[arg];
5899 enum bpf_reg_type type = reg->type;
5900 u32 *arg_btf_id = NULL;
5903 if (arg_type == ARG_DONTCARE)
5906 err = check_reg_arg(env, regno, SRC_OP);
5910 if (arg_type == ARG_ANYTHING) {
5911 if (is_pointer_value(env, regno)) {
5912 verbose(env, "R%d leaks addr into helper function\n",
5919 if (type_is_pkt_pointer(type) &&
5920 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5921 verbose(env, "helper access to the packet is not allowed\n");
5925 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5926 err = resolve_map_arg_type(env, meta, &arg_type);
5931 if (register_is_null(reg) && type_may_be_null(arg_type))
5932 /* A NULL register has a SCALAR_VALUE type, so skip
5935 goto skip_type_check;
5937 /* arg_btf_id and arg_size are in a union. */
5938 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5939 arg_btf_id = fn->arg_btf_id[arg];
5941 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5945 err = check_func_arg_reg_off(env, reg, regno, arg_type);
5950 if (arg_type_is_release(arg_type)) {
5951 if (arg_type_is_dynptr(arg_type)) {
5952 struct bpf_func_state *state = func(env, reg);
5953 int spi = get_spi(reg->off);
5955 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
5956 !state->stack[spi].spilled_ptr.id) {
5957 verbose(env, "arg %d is an unacquired reference\n", regno);
5960 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
5961 verbose(env, "R%d must be referenced when passed to release function\n",
5965 if (meta->release_regno) {
5966 verbose(env, "verifier internal error: more than one release argument\n");
5969 meta->release_regno = regno;
5972 if (reg->ref_obj_id) {
5973 if (meta->ref_obj_id) {
5974 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5975 regno, reg->ref_obj_id,
5979 meta->ref_obj_id = reg->ref_obj_id;
5982 switch (base_type(arg_type)) {
5983 case ARG_CONST_MAP_PTR:
5984 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5985 if (meta->map_ptr) {
5986 /* Use map_uid (which is unique id of inner map) to reject:
5987 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5988 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5989 * if (inner_map1 && inner_map2) {
5990 * timer = bpf_map_lookup_elem(inner_map1);
5992 * // mismatch would have been allowed
5993 * bpf_timer_init(timer, inner_map2);
5996 * Comparing map_ptr is enough to distinguish normal and outer maps.
5998 if (meta->map_ptr != reg->map_ptr ||
5999 meta->map_uid != reg->map_uid) {
6001 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6002 meta->map_uid, reg->map_uid);
6006 meta->map_ptr = reg->map_ptr;
6007 meta->map_uid = reg->map_uid;
6009 case ARG_PTR_TO_MAP_KEY:
6010 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6011 * check that [key, key + map->key_size) are within
6012 * stack limits and initialized
6014 if (!meta->map_ptr) {
6015 /* in function declaration map_ptr must come before
6016 * map_key, so that it's verified and known before
6017 * we have to check map_key here. Otherwise it means
6018 * that kernel subsystem misconfigured verifier
6020 verbose(env, "invalid map_ptr to access map->key\n");
6023 err = check_helper_mem_access(env, regno,
6024 meta->map_ptr->key_size, false,
6027 case ARG_PTR_TO_MAP_VALUE:
6028 if (type_may_be_null(arg_type) && register_is_null(reg))
6031 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6032 * check [value, value + map->value_size) validity
6034 if (!meta->map_ptr) {
6035 /* kernel subsystem misconfigured verifier */
6036 verbose(env, "invalid map_ptr to access map->value\n");
6039 meta->raw_mode = arg_type & MEM_UNINIT;
6040 err = check_helper_mem_access(env, regno,
6041 meta->map_ptr->value_size, false,
6044 case ARG_PTR_TO_PERCPU_BTF_ID:
6046 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6049 meta->ret_btf = reg->btf;
6050 meta->ret_btf_id = reg->btf_id;
6052 case ARG_PTR_TO_SPIN_LOCK:
6053 if (meta->func_id == BPF_FUNC_spin_lock) {
6054 if (process_spin_lock(env, regno, true))
6056 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6057 if (process_spin_lock(env, regno, false))
6060 verbose(env, "verifier internal error\n");
6064 case ARG_PTR_TO_TIMER:
6065 if (process_timer_func(env, regno, meta))
6068 case ARG_PTR_TO_FUNC:
6069 meta->subprogno = reg->subprogno;
6071 case ARG_PTR_TO_MEM:
6072 /* The access to this pointer is only checked when we hit the
6073 * next is_mem_size argument below.
6075 meta->raw_mode = arg_type & MEM_UNINIT;
6076 if (arg_type & MEM_FIXED_SIZE) {
6077 err = check_helper_mem_access(env, regno,
6078 fn->arg_size[arg], false,
6082 case ARG_CONST_SIZE:
6083 err = check_mem_size_reg(env, reg, regno, false, meta);
6085 case ARG_CONST_SIZE_OR_ZERO:
6086 err = check_mem_size_reg(env, reg, regno, true, meta);
6088 case ARG_PTR_TO_DYNPTR:
6089 /* We only need to check for initialized / uninitialized helper
6090 * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6091 * assumption is that if it is, that a helper function
6092 * initialized the dynptr on behalf of the BPF program.
6094 if (base_type(reg->type) == PTR_TO_DYNPTR)
6096 if (arg_type & MEM_UNINIT) {
6097 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6098 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6102 /* We only support one dynptr being uninitialized at the moment,
6103 * which is sufficient for the helper functions we have right now.
6105 if (meta->uninit_dynptr_regno) {
6106 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6110 meta->uninit_dynptr_regno = regno;
6111 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6113 "Expected an initialized dynptr as arg #%d\n",
6116 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6117 const char *err_extra = "";
6119 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6120 case DYNPTR_TYPE_LOCAL:
6121 err_extra = "local";
6123 case DYNPTR_TYPE_RINGBUF:
6124 err_extra = "ringbuf";
6127 err_extra = "<unknown>";
6131 "Expected a dynptr of type %s as arg #%d\n",
6132 err_extra, arg + 1);
6136 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6137 if (!tnum_is_const(reg->var_off)) {
6138 verbose(env, "R%d is not a known constant'\n",
6142 meta->mem_size = reg->var_off.value;
6143 err = mark_chain_precision(env, regno);
6147 case ARG_PTR_TO_INT:
6148 case ARG_PTR_TO_LONG:
6150 int size = int_ptr_type_to_size(arg_type);
6152 err = check_helper_mem_access(env, regno, size, false, meta);
6155 err = check_ptr_alignment(env, reg, 0, size, true);
6158 case ARG_PTR_TO_CONST_STR:
6160 struct bpf_map *map = reg->map_ptr;
6165 if (!bpf_map_is_rdonly(map)) {
6166 verbose(env, "R%d does not point to a readonly map'\n", regno);
6170 if (!tnum_is_const(reg->var_off)) {
6171 verbose(env, "R%d is not a constant address'\n", regno);
6175 if (!map->ops->map_direct_value_addr) {
6176 verbose(env, "no direct value access support for this map type\n");
6180 err = check_map_access(env, regno, reg->off,
6181 map->value_size - reg->off, false,
6186 map_off = reg->off + reg->var_off.value;
6187 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6189 verbose(env, "direct value access on string failed\n");
6193 str_ptr = (char *)(long)(map_addr);
6194 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6195 verbose(env, "string is not zero-terminated\n");
6200 case ARG_PTR_TO_KPTR:
6201 if (process_kptr_func(env, regno, meta))
6209 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6211 enum bpf_attach_type eatype = env->prog->expected_attach_type;
6212 enum bpf_prog_type type = resolve_prog_type(env->prog);
6214 if (func_id != BPF_FUNC_map_update_elem)
6217 /* It's not possible to get access to a locked struct sock in these
6218 * contexts, so updating is safe.
6221 case BPF_PROG_TYPE_TRACING:
6222 if (eatype == BPF_TRACE_ITER)
6225 case BPF_PROG_TYPE_SOCKET_FILTER:
6226 case BPF_PROG_TYPE_SCHED_CLS:
6227 case BPF_PROG_TYPE_SCHED_ACT:
6228 case BPF_PROG_TYPE_XDP:
6229 case BPF_PROG_TYPE_SK_REUSEPORT:
6230 case BPF_PROG_TYPE_FLOW_DISSECTOR:
6231 case BPF_PROG_TYPE_SK_LOOKUP:
6237 verbose(env, "cannot update sockmap in this context\n");
6241 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6243 return env->prog->jit_requested &&
6244 bpf_jit_supports_subprog_tailcalls();
6247 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6248 struct bpf_map *map, int func_id)
6253 /* We need a two way check, first is from map perspective ... */
6254 switch (map->map_type) {
6255 case BPF_MAP_TYPE_PROG_ARRAY:
6256 if (func_id != BPF_FUNC_tail_call)
6259 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6260 if (func_id != BPF_FUNC_perf_event_read &&
6261 func_id != BPF_FUNC_perf_event_output &&
6262 func_id != BPF_FUNC_skb_output &&
6263 func_id != BPF_FUNC_perf_event_read_value &&
6264 func_id != BPF_FUNC_xdp_output)
6267 case BPF_MAP_TYPE_RINGBUF:
6268 if (func_id != BPF_FUNC_ringbuf_output &&
6269 func_id != BPF_FUNC_ringbuf_reserve &&
6270 func_id != BPF_FUNC_ringbuf_query &&
6271 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6272 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6273 func_id != BPF_FUNC_ringbuf_discard_dynptr)
6276 case BPF_MAP_TYPE_USER_RINGBUF:
6277 if (func_id != BPF_FUNC_user_ringbuf_drain)
6280 case BPF_MAP_TYPE_STACK_TRACE:
6281 if (func_id != BPF_FUNC_get_stackid)
6284 case BPF_MAP_TYPE_CGROUP_ARRAY:
6285 if (func_id != BPF_FUNC_skb_under_cgroup &&
6286 func_id != BPF_FUNC_current_task_under_cgroup)
6289 case BPF_MAP_TYPE_CGROUP_STORAGE:
6290 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6291 if (func_id != BPF_FUNC_get_local_storage)
6294 case BPF_MAP_TYPE_DEVMAP:
6295 case BPF_MAP_TYPE_DEVMAP_HASH:
6296 if (func_id != BPF_FUNC_redirect_map &&
6297 func_id != BPF_FUNC_map_lookup_elem)
6300 /* Restrict bpf side of cpumap and xskmap, open when use-cases
6303 case BPF_MAP_TYPE_CPUMAP:
6304 if (func_id != BPF_FUNC_redirect_map)
6307 case BPF_MAP_TYPE_XSKMAP:
6308 if (func_id != BPF_FUNC_redirect_map &&
6309 func_id != BPF_FUNC_map_lookup_elem)
6312 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6313 case BPF_MAP_TYPE_HASH_OF_MAPS:
6314 if (func_id != BPF_FUNC_map_lookup_elem)
6317 case BPF_MAP_TYPE_SOCKMAP:
6318 if (func_id != BPF_FUNC_sk_redirect_map &&
6319 func_id != BPF_FUNC_sock_map_update &&
6320 func_id != BPF_FUNC_map_delete_elem &&
6321 func_id != BPF_FUNC_msg_redirect_map &&
6322 func_id != BPF_FUNC_sk_select_reuseport &&
6323 func_id != BPF_FUNC_map_lookup_elem &&
6324 !may_update_sockmap(env, func_id))
6327 case BPF_MAP_TYPE_SOCKHASH:
6328 if (func_id != BPF_FUNC_sk_redirect_hash &&
6329 func_id != BPF_FUNC_sock_hash_update &&
6330 func_id != BPF_FUNC_map_delete_elem &&
6331 func_id != BPF_FUNC_msg_redirect_hash &&
6332 func_id != BPF_FUNC_sk_select_reuseport &&
6333 func_id != BPF_FUNC_map_lookup_elem &&
6334 !may_update_sockmap(env, func_id))
6337 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6338 if (func_id != BPF_FUNC_sk_select_reuseport)
6341 case BPF_MAP_TYPE_QUEUE:
6342 case BPF_MAP_TYPE_STACK:
6343 if (func_id != BPF_FUNC_map_peek_elem &&
6344 func_id != BPF_FUNC_map_pop_elem &&
6345 func_id != BPF_FUNC_map_push_elem)
6348 case BPF_MAP_TYPE_SK_STORAGE:
6349 if (func_id != BPF_FUNC_sk_storage_get &&
6350 func_id != BPF_FUNC_sk_storage_delete)
6353 case BPF_MAP_TYPE_INODE_STORAGE:
6354 if (func_id != BPF_FUNC_inode_storage_get &&
6355 func_id != BPF_FUNC_inode_storage_delete)
6358 case BPF_MAP_TYPE_TASK_STORAGE:
6359 if (func_id != BPF_FUNC_task_storage_get &&
6360 func_id != BPF_FUNC_task_storage_delete)
6363 case BPF_MAP_TYPE_BLOOM_FILTER:
6364 if (func_id != BPF_FUNC_map_peek_elem &&
6365 func_id != BPF_FUNC_map_push_elem)
6372 /* ... and second from the function itself. */
6374 case BPF_FUNC_tail_call:
6375 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6377 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6378 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6382 case BPF_FUNC_perf_event_read:
6383 case BPF_FUNC_perf_event_output:
6384 case BPF_FUNC_perf_event_read_value:
6385 case BPF_FUNC_skb_output:
6386 case BPF_FUNC_xdp_output:
6387 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6390 case BPF_FUNC_ringbuf_output:
6391 case BPF_FUNC_ringbuf_reserve:
6392 case BPF_FUNC_ringbuf_query:
6393 case BPF_FUNC_ringbuf_reserve_dynptr:
6394 case BPF_FUNC_ringbuf_submit_dynptr:
6395 case BPF_FUNC_ringbuf_discard_dynptr:
6396 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6399 case BPF_FUNC_user_ringbuf_drain:
6400 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6403 case BPF_FUNC_get_stackid:
6404 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6407 case BPF_FUNC_current_task_under_cgroup:
6408 case BPF_FUNC_skb_under_cgroup:
6409 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6412 case BPF_FUNC_redirect_map:
6413 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6414 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6415 map->map_type != BPF_MAP_TYPE_CPUMAP &&
6416 map->map_type != BPF_MAP_TYPE_XSKMAP)
6419 case BPF_FUNC_sk_redirect_map:
6420 case BPF_FUNC_msg_redirect_map:
6421 case BPF_FUNC_sock_map_update:
6422 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6425 case BPF_FUNC_sk_redirect_hash:
6426 case BPF_FUNC_msg_redirect_hash:
6427 case BPF_FUNC_sock_hash_update:
6428 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6431 case BPF_FUNC_get_local_storage:
6432 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6433 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6436 case BPF_FUNC_sk_select_reuseport:
6437 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6438 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6439 map->map_type != BPF_MAP_TYPE_SOCKHASH)
6442 case BPF_FUNC_map_pop_elem:
6443 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6444 map->map_type != BPF_MAP_TYPE_STACK)
6447 case BPF_FUNC_map_peek_elem:
6448 case BPF_FUNC_map_push_elem:
6449 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6450 map->map_type != BPF_MAP_TYPE_STACK &&
6451 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6454 case BPF_FUNC_map_lookup_percpu_elem:
6455 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6456 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6457 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6460 case BPF_FUNC_sk_storage_get:
6461 case BPF_FUNC_sk_storage_delete:
6462 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6465 case BPF_FUNC_inode_storage_get:
6466 case BPF_FUNC_inode_storage_delete:
6467 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6470 case BPF_FUNC_task_storage_get:
6471 case BPF_FUNC_task_storage_delete:
6472 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6481 verbose(env, "cannot pass map_type %d into func %s#%d\n",
6482 map->map_type, func_id_name(func_id), func_id);
6486 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6490 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6492 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6494 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6496 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6498 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6501 /* We only support one arg being in raw mode at the moment,
6502 * which is sufficient for the helper functions we have
6508 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6510 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6511 bool has_size = fn->arg_size[arg] != 0;
6512 bool is_next_size = false;
6514 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6515 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6517 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6518 return is_next_size;
6520 return has_size == is_next_size || is_next_size == is_fixed;
6523 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6525 /* bpf_xxx(..., buf, len) call will access 'len'
6526 * bytes from memory 'buf'. Both arg types need
6527 * to be paired, so make sure there's no buggy
6528 * helper function specification.
6530 if (arg_type_is_mem_size(fn->arg1_type) ||
6531 check_args_pair_invalid(fn, 0) ||
6532 check_args_pair_invalid(fn, 1) ||
6533 check_args_pair_invalid(fn, 2) ||
6534 check_args_pair_invalid(fn, 3) ||
6535 check_args_pair_invalid(fn, 4))
6541 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6545 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6546 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6549 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6550 /* arg_btf_id and arg_size are in a union. */
6551 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6552 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6559 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6561 return check_raw_mode_ok(fn) &&
6562 check_arg_pair_ok(fn) &&
6563 check_btf_id_ok(fn) ? 0 : -EINVAL;
6566 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6567 * are now invalid, so turn them into unknown SCALAR_VALUE.
6569 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6571 struct bpf_func_state *state;
6572 struct bpf_reg_state *reg;
6574 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6575 if (reg_is_pkt_pointer_any(reg))
6576 __mark_reg_unknown(env, reg);
6582 BEYOND_PKT_END = -2,
6585 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6587 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6588 struct bpf_reg_state *reg = &state->regs[regn];
6590 if (reg->type != PTR_TO_PACKET)
6591 /* PTR_TO_PACKET_META is not supported yet */
6594 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6595 * How far beyond pkt_end it goes is unknown.
6596 * if (!range_open) it's the case of pkt >= pkt_end
6597 * if (range_open) it's the case of pkt > pkt_end
6598 * hence this pointer is at least 1 byte bigger than pkt_end
6601 reg->range = BEYOND_PKT_END;
6603 reg->range = AT_PKT_END;
6606 /* The pointer with the specified id has released its reference to kernel
6607 * resources. Identify all copies of the same pointer and clear the reference.
6609 static int release_reference(struct bpf_verifier_env *env,
6612 struct bpf_func_state *state;
6613 struct bpf_reg_state *reg;
6616 err = release_reference_state(cur_func(env), ref_obj_id);
6620 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6621 if (reg->ref_obj_id == ref_obj_id)
6622 __mark_reg_unknown(env, reg);
6628 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6629 struct bpf_reg_state *regs)
6633 /* after the call registers r0 - r5 were scratched */
6634 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6635 mark_reg_not_init(env, regs, caller_saved[i]);
6636 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6640 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6641 struct bpf_func_state *caller,
6642 struct bpf_func_state *callee,
6645 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6646 int *insn_idx, int subprog,
6647 set_callee_state_fn set_callee_state_cb)
6649 struct bpf_verifier_state *state = env->cur_state;
6650 struct bpf_func_info_aux *func_info_aux;
6651 struct bpf_func_state *caller, *callee;
6653 bool is_global = false;
6655 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6656 verbose(env, "the call stack of %d frames is too deep\n",
6657 state->curframe + 2);
6661 caller = state->frame[state->curframe];
6662 if (state->frame[state->curframe + 1]) {
6663 verbose(env, "verifier bug. Frame %d already allocated\n",
6664 state->curframe + 1);
6668 func_info_aux = env->prog->aux->func_info_aux;
6670 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6671 err = btf_check_subprog_call(env, subprog, caller->regs);
6676 verbose(env, "Caller passes invalid args into func#%d\n",
6680 if (env->log.level & BPF_LOG_LEVEL)
6682 "Func#%d is global and valid. Skipping.\n",
6684 clear_caller_saved_regs(env, caller->regs);
6686 /* All global functions return a 64-bit SCALAR_VALUE */
6687 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6688 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6690 /* continue with next insn after call */
6695 if (insn->code == (BPF_JMP | BPF_CALL) &&
6696 insn->src_reg == 0 &&
6697 insn->imm == BPF_FUNC_timer_set_callback) {
6698 struct bpf_verifier_state *async_cb;
6700 /* there is no real recursion here. timer callbacks are async */
6701 env->subprog_info[subprog].is_async_cb = true;
6702 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6703 *insn_idx, subprog);
6706 callee = async_cb->frame[0];
6707 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6709 /* Convert bpf_timer_set_callback() args into timer callback args */
6710 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6714 clear_caller_saved_regs(env, caller->regs);
6715 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6716 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6717 /* continue with next insn after call */
6721 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6724 state->frame[state->curframe + 1] = callee;
6726 /* callee cannot access r0, r6 - r9 for reading and has to write
6727 * into its own stack before reading from it.
6728 * callee can read/write into caller's stack
6730 init_func_state(env, callee,
6731 /* remember the callsite, it will be used by bpf_exit */
6732 *insn_idx /* callsite */,
6733 state->curframe + 1 /* frameno within this callchain */,
6734 subprog /* subprog number within this prog */);
6736 /* Transfer references to the callee */
6737 err = copy_reference_state(callee, caller);
6741 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6745 clear_caller_saved_regs(env, caller->regs);
6747 /* only increment it after check_reg_arg() finished */
6750 /* and go analyze first insn of the callee */
6751 *insn_idx = env->subprog_info[subprog].start - 1;
6753 if (env->log.level & BPF_LOG_LEVEL) {
6754 verbose(env, "caller:\n");
6755 print_verifier_state(env, caller, true);
6756 verbose(env, "callee:\n");
6757 print_verifier_state(env, callee, true);
6762 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6763 struct bpf_func_state *caller,
6764 struct bpf_func_state *callee)
6766 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6767 * void *callback_ctx, u64 flags);
6768 * callback_fn(struct bpf_map *map, void *key, void *value,
6769 * void *callback_ctx);
6771 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6773 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6774 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6775 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6777 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6778 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6779 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6781 /* pointer to stack or null */
6782 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6785 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6789 static int set_callee_state(struct bpf_verifier_env *env,
6790 struct bpf_func_state *caller,
6791 struct bpf_func_state *callee, int insn_idx)
6795 /* copy r1 - r5 args that callee can access. The copy includes parent
6796 * pointers, which connects us up to the liveness chain
6798 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6799 callee->regs[i] = caller->regs[i];
6803 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6806 int subprog, target_insn;
6808 target_insn = *insn_idx + insn->imm + 1;
6809 subprog = find_subprog(env, target_insn);
6811 verbose(env, "verifier bug. No program starts at insn %d\n",
6816 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6819 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6820 struct bpf_func_state *caller,
6821 struct bpf_func_state *callee,
6824 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6825 struct bpf_map *map;
6828 if (bpf_map_ptr_poisoned(insn_aux)) {
6829 verbose(env, "tail_call abusing map_ptr\n");
6833 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6834 if (!map->ops->map_set_for_each_callback_args ||
6835 !map->ops->map_for_each_callback) {
6836 verbose(env, "callback function not allowed for map\n");
6840 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6844 callee->in_callback_fn = true;
6845 callee->callback_ret_range = tnum_range(0, 1);
6849 static int set_loop_callback_state(struct bpf_verifier_env *env,
6850 struct bpf_func_state *caller,
6851 struct bpf_func_state *callee,
6854 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6856 * callback_fn(u32 index, void *callback_ctx);
6858 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6859 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6862 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6863 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6864 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6866 callee->in_callback_fn = true;
6867 callee->callback_ret_range = tnum_range(0, 1);
6871 static int set_timer_callback_state(struct bpf_verifier_env *env,
6872 struct bpf_func_state *caller,
6873 struct bpf_func_state *callee,
6876 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6878 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6879 * callback_fn(struct bpf_map *map, void *key, void *value);
6881 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6882 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6883 callee->regs[BPF_REG_1].map_ptr = map_ptr;
6885 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6886 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6887 callee->regs[BPF_REG_2].map_ptr = map_ptr;
6889 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6890 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6891 callee->regs[BPF_REG_3].map_ptr = map_ptr;
6894 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6895 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6896 callee->in_async_callback_fn = true;
6897 callee->callback_ret_range = tnum_range(0, 1);
6901 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6902 struct bpf_func_state *caller,
6903 struct bpf_func_state *callee,
6906 /* bpf_find_vma(struct task_struct *task, u64 addr,
6907 * void *callback_fn, void *callback_ctx, u64 flags)
6908 * (callback_fn)(struct task_struct *task,
6909 * struct vm_area_struct *vma, void *callback_ctx);
6911 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6913 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6914 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6915 callee->regs[BPF_REG_2].btf = btf_vmlinux;
6916 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6918 /* pointer to stack or null */
6919 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6922 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6923 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6924 callee->in_callback_fn = true;
6925 callee->callback_ret_range = tnum_range(0, 1);
6929 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
6930 struct bpf_func_state *caller,
6931 struct bpf_func_state *callee,
6934 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
6935 * callback_ctx, u64 flags);
6936 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
6938 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
6939 callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
6940 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6941 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6944 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6945 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6946 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6948 callee->in_callback_fn = true;
6952 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6954 struct bpf_verifier_state *state = env->cur_state;
6955 struct bpf_func_state *caller, *callee;
6956 struct bpf_reg_state *r0;
6959 callee = state->frame[state->curframe];
6960 r0 = &callee->regs[BPF_REG_0];
6961 if (r0->type == PTR_TO_STACK) {
6962 /* technically it's ok to return caller's stack pointer
6963 * (or caller's caller's pointer) back to the caller,
6964 * since these pointers are valid. Only current stack
6965 * pointer will be invalid as soon as function exits,
6966 * but let's be conservative
6968 verbose(env, "cannot return stack pointer to the caller\n");
6973 caller = state->frame[state->curframe];
6974 if (callee->in_callback_fn) {
6975 /* enforce R0 return value range [0, 1]. */
6976 struct tnum range = callee->callback_ret_range;
6978 if (r0->type != SCALAR_VALUE) {
6979 verbose(env, "R0 not a scalar value\n");
6982 if (!tnum_in(range, r0->var_off)) {
6983 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6987 /* return to the caller whatever r0 had in the callee */
6988 caller->regs[BPF_REG_0] = *r0;
6991 /* callback_fn frame should have released its own additions to parent's
6992 * reference state at this point, or check_reference_leak would
6993 * complain, hence it must be the same as the caller. There is no need
6996 if (!callee->in_callback_fn) {
6997 /* Transfer references to the caller */
6998 err = copy_reference_state(caller, callee);
7003 *insn_idx = callee->callsite + 1;
7004 if (env->log.level & BPF_LOG_LEVEL) {
7005 verbose(env, "returning from callee:\n");
7006 print_verifier_state(env, callee, true);
7007 verbose(env, "to caller at %d:\n", *insn_idx);
7008 print_verifier_state(env, caller, true);
7010 /* clear everything in the callee */
7011 free_func_state(callee);
7012 state->frame[state->curframe + 1] = NULL;
7016 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7018 struct bpf_call_arg_meta *meta)
7020 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
7022 if (ret_type != RET_INTEGER ||
7023 (func_id != BPF_FUNC_get_stack &&
7024 func_id != BPF_FUNC_get_task_stack &&
7025 func_id != BPF_FUNC_probe_read_str &&
7026 func_id != BPF_FUNC_probe_read_kernel_str &&
7027 func_id != BPF_FUNC_probe_read_user_str))
7030 ret_reg->smax_value = meta->msize_max_value;
7031 ret_reg->s32_max_value = meta->msize_max_value;
7032 ret_reg->smin_value = -MAX_ERRNO;
7033 ret_reg->s32_min_value = -MAX_ERRNO;
7034 reg_bounds_sync(ret_reg);
7038 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7039 int func_id, int insn_idx)
7041 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7042 struct bpf_map *map = meta->map_ptr;
7044 if (func_id != BPF_FUNC_tail_call &&
7045 func_id != BPF_FUNC_map_lookup_elem &&
7046 func_id != BPF_FUNC_map_update_elem &&
7047 func_id != BPF_FUNC_map_delete_elem &&
7048 func_id != BPF_FUNC_map_push_elem &&
7049 func_id != BPF_FUNC_map_pop_elem &&
7050 func_id != BPF_FUNC_map_peek_elem &&
7051 func_id != BPF_FUNC_for_each_map_elem &&
7052 func_id != BPF_FUNC_redirect_map &&
7053 func_id != BPF_FUNC_map_lookup_percpu_elem)
7057 verbose(env, "kernel subsystem misconfigured verifier\n");
7061 /* In case of read-only, some additional restrictions
7062 * need to be applied in order to prevent altering the
7063 * state of the map from program side.
7065 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7066 (func_id == BPF_FUNC_map_delete_elem ||
7067 func_id == BPF_FUNC_map_update_elem ||
7068 func_id == BPF_FUNC_map_push_elem ||
7069 func_id == BPF_FUNC_map_pop_elem)) {
7070 verbose(env, "write into map forbidden\n");
7074 if (!BPF_MAP_PTR(aux->map_ptr_state))
7075 bpf_map_ptr_store(aux, meta->map_ptr,
7076 !meta->map_ptr->bypass_spec_v1);
7077 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7078 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7079 !meta->map_ptr->bypass_spec_v1);
7084 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7085 int func_id, int insn_idx)
7087 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7088 struct bpf_reg_state *regs = cur_regs(env), *reg;
7089 struct bpf_map *map = meta->map_ptr;
7093 if (func_id != BPF_FUNC_tail_call)
7095 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7096 verbose(env, "kernel subsystem misconfigured verifier\n");
7100 reg = ®s[BPF_REG_3];
7101 val = reg->var_off.value;
7102 max = map->max_entries;
7104 if (!(register_is_const(reg) && val < max)) {
7105 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7109 err = mark_chain_precision(env, BPF_REG_3);
7112 if (bpf_map_key_unseen(aux))
7113 bpf_map_key_store(aux, val);
7114 else if (!bpf_map_key_poisoned(aux) &&
7115 bpf_map_key_immediate(aux) != val)
7116 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7120 static int check_reference_leak(struct bpf_verifier_env *env)
7122 struct bpf_func_state *state = cur_func(env);
7123 bool refs_lingering = false;
7126 if (state->frameno && !state->in_callback_fn)
7129 for (i = 0; i < state->acquired_refs; i++) {
7130 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7132 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7133 state->refs[i].id, state->refs[i].insn_idx);
7134 refs_lingering = true;
7136 return refs_lingering ? -EINVAL : 0;
7139 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7140 struct bpf_reg_state *regs)
7142 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
7143 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
7144 struct bpf_map *fmt_map = fmt_reg->map_ptr;
7145 int err, fmt_map_off, num_args;
7149 /* data must be an array of u64 */
7150 if (data_len_reg->var_off.value % 8)
7152 num_args = data_len_reg->var_off.value / 8;
7154 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7155 * and map_direct_value_addr is set.
7157 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7158 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7161 verbose(env, "verifier bug\n");
7164 fmt = (char *)(long)fmt_addr + fmt_map_off;
7166 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7167 * can focus on validating the format specifiers.
7169 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7171 verbose(env, "Invalid format string\n");
7176 static int check_get_func_ip(struct bpf_verifier_env *env)
7178 enum bpf_prog_type type = resolve_prog_type(env->prog);
7179 int func_id = BPF_FUNC_get_func_ip;
7181 if (type == BPF_PROG_TYPE_TRACING) {
7182 if (!bpf_prog_has_trampoline(env->prog)) {
7183 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7184 func_id_name(func_id), func_id);
7188 } else if (type == BPF_PROG_TYPE_KPROBE) {
7192 verbose(env, "func %s#%d not supported for program type %d\n",
7193 func_id_name(func_id), func_id, type);
7197 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7199 return &env->insn_aux_data[env->insn_idx];
7202 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7204 struct bpf_reg_state *regs = cur_regs(env);
7205 struct bpf_reg_state *reg = ®s[BPF_REG_4];
7206 bool reg_is_null = register_is_null(reg);
7209 mark_chain_precision(env, BPF_REG_4);
7214 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7216 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7218 if (!state->initialized) {
7219 state->initialized = 1;
7220 state->fit_for_inline = loop_flag_is_zero(env);
7221 state->callback_subprogno = subprogno;
7225 if (!state->fit_for_inline)
7228 state->fit_for_inline = (loop_flag_is_zero(env) &&
7229 state->callback_subprogno == subprogno);
7232 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7235 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7236 const struct bpf_func_proto *fn = NULL;
7237 enum bpf_return_type ret_type;
7238 enum bpf_type_flag ret_flag;
7239 struct bpf_reg_state *regs;
7240 struct bpf_call_arg_meta meta;
7241 int insn_idx = *insn_idx_p;
7243 int i, err, func_id;
7245 /* find function prototype */
7246 func_id = insn->imm;
7247 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7248 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7253 if (env->ops->get_func_proto)
7254 fn = env->ops->get_func_proto(func_id, env->prog);
7256 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7261 /* eBPF programs must be GPL compatible to use GPL-ed functions */
7262 if (!env->prog->gpl_compatible && fn->gpl_only) {
7263 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7267 if (fn->allowed && !fn->allowed(env->prog)) {
7268 verbose(env, "helper call is not allowed in probe\n");
7272 /* With LD_ABS/IND some JITs save/restore skb from r1. */
7273 changes_data = bpf_helper_changes_pkt_data(fn->func);
7274 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7275 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7276 func_id_name(func_id), func_id);
7280 memset(&meta, 0, sizeof(meta));
7281 meta.pkt_access = fn->pkt_access;
7283 err = check_func_proto(fn, func_id);
7285 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7286 func_id_name(func_id), func_id);
7290 meta.func_id = func_id;
7292 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7293 err = check_func_arg(env, i, &meta, fn);
7298 err = record_func_map(env, &meta, func_id, insn_idx);
7302 err = record_func_key(env, &meta, func_id, insn_idx);
7306 /* Mark slots with STACK_MISC in case of raw mode, stack offset
7307 * is inferred from register state.
7309 for (i = 0; i < meta.access_size; i++) {
7310 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7311 BPF_WRITE, -1, false);
7316 regs = cur_regs(env);
7318 if (meta.uninit_dynptr_regno) {
7319 /* we write BPF_DW bits (8 bytes) at a time */
7320 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7321 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7322 i, BPF_DW, BPF_WRITE, -1, false);
7327 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno],
7328 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7334 if (meta.release_regno) {
7336 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7337 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
7338 else if (meta.ref_obj_id)
7339 err = release_reference(env, meta.ref_obj_id);
7340 /* meta.ref_obj_id can only be 0 if register that is meant to be
7341 * released is NULL, which must be > R0.
7343 else if (register_is_null(®s[meta.release_regno]))
7346 verbose(env, "func %s#%d reference has not been acquired before\n",
7347 func_id_name(func_id), func_id);
7353 case BPF_FUNC_tail_call:
7354 err = check_reference_leak(env);
7356 verbose(env, "tail_call would lead to reference leak\n");
7360 case BPF_FUNC_get_local_storage:
7361 /* check that flags argument in get_local_storage(map, flags) is 0,
7362 * this is required because get_local_storage() can't return an error.
7364 if (!register_is_null(®s[BPF_REG_2])) {
7365 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7369 case BPF_FUNC_for_each_map_elem:
7370 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7371 set_map_elem_callback_state);
7373 case BPF_FUNC_timer_set_callback:
7374 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7375 set_timer_callback_state);
7377 case BPF_FUNC_find_vma:
7378 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7379 set_find_vma_callback_state);
7381 case BPF_FUNC_snprintf:
7382 err = check_bpf_snprintf_call(env, regs);
7385 update_loop_inline_state(env, meta.subprogno);
7386 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7387 set_loop_callback_state);
7389 case BPF_FUNC_dynptr_from_mem:
7390 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7391 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7392 reg_type_str(env, regs[BPF_REG_1].type));
7396 case BPF_FUNC_set_retval:
7397 if (prog_type == BPF_PROG_TYPE_LSM &&
7398 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7399 if (!env->prog->aux->attach_func_proto->type) {
7400 /* Make sure programs that attach to void
7401 * hooks don't try to modify return value.
7403 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7408 case BPF_FUNC_dynptr_data:
7409 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7410 if (arg_type_is_dynptr(fn->arg_type[i])) {
7411 struct bpf_reg_state *reg = ®s[BPF_REG_1 + i];
7413 if (meta.ref_obj_id) {
7414 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7418 if (base_type(reg->type) != PTR_TO_DYNPTR)
7419 /* Find the id of the dynptr we're
7420 * tracking the reference of
7422 meta.ref_obj_id = stack_slot_get_id(env, reg);
7426 if (i == MAX_BPF_FUNC_REG_ARGS) {
7427 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7431 case BPF_FUNC_user_ringbuf_drain:
7432 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7433 set_user_ringbuf_callback_state);
7440 /* reset caller saved regs */
7441 for (i = 0; i < CALLER_SAVED_REGS; i++) {
7442 mark_reg_not_init(env, regs, caller_saved[i]);
7443 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7446 /* helper call returns 64-bit value. */
7447 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7449 /* update return register (already marked as written above) */
7450 ret_type = fn->ret_type;
7451 ret_flag = type_flag(ret_type);
7453 switch (base_type(ret_type)) {
7455 /* sets type to SCALAR_VALUE */
7456 mark_reg_unknown(env, regs, BPF_REG_0);
7459 regs[BPF_REG_0].type = NOT_INIT;
7461 case RET_PTR_TO_MAP_VALUE:
7462 /* There is no offset yet applied, variable or fixed */
7463 mark_reg_known_zero(env, regs, BPF_REG_0);
7464 /* remember map_ptr, so that check_map_access()
7465 * can check 'value_size' boundary of memory access
7466 * to map element returned from bpf_map_lookup_elem()
7468 if (meta.map_ptr == NULL) {
7470 "kernel subsystem misconfigured verifier\n");
7473 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7474 regs[BPF_REG_0].map_uid = meta.map_uid;
7475 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7476 if (!type_may_be_null(ret_type) &&
7477 map_value_has_spin_lock(meta.map_ptr)) {
7478 regs[BPF_REG_0].id = ++env->id_gen;
7481 case RET_PTR_TO_SOCKET:
7482 mark_reg_known_zero(env, regs, BPF_REG_0);
7483 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7485 case RET_PTR_TO_SOCK_COMMON:
7486 mark_reg_known_zero(env, regs, BPF_REG_0);
7487 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7489 case RET_PTR_TO_TCP_SOCK:
7490 mark_reg_known_zero(env, regs, BPF_REG_0);
7491 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7493 case RET_PTR_TO_ALLOC_MEM:
7494 mark_reg_known_zero(env, regs, BPF_REG_0);
7495 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7496 regs[BPF_REG_0].mem_size = meta.mem_size;
7498 case RET_PTR_TO_MEM_OR_BTF_ID:
7500 const struct btf_type *t;
7502 mark_reg_known_zero(env, regs, BPF_REG_0);
7503 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7504 if (!btf_type_is_struct(t)) {
7506 const struct btf_type *ret;
7509 /* resolve the type size of ksym. */
7510 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7512 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7513 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7514 tname, PTR_ERR(ret));
7517 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7518 regs[BPF_REG_0].mem_size = tsize;
7520 /* MEM_RDONLY may be carried from ret_flag, but it
7521 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7522 * it will confuse the check of PTR_TO_BTF_ID in
7523 * check_mem_access().
7525 ret_flag &= ~MEM_RDONLY;
7527 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7528 regs[BPF_REG_0].btf = meta.ret_btf;
7529 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7533 case RET_PTR_TO_BTF_ID:
7535 struct btf *ret_btf;
7538 mark_reg_known_zero(env, regs, BPF_REG_0);
7539 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7540 if (func_id == BPF_FUNC_kptr_xchg) {
7541 ret_btf = meta.kptr_off_desc->kptr.btf;
7542 ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7544 if (fn->ret_btf_id == BPF_PTR_POISON) {
7545 verbose(env, "verifier internal error:");
7546 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7547 func_id_name(func_id));
7550 ret_btf = btf_vmlinux;
7551 ret_btf_id = *fn->ret_btf_id;
7553 if (ret_btf_id == 0) {
7554 verbose(env, "invalid return type %u of func %s#%d\n",
7555 base_type(ret_type), func_id_name(func_id),
7559 regs[BPF_REG_0].btf = ret_btf;
7560 regs[BPF_REG_0].btf_id = ret_btf_id;
7564 verbose(env, "unknown return type %u of func %s#%d\n",
7565 base_type(ret_type), func_id_name(func_id), func_id);
7569 if (type_may_be_null(regs[BPF_REG_0].type))
7570 regs[BPF_REG_0].id = ++env->id_gen;
7572 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7573 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7574 func_id_name(func_id), func_id);
7578 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7579 /* For release_reference() */
7580 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7581 } else if (is_acquire_function(func_id, meta.map_ptr)) {
7582 int id = acquire_reference_state(env, insn_idx);
7586 /* For mark_ptr_or_null_reg() */
7587 regs[BPF_REG_0].id = id;
7588 /* For release_reference() */
7589 regs[BPF_REG_0].ref_obj_id = id;
7592 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7594 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7598 if ((func_id == BPF_FUNC_get_stack ||
7599 func_id == BPF_FUNC_get_task_stack) &&
7600 !env->prog->has_callchain_buf) {
7601 const char *err_str;
7603 #ifdef CONFIG_PERF_EVENTS
7604 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7605 err_str = "cannot get callchain buffer for func %s#%d\n";
7608 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7611 verbose(env, err_str, func_id_name(func_id), func_id);
7615 env->prog->has_callchain_buf = true;
7618 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7619 env->prog->call_get_stack = true;
7621 if (func_id == BPF_FUNC_get_func_ip) {
7622 if (check_get_func_ip(env))
7624 env->prog->call_get_func_ip = true;
7628 clear_all_pkt_pointers(env);
7632 /* mark_btf_func_reg_size() is used when the reg size is determined by
7633 * the BTF func_proto's return value size and argument.
7635 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7638 struct bpf_reg_state *reg = &cur_regs(env)[regno];
7640 if (regno == BPF_REG_0) {
7641 /* Function return value */
7642 reg->live |= REG_LIVE_WRITTEN;
7643 reg->subreg_def = reg_size == sizeof(u64) ?
7644 DEF_NOT_SUBREG : env->insn_idx + 1;
7646 /* Function argument */
7647 if (reg_size == sizeof(u64)) {
7648 mark_insn_zext(env, reg);
7649 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7651 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7656 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7659 const struct btf_type *t, *func, *func_proto, *ptr_type;
7660 struct bpf_reg_state *regs = cur_regs(env);
7661 struct bpf_kfunc_arg_meta meta = { 0 };
7662 const char *func_name, *ptr_type_name;
7663 u32 i, nargs, func_id, ptr_type_id;
7664 int err, insn_idx = *insn_idx_p;
7665 const struct btf_param *args;
7666 struct btf *desc_btf;
7670 /* skip for now, but return error when we find this in fixup_kfunc_call */
7674 desc_btf = find_kfunc_desc_btf(env, insn->off);
7675 if (IS_ERR(desc_btf))
7676 return PTR_ERR(desc_btf);
7678 func_id = insn->imm;
7679 func = btf_type_by_id(desc_btf, func_id);
7680 func_name = btf_name_by_offset(desc_btf, func->name_off);
7681 func_proto = btf_type_by_id(desc_btf, func->type);
7683 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7685 verbose(env, "calling kernel function %s is not allowed\n",
7689 if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7690 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7694 acq = *kfunc_flags & KF_ACQUIRE;
7696 meta.flags = *kfunc_flags;
7698 /* Check the arguments */
7699 err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7702 /* In case of release function, we get register number of refcounted
7703 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7706 err = release_reference(env, regs[err].ref_obj_id);
7708 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7709 func_name, func_id);
7714 for (i = 0; i < CALLER_SAVED_REGS; i++)
7715 mark_reg_not_init(env, regs, caller_saved[i]);
7717 /* Check return type */
7718 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7720 if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7721 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7725 if (btf_type_is_scalar(t)) {
7726 mark_reg_unknown(env, regs, BPF_REG_0);
7727 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7728 } else if (btf_type_is_ptr(t)) {
7729 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7731 if (!btf_type_is_struct(ptr_type)) {
7732 if (!meta.r0_size) {
7733 ptr_type_name = btf_name_by_offset(desc_btf,
7734 ptr_type->name_off);
7736 "kernel function %s returns pointer type %s %s is not supported\n",
7738 btf_type_str(ptr_type),
7743 mark_reg_known_zero(env, regs, BPF_REG_0);
7744 regs[BPF_REG_0].type = PTR_TO_MEM;
7745 regs[BPF_REG_0].mem_size = meta.r0_size;
7748 regs[BPF_REG_0].type |= MEM_RDONLY;
7750 /* Ensures we don't access the memory after a release_reference() */
7751 if (meta.ref_obj_id)
7752 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7754 mark_reg_known_zero(env, regs, BPF_REG_0);
7755 regs[BPF_REG_0].btf = desc_btf;
7756 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7757 regs[BPF_REG_0].btf_id = ptr_type_id;
7759 if (*kfunc_flags & KF_RET_NULL) {
7760 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7761 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7762 regs[BPF_REG_0].id = ++env->id_gen;
7764 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7766 int id = acquire_reference_state(env, insn_idx);
7770 regs[BPF_REG_0].id = id;
7771 regs[BPF_REG_0].ref_obj_id = id;
7773 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7775 nargs = btf_type_vlen(func_proto);
7776 args = (const struct btf_param *)(func_proto + 1);
7777 for (i = 0; i < nargs; i++) {
7780 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7781 if (btf_type_is_ptr(t))
7782 mark_btf_func_reg_size(env, regno, sizeof(void *));
7784 /* scalar. ensured by btf_check_kfunc_arg_match() */
7785 mark_btf_func_reg_size(env, regno, t->size);
7791 static bool signed_add_overflows(s64 a, s64 b)
7793 /* Do the add in u64, where overflow is well-defined */
7794 s64 res = (s64)((u64)a + (u64)b);
7801 static bool signed_add32_overflows(s32 a, s32 b)
7803 /* Do the add in u32, where overflow is well-defined */
7804 s32 res = (s32)((u32)a + (u32)b);
7811 static bool signed_sub_overflows(s64 a, s64 b)
7813 /* Do the sub in u64, where overflow is well-defined */
7814 s64 res = (s64)((u64)a - (u64)b);
7821 static bool signed_sub32_overflows(s32 a, s32 b)
7823 /* Do the sub in u32, where overflow is well-defined */
7824 s32 res = (s32)((u32)a - (u32)b);
7831 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7832 const struct bpf_reg_state *reg,
7833 enum bpf_reg_type type)
7835 bool known = tnum_is_const(reg->var_off);
7836 s64 val = reg->var_off.value;
7837 s64 smin = reg->smin_value;
7839 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7840 verbose(env, "math between %s pointer and %lld is not allowed\n",
7841 reg_type_str(env, type), val);
7845 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7846 verbose(env, "%s pointer offset %d is not allowed\n",
7847 reg_type_str(env, type), reg->off);
7851 if (smin == S64_MIN) {
7852 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7853 reg_type_str(env, type));
7857 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7858 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7859 smin, reg_type_str(env, type));
7874 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7875 u32 *alu_limit, bool mask_to_left)
7877 u32 max = 0, ptr_limit = 0;
7879 switch (ptr_reg->type) {
7881 /* Offset 0 is out-of-bounds, but acceptable start for the
7882 * left direction, see BPF_REG_FP. Also, unknown scalar
7883 * offset where we would need to deal with min/max bounds is
7884 * currently prohibited for unprivileged.
7886 max = MAX_BPF_STACK + mask_to_left;
7887 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7889 case PTR_TO_MAP_VALUE:
7890 max = ptr_reg->map_ptr->value_size;
7891 ptr_limit = (mask_to_left ?
7892 ptr_reg->smin_value :
7893 ptr_reg->umax_value) + ptr_reg->off;
7899 if (ptr_limit >= max)
7900 return REASON_LIMIT;
7901 *alu_limit = ptr_limit;
7905 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7906 const struct bpf_insn *insn)
7908 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7911 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7912 u32 alu_state, u32 alu_limit)
7914 /* If we arrived here from different branches with different
7915 * state or limits to sanitize, then this won't work.
7917 if (aux->alu_state &&
7918 (aux->alu_state != alu_state ||
7919 aux->alu_limit != alu_limit))
7920 return REASON_PATHS;
7922 /* Corresponding fixup done in do_misc_fixups(). */
7923 aux->alu_state = alu_state;
7924 aux->alu_limit = alu_limit;
7928 static int sanitize_val_alu(struct bpf_verifier_env *env,
7929 struct bpf_insn *insn)
7931 struct bpf_insn_aux_data *aux = cur_aux(env);
7933 if (can_skip_alu_sanitation(env, insn))
7936 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7939 static bool sanitize_needed(u8 opcode)
7941 return opcode == BPF_ADD || opcode == BPF_SUB;
7944 struct bpf_sanitize_info {
7945 struct bpf_insn_aux_data aux;
7949 static struct bpf_verifier_state *
7950 sanitize_speculative_path(struct bpf_verifier_env *env,
7951 const struct bpf_insn *insn,
7952 u32 next_idx, u32 curr_idx)
7954 struct bpf_verifier_state *branch;
7955 struct bpf_reg_state *regs;
7957 branch = push_stack(env, next_idx, curr_idx, true);
7958 if (branch && insn) {
7959 regs = branch->frame[branch->curframe]->regs;
7960 if (BPF_SRC(insn->code) == BPF_K) {
7961 mark_reg_unknown(env, regs, insn->dst_reg);
7962 } else if (BPF_SRC(insn->code) == BPF_X) {
7963 mark_reg_unknown(env, regs, insn->dst_reg);
7964 mark_reg_unknown(env, regs, insn->src_reg);
7970 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7971 struct bpf_insn *insn,
7972 const struct bpf_reg_state *ptr_reg,
7973 const struct bpf_reg_state *off_reg,
7974 struct bpf_reg_state *dst_reg,
7975 struct bpf_sanitize_info *info,
7976 const bool commit_window)
7978 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7979 struct bpf_verifier_state *vstate = env->cur_state;
7980 bool off_is_imm = tnum_is_const(off_reg->var_off);
7981 bool off_is_neg = off_reg->smin_value < 0;
7982 bool ptr_is_dst_reg = ptr_reg == dst_reg;
7983 u8 opcode = BPF_OP(insn->code);
7984 u32 alu_state, alu_limit;
7985 struct bpf_reg_state tmp;
7989 if (can_skip_alu_sanitation(env, insn))
7992 /* We already marked aux for masking from non-speculative
7993 * paths, thus we got here in the first place. We only care
7994 * to explore bad access from here.
7996 if (vstate->speculative)
7999 if (!commit_window) {
8000 if (!tnum_is_const(off_reg->var_off) &&
8001 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8002 return REASON_BOUNDS;
8004 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
8005 (opcode == BPF_SUB && !off_is_neg);
8008 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8012 if (commit_window) {
8013 /* In commit phase we narrow the masking window based on
8014 * the observed pointer move after the simulated operation.
8016 alu_state = info->aux.alu_state;
8017 alu_limit = abs(info->aux.alu_limit - alu_limit);
8019 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8020 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8021 alu_state |= ptr_is_dst_reg ?
8022 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8024 /* Limit pruning on unknown scalars to enable deep search for
8025 * potential masking differences from other program paths.
8028 env->explore_alu_limits = true;
8031 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8035 /* If we're in commit phase, we're done here given we already
8036 * pushed the truncated dst_reg into the speculative verification
8039 * Also, when register is a known constant, we rewrite register-based
8040 * operation to immediate-based, and thus do not need masking (and as
8041 * a consequence, do not need to simulate the zero-truncation either).
8043 if (commit_window || off_is_imm)
8046 /* Simulate and find potential out-of-bounds access under
8047 * speculative execution from truncation as a result of
8048 * masking when off was not within expected range. If off
8049 * sits in dst, then we temporarily need to move ptr there
8050 * to simulate dst (== 0) +/-= ptr. Needed, for example,
8051 * for cases where we use K-based arithmetic in one direction
8052 * and truncated reg-based in the other in order to explore
8055 if (!ptr_is_dst_reg) {
8057 *dst_reg = *ptr_reg;
8059 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8061 if (!ptr_is_dst_reg && ret)
8063 return !ret ? REASON_STACK : 0;
8066 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8068 struct bpf_verifier_state *vstate = env->cur_state;
8070 /* If we simulate paths under speculation, we don't update the
8071 * insn as 'seen' such that when we verify unreachable paths in
8072 * the non-speculative domain, sanitize_dead_code() can still
8073 * rewrite/sanitize them.
8075 if (!vstate->speculative)
8076 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8079 static int sanitize_err(struct bpf_verifier_env *env,
8080 const struct bpf_insn *insn, int reason,
8081 const struct bpf_reg_state *off_reg,
8082 const struct bpf_reg_state *dst_reg)
8084 static const char *err = "pointer arithmetic with it prohibited for !root";
8085 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8086 u32 dst = insn->dst_reg, src = insn->src_reg;
8090 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8091 off_reg == dst_reg ? dst : src, err);
8094 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8095 off_reg == dst_reg ? src : dst, err);
8098 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8102 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8106 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8110 verbose(env, "verifier internal error: unknown reason (%d)\n",
8118 /* check that stack access falls within stack limits and that 'reg' doesn't
8119 * have a variable offset.
8121 * Variable offset is prohibited for unprivileged mode for simplicity since it
8122 * requires corresponding support in Spectre masking for stack ALU. See also
8123 * retrieve_ptr_limit().
8126 * 'off' includes 'reg->off'.
8128 static int check_stack_access_for_ptr_arithmetic(
8129 struct bpf_verifier_env *env,
8131 const struct bpf_reg_state *reg,
8134 if (!tnum_is_const(reg->var_off)) {
8137 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8138 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8139 regno, tn_buf, off);
8143 if (off >= 0 || off < -MAX_BPF_STACK) {
8144 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8145 "prohibited for !root; off=%d\n", regno, off);
8152 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8153 const struct bpf_insn *insn,
8154 const struct bpf_reg_state *dst_reg)
8156 u32 dst = insn->dst_reg;
8158 /* For unprivileged we require that resulting offset must be in bounds
8159 * in order to be able to sanitize access later on.
8161 if (env->bypass_spec_v1)
8164 switch (dst_reg->type) {
8166 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8167 dst_reg->off + dst_reg->var_off.value))
8170 case PTR_TO_MAP_VALUE:
8171 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8172 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8173 "prohibited for !root\n", dst);
8184 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8185 * Caller should also handle BPF_MOV case separately.
8186 * If we return -EACCES, caller may want to try again treating pointer as a
8187 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
8189 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8190 struct bpf_insn *insn,
8191 const struct bpf_reg_state *ptr_reg,
8192 const struct bpf_reg_state *off_reg)
8194 struct bpf_verifier_state *vstate = env->cur_state;
8195 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8196 struct bpf_reg_state *regs = state->regs, *dst_reg;
8197 bool known = tnum_is_const(off_reg->var_off);
8198 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8199 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8200 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8201 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8202 struct bpf_sanitize_info info = {};
8203 u8 opcode = BPF_OP(insn->code);
8204 u32 dst = insn->dst_reg;
8207 dst_reg = ®s[dst];
8209 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8210 smin_val > smax_val || umin_val > umax_val) {
8211 /* Taint dst register if offset had invalid bounds derived from
8212 * e.g. dead branches.
8214 __mark_reg_unknown(env, dst_reg);
8218 if (BPF_CLASS(insn->code) != BPF_ALU64) {
8219 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8220 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8221 __mark_reg_unknown(env, dst_reg);
8226 "R%d 32-bit pointer arithmetic prohibited\n",
8231 if (ptr_reg->type & PTR_MAYBE_NULL) {
8232 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8233 dst, reg_type_str(env, ptr_reg->type));
8237 switch (base_type(ptr_reg->type)) {
8238 case CONST_PTR_TO_MAP:
8239 /* smin_val represents the known value */
8240 if (known && smin_val == 0 && opcode == BPF_ADD)
8243 case PTR_TO_PACKET_END:
8245 case PTR_TO_SOCK_COMMON:
8246 case PTR_TO_TCP_SOCK:
8247 case PTR_TO_XDP_SOCK:
8248 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8249 dst, reg_type_str(env, ptr_reg->type));
8255 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8256 * The id may be overwritten later if we create a new variable offset.
8258 dst_reg->type = ptr_reg->type;
8259 dst_reg->id = ptr_reg->id;
8261 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8262 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8265 /* pointer types do not carry 32-bit bounds at the moment. */
8266 __mark_reg32_unbounded(dst_reg);
8268 if (sanitize_needed(opcode)) {
8269 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8272 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8277 /* We can take a fixed offset as long as it doesn't overflow
8278 * the s32 'off' field
8280 if (known && (ptr_reg->off + smin_val ==
8281 (s64)(s32)(ptr_reg->off + smin_val))) {
8282 /* pointer += K. Accumulate it into fixed offset */
8283 dst_reg->smin_value = smin_ptr;
8284 dst_reg->smax_value = smax_ptr;
8285 dst_reg->umin_value = umin_ptr;
8286 dst_reg->umax_value = umax_ptr;
8287 dst_reg->var_off = ptr_reg->var_off;
8288 dst_reg->off = ptr_reg->off + smin_val;
8289 dst_reg->raw = ptr_reg->raw;
8292 /* A new variable offset is created. Note that off_reg->off
8293 * == 0, since it's a scalar.
8294 * dst_reg gets the pointer type and since some positive
8295 * integer value was added to the pointer, give it a new 'id'
8296 * if it's a PTR_TO_PACKET.
8297 * this creates a new 'base' pointer, off_reg (variable) gets
8298 * added into the variable offset, and we copy the fixed offset
8301 if (signed_add_overflows(smin_ptr, smin_val) ||
8302 signed_add_overflows(smax_ptr, smax_val)) {
8303 dst_reg->smin_value = S64_MIN;
8304 dst_reg->smax_value = S64_MAX;
8306 dst_reg->smin_value = smin_ptr + smin_val;
8307 dst_reg->smax_value = smax_ptr + smax_val;
8309 if (umin_ptr + umin_val < umin_ptr ||
8310 umax_ptr + umax_val < umax_ptr) {
8311 dst_reg->umin_value = 0;
8312 dst_reg->umax_value = U64_MAX;
8314 dst_reg->umin_value = umin_ptr + umin_val;
8315 dst_reg->umax_value = umax_ptr + umax_val;
8317 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8318 dst_reg->off = ptr_reg->off;
8319 dst_reg->raw = ptr_reg->raw;
8320 if (reg_is_pkt_pointer(ptr_reg)) {
8321 dst_reg->id = ++env->id_gen;
8322 /* something was added to pkt_ptr, set range to zero */
8323 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8327 if (dst_reg == off_reg) {
8328 /* scalar -= pointer. Creates an unknown scalar */
8329 verbose(env, "R%d tried to subtract pointer from scalar\n",
8333 /* We don't allow subtraction from FP, because (according to
8334 * test_verifier.c test "invalid fp arithmetic", JITs might not
8335 * be able to deal with it.
8337 if (ptr_reg->type == PTR_TO_STACK) {
8338 verbose(env, "R%d subtraction from stack pointer prohibited\n",
8342 if (known && (ptr_reg->off - smin_val ==
8343 (s64)(s32)(ptr_reg->off - smin_val))) {
8344 /* pointer -= K. Subtract it from fixed offset */
8345 dst_reg->smin_value = smin_ptr;
8346 dst_reg->smax_value = smax_ptr;
8347 dst_reg->umin_value = umin_ptr;
8348 dst_reg->umax_value = umax_ptr;
8349 dst_reg->var_off = ptr_reg->var_off;
8350 dst_reg->id = ptr_reg->id;
8351 dst_reg->off = ptr_reg->off - smin_val;
8352 dst_reg->raw = ptr_reg->raw;
8355 /* A new variable offset is created. If the subtrahend is known
8356 * nonnegative, then any reg->range we had before is still good.
8358 if (signed_sub_overflows(smin_ptr, smax_val) ||
8359 signed_sub_overflows(smax_ptr, smin_val)) {
8360 /* Overflow possible, we know nothing */
8361 dst_reg->smin_value = S64_MIN;
8362 dst_reg->smax_value = S64_MAX;
8364 dst_reg->smin_value = smin_ptr - smax_val;
8365 dst_reg->smax_value = smax_ptr - smin_val;
8367 if (umin_ptr < umax_val) {
8368 /* Overflow possible, we know nothing */
8369 dst_reg->umin_value = 0;
8370 dst_reg->umax_value = U64_MAX;
8372 /* Cannot overflow (as long as bounds are consistent) */
8373 dst_reg->umin_value = umin_ptr - umax_val;
8374 dst_reg->umax_value = umax_ptr - umin_val;
8376 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8377 dst_reg->off = ptr_reg->off;
8378 dst_reg->raw = ptr_reg->raw;
8379 if (reg_is_pkt_pointer(ptr_reg)) {
8380 dst_reg->id = ++env->id_gen;
8381 /* something was added to pkt_ptr, set range to zero */
8383 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8389 /* bitwise ops on pointers are troublesome, prohibit. */
8390 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8391 dst, bpf_alu_string[opcode >> 4]);
8394 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8395 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8396 dst, bpf_alu_string[opcode >> 4]);
8400 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8402 reg_bounds_sync(dst_reg);
8403 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8405 if (sanitize_needed(opcode)) {
8406 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8409 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8415 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8416 struct bpf_reg_state *src_reg)
8418 s32 smin_val = src_reg->s32_min_value;
8419 s32 smax_val = src_reg->s32_max_value;
8420 u32 umin_val = src_reg->u32_min_value;
8421 u32 umax_val = src_reg->u32_max_value;
8423 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8424 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8425 dst_reg->s32_min_value = S32_MIN;
8426 dst_reg->s32_max_value = S32_MAX;
8428 dst_reg->s32_min_value += smin_val;
8429 dst_reg->s32_max_value += smax_val;
8431 if (dst_reg->u32_min_value + umin_val < umin_val ||
8432 dst_reg->u32_max_value + umax_val < umax_val) {
8433 dst_reg->u32_min_value = 0;
8434 dst_reg->u32_max_value = U32_MAX;
8436 dst_reg->u32_min_value += umin_val;
8437 dst_reg->u32_max_value += umax_val;
8441 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8442 struct bpf_reg_state *src_reg)
8444 s64 smin_val = src_reg->smin_value;
8445 s64 smax_val = src_reg->smax_value;
8446 u64 umin_val = src_reg->umin_value;
8447 u64 umax_val = src_reg->umax_value;
8449 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8450 signed_add_overflows(dst_reg->smax_value, smax_val)) {
8451 dst_reg->smin_value = S64_MIN;
8452 dst_reg->smax_value = S64_MAX;
8454 dst_reg->smin_value += smin_val;
8455 dst_reg->smax_value += smax_val;
8457 if (dst_reg->umin_value + umin_val < umin_val ||
8458 dst_reg->umax_value + umax_val < umax_val) {
8459 dst_reg->umin_value = 0;
8460 dst_reg->umax_value = U64_MAX;
8462 dst_reg->umin_value += umin_val;
8463 dst_reg->umax_value += umax_val;
8467 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8468 struct bpf_reg_state *src_reg)
8470 s32 smin_val = src_reg->s32_min_value;
8471 s32 smax_val = src_reg->s32_max_value;
8472 u32 umin_val = src_reg->u32_min_value;
8473 u32 umax_val = src_reg->u32_max_value;
8475 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8476 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8477 /* Overflow possible, we know nothing */
8478 dst_reg->s32_min_value = S32_MIN;
8479 dst_reg->s32_max_value = S32_MAX;
8481 dst_reg->s32_min_value -= smax_val;
8482 dst_reg->s32_max_value -= smin_val;
8484 if (dst_reg->u32_min_value < umax_val) {
8485 /* Overflow possible, we know nothing */
8486 dst_reg->u32_min_value = 0;
8487 dst_reg->u32_max_value = U32_MAX;
8489 /* Cannot overflow (as long as bounds are consistent) */
8490 dst_reg->u32_min_value -= umax_val;
8491 dst_reg->u32_max_value -= umin_val;
8495 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8496 struct bpf_reg_state *src_reg)
8498 s64 smin_val = src_reg->smin_value;
8499 s64 smax_val = src_reg->smax_value;
8500 u64 umin_val = src_reg->umin_value;
8501 u64 umax_val = src_reg->umax_value;
8503 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8504 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8505 /* Overflow possible, we know nothing */
8506 dst_reg->smin_value = S64_MIN;
8507 dst_reg->smax_value = S64_MAX;
8509 dst_reg->smin_value -= smax_val;
8510 dst_reg->smax_value -= smin_val;
8512 if (dst_reg->umin_value < umax_val) {
8513 /* Overflow possible, we know nothing */
8514 dst_reg->umin_value = 0;
8515 dst_reg->umax_value = U64_MAX;
8517 /* Cannot overflow (as long as bounds are consistent) */
8518 dst_reg->umin_value -= umax_val;
8519 dst_reg->umax_value -= umin_val;
8523 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8524 struct bpf_reg_state *src_reg)
8526 s32 smin_val = src_reg->s32_min_value;
8527 u32 umin_val = src_reg->u32_min_value;
8528 u32 umax_val = src_reg->u32_max_value;
8530 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8531 /* Ain't nobody got time to multiply that sign */
8532 __mark_reg32_unbounded(dst_reg);
8535 /* Both values are positive, so we can work with unsigned and
8536 * copy the result to signed (unless it exceeds S32_MAX).
8538 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8539 /* Potential overflow, we know nothing */
8540 __mark_reg32_unbounded(dst_reg);
8543 dst_reg->u32_min_value *= umin_val;
8544 dst_reg->u32_max_value *= umax_val;
8545 if (dst_reg->u32_max_value > S32_MAX) {
8546 /* Overflow possible, we know nothing */
8547 dst_reg->s32_min_value = S32_MIN;
8548 dst_reg->s32_max_value = S32_MAX;
8550 dst_reg->s32_min_value = dst_reg->u32_min_value;
8551 dst_reg->s32_max_value = dst_reg->u32_max_value;
8555 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8556 struct bpf_reg_state *src_reg)
8558 s64 smin_val = src_reg->smin_value;
8559 u64 umin_val = src_reg->umin_value;
8560 u64 umax_val = src_reg->umax_value;
8562 if (smin_val < 0 || dst_reg->smin_value < 0) {
8563 /* Ain't nobody got time to multiply that sign */
8564 __mark_reg64_unbounded(dst_reg);
8567 /* Both values are positive, so we can work with unsigned and
8568 * copy the result to signed (unless it exceeds S64_MAX).
8570 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8571 /* Potential overflow, we know nothing */
8572 __mark_reg64_unbounded(dst_reg);
8575 dst_reg->umin_value *= umin_val;
8576 dst_reg->umax_value *= umax_val;
8577 if (dst_reg->umax_value > S64_MAX) {
8578 /* Overflow possible, we know nothing */
8579 dst_reg->smin_value = S64_MIN;
8580 dst_reg->smax_value = S64_MAX;
8582 dst_reg->smin_value = dst_reg->umin_value;
8583 dst_reg->smax_value = dst_reg->umax_value;
8587 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8588 struct bpf_reg_state *src_reg)
8590 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8591 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8592 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8593 s32 smin_val = src_reg->s32_min_value;
8594 u32 umax_val = src_reg->u32_max_value;
8596 if (src_known && dst_known) {
8597 __mark_reg32_known(dst_reg, var32_off.value);
8601 /* We get our minimum from the var_off, since that's inherently
8602 * bitwise. Our maximum is the minimum of the operands' maxima.
8604 dst_reg->u32_min_value = var32_off.value;
8605 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8606 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8607 /* Lose signed bounds when ANDing negative numbers,
8608 * ain't nobody got time for that.
8610 dst_reg->s32_min_value = S32_MIN;
8611 dst_reg->s32_max_value = S32_MAX;
8613 /* ANDing two positives gives a positive, so safe to
8614 * cast result into s64.
8616 dst_reg->s32_min_value = dst_reg->u32_min_value;
8617 dst_reg->s32_max_value = dst_reg->u32_max_value;
8621 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8622 struct bpf_reg_state *src_reg)
8624 bool src_known = tnum_is_const(src_reg->var_off);
8625 bool dst_known = tnum_is_const(dst_reg->var_off);
8626 s64 smin_val = src_reg->smin_value;
8627 u64 umax_val = src_reg->umax_value;
8629 if (src_known && dst_known) {
8630 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8634 /* We get our minimum from the var_off, since that's inherently
8635 * bitwise. Our maximum is the minimum of the operands' maxima.
8637 dst_reg->umin_value = dst_reg->var_off.value;
8638 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8639 if (dst_reg->smin_value < 0 || smin_val < 0) {
8640 /* Lose signed bounds when ANDing negative numbers,
8641 * ain't nobody got time for that.
8643 dst_reg->smin_value = S64_MIN;
8644 dst_reg->smax_value = S64_MAX;
8646 /* ANDing two positives gives a positive, so safe to
8647 * cast result into s64.
8649 dst_reg->smin_value = dst_reg->umin_value;
8650 dst_reg->smax_value = dst_reg->umax_value;
8652 /* We may learn something more from the var_off */
8653 __update_reg_bounds(dst_reg);
8656 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8657 struct bpf_reg_state *src_reg)
8659 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8660 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8661 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8662 s32 smin_val = src_reg->s32_min_value;
8663 u32 umin_val = src_reg->u32_min_value;
8665 if (src_known && dst_known) {
8666 __mark_reg32_known(dst_reg, var32_off.value);
8670 /* We get our maximum from the var_off, and our minimum is the
8671 * maximum of the operands' minima
8673 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8674 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8675 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8676 /* Lose signed bounds when ORing negative numbers,
8677 * ain't nobody got time for that.
8679 dst_reg->s32_min_value = S32_MIN;
8680 dst_reg->s32_max_value = S32_MAX;
8682 /* ORing two positives gives a positive, so safe to
8683 * cast result into s64.
8685 dst_reg->s32_min_value = dst_reg->u32_min_value;
8686 dst_reg->s32_max_value = dst_reg->u32_max_value;
8690 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8691 struct bpf_reg_state *src_reg)
8693 bool src_known = tnum_is_const(src_reg->var_off);
8694 bool dst_known = tnum_is_const(dst_reg->var_off);
8695 s64 smin_val = src_reg->smin_value;
8696 u64 umin_val = src_reg->umin_value;
8698 if (src_known && dst_known) {
8699 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8703 /* We get our maximum from the var_off, and our minimum is the
8704 * maximum of the operands' minima
8706 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8707 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8708 if (dst_reg->smin_value < 0 || smin_val < 0) {
8709 /* Lose signed bounds when ORing negative numbers,
8710 * ain't nobody got time for that.
8712 dst_reg->smin_value = S64_MIN;
8713 dst_reg->smax_value = S64_MAX;
8715 /* ORing two positives gives a positive, so safe to
8716 * cast result into s64.
8718 dst_reg->smin_value = dst_reg->umin_value;
8719 dst_reg->smax_value = dst_reg->umax_value;
8721 /* We may learn something more from the var_off */
8722 __update_reg_bounds(dst_reg);
8725 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8726 struct bpf_reg_state *src_reg)
8728 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8729 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8730 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8731 s32 smin_val = src_reg->s32_min_value;
8733 if (src_known && dst_known) {
8734 __mark_reg32_known(dst_reg, var32_off.value);
8738 /* We get both minimum and maximum from the var32_off. */
8739 dst_reg->u32_min_value = var32_off.value;
8740 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8742 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8743 /* XORing two positive sign numbers gives a positive,
8744 * so safe to cast u32 result into s32.
8746 dst_reg->s32_min_value = dst_reg->u32_min_value;
8747 dst_reg->s32_max_value = dst_reg->u32_max_value;
8749 dst_reg->s32_min_value = S32_MIN;
8750 dst_reg->s32_max_value = S32_MAX;
8754 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8755 struct bpf_reg_state *src_reg)
8757 bool src_known = tnum_is_const(src_reg->var_off);
8758 bool dst_known = tnum_is_const(dst_reg->var_off);
8759 s64 smin_val = src_reg->smin_value;
8761 if (src_known && dst_known) {
8762 /* dst_reg->var_off.value has been updated earlier */
8763 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8767 /* We get both minimum and maximum from the var_off. */
8768 dst_reg->umin_value = dst_reg->var_off.value;
8769 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8771 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8772 /* XORing two positive sign numbers gives a positive,
8773 * so safe to cast u64 result into s64.
8775 dst_reg->smin_value = dst_reg->umin_value;
8776 dst_reg->smax_value = dst_reg->umax_value;
8778 dst_reg->smin_value = S64_MIN;
8779 dst_reg->smax_value = S64_MAX;
8782 __update_reg_bounds(dst_reg);
8785 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8786 u64 umin_val, u64 umax_val)
8788 /* We lose all sign bit information (except what we can pick
8791 dst_reg->s32_min_value = S32_MIN;
8792 dst_reg->s32_max_value = S32_MAX;
8793 /* If we might shift our top bit out, then we know nothing */
8794 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8795 dst_reg->u32_min_value = 0;
8796 dst_reg->u32_max_value = U32_MAX;
8798 dst_reg->u32_min_value <<= umin_val;
8799 dst_reg->u32_max_value <<= umax_val;
8803 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8804 struct bpf_reg_state *src_reg)
8806 u32 umax_val = src_reg->u32_max_value;
8807 u32 umin_val = src_reg->u32_min_value;
8808 /* u32 alu operation will zext upper bits */
8809 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8811 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8812 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8813 /* Not required but being careful mark reg64 bounds as unknown so
8814 * that we are forced to pick them up from tnum and zext later and
8815 * if some path skips this step we are still safe.
8817 __mark_reg64_unbounded(dst_reg);
8818 __update_reg32_bounds(dst_reg);
8821 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8822 u64 umin_val, u64 umax_val)
8824 /* Special case <<32 because it is a common compiler pattern to sign
8825 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8826 * positive we know this shift will also be positive so we can track
8827 * bounds correctly. Otherwise we lose all sign bit information except
8828 * what we can pick up from var_off. Perhaps we can generalize this
8829 * later to shifts of any length.
8831 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8832 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8834 dst_reg->smax_value = S64_MAX;
8836 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8837 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8839 dst_reg->smin_value = S64_MIN;
8841 /* If we might shift our top bit out, then we know nothing */
8842 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8843 dst_reg->umin_value = 0;
8844 dst_reg->umax_value = U64_MAX;
8846 dst_reg->umin_value <<= umin_val;
8847 dst_reg->umax_value <<= umax_val;
8851 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8852 struct bpf_reg_state *src_reg)
8854 u64 umax_val = src_reg->umax_value;
8855 u64 umin_val = src_reg->umin_value;
8857 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8858 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8859 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8861 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8862 /* We may learn something more from the var_off */
8863 __update_reg_bounds(dst_reg);
8866 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8867 struct bpf_reg_state *src_reg)
8869 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8870 u32 umax_val = src_reg->u32_max_value;
8871 u32 umin_val = src_reg->u32_min_value;
8873 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8874 * be negative, then either:
8875 * 1) src_reg might be zero, so the sign bit of the result is
8876 * unknown, so we lose our signed bounds
8877 * 2) it's known negative, thus the unsigned bounds capture the
8879 * 3) the signed bounds cross zero, so they tell us nothing
8881 * If the value in dst_reg is known nonnegative, then again the
8882 * unsigned bounds capture the signed bounds.
8883 * Thus, in all cases it suffices to blow away our signed bounds
8884 * and rely on inferring new ones from the unsigned bounds and
8885 * var_off of the result.
8887 dst_reg->s32_min_value = S32_MIN;
8888 dst_reg->s32_max_value = S32_MAX;
8890 dst_reg->var_off = tnum_rshift(subreg, umin_val);
8891 dst_reg->u32_min_value >>= umax_val;
8892 dst_reg->u32_max_value >>= umin_val;
8894 __mark_reg64_unbounded(dst_reg);
8895 __update_reg32_bounds(dst_reg);
8898 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8899 struct bpf_reg_state *src_reg)
8901 u64 umax_val = src_reg->umax_value;
8902 u64 umin_val = src_reg->umin_value;
8904 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8905 * be negative, then either:
8906 * 1) src_reg might be zero, so the sign bit of the result is
8907 * unknown, so we lose our signed bounds
8908 * 2) it's known negative, thus the unsigned bounds capture the
8910 * 3) the signed bounds cross zero, so they tell us nothing
8912 * If the value in dst_reg is known nonnegative, then again the
8913 * unsigned bounds capture the signed bounds.
8914 * Thus, in all cases it suffices to blow away our signed bounds
8915 * and rely on inferring new ones from the unsigned bounds and
8916 * var_off of the result.
8918 dst_reg->smin_value = S64_MIN;
8919 dst_reg->smax_value = S64_MAX;
8920 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8921 dst_reg->umin_value >>= umax_val;
8922 dst_reg->umax_value >>= umin_val;
8924 /* Its not easy to operate on alu32 bounds here because it depends
8925 * on bits being shifted in. Take easy way out and mark unbounded
8926 * so we can recalculate later from tnum.
8928 __mark_reg32_unbounded(dst_reg);
8929 __update_reg_bounds(dst_reg);
8932 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8933 struct bpf_reg_state *src_reg)
8935 u64 umin_val = src_reg->u32_min_value;
8937 /* Upon reaching here, src_known is true and
8938 * umax_val is equal to umin_val.
8940 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8941 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8943 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8945 /* blow away the dst_reg umin_value/umax_value and rely on
8946 * dst_reg var_off to refine the result.
8948 dst_reg->u32_min_value = 0;
8949 dst_reg->u32_max_value = U32_MAX;
8951 __mark_reg64_unbounded(dst_reg);
8952 __update_reg32_bounds(dst_reg);
8955 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8956 struct bpf_reg_state *src_reg)
8958 u64 umin_val = src_reg->umin_value;
8960 /* Upon reaching here, src_known is true and umax_val is equal
8963 dst_reg->smin_value >>= umin_val;
8964 dst_reg->smax_value >>= umin_val;
8966 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8968 /* blow away the dst_reg umin_value/umax_value and rely on
8969 * dst_reg var_off to refine the result.
8971 dst_reg->umin_value = 0;
8972 dst_reg->umax_value = U64_MAX;
8974 /* Its not easy to operate on alu32 bounds here because it depends
8975 * on bits being shifted in from upper 32-bits. Take easy way out
8976 * and mark unbounded so we can recalculate later from tnum.
8978 __mark_reg32_unbounded(dst_reg);
8979 __update_reg_bounds(dst_reg);
8982 /* WARNING: This function does calculations on 64-bit values, but the actual
8983 * execution may occur on 32-bit values. Therefore, things like bitshifts
8984 * need extra checks in the 32-bit case.
8986 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8987 struct bpf_insn *insn,
8988 struct bpf_reg_state *dst_reg,
8989 struct bpf_reg_state src_reg)
8991 struct bpf_reg_state *regs = cur_regs(env);
8992 u8 opcode = BPF_OP(insn->code);
8994 s64 smin_val, smax_val;
8995 u64 umin_val, umax_val;
8996 s32 s32_min_val, s32_max_val;
8997 u32 u32_min_val, u32_max_val;
8998 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
8999 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9002 smin_val = src_reg.smin_value;
9003 smax_val = src_reg.smax_value;
9004 umin_val = src_reg.umin_value;
9005 umax_val = src_reg.umax_value;
9007 s32_min_val = src_reg.s32_min_value;
9008 s32_max_val = src_reg.s32_max_value;
9009 u32_min_val = src_reg.u32_min_value;
9010 u32_max_val = src_reg.u32_max_value;
9013 src_known = tnum_subreg_is_const(src_reg.var_off);
9015 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9016 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9017 /* Taint dst register if offset had invalid bounds
9018 * derived from e.g. dead branches.
9020 __mark_reg_unknown(env, dst_reg);
9024 src_known = tnum_is_const(src_reg.var_off);
9026 (smin_val != smax_val || umin_val != umax_val)) ||
9027 smin_val > smax_val || umin_val > umax_val) {
9028 /* Taint dst register if offset had invalid bounds
9029 * derived from e.g. dead branches.
9031 __mark_reg_unknown(env, dst_reg);
9037 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9038 __mark_reg_unknown(env, dst_reg);
9042 if (sanitize_needed(opcode)) {
9043 ret = sanitize_val_alu(env, insn);
9045 return sanitize_err(env, insn, ret, NULL, NULL);
9048 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9049 * There are two classes of instructions: The first class we track both
9050 * alu32 and alu64 sign/unsigned bounds independently this provides the
9051 * greatest amount of precision when alu operations are mixed with jmp32
9052 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9053 * and BPF_OR. This is possible because these ops have fairly easy to
9054 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9055 * See alu32 verifier tests for examples. The second class of
9056 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9057 * with regards to tracking sign/unsigned bounds because the bits may
9058 * cross subreg boundaries in the alu64 case. When this happens we mark
9059 * the reg unbounded in the subreg bound space and use the resulting
9060 * tnum to calculate an approximation of the sign/unsigned bounds.
9064 scalar32_min_max_add(dst_reg, &src_reg);
9065 scalar_min_max_add(dst_reg, &src_reg);
9066 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9069 scalar32_min_max_sub(dst_reg, &src_reg);
9070 scalar_min_max_sub(dst_reg, &src_reg);
9071 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9074 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9075 scalar32_min_max_mul(dst_reg, &src_reg);
9076 scalar_min_max_mul(dst_reg, &src_reg);
9079 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9080 scalar32_min_max_and(dst_reg, &src_reg);
9081 scalar_min_max_and(dst_reg, &src_reg);
9084 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9085 scalar32_min_max_or(dst_reg, &src_reg);
9086 scalar_min_max_or(dst_reg, &src_reg);
9089 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9090 scalar32_min_max_xor(dst_reg, &src_reg);
9091 scalar_min_max_xor(dst_reg, &src_reg);
9094 if (umax_val >= insn_bitness) {
9095 /* Shifts greater than 31 or 63 are undefined.
9096 * This includes shifts by a negative number.
9098 mark_reg_unknown(env, regs, insn->dst_reg);
9102 scalar32_min_max_lsh(dst_reg, &src_reg);
9104 scalar_min_max_lsh(dst_reg, &src_reg);
9107 if (umax_val >= insn_bitness) {
9108 /* Shifts greater than 31 or 63 are undefined.
9109 * This includes shifts by a negative number.
9111 mark_reg_unknown(env, regs, insn->dst_reg);
9115 scalar32_min_max_rsh(dst_reg, &src_reg);
9117 scalar_min_max_rsh(dst_reg, &src_reg);
9120 if (umax_val >= insn_bitness) {
9121 /* Shifts greater than 31 or 63 are undefined.
9122 * This includes shifts by a negative number.
9124 mark_reg_unknown(env, regs, insn->dst_reg);
9128 scalar32_min_max_arsh(dst_reg, &src_reg);
9130 scalar_min_max_arsh(dst_reg, &src_reg);
9133 mark_reg_unknown(env, regs, insn->dst_reg);
9137 /* ALU32 ops are zero extended into 64bit register */
9139 zext_32_to_64(dst_reg);
9140 reg_bounds_sync(dst_reg);
9144 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9147 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9148 struct bpf_insn *insn)
9150 struct bpf_verifier_state *vstate = env->cur_state;
9151 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9152 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9153 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9154 u8 opcode = BPF_OP(insn->code);
9157 dst_reg = ®s[insn->dst_reg];
9159 if (dst_reg->type != SCALAR_VALUE)
9162 /* Make sure ID is cleared otherwise dst_reg min/max could be
9163 * incorrectly propagated into other registers by find_equal_scalars()
9166 if (BPF_SRC(insn->code) == BPF_X) {
9167 src_reg = ®s[insn->src_reg];
9168 if (src_reg->type != SCALAR_VALUE) {
9169 if (dst_reg->type != SCALAR_VALUE) {
9170 /* Combining two pointers by any ALU op yields
9171 * an arbitrary scalar. Disallow all math except
9172 * pointer subtraction
9174 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9175 mark_reg_unknown(env, regs, insn->dst_reg);
9178 verbose(env, "R%d pointer %s pointer prohibited\n",
9180 bpf_alu_string[opcode >> 4]);
9183 /* scalar += pointer
9184 * This is legal, but we have to reverse our
9185 * src/dest handling in computing the range
9187 err = mark_chain_precision(env, insn->dst_reg);
9190 return adjust_ptr_min_max_vals(env, insn,
9193 } else if (ptr_reg) {
9194 /* pointer += scalar */
9195 err = mark_chain_precision(env, insn->src_reg);
9198 return adjust_ptr_min_max_vals(env, insn,
9202 /* Pretend the src is a reg with a known value, since we only
9203 * need to be able to read from this state.
9205 off_reg.type = SCALAR_VALUE;
9206 __mark_reg_known(&off_reg, insn->imm);
9208 if (ptr_reg) /* pointer += K */
9209 return adjust_ptr_min_max_vals(env, insn,
9213 /* Got here implies adding two SCALAR_VALUEs */
9214 if (WARN_ON_ONCE(ptr_reg)) {
9215 print_verifier_state(env, state, true);
9216 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9219 if (WARN_ON(!src_reg)) {
9220 print_verifier_state(env, state, true);
9221 verbose(env, "verifier internal error: no src_reg\n");
9224 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9227 /* check validity of 32-bit and 64-bit arithmetic operations */
9228 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9230 struct bpf_reg_state *regs = cur_regs(env);
9231 u8 opcode = BPF_OP(insn->code);
9234 if (opcode == BPF_END || opcode == BPF_NEG) {
9235 if (opcode == BPF_NEG) {
9236 if (BPF_SRC(insn->code) != BPF_K ||
9237 insn->src_reg != BPF_REG_0 ||
9238 insn->off != 0 || insn->imm != 0) {
9239 verbose(env, "BPF_NEG uses reserved fields\n");
9243 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9244 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9245 BPF_CLASS(insn->code) == BPF_ALU64) {
9246 verbose(env, "BPF_END uses reserved fields\n");
9251 /* check src operand */
9252 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9256 if (is_pointer_value(env, insn->dst_reg)) {
9257 verbose(env, "R%d pointer arithmetic prohibited\n",
9262 /* check dest operand */
9263 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9267 } else if (opcode == BPF_MOV) {
9269 if (BPF_SRC(insn->code) == BPF_X) {
9270 if (insn->imm != 0 || insn->off != 0) {
9271 verbose(env, "BPF_MOV uses reserved fields\n");
9275 /* check src operand */
9276 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9280 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9281 verbose(env, "BPF_MOV uses reserved fields\n");
9286 /* check dest operand, mark as required later */
9287 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9291 if (BPF_SRC(insn->code) == BPF_X) {
9292 struct bpf_reg_state *src_reg = regs + insn->src_reg;
9293 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9295 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9297 * copy register state to dest reg
9299 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9300 /* Assign src and dst registers the same ID
9301 * that will be used by find_equal_scalars()
9302 * to propagate min/max range.
9304 src_reg->id = ++env->id_gen;
9305 *dst_reg = *src_reg;
9306 dst_reg->live |= REG_LIVE_WRITTEN;
9307 dst_reg->subreg_def = DEF_NOT_SUBREG;
9310 if (is_pointer_value(env, insn->src_reg)) {
9312 "R%d partial copy of pointer\n",
9315 } else if (src_reg->type == SCALAR_VALUE) {
9316 *dst_reg = *src_reg;
9317 /* Make sure ID is cleared otherwise
9318 * dst_reg min/max could be incorrectly
9319 * propagated into src_reg by find_equal_scalars()
9322 dst_reg->live |= REG_LIVE_WRITTEN;
9323 dst_reg->subreg_def = env->insn_idx + 1;
9325 mark_reg_unknown(env, regs,
9328 zext_32_to_64(dst_reg);
9329 reg_bounds_sync(dst_reg);
9333 * remember the value we stored into this reg
9335 /* clear any state __mark_reg_known doesn't set */
9336 mark_reg_unknown(env, regs, insn->dst_reg);
9337 regs[insn->dst_reg].type = SCALAR_VALUE;
9338 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9339 __mark_reg_known(regs + insn->dst_reg,
9342 __mark_reg_known(regs + insn->dst_reg,
9347 } else if (opcode > BPF_END) {
9348 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9351 } else { /* all other ALU ops: and, sub, xor, add, ... */
9353 if (BPF_SRC(insn->code) == BPF_X) {
9354 if (insn->imm != 0 || insn->off != 0) {
9355 verbose(env, "BPF_ALU uses reserved fields\n");
9358 /* check src1 operand */
9359 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9363 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9364 verbose(env, "BPF_ALU uses reserved fields\n");
9369 /* check src2 operand */
9370 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9374 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9375 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9376 verbose(env, "div by zero\n");
9380 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9381 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9382 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9384 if (insn->imm < 0 || insn->imm >= size) {
9385 verbose(env, "invalid shift %d\n", insn->imm);
9390 /* check dest operand */
9391 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9395 return adjust_reg_min_max_vals(env, insn);
9401 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9402 struct bpf_reg_state *dst_reg,
9403 enum bpf_reg_type type,
9404 bool range_right_open)
9406 struct bpf_func_state *state;
9407 struct bpf_reg_state *reg;
9410 if (dst_reg->off < 0 ||
9411 (dst_reg->off == 0 && range_right_open))
9412 /* This doesn't give us any range */
9415 if (dst_reg->umax_value > MAX_PACKET_OFF ||
9416 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9417 /* Risk of overflow. For instance, ptr + (1<<63) may be less
9418 * than pkt_end, but that's because it's also less than pkt.
9422 new_range = dst_reg->off;
9423 if (range_right_open)
9426 /* Examples for register markings:
9428 * pkt_data in dst register:
9432 * if (r2 > pkt_end) goto <handle exception>
9437 * if (r2 < pkt_end) goto <access okay>
9438 * <handle exception>
9441 * r2 == dst_reg, pkt_end == src_reg
9442 * r2=pkt(id=n,off=8,r=0)
9443 * r3=pkt(id=n,off=0,r=0)
9445 * pkt_data in src register:
9449 * if (pkt_end >= r2) goto <access okay>
9450 * <handle exception>
9454 * if (pkt_end <= r2) goto <handle exception>
9458 * pkt_end == dst_reg, r2 == src_reg
9459 * r2=pkt(id=n,off=8,r=0)
9460 * r3=pkt(id=n,off=0,r=0)
9462 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9463 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9464 * and [r3, r3 + 8-1) respectively is safe to access depending on
9468 /* If our ids match, then we must have the same max_value. And we
9469 * don't care about the other reg's fixed offset, since if it's too big
9470 * the range won't allow anything.
9471 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9473 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9474 if (reg->type == type && reg->id == dst_reg->id)
9475 /* keep the maximum range already checked */
9476 reg->range = max(reg->range, new_range);
9480 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9482 struct tnum subreg = tnum_subreg(reg->var_off);
9483 s32 sval = (s32)val;
9487 if (tnum_is_const(subreg))
9488 return !!tnum_equals_const(subreg, val);
9491 if (tnum_is_const(subreg))
9492 return !tnum_equals_const(subreg, val);
9495 if ((~subreg.mask & subreg.value) & val)
9497 if (!((subreg.mask | subreg.value) & val))
9501 if (reg->u32_min_value > val)
9503 else if (reg->u32_max_value <= val)
9507 if (reg->s32_min_value > sval)
9509 else if (reg->s32_max_value <= sval)
9513 if (reg->u32_max_value < val)
9515 else if (reg->u32_min_value >= val)
9519 if (reg->s32_max_value < sval)
9521 else if (reg->s32_min_value >= sval)
9525 if (reg->u32_min_value >= val)
9527 else if (reg->u32_max_value < val)
9531 if (reg->s32_min_value >= sval)
9533 else if (reg->s32_max_value < sval)
9537 if (reg->u32_max_value <= val)
9539 else if (reg->u32_min_value > val)
9543 if (reg->s32_max_value <= sval)
9545 else if (reg->s32_min_value > sval)
9554 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9556 s64 sval = (s64)val;
9560 if (tnum_is_const(reg->var_off))
9561 return !!tnum_equals_const(reg->var_off, val);
9564 if (tnum_is_const(reg->var_off))
9565 return !tnum_equals_const(reg->var_off, val);
9568 if ((~reg->var_off.mask & reg->var_off.value) & val)
9570 if (!((reg->var_off.mask | reg->var_off.value) & val))
9574 if (reg->umin_value > val)
9576 else if (reg->umax_value <= val)
9580 if (reg->smin_value > sval)
9582 else if (reg->smax_value <= sval)
9586 if (reg->umax_value < val)
9588 else if (reg->umin_value >= val)
9592 if (reg->smax_value < sval)
9594 else if (reg->smin_value >= sval)
9598 if (reg->umin_value >= val)
9600 else if (reg->umax_value < val)
9604 if (reg->smin_value >= sval)
9606 else if (reg->smax_value < sval)
9610 if (reg->umax_value <= val)
9612 else if (reg->umin_value > val)
9616 if (reg->smax_value <= sval)
9618 else if (reg->smin_value > sval)
9626 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9628 * 1 - branch will be taken and "goto target" will be executed
9629 * 0 - branch will not be taken and fall-through to next insn
9630 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9633 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9636 if (__is_pointer_value(false, reg)) {
9637 if (!reg_type_not_null(reg->type))
9640 /* If pointer is valid tests against zero will fail so we can
9641 * use this to direct branch taken.
9657 return is_branch32_taken(reg, val, opcode);
9658 return is_branch64_taken(reg, val, opcode);
9661 static int flip_opcode(u32 opcode)
9663 /* How can we transform "a <op> b" into "b <op> a"? */
9664 static const u8 opcode_flip[16] = {
9665 /* these stay the same */
9666 [BPF_JEQ >> 4] = BPF_JEQ,
9667 [BPF_JNE >> 4] = BPF_JNE,
9668 [BPF_JSET >> 4] = BPF_JSET,
9669 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9670 [BPF_JGE >> 4] = BPF_JLE,
9671 [BPF_JGT >> 4] = BPF_JLT,
9672 [BPF_JLE >> 4] = BPF_JGE,
9673 [BPF_JLT >> 4] = BPF_JGT,
9674 [BPF_JSGE >> 4] = BPF_JSLE,
9675 [BPF_JSGT >> 4] = BPF_JSLT,
9676 [BPF_JSLE >> 4] = BPF_JSGE,
9677 [BPF_JSLT >> 4] = BPF_JSGT
9679 return opcode_flip[opcode >> 4];
9682 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9683 struct bpf_reg_state *src_reg,
9686 struct bpf_reg_state *pkt;
9688 if (src_reg->type == PTR_TO_PACKET_END) {
9690 } else if (dst_reg->type == PTR_TO_PACKET_END) {
9692 opcode = flip_opcode(opcode);
9697 if (pkt->range >= 0)
9702 /* pkt <= pkt_end */
9706 if (pkt->range == BEYOND_PKT_END)
9707 /* pkt has at last one extra byte beyond pkt_end */
9708 return opcode == BPF_JGT;
9714 /* pkt >= pkt_end */
9715 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9716 return opcode == BPF_JGE;
9722 /* Adjusts the register min/max values in the case that the dst_reg is the
9723 * variable register that we are working on, and src_reg is a constant or we're
9724 * simply doing a BPF_K check.
9725 * In JEQ/JNE cases we also adjust the var_off values.
9727 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9728 struct bpf_reg_state *false_reg,
9730 u8 opcode, bool is_jmp32)
9732 struct tnum false_32off = tnum_subreg(false_reg->var_off);
9733 struct tnum false_64off = false_reg->var_off;
9734 struct tnum true_32off = tnum_subreg(true_reg->var_off);
9735 struct tnum true_64off = true_reg->var_off;
9736 s64 sval = (s64)val;
9737 s32 sval32 = (s32)val32;
9739 /* If the dst_reg is a pointer, we can't learn anything about its
9740 * variable offset from the compare (unless src_reg were a pointer into
9741 * the same object, but we don't bother with that.
9742 * Since false_reg and true_reg have the same type by construction, we
9743 * only need to check one of them for pointerness.
9745 if (__is_pointer_value(false, false_reg))
9749 /* JEQ/JNE comparison doesn't change the register equivalence.
9752 * if (r1 == 42) goto label;
9754 * label: // here both r1 and r2 are known to be 42.
9756 * Hence when marking register as known preserve it's ID.
9760 __mark_reg32_known(true_reg, val32);
9761 true_32off = tnum_subreg(true_reg->var_off);
9763 ___mark_reg_known(true_reg, val);
9764 true_64off = true_reg->var_off;
9769 __mark_reg32_known(false_reg, val32);
9770 false_32off = tnum_subreg(false_reg->var_off);
9772 ___mark_reg_known(false_reg, val);
9773 false_64off = false_reg->var_off;
9778 false_32off = tnum_and(false_32off, tnum_const(~val32));
9779 if (is_power_of_2(val32))
9780 true_32off = tnum_or(true_32off,
9783 false_64off = tnum_and(false_64off, tnum_const(~val));
9784 if (is_power_of_2(val))
9785 true_64off = tnum_or(true_64off,
9793 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
9794 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9796 false_reg->u32_max_value = min(false_reg->u32_max_value,
9798 true_reg->u32_min_value = max(true_reg->u32_min_value,
9801 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
9802 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9804 false_reg->umax_value = min(false_reg->umax_value, false_umax);
9805 true_reg->umin_value = max(true_reg->umin_value, true_umin);
9813 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
9814 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9816 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9817 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9819 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
9820 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9822 false_reg->smax_value = min(false_reg->smax_value, false_smax);
9823 true_reg->smin_value = max(true_reg->smin_value, true_smin);
9831 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
9832 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9834 false_reg->u32_min_value = max(false_reg->u32_min_value,
9836 true_reg->u32_max_value = min(true_reg->u32_max_value,
9839 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
9840 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9842 false_reg->umin_value = max(false_reg->umin_value, false_umin);
9843 true_reg->umax_value = min(true_reg->umax_value, true_umax);
9851 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
9852 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9854 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9855 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9857 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
9858 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9860 false_reg->smin_value = max(false_reg->smin_value, false_smin);
9861 true_reg->smax_value = min(true_reg->smax_value, true_smax);
9870 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9871 tnum_subreg(false_32off));
9872 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9873 tnum_subreg(true_32off));
9874 __reg_combine_32_into_64(false_reg);
9875 __reg_combine_32_into_64(true_reg);
9877 false_reg->var_off = false_64off;
9878 true_reg->var_off = true_64off;
9879 __reg_combine_64_into_32(false_reg);
9880 __reg_combine_64_into_32(true_reg);
9884 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9887 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9888 struct bpf_reg_state *false_reg,
9890 u8 opcode, bool is_jmp32)
9892 opcode = flip_opcode(opcode);
9893 /* This uses zero as "not present in table"; luckily the zero opcode,
9894 * BPF_JA, can't get here.
9897 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9900 /* Regs are known to be equal, so intersect their min/max/var_off */
9901 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9902 struct bpf_reg_state *dst_reg)
9904 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9905 dst_reg->umin_value);
9906 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9907 dst_reg->umax_value);
9908 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9909 dst_reg->smin_value);
9910 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9911 dst_reg->smax_value);
9912 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9914 reg_bounds_sync(src_reg);
9915 reg_bounds_sync(dst_reg);
9918 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9919 struct bpf_reg_state *true_dst,
9920 struct bpf_reg_state *false_src,
9921 struct bpf_reg_state *false_dst,
9926 __reg_combine_min_max(true_src, true_dst);
9929 __reg_combine_min_max(false_src, false_dst);
9934 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9935 struct bpf_reg_state *reg, u32 id,
9938 if (type_may_be_null(reg->type) && reg->id == id &&
9939 !WARN_ON_ONCE(!reg->id)) {
9940 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9941 !tnum_equals_const(reg->var_off, 0) ||
9943 /* Old offset (both fixed and variable parts) should
9944 * have been known-zero, because we don't allow pointer
9945 * arithmetic on pointers that might be NULL. If we
9946 * see this happening, don't convert the register.
9951 reg->type = SCALAR_VALUE;
9952 /* We don't need id and ref_obj_id from this point
9953 * onwards anymore, thus we should better reset it,
9954 * so that state pruning has chances to take effect.
9957 reg->ref_obj_id = 0;
9962 mark_ptr_not_null_reg(reg);
9964 if (!reg_may_point_to_spin_lock(reg)) {
9965 /* For not-NULL ptr, reg->ref_obj_id will be reset
9966 * in release_reference().
9968 * reg->id is still used by spin_lock ptr. Other
9969 * than spin_lock ptr type, reg->id can be reset.
9976 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9977 * be folded together at some point.
9979 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9982 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9983 struct bpf_reg_state *regs = state->regs, *reg;
9984 u32 ref_obj_id = regs[regno].ref_obj_id;
9985 u32 id = regs[regno].id;
9987 if (ref_obj_id && ref_obj_id == id && is_null)
9988 /* regs[regno] is in the " == NULL" branch.
9989 * No one could have freed the reference state before
9990 * doing the NULL check.
9992 WARN_ON_ONCE(release_reference_state(state, id));
9994 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9995 mark_ptr_or_null_reg(state, reg, id, is_null);
9999 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10000 struct bpf_reg_state *dst_reg,
10001 struct bpf_reg_state *src_reg,
10002 struct bpf_verifier_state *this_branch,
10003 struct bpf_verifier_state *other_branch)
10005 if (BPF_SRC(insn->code) != BPF_X)
10008 /* Pointers are always 64-bit. */
10009 if (BPF_CLASS(insn->code) == BPF_JMP32)
10012 switch (BPF_OP(insn->code)) {
10014 if ((dst_reg->type == PTR_TO_PACKET &&
10015 src_reg->type == PTR_TO_PACKET_END) ||
10016 (dst_reg->type == PTR_TO_PACKET_META &&
10017 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10018 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10019 find_good_pkt_pointers(this_branch, dst_reg,
10020 dst_reg->type, false);
10021 mark_pkt_end(other_branch, insn->dst_reg, true);
10022 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10023 src_reg->type == PTR_TO_PACKET) ||
10024 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10025 src_reg->type == PTR_TO_PACKET_META)) {
10026 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
10027 find_good_pkt_pointers(other_branch, src_reg,
10028 src_reg->type, true);
10029 mark_pkt_end(this_branch, insn->src_reg, false);
10035 if ((dst_reg->type == PTR_TO_PACKET &&
10036 src_reg->type == PTR_TO_PACKET_END) ||
10037 (dst_reg->type == PTR_TO_PACKET_META &&
10038 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10039 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10040 find_good_pkt_pointers(other_branch, dst_reg,
10041 dst_reg->type, true);
10042 mark_pkt_end(this_branch, insn->dst_reg, false);
10043 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10044 src_reg->type == PTR_TO_PACKET) ||
10045 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10046 src_reg->type == PTR_TO_PACKET_META)) {
10047 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
10048 find_good_pkt_pointers(this_branch, src_reg,
10049 src_reg->type, false);
10050 mark_pkt_end(other_branch, insn->src_reg, true);
10056 if ((dst_reg->type == PTR_TO_PACKET &&
10057 src_reg->type == PTR_TO_PACKET_END) ||
10058 (dst_reg->type == PTR_TO_PACKET_META &&
10059 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10060 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10061 find_good_pkt_pointers(this_branch, dst_reg,
10062 dst_reg->type, true);
10063 mark_pkt_end(other_branch, insn->dst_reg, false);
10064 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10065 src_reg->type == PTR_TO_PACKET) ||
10066 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10067 src_reg->type == PTR_TO_PACKET_META)) {
10068 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10069 find_good_pkt_pointers(other_branch, src_reg,
10070 src_reg->type, false);
10071 mark_pkt_end(this_branch, insn->src_reg, true);
10077 if ((dst_reg->type == PTR_TO_PACKET &&
10078 src_reg->type == PTR_TO_PACKET_END) ||
10079 (dst_reg->type == PTR_TO_PACKET_META &&
10080 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10081 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10082 find_good_pkt_pointers(other_branch, dst_reg,
10083 dst_reg->type, false);
10084 mark_pkt_end(this_branch, insn->dst_reg, true);
10085 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10086 src_reg->type == PTR_TO_PACKET) ||
10087 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10088 src_reg->type == PTR_TO_PACKET_META)) {
10089 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10090 find_good_pkt_pointers(this_branch, src_reg,
10091 src_reg->type, true);
10092 mark_pkt_end(other_branch, insn->src_reg, false);
10104 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10105 struct bpf_reg_state *known_reg)
10107 struct bpf_func_state *state;
10108 struct bpf_reg_state *reg;
10110 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10111 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10116 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10117 struct bpf_insn *insn, int *insn_idx)
10119 struct bpf_verifier_state *this_branch = env->cur_state;
10120 struct bpf_verifier_state *other_branch;
10121 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10122 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10123 u8 opcode = BPF_OP(insn->code);
10128 /* Only conditional jumps are expected to reach here. */
10129 if (opcode == BPF_JA || opcode > BPF_JSLE) {
10130 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10134 if (BPF_SRC(insn->code) == BPF_X) {
10135 if (insn->imm != 0) {
10136 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10140 /* check src1 operand */
10141 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10145 if (is_pointer_value(env, insn->src_reg)) {
10146 verbose(env, "R%d pointer comparison prohibited\n",
10150 src_reg = ®s[insn->src_reg];
10152 if (insn->src_reg != BPF_REG_0) {
10153 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10158 /* check src2 operand */
10159 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10163 dst_reg = ®s[insn->dst_reg];
10164 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10166 if (BPF_SRC(insn->code) == BPF_K) {
10167 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10168 } else if (src_reg->type == SCALAR_VALUE &&
10169 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10170 pred = is_branch_taken(dst_reg,
10171 tnum_subreg(src_reg->var_off).value,
10174 } else if (src_reg->type == SCALAR_VALUE &&
10175 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10176 pred = is_branch_taken(dst_reg,
10177 src_reg->var_off.value,
10180 } else if (reg_is_pkt_pointer_any(dst_reg) &&
10181 reg_is_pkt_pointer_any(src_reg) &&
10183 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10187 /* If we get here with a dst_reg pointer type it is because
10188 * above is_branch_taken() special cased the 0 comparison.
10190 if (!__is_pointer_value(false, dst_reg))
10191 err = mark_chain_precision(env, insn->dst_reg);
10192 if (BPF_SRC(insn->code) == BPF_X && !err &&
10193 !__is_pointer_value(false, src_reg))
10194 err = mark_chain_precision(env, insn->src_reg);
10200 /* Only follow the goto, ignore fall-through. If needed, push
10201 * the fall-through branch for simulation under speculative
10204 if (!env->bypass_spec_v1 &&
10205 !sanitize_speculative_path(env, insn, *insn_idx + 1,
10208 *insn_idx += insn->off;
10210 } else if (pred == 0) {
10211 /* Only follow the fall-through branch, since that's where the
10212 * program will go. If needed, push the goto branch for
10213 * simulation under speculative execution.
10215 if (!env->bypass_spec_v1 &&
10216 !sanitize_speculative_path(env, insn,
10217 *insn_idx + insn->off + 1,
10223 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10227 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10229 /* detect if we are comparing against a constant value so we can adjust
10230 * our min/max values for our dst register.
10231 * this is only legit if both are scalars (or pointers to the same
10232 * object, I suppose, but we don't support that right now), because
10233 * otherwise the different base pointers mean the offsets aren't
10236 if (BPF_SRC(insn->code) == BPF_X) {
10237 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
10239 if (dst_reg->type == SCALAR_VALUE &&
10240 src_reg->type == SCALAR_VALUE) {
10241 if (tnum_is_const(src_reg->var_off) ||
10243 tnum_is_const(tnum_subreg(src_reg->var_off))))
10244 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10246 src_reg->var_off.value,
10247 tnum_subreg(src_reg->var_off).value,
10249 else if (tnum_is_const(dst_reg->var_off) ||
10251 tnum_is_const(tnum_subreg(dst_reg->var_off))))
10252 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10254 dst_reg->var_off.value,
10255 tnum_subreg(dst_reg->var_off).value,
10257 else if (!is_jmp32 &&
10258 (opcode == BPF_JEQ || opcode == BPF_JNE))
10259 /* Comparing for equality, we can combine knowledge */
10260 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10261 &other_branch_regs[insn->dst_reg],
10262 src_reg, dst_reg, opcode);
10264 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10265 find_equal_scalars(this_branch, src_reg);
10266 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10270 } else if (dst_reg->type == SCALAR_VALUE) {
10271 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10272 dst_reg, insn->imm, (u32)insn->imm,
10276 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10277 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10278 find_equal_scalars(this_branch, dst_reg);
10279 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10282 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10283 * NOTE: these optimizations below are related with pointer comparison
10284 * which will never be JMP32.
10286 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10287 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10288 type_may_be_null(dst_reg->type)) {
10289 /* Mark all identical registers in each branch as either
10290 * safe or unknown depending R == 0 or R != 0 conditional.
10292 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10293 opcode == BPF_JNE);
10294 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10295 opcode == BPF_JEQ);
10296 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
10297 this_branch, other_branch) &&
10298 is_pointer_value(env, insn->dst_reg)) {
10299 verbose(env, "R%d pointer comparison prohibited\n",
10303 if (env->log.level & BPF_LOG_LEVEL)
10304 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10308 /* verify BPF_LD_IMM64 instruction */
10309 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10311 struct bpf_insn_aux_data *aux = cur_aux(env);
10312 struct bpf_reg_state *regs = cur_regs(env);
10313 struct bpf_reg_state *dst_reg;
10314 struct bpf_map *map;
10317 if (BPF_SIZE(insn->code) != BPF_DW) {
10318 verbose(env, "invalid BPF_LD_IMM insn\n");
10321 if (insn->off != 0) {
10322 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10326 err = check_reg_arg(env, insn->dst_reg, DST_OP);
10330 dst_reg = ®s[insn->dst_reg];
10331 if (insn->src_reg == 0) {
10332 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10334 dst_reg->type = SCALAR_VALUE;
10335 __mark_reg_known(®s[insn->dst_reg], imm);
10339 /* All special src_reg cases are listed below. From this point onwards
10340 * we either succeed and assign a corresponding dst_reg->type after
10341 * zeroing the offset, or fail and reject the program.
10343 mark_reg_known_zero(env, regs, insn->dst_reg);
10345 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10346 dst_reg->type = aux->btf_var.reg_type;
10347 switch (base_type(dst_reg->type)) {
10349 dst_reg->mem_size = aux->btf_var.mem_size;
10351 case PTR_TO_BTF_ID:
10352 dst_reg->btf = aux->btf_var.btf;
10353 dst_reg->btf_id = aux->btf_var.btf_id;
10356 verbose(env, "bpf verifier is misconfigured\n");
10362 if (insn->src_reg == BPF_PSEUDO_FUNC) {
10363 struct bpf_prog_aux *aux = env->prog->aux;
10364 u32 subprogno = find_subprog(env,
10365 env->insn_idx + insn->imm + 1);
10367 if (!aux->func_info) {
10368 verbose(env, "missing btf func_info\n");
10371 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10372 verbose(env, "callback function not static\n");
10376 dst_reg->type = PTR_TO_FUNC;
10377 dst_reg->subprogno = subprogno;
10381 map = env->used_maps[aux->map_index];
10382 dst_reg->map_ptr = map;
10384 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10385 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10386 dst_reg->type = PTR_TO_MAP_VALUE;
10387 dst_reg->off = aux->map_off;
10388 if (map_value_has_spin_lock(map))
10389 dst_reg->id = ++env->id_gen;
10390 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10391 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10392 dst_reg->type = CONST_PTR_TO_MAP;
10394 verbose(env, "bpf verifier is misconfigured\n");
10401 static bool may_access_skb(enum bpf_prog_type type)
10404 case BPF_PROG_TYPE_SOCKET_FILTER:
10405 case BPF_PROG_TYPE_SCHED_CLS:
10406 case BPF_PROG_TYPE_SCHED_ACT:
10413 /* verify safety of LD_ABS|LD_IND instructions:
10414 * - they can only appear in the programs where ctx == skb
10415 * - since they are wrappers of function calls, they scratch R1-R5 registers,
10416 * preserve R6-R9, and store return value into R0
10419 * ctx == skb == R6 == CTX
10422 * SRC == any register
10423 * IMM == 32-bit immediate
10426 * R0 - 8/16/32-bit skb data converted to cpu endianness
10428 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10430 struct bpf_reg_state *regs = cur_regs(env);
10431 static const int ctx_reg = BPF_REG_6;
10432 u8 mode = BPF_MODE(insn->code);
10435 if (!may_access_skb(resolve_prog_type(env->prog))) {
10436 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10440 if (!env->ops->gen_ld_abs) {
10441 verbose(env, "bpf verifier is misconfigured\n");
10445 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10446 BPF_SIZE(insn->code) == BPF_DW ||
10447 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10448 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10452 /* check whether implicit source operand (register R6) is readable */
10453 err = check_reg_arg(env, ctx_reg, SRC_OP);
10457 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10458 * gen_ld_abs() may terminate the program at runtime, leading to
10461 err = check_reference_leak(env);
10463 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10467 if (env->cur_state->active_spin_lock) {
10468 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10472 if (regs[ctx_reg].type != PTR_TO_CTX) {
10474 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10478 if (mode == BPF_IND) {
10479 /* check explicit source operand */
10480 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10485 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
10489 /* reset caller saved regs to unreadable */
10490 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10491 mark_reg_not_init(env, regs, caller_saved[i]);
10492 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10495 /* mark destination R0 register as readable, since it contains
10496 * the value fetched from the packet.
10497 * Already marked as written above.
10499 mark_reg_unknown(env, regs, BPF_REG_0);
10500 /* ld_abs load up to 32-bit skb data. */
10501 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10505 static int check_return_code(struct bpf_verifier_env *env)
10507 struct tnum enforce_attach_type_range = tnum_unknown;
10508 const struct bpf_prog *prog = env->prog;
10509 struct bpf_reg_state *reg;
10510 struct tnum range = tnum_range(0, 1);
10511 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10513 struct bpf_func_state *frame = env->cur_state->frame[0];
10514 const bool is_subprog = frame->subprogno;
10516 /* LSM and struct_ops func-ptr's return type could be "void" */
10518 switch (prog_type) {
10519 case BPF_PROG_TYPE_LSM:
10520 if (prog->expected_attach_type == BPF_LSM_CGROUP)
10521 /* See below, can be 0 or 0-1 depending on hook. */
10524 case BPF_PROG_TYPE_STRUCT_OPS:
10525 if (!prog->aux->attach_func_proto->type)
10533 /* eBPF calling convention is such that R0 is used
10534 * to return the value from eBPF program.
10535 * Make sure that it's readable at this time
10536 * of bpf_exit, which means that program wrote
10537 * something into it earlier
10539 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10543 if (is_pointer_value(env, BPF_REG_0)) {
10544 verbose(env, "R0 leaks addr as return value\n");
10548 reg = cur_regs(env) + BPF_REG_0;
10550 if (frame->in_async_callback_fn) {
10551 /* enforce return zero from async callbacks like timer */
10552 if (reg->type != SCALAR_VALUE) {
10553 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10554 reg_type_str(env, reg->type));
10558 if (!tnum_in(tnum_const(0), reg->var_off)) {
10559 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10566 if (reg->type != SCALAR_VALUE) {
10567 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10568 reg_type_str(env, reg->type));
10574 switch (prog_type) {
10575 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10576 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10577 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10578 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10579 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10580 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10581 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10582 range = tnum_range(1, 1);
10583 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10584 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10585 range = tnum_range(0, 3);
10587 case BPF_PROG_TYPE_CGROUP_SKB:
10588 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10589 range = tnum_range(0, 3);
10590 enforce_attach_type_range = tnum_range(2, 3);
10593 case BPF_PROG_TYPE_CGROUP_SOCK:
10594 case BPF_PROG_TYPE_SOCK_OPS:
10595 case BPF_PROG_TYPE_CGROUP_DEVICE:
10596 case BPF_PROG_TYPE_CGROUP_SYSCTL:
10597 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10599 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10600 if (!env->prog->aux->attach_btf_id)
10602 range = tnum_const(0);
10604 case BPF_PROG_TYPE_TRACING:
10605 switch (env->prog->expected_attach_type) {
10606 case BPF_TRACE_FENTRY:
10607 case BPF_TRACE_FEXIT:
10608 range = tnum_const(0);
10610 case BPF_TRACE_RAW_TP:
10611 case BPF_MODIFY_RETURN:
10613 case BPF_TRACE_ITER:
10619 case BPF_PROG_TYPE_SK_LOOKUP:
10620 range = tnum_range(SK_DROP, SK_PASS);
10623 case BPF_PROG_TYPE_LSM:
10624 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10625 /* Regular BPF_PROG_TYPE_LSM programs can return
10630 if (!env->prog->aux->attach_func_proto->type) {
10631 /* Make sure programs that attach to void
10632 * hooks don't try to modify return value.
10634 range = tnum_range(1, 1);
10638 case BPF_PROG_TYPE_EXT:
10639 /* freplace program can return anything as its return value
10640 * depends on the to-be-replaced kernel func or bpf program.
10646 if (reg->type != SCALAR_VALUE) {
10647 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10648 reg_type_str(env, reg->type));
10652 if (!tnum_in(range, reg->var_off)) {
10653 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10654 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10655 prog_type == BPF_PROG_TYPE_LSM &&
10656 !prog->aux->attach_func_proto->type)
10657 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10661 if (!tnum_is_unknown(enforce_attach_type_range) &&
10662 tnum_in(enforce_attach_type_range, reg->var_off))
10663 env->prog->enforce_expected_attach_type = 1;
10667 /* non-recursive DFS pseudo code
10668 * 1 procedure DFS-iterative(G,v):
10669 * 2 label v as discovered
10670 * 3 let S be a stack
10672 * 5 while S is not empty
10674 * 7 if t is what we're looking for:
10676 * 9 for all edges e in G.adjacentEdges(t) do
10677 * 10 if edge e is already labelled
10678 * 11 continue with the next edge
10679 * 12 w <- G.adjacentVertex(t,e)
10680 * 13 if vertex w is not discovered and not explored
10681 * 14 label e as tree-edge
10682 * 15 label w as discovered
10685 * 18 else if vertex w is discovered
10686 * 19 label e as back-edge
10688 * 21 // vertex w is explored
10689 * 22 label e as forward- or cross-edge
10690 * 23 label t as explored
10694 * 0x10 - discovered
10695 * 0x11 - discovered and fall-through edge labelled
10696 * 0x12 - discovered and fall-through and branch edges labelled
10707 static u32 state_htab_size(struct bpf_verifier_env *env)
10709 return env->prog->len;
10712 static struct bpf_verifier_state_list **explored_state(
10713 struct bpf_verifier_env *env,
10716 struct bpf_verifier_state *cur = env->cur_state;
10717 struct bpf_func_state *state = cur->frame[cur->curframe];
10719 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10722 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10724 env->insn_aux_data[idx].prune_point = true;
10728 DONE_EXPLORING = 0,
10729 KEEP_EXPLORING = 1,
10732 /* t, w, e - match pseudo-code above:
10733 * t - index of current instruction
10734 * w - next instruction
10737 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10740 int *insn_stack = env->cfg.insn_stack;
10741 int *insn_state = env->cfg.insn_state;
10743 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10744 return DONE_EXPLORING;
10746 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10747 return DONE_EXPLORING;
10749 if (w < 0 || w >= env->prog->len) {
10750 verbose_linfo(env, t, "%d: ", t);
10751 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10756 /* mark branch target for state pruning */
10757 init_explored_state(env, w);
10759 if (insn_state[w] == 0) {
10761 insn_state[t] = DISCOVERED | e;
10762 insn_state[w] = DISCOVERED;
10763 if (env->cfg.cur_stack >= env->prog->len)
10765 insn_stack[env->cfg.cur_stack++] = w;
10766 return KEEP_EXPLORING;
10767 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10768 if (loop_ok && env->bpf_capable)
10769 return DONE_EXPLORING;
10770 verbose_linfo(env, t, "%d: ", t);
10771 verbose_linfo(env, w, "%d: ", w);
10772 verbose(env, "back-edge from insn %d to %d\n", t, w);
10774 } else if (insn_state[w] == EXPLORED) {
10775 /* forward- or cross-edge */
10776 insn_state[t] = DISCOVERED | e;
10778 verbose(env, "insn state internal bug\n");
10781 return DONE_EXPLORING;
10784 static int visit_func_call_insn(int t, int insn_cnt,
10785 struct bpf_insn *insns,
10786 struct bpf_verifier_env *env,
10791 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10795 if (t + 1 < insn_cnt)
10796 init_explored_state(env, t + 1);
10797 if (visit_callee) {
10798 init_explored_state(env, t);
10799 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10800 /* It's ok to allow recursion from CFG point of
10801 * view. __check_func_call() will do the actual
10804 bpf_pseudo_func(insns + t));
10809 /* Visits the instruction at index t and returns one of the following:
10810 * < 0 - an error occurred
10811 * DONE_EXPLORING - the instruction was fully explored
10812 * KEEP_EXPLORING - there is still work to be done before it is fully explored
10814 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10816 struct bpf_insn *insns = env->prog->insnsi;
10819 if (bpf_pseudo_func(insns + t))
10820 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10822 /* All non-branch instructions have a single fall-through edge. */
10823 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10824 BPF_CLASS(insns[t].code) != BPF_JMP32)
10825 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10827 switch (BPF_OP(insns[t].code)) {
10829 return DONE_EXPLORING;
10832 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10833 /* Mark this call insn to trigger is_state_visited() check
10834 * before call itself is processed by __check_func_call().
10835 * Otherwise new async state will be pushed for further
10838 init_explored_state(env, t);
10839 return visit_func_call_insn(t, insn_cnt, insns, env,
10840 insns[t].src_reg == BPF_PSEUDO_CALL);
10843 if (BPF_SRC(insns[t].code) != BPF_K)
10846 /* unconditional jump with single edge */
10847 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10852 /* unconditional jmp is not a good pruning point,
10853 * but it's marked, since backtracking needs
10854 * to record jmp history in is_state_visited().
10856 init_explored_state(env, t + insns[t].off + 1);
10857 /* tell verifier to check for equivalent states
10858 * after every call and jump
10860 if (t + 1 < insn_cnt)
10861 init_explored_state(env, t + 1);
10866 /* conditional jump with two edges */
10867 init_explored_state(env, t);
10868 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10872 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10876 /* non-recursive depth-first-search to detect loops in BPF program
10877 * loop == back-edge in directed graph
10879 static int check_cfg(struct bpf_verifier_env *env)
10881 int insn_cnt = env->prog->len;
10882 int *insn_stack, *insn_state;
10886 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10890 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10892 kvfree(insn_state);
10896 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10897 insn_stack[0] = 0; /* 0 is the first instruction */
10898 env->cfg.cur_stack = 1;
10900 while (env->cfg.cur_stack > 0) {
10901 int t = insn_stack[env->cfg.cur_stack - 1];
10903 ret = visit_insn(t, insn_cnt, env);
10905 case DONE_EXPLORING:
10906 insn_state[t] = EXPLORED;
10907 env->cfg.cur_stack--;
10909 case KEEP_EXPLORING:
10913 verbose(env, "visit_insn internal bug\n");
10920 if (env->cfg.cur_stack < 0) {
10921 verbose(env, "pop stack internal bug\n");
10926 for (i = 0; i < insn_cnt; i++) {
10927 if (insn_state[i] != EXPLORED) {
10928 verbose(env, "unreachable insn %d\n", i);
10933 ret = 0; /* cfg looks good */
10936 kvfree(insn_state);
10937 kvfree(insn_stack);
10938 env->cfg.insn_state = env->cfg.insn_stack = NULL;
10942 static int check_abnormal_return(struct bpf_verifier_env *env)
10946 for (i = 1; i < env->subprog_cnt; i++) {
10947 if (env->subprog_info[i].has_ld_abs) {
10948 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10951 if (env->subprog_info[i].has_tail_call) {
10952 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10959 /* The minimum supported BTF func info size */
10960 #define MIN_BPF_FUNCINFO_SIZE 8
10961 #define MAX_FUNCINFO_REC_SIZE 252
10963 static int check_btf_func(struct bpf_verifier_env *env,
10964 const union bpf_attr *attr,
10967 const struct btf_type *type, *func_proto, *ret_type;
10968 u32 i, nfuncs, urec_size, min_size;
10969 u32 krec_size = sizeof(struct bpf_func_info);
10970 struct bpf_func_info *krecord;
10971 struct bpf_func_info_aux *info_aux = NULL;
10972 struct bpf_prog *prog;
10973 const struct btf *btf;
10975 u32 prev_offset = 0;
10976 bool scalar_return;
10979 nfuncs = attr->func_info_cnt;
10981 if (check_abnormal_return(env))
10986 if (nfuncs != env->subprog_cnt) {
10987 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10991 urec_size = attr->func_info_rec_size;
10992 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10993 urec_size > MAX_FUNCINFO_REC_SIZE ||
10994 urec_size % sizeof(u32)) {
10995 verbose(env, "invalid func info rec size %u\n", urec_size);
11000 btf = prog->aux->btf;
11002 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11003 min_size = min_t(u32, krec_size, urec_size);
11005 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11008 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11012 for (i = 0; i < nfuncs; i++) {
11013 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11015 if (ret == -E2BIG) {
11016 verbose(env, "nonzero tailing record in func info");
11017 /* set the size kernel expects so loader can zero
11018 * out the rest of the record.
11020 if (copy_to_bpfptr_offset(uattr,
11021 offsetof(union bpf_attr, func_info_rec_size),
11022 &min_size, sizeof(min_size)))
11028 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11033 /* check insn_off */
11036 if (krecord[i].insn_off) {
11038 "nonzero insn_off %u for the first func info record",
11039 krecord[i].insn_off);
11042 } else if (krecord[i].insn_off <= prev_offset) {
11044 "same or smaller insn offset (%u) than previous func info record (%u)",
11045 krecord[i].insn_off, prev_offset);
11049 if (env->subprog_info[i].start != krecord[i].insn_off) {
11050 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11054 /* check type_id */
11055 type = btf_type_by_id(btf, krecord[i].type_id);
11056 if (!type || !btf_type_is_func(type)) {
11057 verbose(env, "invalid type id %d in func info",
11058 krecord[i].type_id);
11061 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11063 func_proto = btf_type_by_id(btf, type->type);
11064 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11065 /* btf_func_check() already verified it during BTF load */
11067 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11069 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11070 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11071 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11074 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11075 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11079 prev_offset = krecord[i].insn_off;
11080 bpfptr_add(&urecord, urec_size);
11083 prog->aux->func_info = krecord;
11084 prog->aux->func_info_cnt = nfuncs;
11085 prog->aux->func_info_aux = info_aux;
11094 static void adjust_btf_func(struct bpf_verifier_env *env)
11096 struct bpf_prog_aux *aux = env->prog->aux;
11099 if (!aux->func_info)
11102 for (i = 0; i < env->subprog_cnt; i++)
11103 aux->func_info[i].insn_off = env->subprog_info[i].start;
11106 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
11107 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
11109 static int check_btf_line(struct bpf_verifier_env *env,
11110 const union bpf_attr *attr,
11113 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11114 struct bpf_subprog_info *sub;
11115 struct bpf_line_info *linfo;
11116 struct bpf_prog *prog;
11117 const struct btf *btf;
11121 nr_linfo = attr->line_info_cnt;
11124 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11127 rec_size = attr->line_info_rec_size;
11128 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11129 rec_size > MAX_LINEINFO_REC_SIZE ||
11130 rec_size & (sizeof(u32) - 1))
11133 /* Need to zero it in case the userspace may
11134 * pass in a smaller bpf_line_info object.
11136 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11137 GFP_KERNEL | __GFP_NOWARN);
11142 btf = prog->aux->btf;
11145 sub = env->subprog_info;
11146 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11147 expected_size = sizeof(struct bpf_line_info);
11148 ncopy = min_t(u32, expected_size, rec_size);
11149 for (i = 0; i < nr_linfo; i++) {
11150 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11152 if (err == -E2BIG) {
11153 verbose(env, "nonzero tailing record in line_info");
11154 if (copy_to_bpfptr_offset(uattr,
11155 offsetof(union bpf_attr, line_info_rec_size),
11156 &expected_size, sizeof(expected_size)))
11162 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11168 * Check insn_off to ensure
11169 * 1) strictly increasing AND
11170 * 2) bounded by prog->len
11172 * The linfo[0].insn_off == 0 check logically falls into
11173 * the later "missing bpf_line_info for func..." case
11174 * because the first linfo[0].insn_off must be the
11175 * first sub also and the first sub must have
11176 * subprog_info[0].start == 0.
11178 if ((i && linfo[i].insn_off <= prev_offset) ||
11179 linfo[i].insn_off >= prog->len) {
11180 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11181 i, linfo[i].insn_off, prev_offset,
11187 if (!prog->insnsi[linfo[i].insn_off].code) {
11189 "Invalid insn code at line_info[%u].insn_off\n",
11195 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11196 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11197 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11202 if (s != env->subprog_cnt) {
11203 if (linfo[i].insn_off == sub[s].start) {
11204 sub[s].linfo_idx = i;
11206 } else if (sub[s].start < linfo[i].insn_off) {
11207 verbose(env, "missing bpf_line_info for func#%u\n", s);
11213 prev_offset = linfo[i].insn_off;
11214 bpfptr_add(&ulinfo, rec_size);
11217 if (s != env->subprog_cnt) {
11218 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11219 env->subprog_cnt - s, s);
11224 prog->aux->linfo = linfo;
11225 prog->aux->nr_linfo = nr_linfo;
11234 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
11235 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
11237 static int check_core_relo(struct bpf_verifier_env *env,
11238 const union bpf_attr *attr,
11241 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11242 struct bpf_core_relo core_relo = {};
11243 struct bpf_prog *prog = env->prog;
11244 const struct btf *btf = prog->aux->btf;
11245 struct bpf_core_ctx ctx = {
11249 bpfptr_t u_core_relo;
11252 nr_core_relo = attr->core_relo_cnt;
11255 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11258 rec_size = attr->core_relo_rec_size;
11259 if (rec_size < MIN_CORE_RELO_SIZE ||
11260 rec_size > MAX_CORE_RELO_SIZE ||
11261 rec_size % sizeof(u32))
11264 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11265 expected_size = sizeof(struct bpf_core_relo);
11266 ncopy = min_t(u32, expected_size, rec_size);
11268 /* Unlike func_info and line_info, copy and apply each CO-RE
11269 * relocation record one at a time.
11271 for (i = 0; i < nr_core_relo; i++) {
11272 /* future proofing when sizeof(bpf_core_relo) changes */
11273 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11275 if (err == -E2BIG) {
11276 verbose(env, "nonzero tailing record in core_relo");
11277 if (copy_to_bpfptr_offset(uattr,
11278 offsetof(union bpf_attr, core_relo_rec_size),
11279 &expected_size, sizeof(expected_size)))
11285 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11290 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11291 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11292 i, core_relo.insn_off, prog->len);
11297 err = bpf_core_apply(&ctx, &core_relo, i,
11298 &prog->insnsi[core_relo.insn_off / 8]);
11301 bpfptr_add(&u_core_relo, rec_size);
11306 static int check_btf_info(struct bpf_verifier_env *env,
11307 const union bpf_attr *attr,
11313 if (!attr->func_info_cnt && !attr->line_info_cnt) {
11314 if (check_abnormal_return(env))
11319 btf = btf_get_by_fd(attr->prog_btf_fd);
11321 return PTR_ERR(btf);
11322 if (btf_is_kernel(btf)) {
11326 env->prog->aux->btf = btf;
11328 err = check_btf_func(env, attr, uattr);
11332 err = check_btf_line(env, attr, uattr);
11336 err = check_core_relo(env, attr, uattr);
11343 /* check %cur's range satisfies %old's */
11344 static bool range_within(struct bpf_reg_state *old,
11345 struct bpf_reg_state *cur)
11347 return old->umin_value <= cur->umin_value &&
11348 old->umax_value >= cur->umax_value &&
11349 old->smin_value <= cur->smin_value &&
11350 old->smax_value >= cur->smax_value &&
11351 old->u32_min_value <= cur->u32_min_value &&
11352 old->u32_max_value >= cur->u32_max_value &&
11353 old->s32_min_value <= cur->s32_min_value &&
11354 old->s32_max_value >= cur->s32_max_value;
11357 /* If in the old state two registers had the same id, then they need to have
11358 * the same id in the new state as well. But that id could be different from
11359 * the old state, so we need to track the mapping from old to new ids.
11360 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11361 * regs with old id 5 must also have new id 9 for the new state to be safe. But
11362 * regs with a different old id could still have new id 9, we don't care about
11364 * So we look through our idmap to see if this old id has been seen before. If
11365 * so, we require the new id to match; otherwise, we add the id pair to the map.
11367 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11371 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11372 if (!idmap[i].old) {
11373 /* Reached an empty slot; haven't seen this id before */
11374 idmap[i].old = old_id;
11375 idmap[i].cur = cur_id;
11378 if (idmap[i].old == old_id)
11379 return idmap[i].cur == cur_id;
11381 /* We ran out of idmap slots, which should be impossible */
11386 static void clean_func_state(struct bpf_verifier_env *env,
11387 struct bpf_func_state *st)
11389 enum bpf_reg_liveness live;
11392 for (i = 0; i < BPF_REG_FP; i++) {
11393 live = st->regs[i].live;
11394 /* liveness must not touch this register anymore */
11395 st->regs[i].live |= REG_LIVE_DONE;
11396 if (!(live & REG_LIVE_READ))
11397 /* since the register is unused, clear its state
11398 * to make further comparison simpler
11400 __mark_reg_not_init(env, &st->regs[i]);
11403 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11404 live = st->stack[i].spilled_ptr.live;
11405 /* liveness must not touch this stack slot anymore */
11406 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11407 if (!(live & REG_LIVE_READ)) {
11408 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11409 for (j = 0; j < BPF_REG_SIZE; j++)
11410 st->stack[i].slot_type[j] = STACK_INVALID;
11415 static void clean_verifier_state(struct bpf_verifier_env *env,
11416 struct bpf_verifier_state *st)
11420 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11421 /* all regs in this state in all frames were already marked */
11424 for (i = 0; i <= st->curframe; i++)
11425 clean_func_state(env, st->frame[i]);
11428 /* the parentage chains form a tree.
11429 * the verifier states are added to state lists at given insn and
11430 * pushed into state stack for future exploration.
11431 * when the verifier reaches bpf_exit insn some of the verifer states
11432 * stored in the state lists have their final liveness state already,
11433 * but a lot of states will get revised from liveness point of view when
11434 * the verifier explores other branches.
11437 * 2: if r1 == 100 goto pc+1
11440 * when the verifier reaches exit insn the register r0 in the state list of
11441 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11442 * of insn 2 and goes exploring further. At the insn 4 it will walk the
11443 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11445 * Since the verifier pushes the branch states as it sees them while exploring
11446 * the program the condition of walking the branch instruction for the second
11447 * time means that all states below this branch were already explored and
11448 * their final liveness marks are already propagated.
11449 * Hence when the verifier completes the search of state list in is_state_visited()
11450 * we can call this clean_live_states() function to mark all liveness states
11451 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11452 * will not be used.
11453 * This function also clears the registers and stack for states that !READ
11454 * to simplify state merging.
11456 * Important note here that walking the same branch instruction in the callee
11457 * doesn't meant that the states are DONE. The verifier has to compare
11460 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11461 struct bpf_verifier_state *cur)
11463 struct bpf_verifier_state_list *sl;
11466 sl = *explored_state(env, insn);
11468 if (sl->state.branches)
11470 if (sl->state.insn_idx != insn ||
11471 sl->state.curframe != cur->curframe)
11473 for (i = 0; i <= cur->curframe; i++)
11474 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11476 clean_verifier_state(env, &sl->state);
11482 /* Returns true if (rold safe implies rcur safe) */
11483 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11484 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11488 if (!(rold->live & REG_LIVE_READ))
11489 /* explored state didn't use this */
11492 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11494 if (rold->type == PTR_TO_STACK)
11495 /* two stack pointers are equal only if they're pointing to
11496 * the same stack frame, since fp-8 in foo != fp-8 in bar
11498 return equal && rold->frameno == rcur->frameno;
11503 if (rold->type == NOT_INIT)
11504 /* explored state can't have used this */
11506 if (rcur->type == NOT_INIT)
11508 switch (base_type(rold->type)) {
11510 if (env->explore_alu_limits)
11512 if (rcur->type == SCALAR_VALUE) {
11513 if (!rold->precise && !rcur->precise)
11515 /* new val must satisfy old val knowledge */
11516 return range_within(rold, rcur) &&
11517 tnum_in(rold->var_off, rcur->var_off);
11519 /* We're trying to use a pointer in place of a scalar.
11520 * Even if the scalar was unbounded, this could lead to
11521 * pointer leaks because scalars are allowed to leak
11522 * while pointers are not. We could make this safe in
11523 * special cases if root is calling us, but it's
11524 * probably not worth the hassle.
11528 case PTR_TO_MAP_KEY:
11529 case PTR_TO_MAP_VALUE:
11530 /* a PTR_TO_MAP_VALUE could be safe to use as a
11531 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11532 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11533 * checked, doing so could have affected others with the same
11534 * id, and we can't check for that because we lost the id when
11535 * we converted to a PTR_TO_MAP_VALUE.
11537 if (type_may_be_null(rold->type)) {
11538 if (!type_may_be_null(rcur->type))
11540 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11542 /* Check our ids match any regs they're supposed to */
11543 return check_ids(rold->id, rcur->id, idmap);
11546 /* If the new min/max/var_off satisfy the old ones and
11547 * everything else matches, we are OK.
11548 * 'id' is not compared, since it's only used for maps with
11549 * bpf_spin_lock inside map element and in such cases if
11550 * the rest of the prog is valid for one map element then
11551 * it's valid for all map elements regardless of the key
11552 * used in bpf_map_lookup()
11554 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11555 range_within(rold, rcur) &&
11556 tnum_in(rold->var_off, rcur->var_off);
11557 case PTR_TO_PACKET_META:
11558 case PTR_TO_PACKET:
11559 if (rcur->type != rold->type)
11561 /* We must have at least as much range as the old ptr
11562 * did, so that any accesses which were safe before are
11563 * still safe. This is true even if old range < old off,
11564 * since someone could have accessed through (ptr - k), or
11565 * even done ptr -= k in a register, to get a safe access.
11567 if (rold->range > rcur->range)
11569 /* If the offsets don't match, we can't trust our alignment;
11570 * nor can we be sure that we won't fall out of range.
11572 if (rold->off != rcur->off)
11574 /* id relations must be preserved */
11575 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11577 /* new val must satisfy old val knowledge */
11578 return range_within(rold, rcur) &&
11579 tnum_in(rold->var_off, rcur->var_off);
11581 case CONST_PTR_TO_MAP:
11582 case PTR_TO_PACKET_END:
11583 case PTR_TO_FLOW_KEYS:
11584 case PTR_TO_SOCKET:
11585 case PTR_TO_SOCK_COMMON:
11586 case PTR_TO_TCP_SOCK:
11587 case PTR_TO_XDP_SOCK:
11588 /* Only valid matches are exact, which memcmp() above
11589 * would have accepted
11592 /* Don't know what's going on, just say it's not safe */
11596 /* Shouldn't get here; if we do, say it's not safe */
11601 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11602 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11606 /* walk slots of the explored stack and ignore any additional
11607 * slots in the current stack, since explored(safe) state
11610 for (i = 0; i < old->allocated_stack; i++) {
11611 spi = i / BPF_REG_SIZE;
11613 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11614 i += BPF_REG_SIZE - 1;
11615 /* explored state didn't use this */
11619 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11622 /* explored stack has more populated slots than current stack
11623 * and these slots were used
11625 if (i >= cur->allocated_stack)
11628 /* if old state was safe with misc data in the stack
11629 * it will be safe with zero-initialized stack.
11630 * The opposite is not true
11632 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11633 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11635 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11636 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11637 /* Ex: old explored (safe) state has STACK_SPILL in
11638 * this stack slot, but current has STACK_MISC ->
11639 * this verifier states are not equivalent,
11640 * return false to continue verification of this path
11643 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11645 if (!is_spilled_reg(&old->stack[spi]))
11647 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11648 &cur->stack[spi].spilled_ptr, idmap))
11649 /* when explored and current stack slot are both storing
11650 * spilled registers, check that stored pointers types
11651 * are the same as well.
11652 * Ex: explored safe path could have stored
11653 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11654 * but current path has stored:
11655 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11656 * such verifier states are not equivalent.
11657 * return false to continue verification of this path
11664 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11666 if (old->acquired_refs != cur->acquired_refs)
11668 return !memcmp(old->refs, cur->refs,
11669 sizeof(*old->refs) * old->acquired_refs);
11672 /* compare two verifier states
11674 * all states stored in state_list are known to be valid, since
11675 * verifier reached 'bpf_exit' instruction through them
11677 * this function is called when verifier exploring different branches of
11678 * execution popped from the state stack. If it sees an old state that has
11679 * more strict register state and more strict stack state then this execution
11680 * branch doesn't need to be explored further, since verifier already
11681 * concluded that more strict state leads to valid finish.
11683 * Therefore two states are equivalent if register state is more conservative
11684 * and explored stack state is more conservative than the current one.
11687 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11688 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11690 * In other words if current stack state (one being explored) has more
11691 * valid slots than old one that already passed validation, it means
11692 * the verifier can stop exploring and conclude that current state is valid too
11694 * Similarly with registers. If explored state has register type as invalid
11695 * whereas register type in current state is meaningful, it means that
11696 * the current state will reach 'bpf_exit' instruction safely
11698 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11699 struct bpf_func_state *cur)
11703 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11704 for (i = 0; i < MAX_BPF_REG; i++)
11705 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11706 env->idmap_scratch))
11709 if (!stacksafe(env, old, cur, env->idmap_scratch))
11712 if (!refsafe(old, cur))
11718 static bool states_equal(struct bpf_verifier_env *env,
11719 struct bpf_verifier_state *old,
11720 struct bpf_verifier_state *cur)
11724 if (old->curframe != cur->curframe)
11727 /* Verification state from speculative execution simulation
11728 * must never prune a non-speculative execution one.
11730 if (old->speculative && !cur->speculative)
11733 if (old->active_spin_lock != cur->active_spin_lock)
11736 /* for states to be equal callsites have to be the same
11737 * and all frame states need to be equivalent
11739 for (i = 0; i <= old->curframe; i++) {
11740 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11742 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11748 /* Return 0 if no propagation happened. Return negative error code if error
11749 * happened. Otherwise, return the propagated bit.
11751 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11752 struct bpf_reg_state *reg,
11753 struct bpf_reg_state *parent_reg)
11755 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11756 u8 flag = reg->live & REG_LIVE_READ;
11759 /* When comes here, read flags of PARENT_REG or REG could be any of
11760 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11761 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11763 if (parent_flag == REG_LIVE_READ64 ||
11764 /* Or if there is no read flag from REG. */
11766 /* Or if the read flag from REG is the same as PARENT_REG. */
11767 parent_flag == flag)
11770 err = mark_reg_read(env, reg, parent_reg, flag);
11777 /* A write screens off any subsequent reads; but write marks come from the
11778 * straight-line code between a state and its parent. When we arrive at an
11779 * equivalent state (jump target or such) we didn't arrive by the straight-line
11780 * code, so read marks in the state must propagate to the parent regardless
11781 * of the state's write marks. That's what 'parent == state->parent' comparison
11782 * in mark_reg_read() is for.
11784 static int propagate_liveness(struct bpf_verifier_env *env,
11785 const struct bpf_verifier_state *vstate,
11786 struct bpf_verifier_state *vparent)
11788 struct bpf_reg_state *state_reg, *parent_reg;
11789 struct bpf_func_state *state, *parent;
11790 int i, frame, err = 0;
11792 if (vparent->curframe != vstate->curframe) {
11793 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11794 vparent->curframe, vstate->curframe);
11797 /* Propagate read liveness of registers... */
11798 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11799 for (frame = 0; frame <= vstate->curframe; frame++) {
11800 parent = vparent->frame[frame];
11801 state = vstate->frame[frame];
11802 parent_reg = parent->regs;
11803 state_reg = state->regs;
11804 /* We don't need to worry about FP liveness, it's read-only */
11805 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11806 err = propagate_liveness_reg(env, &state_reg[i],
11810 if (err == REG_LIVE_READ64)
11811 mark_insn_zext(env, &parent_reg[i]);
11814 /* Propagate stack slots. */
11815 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11816 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11817 parent_reg = &parent->stack[i].spilled_ptr;
11818 state_reg = &state->stack[i].spilled_ptr;
11819 err = propagate_liveness_reg(env, state_reg,
11828 /* find precise scalars in the previous equivalent state and
11829 * propagate them into the current state
11831 static int propagate_precision(struct bpf_verifier_env *env,
11832 const struct bpf_verifier_state *old)
11834 struct bpf_reg_state *state_reg;
11835 struct bpf_func_state *state;
11838 state = old->frame[old->curframe];
11839 state_reg = state->regs;
11840 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11841 if (state_reg->type != SCALAR_VALUE ||
11842 !state_reg->precise)
11844 if (env->log.level & BPF_LOG_LEVEL2)
11845 verbose(env, "propagating r%d\n", i);
11846 err = mark_chain_precision(env, i);
11851 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11852 if (!is_spilled_reg(&state->stack[i]))
11854 state_reg = &state->stack[i].spilled_ptr;
11855 if (state_reg->type != SCALAR_VALUE ||
11856 !state_reg->precise)
11858 if (env->log.level & BPF_LOG_LEVEL2)
11859 verbose(env, "propagating fp%d\n",
11860 (-i - 1) * BPF_REG_SIZE);
11861 err = mark_chain_precision_stack(env, i);
11868 static bool states_maybe_looping(struct bpf_verifier_state *old,
11869 struct bpf_verifier_state *cur)
11871 struct bpf_func_state *fold, *fcur;
11872 int i, fr = cur->curframe;
11874 if (old->curframe != fr)
11877 fold = old->frame[fr];
11878 fcur = cur->frame[fr];
11879 for (i = 0; i < MAX_BPF_REG; i++)
11880 if (memcmp(&fold->regs[i], &fcur->regs[i],
11881 offsetof(struct bpf_reg_state, parent)))
11887 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11889 struct bpf_verifier_state_list *new_sl;
11890 struct bpf_verifier_state_list *sl, **pprev;
11891 struct bpf_verifier_state *cur = env->cur_state, *new;
11892 int i, j, err, states_cnt = 0;
11893 bool add_new_state = env->test_state_freq ? true : false;
11895 cur->last_insn_idx = env->prev_insn_idx;
11896 if (!env->insn_aux_data[insn_idx].prune_point)
11897 /* this 'insn_idx' instruction wasn't marked, so we will not
11898 * be doing state search here
11902 /* bpf progs typically have pruning point every 4 instructions
11903 * http://vger.kernel.org/bpfconf2019.html#session-1
11904 * Do not add new state for future pruning if the verifier hasn't seen
11905 * at least 2 jumps and at least 8 instructions.
11906 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11907 * In tests that amounts to up to 50% reduction into total verifier
11908 * memory consumption and 20% verifier time speedup.
11910 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11911 env->insn_processed - env->prev_insn_processed >= 8)
11912 add_new_state = true;
11914 pprev = explored_state(env, insn_idx);
11917 clean_live_states(env, insn_idx, cur);
11921 if (sl->state.insn_idx != insn_idx)
11924 if (sl->state.branches) {
11925 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11927 if (frame->in_async_callback_fn &&
11928 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11929 /* Different async_entry_cnt means that the verifier is
11930 * processing another entry into async callback.
11931 * Seeing the same state is not an indication of infinite
11932 * loop or infinite recursion.
11933 * But finding the same state doesn't mean that it's safe
11934 * to stop processing the current state. The previous state
11935 * hasn't yet reached bpf_exit, since state.branches > 0.
11936 * Checking in_async_callback_fn alone is not enough either.
11937 * Since the verifier still needs to catch infinite loops
11938 * inside async callbacks.
11940 } else if (states_maybe_looping(&sl->state, cur) &&
11941 states_equal(env, &sl->state, cur)) {
11942 verbose_linfo(env, insn_idx, "; ");
11943 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11946 /* if the verifier is processing a loop, avoid adding new state
11947 * too often, since different loop iterations have distinct
11948 * states and may not help future pruning.
11949 * This threshold shouldn't be too low to make sure that
11950 * a loop with large bound will be rejected quickly.
11951 * The most abusive loop will be:
11953 * if r1 < 1000000 goto pc-2
11954 * 1M insn_procssed limit / 100 == 10k peak states.
11955 * This threshold shouldn't be too high either, since states
11956 * at the end of the loop are likely to be useful in pruning.
11958 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11959 env->insn_processed - env->prev_insn_processed < 100)
11960 add_new_state = false;
11963 if (states_equal(env, &sl->state, cur)) {
11965 /* reached equivalent register/stack state,
11966 * prune the search.
11967 * Registers read by the continuation are read by us.
11968 * If we have any write marks in env->cur_state, they
11969 * will prevent corresponding reads in the continuation
11970 * from reaching our parent (an explored_state). Our
11971 * own state will get the read marks recorded, but
11972 * they'll be immediately forgotten as we're pruning
11973 * this state and will pop a new one.
11975 err = propagate_liveness(env, &sl->state, cur);
11977 /* if previous state reached the exit with precision and
11978 * current state is equivalent to it (except precsion marks)
11979 * the precision needs to be propagated back in
11980 * the current state.
11982 err = err ? : push_jmp_history(env, cur);
11983 err = err ? : propagate_precision(env, &sl->state);
11989 /* when new state is not going to be added do not increase miss count.
11990 * Otherwise several loop iterations will remove the state
11991 * recorded earlier. The goal of these heuristics is to have
11992 * states from some iterations of the loop (some in the beginning
11993 * and some at the end) to help pruning.
11997 /* heuristic to determine whether this state is beneficial
11998 * to keep checking from state equivalence point of view.
11999 * Higher numbers increase max_states_per_insn and verification time,
12000 * but do not meaningfully decrease insn_processed.
12002 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12003 /* the state is unlikely to be useful. Remove it to
12004 * speed up verification
12007 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12008 u32 br = sl->state.branches;
12011 "BUG live_done but branches_to_explore %d\n",
12013 free_verifier_state(&sl->state, false);
12015 env->peak_states--;
12017 /* cannot free this state, since parentage chain may
12018 * walk it later. Add it for free_list instead to
12019 * be freed at the end of verification
12021 sl->next = env->free_list;
12022 env->free_list = sl;
12032 if (env->max_states_per_insn < states_cnt)
12033 env->max_states_per_insn = states_cnt;
12035 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12036 return push_jmp_history(env, cur);
12038 if (!add_new_state)
12039 return push_jmp_history(env, cur);
12041 /* There were no equivalent states, remember the current one.
12042 * Technically the current state is not proven to be safe yet,
12043 * but it will either reach outer most bpf_exit (which means it's safe)
12044 * or it will be rejected. When there are no loops the verifier won't be
12045 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12046 * again on the way to bpf_exit.
12047 * When looping the sl->state.branches will be > 0 and this state
12048 * will not be considered for equivalence until branches == 0.
12050 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12053 env->total_states++;
12054 env->peak_states++;
12055 env->prev_jmps_processed = env->jmps_processed;
12056 env->prev_insn_processed = env->insn_processed;
12058 /* add new state to the head of linked list */
12059 new = &new_sl->state;
12060 err = copy_verifier_state(new, cur);
12062 free_verifier_state(new, false);
12066 new->insn_idx = insn_idx;
12067 WARN_ONCE(new->branches != 1,
12068 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12071 cur->first_insn_idx = insn_idx;
12072 clear_jmp_history(cur);
12073 new_sl->next = *explored_state(env, insn_idx);
12074 *explored_state(env, insn_idx) = new_sl;
12075 /* connect new state to parentage chain. Current frame needs all
12076 * registers connected. Only r6 - r9 of the callers are alive (pushed
12077 * to the stack implicitly by JITs) so in callers' frames connect just
12078 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12079 * the state of the call instruction (with WRITTEN set), and r0 comes
12080 * from callee with its full parentage chain, anyway.
12082 /* clear write marks in current state: the writes we did are not writes
12083 * our child did, so they don't screen off its reads from us.
12084 * (There are no read marks in current state, because reads always mark
12085 * their parent and current state never has children yet. Only
12086 * explored_states can get read marks.)
12088 for (j = 0; j <= cur->curframe; j++) {
12089 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12090 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12091 for (i = 0; i < BPF_REG_FP; i++)
12092 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12095 /* all stack frames are accessible from callee, clear them all */
12096 for (j = 0; j <= cur->curframe; j++) {
12097 struct bpf_func_state *frame = cur->frame[j];
12098 struct bpf_func_state *newframe = new->frame[j];
12100 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12101 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12102 frame->stack[i].spilled_ptr.parent =
12103 &newframe->stack[i].spilled_ptr;
12109 /* Return true if it's OK to have the same insn return a different type. */
12110 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12112 switch (base_type(type)) {
12114 case PTR_TO_SOCKET:
12115 case PTR_TO_SOCK_COMMON:
12116 case PTR_TO_TCP_SOCK:
12117 case PTR_TO_XDP_SOCK:
12118 case PTR_TO_BTF_ID:
12125 /* If an instruction was previously used with particular pointer types, then we
12126 * need to be careful to avoid cases such as the below, where it may be ok
12127 * for one branch accessing the pointer, but not ok for the other branch:
12132 * R1 = some_other_valid_ptr;
12135 * R2 = *(u32 *)(R1 + 0);
12137 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12139 return src != prev && (!reg_type_mismatch_ok(src) ||
12140 !reg_type_mismatch_ok(prev));
12143 static int do_check(struct bpf_verifier_env *env)
12145 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12146 struct bpf_verifier_state *state = env->cur_state;
12147 struct bpf_insn *insns = env->prog->insnsi;
12148 struct bpf_reg_state *regs;
12149 int insn_cnt = env->prog->len;
12150 bool do_print_state = false;
12151 int prev_insn_idx = -1;
12154 struct bpf_insn *insn;
12158 env->prev_insn_idx = prev_insn_idx;
12159 if (env->insn_idx >= insn_cnt) {
12160 verbose(env, "invalid insn idx %d insn_cnt %d\n",
12161 env->insn_idx, insn_cnt);
12165 insn = &insns[env->insn_idx];
12166 class = BPF_CLASS(insn->code);
12168 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12170 "BPF program is too large. Processed %d insn\n",
12171 env->insn_processed);
12175 err = is_state_visited(env, env->insn_idx);
12179 /* found equivalent state, can prune the search */
12180 if (env->log.level & BPF_LOG_LEVEL) {
12181 if (do_print_state)
12182 verbose(env, "\nfrom %d to %d%s: safe\n",
12183 env->prev_insn_idx, env->insn_idx,
12184 env->cur_state->speculative ?
12185 " (speculative execution)" : "");
12187 verbose(env, "%d: safe\n", env->insn_idx);
12189 goto process_bpf_exit;
12192 if (signal_pending(current))
12195 if (need_resched())
12198 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12199 verbose(env, "\nfrom %d to %d%s:",
12200 env->prev_insn_idx, env->insn_idx,
12201 env->cur_state->speculative ?
12202 " (speculative execution)" : "");
12203 print_verifier_state(env, state->frame[state->curframe], true);
12204 do_print_state = false;
12207 if (env->log.level & BPF_LOG_LEVEL) {
12208 const struct bpf_insn_cbs cbs = {
12209 .cb_call = disasm_kfunc_name,
12210 .cb_print = verbose,
12211 .private_data = env,
12214 if (verifier_state_scratched(env))
12215 print_insn_state(env, state->frame[state->curframe]);
12217 verbose_linfo(env, env->insn_idx, "; ");
12218 env->prev_log_len = env->log.len_used;
12219 verbose(env, "%d: ", env->insn_idx);
12220 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12221 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12222 env->prev_log_len = env->log.len_used;
12225 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12226 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12227 env->prev_insn_idx);
12232 regs = cur_regs(env);
12233 sanitize_mark_insn_seen(env);
12234 prev_insn_idx = env->insn_idx;
12236 if (class == BPF_ALU || class == BPF_ALU64) {
12237 err = check_alu_op(env, insn);
12241 } else if (class == BPF_LDX) {
12242 enum bpf_reg_type *prev_src_type, src_reg_type;
12244 /* check for reserved fields is already done */
12246 /* check src operand */
12247 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12251 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12255 src_reg_type = regs[insn->src_reg].type;
12257 /* check that memory (src_reg + off) is readable,
12258 * the state of dst_reg will be updated by this func
12260 err = check_mem_access(env, env->insn_idx, insn->src_reg,
12261 insn->off, BPF_SIZE(insn->code),
12262 BPF_READ, insn->dst_reg, false);
12266 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12268 if (*prev_src_type == NOT_INIT) {
12269 /* saw a valid insn
12270 * dst_reg = *(u32 *)(src_reg + off)
12271 * save type to validate intersecting paths
12273 *prev_src_type = src_reg_type;
12275 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12276 /* ABuser program is trying to use the same insn
12277 * dst_reg = *(u32*) (src_reg + off)
12278 * with different pointer types:
12279 * src_reg == ctx in one branch and
12280 * src_reg == stack|map in some other branch.
12283 verbose(env, "same insn cannot be used with different pointers\n");
12287 } else if (class == BPF_STX) {
12288 enum bpf_reg_type *prev_dst_type, dst_reg_type;
12290 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12291 err = check_atomic(env, env->insn_idx, insn);
12298 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12299 verbose(env, "BPF_STX uses reserved fields\n");
12303 /* check src1 operand */
12304 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12307 /* check src2 operand */
12308 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12312 dst_reg_type = regs[insn->dst_reg].type;
12314 /* check that memory (dst_reg + off) is writeable */
12315 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12316 insn->off, BPF_SIZE(insn->code),
12317 BPF_WRITE, insn->src_reg, false);
12321 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12323 if (*prev_dst_type == NOT_INIT) {
12324 *prev_dst_type = dst_reg_type;
12325 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12326 verbose(env, "same insn cannot be used with different pointers\n");
12330 } else if (class == BPF_ST) {
12331 if (BPF_MODE(insn->code) != BPF_MEM ||
12332 insn->src_reg != BPF_REG_0) {
12333 verbose(env, "BPF_ST uses reserved fields\n");
12336 /* check src operand */
12337 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12341 if (is_ctx_reg(env, insn->dst_reg)) {
12342 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12344 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12348 /* check that memory (dst_reg + off) is writeable */
12349 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12350 insn->off, BPF_SIZE(insn->code),
12351 BPF_WRITE, -1, false);
12355 } else if (class == BPF_JMP || class == BPF_JMP32) {
12356 u8 opcode = BPF_OP(insn->code);
12358 env->jmps_processed++;
12359 if (opcode == BPF_CALL) {
12360 if (BPF_SRC(insn->code) != BPF_K ||
12361 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12362 && insn->off != 0) ||
12363 (insn->src_reg != BPF_REG_0 &&
12364 insn->src_reg != BPF_PSEUDO_CALL &&
12365 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12366 insn->dst_reg != BPF_REG_0 ||
12367 class == BPF_JMP32) {
12368 verbose(env, "BPF_CALL uses reserved fields\n");
12372 if (env->cur_state->active_spin_lock &&
12373 (insn->src_reg == BPF_PSEUDO_CALL ||
12374 insn->imm != BPF_FUNC_spin_unlock)) {
12375 verbose(env, "function calls are not allowed while holding a lock\n");
12378 if (insn->src_reg == BPF_PSEUDO_CALL)
12379 err = check_func_call(env, insn, &env->insn_idx);
12380 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12381 err = check_kfunc_call(env, insn, &env->insn_idx);
12383 err = check_helper_call(env, insn, &env->insn_idx);
12386 } else if (opcode == BPF_JA) {
12387 if (BPF_SRC(insn->code) != BPF_K ||
12389 insn->src_reg != BPF_REG_0 ||
12390 insn->dst_reg != BPF_REG_0 ||
12391 class == BPF_JMP32) {
12392 verbose(env, "BPF_JA uses reserved fields\n");
12396 env->insn_idx += insn->off + 1;
12399 } else if (opcode == BPF_EXIT) {
12400 if (BPF_SRC(insn->code) != BPF_K ||
12402 insn->src_reg != BPF_REG_0 ||
12403 insn->dst_reg != BPF_REG_0 ||
12404 class == BPF_JMP32) {
12405 verbose(env, "BPF_EXIT uses reserved fields\n");
12409 if (env->cur_state->active_spin_lock) {
12410 verbose(env, "bpf_spin_unlock is missing\n");
12414 /* We must do check_reference_leak here before
12415 * prepare_func_exit to handle the case when
12416 * state->curframe > 0, it may be a callback
12417 * function, for which reference_state must
12418 * match caller reference state when it exits.
12420 err = check_reference_leak(env);
12424 if (state->curframe) {
12425 /* exit from nested function */
12426 err = prepare_func_exit(env, &env->insn_idx);
12429 do_print_state = true;
12433 err = check_return_code(env);
12437 mark_verifier_state_scratched(env);
12438 update_branch_counts(env, env->cur_state);
12439 err = pop_stack(env, &prev_insn_idx,
12440 &env->insn_idx, pop_log);
12442 if (err != -ENOENT)
12446 do_print_state = true;
12450 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12454 } else if (class == BPF_LD) {
12455 u8 mode = BPF_MODE(insn->code);
12457 if (mode == BPF_ABS || mode == BPF_IND) {
12458 err = check_ld_abs(env, insn);
12462 } else if (mode == BPF_IMM) {
12463 err = check_ld_imm(env, insn);
12468 sanitize_mark_insn_seen(env);
12470 verbose(env, "invalid BPF_LD mode\n");
12474 verbose(env, "unknown insn class %d\n", class);
12484 static int find_btf_percpu_datasec(struct btf *btf)
12486 const struct btf_type *t;
12491 * Both vmlinux and module each have their own ".data..percpu"
12492 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12493 * types to look at only module's own BTF types.
12495 n = btf_nr_types(btf);
12496 if (btf_is_module(btf))
12497 i = btf_nr_types(btf_vmlinux);
12501 for(; i < n; i++) {
12502 t = btf_type_by_id(btf, i);
12503 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12506 tname = btf_name_by_offset(btf, t->name_off);
12507 if (!strcmp(tname, ".data..percpu"))
12514 /* replace pseudo btf_id with kernel symbol address */
12515 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12516 struct bpf_insn *insn,
12517 struct bpf_insn_aux_data *aux)
12519 const struct btf_var_secinfo *vsi;
12520 const struct btf_type *datasec;
12521 struct btf_mod_pair *btf_mod;
12522 const struct btf_type *t;
12523 const char *sym_name;
12524 bool percpu = false;
12525 u32 type, id = insn->imm;
12529 int i, btf_fd, err;
12531 btf_fd = insn[1].imm;
12533 btf = btf_get_by_fd(btf_fd);
12535 verbose(env, "invalid module BTF object FD specified.\n");
12539 if (!btf_vmlinux) {
12540 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12547 t = btf_type_by_id(btf, id);
12549 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12554 if (!btf_type_is_var(t)) {
12555 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12560 sym_name = btf_name_by_offset(btf, t->name_off);
12561 addr = kallsyms_lookup_name(sym_name);
12563 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12569 datasec_id = find_btf_percpu_datasec(btf);
12570 if (datasec_id > 0) {
12571 datasec = btf_type_by_id(btf, datasec_id);
12572 for_each_vsi(i, datasec, vsi) {
12573 if (vsi->type == id) {
12580 insn[0].imm = (u32)addr;
12581 insn[1].imm = addr >> 32;
12584 t = btf_type_skip_modifiers(btf, type, NULL);
12586 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12587 aux->btf_var.btf = btf;
12588 aux->btf_var.btf_id = type;
12589 } else if (!btf_type_is_struct(t)) {
12590 const struct btf_type *ret;
12594 /* resolve the type size of ksym. */
12595 ret = btf_resolve_size(btf, t, &tsize);
12597 tname = btf_name_by_offset(btf, t->name_off);
12598 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12599 tname, PTR_ERR(ret));
12603 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12604 aux->btf_var.mem_size = tsize;
12606 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12607 aux->btf_var.btf = btf;
12608 aux->btf_var.btf_id = type;
12611 /* check whether we recorded this BTF (and maybe module) already */
12612 for (i = 0; i < env->used_btf_cnt; i++) {
12613 if (env->used_btfs[i].btf == btf) {
12619 if (env->used_btf_cnt >= MAX_USED_BTFS) {
12624 btf_mod = &env->used_btfs[env->used_btf_cnt];
12625 btf_mod->btf = btf;
12626 btf_mod->module = NULL;
12628 /* if we reference variables from kernel module, bump its refcount */
12629 if (btf_is_module(btf)) {
12630 btf_mod->module = btf_try_get_module(btf);
12631 if (!btf_mod->module) {
12637 env->used_btf_cnt++;
12645 static bool is_tracing_prog_type(enum bpf_prog_type type)
12648 case BPF_PROG_TYPE_KPROBE:
12649 case BPF_PROG_TYPE_TRACEPOINT:
12650 case BPF_PROG_TYPE_PERF_EVENT:
12651 case BPF_PROG_TYPE_RAW_TRACEPOINT:
12652 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12659 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12660 struct bpf_map *map,
12661 struct bpf_prog *prog)
12664 enum bpf_prog_type prog_type = resolve_prog_type(prog);
12666 if (map_value_has_spin_lock(map)) {
12667 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12668 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12672 if (is_tracing_prog_type(prog_type)) {
12673 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12677 if (prog->aux->sleepable) {
12678 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12683 if (map_value_has_timer(map)) {
12684 if (is_tracing_prog_type(prog_type)) {
12685 verbose(env, "tracing progs cannot use bpf_timer yet\n");
12690 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12691 !bpf_offload_prog_map_match(prog, map)) {
12692 verbose(env, "offload device mismatch between prog and map\n");
12696 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12697 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12701 if (prog->aux->sleepable)
12702 switch (map->map_type) {
12703 case BPF_MAP_TYPE_HASH:
12704 case BPF_MAP_TYPE_LRU_HASH:
12705 case BPF_MAP_TYPE_ARRAY:
12706 case BPF_MAP_TYPE_PERCPU_HASH:
12707 case BPF_MAP_TYPE_PERCPU_ARRAY:
12708 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12709 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12710 case BPF_MAP_TYPE_HASH_OF_MAPS:
12711 case BPF_MAP_TYPE_RINGBUF:
12712 case BPF_MAP_TYPE_USER_RINGBUF:
12713 case BPF_MAP_TYPE_INODE_STORAGE:
12714 case BPF_MAP_TYPE_SK_STORAGE:
12715 case BPF_MAP_TYPE_TASK_STORAGE:
12719 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12726 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12728 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12729 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12732 /* find and rewrite pseudo imm in ld_imm64 instructions:
12734 * 1. if it accesses map FD, replace it with actual map pointer.
12735 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12737 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12739 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12741 struct bpf_insn *insn = env->prog->insnsi;
12742 int insn_cnt = env->prog->len;
12745 err = bpf_prog_calc_tag(env->prog);
12749 for (i = 0; i < insn_cnt; i++, insn++) {
12750 if (BPF_CLASS(insn->code) == BPF_LDX &&
12751 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12752 verbose(env, "BPF_LDX uses reserved fields\n");
12756 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12757 struct bpf_insn_aux_data *aux;
12758 struct bpf_map *map;
12763 if (i == insn_cnt - 1 || insn[1].code != 0 ||
12764 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12765 insn[1].off != 0) {
12766 verbose(env, "invalid bpf_ld_imm64 insn\n");
12770 if (insn[0].src_reg == 0)
12771 /* valid generic load 64-bit imm */
12774 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12775 aux = &env->insn_aux_data[i];
12776 err = check_pseudo_btf_id(env, insn, aux);
12782 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12783 aux = &env->insn_aux_data[i];
12784 aux->ptr_type = PTR_TO_FUNC;
12788 /* In final convert_pseudo_ld_imm64() step, this is
12789 * converted into regular 64-bit imm load insn.
12791 switch (insn[0].src_reg) {
12792 case BPF_PSEUDO_MAP_VALUE:
12793 case BPF_PSEUDO_MAP_IDX_VALUE:
12795 case BPF_PSEUDO_MAP_FD:
12796 case BPF_PSEUDO_MAP_IDX:
12797 if (insn[1].imm == 0)
12801 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12805 switch (insn[0].src_reg) {
12806 case BPF_PSEUDO_MAP_IDX_VALUE:
12807 case BPF_PSEUDO_MAP_IDX:
12808 if (bpfptr_is_null(env->fd_array)) {
12809 verbose(env, "fd_idx without fd_array is invalid\n");
12812 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12813 insn[0].imm * sizeof(fd),
12823 map = __bpf_map_get(f);
12825 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12827 return PTR_ERR(map);
12830 err = check_map_prog_compatibility(env, map, env->prog);
12836 aux = &env->insn_aux_data[i];
12837 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12838 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12839 addr = (unsigned long)map;
12841 u32 off = insn[1].imm;
12843 if (off >= BPF_MAX_VAR_OFF) {
12844 verbose(env, "direct value offset of %u is not allowed\n", off);
12849 if (!map->ops->map_direct_value_addr) {
12850 verbose(env, "no direct value access support for this map type\n");
12855 err = map->ops->map_direct_value_addr(map, &addr, off);
12857 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12858 map->value_size, off);
12863 aux->map_off = off;
12867 insn[0].imm = (u32)addr;
12868 insn[1].imm = addr >> 32;
12870 /* check whether we recorded this map already */
12871 for (j = 0; j < env->used_map_cnt; j++) {
12872 if (env->used_maps[j] == map) {
12873 aux->map_index = j;
12879 if (env->used_map_cnt >= MAX_USED_MAPS) {
12884 /* hold the map. If the program is rejected by verifier,
12885 * the map will be released by release_maps() or it
12886 * will be used by the valid program until it's unloaded
12887 * and all maps are released in free_used_maps()
12891 aux->map_index = env->used_map_cnt;
12892 env->used_maps[env->used_map_cnt++] = map;
12894 if (bpf_map_is_cgroup_storage(map) &&
12895 bpf_cgroup_storage_assign(env->prog->aux, map)) {
12896 verbose(env, "only one cgroup storage of each type is allowed\n");
12908 /* Basic sanity check before we invest more work here. */
12909 if (!bpf_opcode_in_insntable(insn->code)) {
12910 verbose(env, "unknown opcode %02x\n", insn->code);
12915 /* now all pseudo BPF_LD_IMM64 instructions load valid
12916 * 'struct bpf_map *' into a register instead of user map_fd.
12917 * These pointers will be used later by verifier to validate map access.
12922 /* drop refcnt of maps used by the rejected program */
12923 static void release_maps(struct bpf_verifier_env *env)
12925 __bpf_free_used_maps(env->prog->aux, env->used_maps,
12926 env->used_map_cnt);
12929 /* drop refcnt of maps used by the rejected program */
12930 static void release_btfs(struct bpf_verifier_env *env)
12932 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12933 env->used_btf_cnt);
12936 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12937 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12939 struct bpf_insn *insn = env->prog->insnsi;
12940 int insn_cnt = env->prog->len;
12943 for (i = 0; i < insn_cnt; i++, insn++) {
12944 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12946 if (insn->src_reg == BPF_PSEUDO_FUNC)
12952 /* single env->prog->insni[off] instruction was replaced with the range
12953 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
12954 * [0, off) and [off, end) to new locations, so the patched range stays zero
12956 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12957 struct bpf_insn_aux_data *new_data,
12958 struct bpf_prog *new_prog, u32 off, u32 cnt)
12960 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
12961 struct bpf_insn *insn = new_prog->insnsi;
12962 u32 old_seen = old_data[off].seen;
12966 /* aux info at OFF always needs adjustment, no matter fast path
12967 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12968 * original insn at old prog.
12970 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12974 prog_len = new_prog->len;
12976 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12977 memcpy(new_data + off + cnt - 1, old_data + off,
12978 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
12979 for (i = off; i < off + cnt - 1; i++) {
12980 /* Expand insni[off]'s seen count to the patched range. */
12981 new_data[i].seen = old_seen;
12982 new_data[i].zext_dst = insn_has_def32(env, insn + i);
12984 env->insn_aux_data = new_data;
12988 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
12994 /* NOTE: fake 'exit' subprog should be updated as well. */
12995 for (i = 0; i <= env->subprog_cnt; i++) {
12996 if (env->subprog_info[i].start <= off)
12998 env->subprog_info[i].start += len - 1;
13002 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13004 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13005 int i, sz = prog->aux->size_poke_tab;
13006 struct bpf_jit_poke_descriptor *desc;
13008 for (i = 0; i < sz; i++) {
13010 if (desc->insn_idx <= off)
13012 desc->insn_idx += len - 1;
13016 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13017 const struct bpf_insn *patch, u32 len)
13019 struct bpf_prog *new_prog;
13020 struct bpf_insn_aux_data *new_data = NULL;
13023 new_data = vzalloc(array_size(env->prog->len + len - 1,
13024 sizeof(struct bpf_insn_aux_data)));
13029 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13030 if (IS_ERR(new_prog)) {
13031 if (PTR_ERR(new_prog) == -ERANGE)
13033 "insn %d cannot be patched due to 16-bit range\n",
13034 env->insn_aux_data[off].orig_idx);
13038 adjust_insn_aux_data(env, new_data, new_prog, off, len);
13039 adjust_subprog_starts(env, off, len);
13040 adjust_poke_descs(new_prog, off, len);
13044 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13049 /* find first prog starting at or after off (first to remove) */
13050 for (i = 0; i < env->subprog_cnt; i++)
13051 if (env->subprog_info[i].start >= off)
13053 /* find first prog starting at or after off + cnt (first to stay) */
13054 for (j = i; j < env->subprog_cnt; j++)
13055 if (env->subprog_info[j].start >= off + cnt)
13057 /* if j doesn't start exactly at off + cnt, we are just removing
13058 * the front of previous prog
13060 if (env->subprog_info[j].start != off + cnt)
13064 struct bpf_prog_aux *aux = env->prog->aux;
13067 /* move fake 'exit' subprog as well */
13068 move = env->subprog_cnt + 1 - j;
13070 memmove(env->subprog_info + i,
13071 env->subprog_info + j,
13072 sizeof(*env->subprog_info) * move);
13073 env->subprog_cnt -= j - i;
13075 /* remove func_info */
13076 if (aux->func_info) {
13077 move = aux->func_info_cnt - j;
13079 memmove(aux->func_info + i,
13080 aux->func_info + j,
13081 sizeof(*aux->func_info) * move);
13082 aux->func_info_cnt -= j - i;
13083 /* func_info->insn_off is set after all code rewrites,
13084 * in adjust_btf_func() - no need to adjust
13088 /* convert i from "first prog to remove" to "first to adjust" */
13089 if (env->subprog_info[i].start == off)
13093 /* update fake 'exit' subprog as well */
13094 for (; i <= env->subprog_cnt; i++)
13095 env->subprog_info[i].start -= cnt;
13100 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13103 struct bpf_prog *prog = env->prog;
13104 u32 i, l_off, l_cnt, nr_linfo;
13105 struct bpf_line_info *linfo;
13107 nr_linfo = prog->aux->nr_linfo;
13111 linfo = prog->aux->linfo;
13113 /* find first line info to remove, count lines to be removed */
13114 for (i = 0; i < nr_linfo; i++)
13115 if (linfo[i].insn_off >= off)
13120 for (; i < nr_linfo; i++)
13121 if (linfo[i].insn_off < off + cnt)
13126 /* First live insn doesn't match first live linfo, it needs to "inherit"
13127 * last removed linfo. prog is already modified, so prog->len == off
13128 * means no live instructions after (tail of the program was removed).
13130 if (prog->len != off && l_cnt &&
13131 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13133 linfo[--i].insn_off = off + cnt;
13136 /* remove the line info which refer to the removed instructions */
13138 memmove(linfo + l_off, linfo + i,
13139 sizeof(*linfo) * (nr_linfo - i));
13141 prog->aux->nr_linfo -= l_cnt;
13142 nr_linfo = prog->aux->nr_linfo;
13145 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13146 for (i = l_off; i < nr_linfo; i++)
13147 linfo[i].insn_off -= cnt;
13149 /* fix up all subprogs (incl. 'exit') which start >= off */
13150 for (i = 0; i <= env->subprog_cnt; i++)
13151 if (env->subprog_info[i].linfo_idx > l_off) {
13152 /* program may have started in the removed region but
13153 * may not be fully removed
13155 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13156 env->subprog_info[i].linfo_idx -= l_cnt;
13158 env->subprog_info[i].linfo_idx = l_off;
13164 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13166 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13167 unsigned int orig_prog_len = env->prog->len;
13170 if (bpf_prog_is_dev_bound(env->prog->aux))
13171 bpf_prog_offload_remove_insns(env, off, cnt);
13173 err = bpf_remove_insns(env->prog, off, cnt);
13177 err = adjust_subprog_starts_after_remove(env, off, cnt);
13181 err = bpf_adj_linfo_after_remove(env, off, cnt);
13185 memmove(aux_data + off, aux_data + off + cnt,
13186 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13191 /* The verifier does more data flow analysis than llvm and will not
13192 * explore branches that are dead at run time. Malicious programs can
13193 * have dead code too. Therefore replace all dead at-run-time code
13196 * Just nops are not optimal, e.g. if they would sit at the end of the
13197 * program and through another bug we would manage to jump there, then
13198 * we'd execute beyond program memory otherwise. Returning exception
13199 * code also wouldn't work since we can have subprogs where the dead
13200 * code could be located.
13202 static void sanitize_dead_code(struct bpf_verifier_env *env)
13204 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13205 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13206 struct bpf_insn *insn = env->prog->insnsi;
13207 const int insn_cnt = env->prog->len;
13210 for (i = 0; i < insn_cnt; i++) {
13211 if (aux_data[i].seen)
13213 memcpy(insn + i, &trap, sizeof(trap));
13214 aux_data[i].zext_dst = false;
13218 static bool insn_is_cond_jump(u8 code)
13222 if (BPF_CLASS(code) == BPF_JMP32)
13225 if (BPF_CLASS(code) != BPF_JMP)
13229 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13232 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13234 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13235 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13236 struct bpf_insn *insn = env->prog->insnsi;
13237 const int insn_cnt = env->prog->len;
13240 for (i = 0; i < insn_cnt; i++, insn++) {
13241 if (!insn_is_cond_jump(insn->code))
13244 if (!aux_data[i + 1].seen)
13245 ja.off = insn->off;
13246 else if (!aux_data[i + 1 + insn->off].seen)
13251 if (bpf_prog_is_dev_bound(env->prog->aux))
13252 bpf_prog_offload_replace_insn(env, i, &ja);
13254 memcpy(insn, &ja, sizeof(ja));
13258 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13260 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13261 int insn_cnt = env->prog->len;
13264 for (i = 0; i < insn_cnt; i++) {
13268 while (i + j < insn_cnt && !aux_data[i + j].seen)
13273 err = verifier_remove_insns(env, i, j);
13276 insn_cnt = env->prog->len;
13282 static int opt_remove_nops(struct bpf_verifier_env *env)
13284 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13285 struct bpf_insn *insn = env->prog->insnsi;
13286 int insn_cnt = env->prog->len;
13289 for (i = 0; i < insn_cnt; i++) {
13290 if (memcmp(&insn[i], &ja, sizeof(ja)))
13293 err = verifier_remove_insns(env, i, 1);
13303 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13304 const union bpf_attr *attr)
13306 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13307 struct bpf_insn_aux_data *aux = env->insn_aux_data;
13308 int i, patch_len, delta = 0, len = env->prog->len;
13309 struct bpf_insn *insns = env->prog->insnsi;
13310 struct bpf_prog *new_prog;
13313 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13314 zext_patch[1] = BPF_ZEXT_REG(0);
13315 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13316 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13317 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13318 for (i = 0; i < len; i++) {
13319 int adj_idx = i + delta;
13320 struct bpf_insn insn;
13323 insn = insns[adj_idx];
13324 load_reg = insn_def_regno(&insn);
13325 if (!aux[adj_idx].zext_dst) {
13333 class = BPF_CLASS(code);
13334 if (load_reg == -1)
13337 /* NOTE: arg "reg" (the fourth one) is only used for
13338 * BPF_STX + SRC_OP, so it is safe to pass NULL
13341 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13342 if (class == BPF_LD &&
13343 BPF_MODE(code) == BPF_IMM)
13348 /* ctx load could be transformed into wider load. */
13349 if (class == BPF_LDX &&
13350 aux[adj_idx].ptr_type == PTR_TO_CTX)
13353 imm_rnd = get_random_u32();
13354 rnd_hi32_patch[0] = insn;
13355 rnd_hi32_patch[1].imm = imm_rnd;
13356 rnd_hi32_patch[3].dst_reg = load_reg;
13357 patch = rnd_hi32_patch;
13359 goto apply_patch_buffer;
13362 /* Add in an zero-extend instruction if a) the JIT has requested
13363 * it or b) it's a CMPXCHG.
13365 * The latter is because: BPF_CMPXCHG always loads a value into
13366 * R0, therefore always zero-extends. However some archs'
13367 * equivalent instruction only does this load when the
13368 * comparison is successful. This detail of CMPXCHG is
13369 * orthogonal to the general zero-extension behaviour of the
13370 * CPU, so it's treated independently of bpf_jit_needs_zext.
13372 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13375 if (WARN_ON(load_reg == -1)) {
13376 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13380 zext_patch[0] = insn;
13381 zext_patch[1].dst_reg = load_reg;
13382 zext_patch[1].src_reg = load_reg;
13383 patch = zext_patch;
13385 apply_patch_buffer:
13386 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13389 env->prog = new_prog;
13390 insns = new_prog->insnsi;
13391 aux = env->insn_aux_data;
13392 delta += patch_len - 1;
13398 /* convert load instructions that access fields of a context type into a
13399 * sequence of instructions that access fields of the underlying structure:
13400 * struct __sk_buff -> struct sk_buff
13401 * struct bpf_sock_ops -> struct sock
13403 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13405 const struct bpf_verifier_ops *ops = env->ops;
13406 int i, cnt, size, ctx_field_size, delta = 0;
13407 const int insn_cnt = env->prog->len;
13408 struct bpf_insn insn_buf[16], *insn;
13409 u32 target_size, size_default, off;
13410 struct bpf_prog *new_prog;
13411 enum bpf_access_type type;
13412 bool is_narrower_load;
13414 if (ops->gen_prologue || env->seen_direct_write) {
13415 if (!ops->gen_prologue) {
13416 verbose(env, "bpf verifier is misconfigured\n");
13419 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13421 if (cnt >= ARRAY_SIZE(insn_buf)) {
13422 verbose(env, "bpf verifier is misconfigured\n");
13425 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13429 env->prog = new_prog;
13434 if (bpf_prog_is_dev_bound(env->prog->aux))
13437 insn = env->prog->insnsi + delta;
13439 for (i = 0; i < insn_cnt; i++, insn++) {
13440 bpf_convert_ctx_access_t convert_ctx_access;
13443 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13444 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13445 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13446 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13449 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13450 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13451 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13452 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13453 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13454 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13455 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13456 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13458 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13463 if (type == BPF_WRITE &&
13464 env->insn_aux_data[i + delta].sanitize_stack_spill) {
13465 struct bpf_insn patch[] = {
13470 cnt = ARRAY_SIZE(patch);
13471 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13476 env->prog = new_prog;
13477 insn = new_prog->insnsi + i + delta;
13484 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13486 if (!ops->convert_ctx_access)
13488 convert_ctx_access = ops->convert_ctx_access;
13490 case PTR_TO_SOCKET:
13491 case PTR_TO_SOCK_COMMON:
13492 convert_ctx_access = bpf_sock_convert_ctx_access;
13494 case PTR_TO_TCP_SOCK:
13495 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13497 case PTR_TO_XDP_SOCK:
13498 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13500 case PTR_TO_BTF_ID:
13501 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13502 if (type == BPF_READ) {
13503 insn->code = BPF_LDX | BPF_PROBE_MEM |
13504 BPF_SIZE((insn)->code);
13505 env->prog->aux->num_exentries++;
13512 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13513 size = BPF_LDST_BYTES(insn);
13515 /* If the read access is a narrower load of the field,
13516 * convert to a 4/8-byte load, to minimum program type specific
13517 * convert_ctx_access changes. If conversion is successful,
13518 * we will apply proper mask to the result.
13520 is_narrower_load = size < ctx_field_size;
13521 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13523 if (is_narrower_load) {
13526 if (type == BPF_WRITE) {
13527 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13532 if (ctx_field_size == 4)
13534 else if (ctx_field_size == 8)
13535 size_code = BPF_DW;
13537 insn->off = off & ~(size_default - 1);
13538 insn->code = BPF_LDX | BPF_MEM | size_code;
13542 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13544 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13545 (ctx_field_size && !target_size)) {
13546 verbose(env, "bpf verifier is misconfigured\n");
13550 if (is_narrower_load && size < target_size) {
13551 u8 shift = bpf_ctx_narrow_access_offset(
13552 off, size, size_default) * 8;
13553 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13554 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13557 if (ctx_field_size <= 4) {
13559 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13562 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13563 (1 << size * 8) - 1);
13566 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13569 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13570 (1ULL << size * 8) - 1);
13574 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13580 /* keep walking new program and skip insns we just inserted */
13581 env->prog = new_prog;
13582 insn = new_prog->insnsi + i + delta;
13588 static int jit_subprogs(struct bpf_verifier_env *env)
13590 struct bpf_prog *prog = env->prog, **func, *tmp;
13591 int i, j, subprog_start, subprog_end = 0, len, subprog;
13592 struct bpf_map *map_ptr;
13593 struct bpf_insn *insn;
13594 void *old_bpf_func;
13595 int err, num_exentries;
13597 if (env->subprog_cnt <= 1)
13600 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13601 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13604 /* Upon error here we cannot fall back to interpreter but
13605 * need a hard reject of the program. Thus -EFAULT is
13606 * propagated in any case.
13608 subprog = find_subprog(env, i + insn->imm + 1);
13610 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13611 i + insn->imm + 1);
13614 /* temporarily remember subprog id inside insn instead of
13615 * aux_data, since next loop will split up all insns into funcs
13617 insn->off = subprog;
13618 /* remember original imm in case JIT fails and fallback
13619 * to interpreter will be needed
13621 env->insn_aux_data[i].call_imm = insn->imm;
13622 /* point imm to __bpf_call_base+1 from JITs point of view */
13624 if (bpf_pseudo_func(insn))
13625 /* jit (e.g. x86_64) may emit fewer instructions
13626 * if it learns a u32 imm is the same as a u64 imm.
13627 * Force a non zero here.
13632 err = bpf_prog_alloc_jited_linfo(prog);
13634 goto out_undo_insn;
13637 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13639 goto out_undo_insn;
13641 for (i = 0; i < env->subprog_cnt; i++) {
13642 subprog_start = subprog_end;
13643 subprog_end = env->subprog_info[i + 1].start;
13645 len = subprog_end - subprog_start;
13646 /* bpf_prog_run() doesn't call subprogs directly,
13647 * hence main prog stats include the runtime of subprogs.
13648 * subprogs don't have IDs and not reachable via prog_get_next_id
13649 * func[i]->stats will never be accessed and stays NULL
13651 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13654 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13655 len * sizeof(struct bpf_insn));
13656 func[i]->type = prog->type;
13657 func[i]->len = len;
13658 if (bpf_prog_calc_tag(func[i]))
13660 func[i]->is_func = 1;
13661 func[i]->aux->func_idx = i;
13662 /* Below members will be freed only at prog->aux */
13663 func[i]->aux->btf = prog->aux->btf;
13664 func[i]->aux->func_info = prog->aux->func_info;
13665 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13666 func[i]->aux->poke_tab = prog->aux->poke_tab;
13667 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13669 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13670 struct bpf_jit_poke_descriptor *poke;
13672 poke = &prog->aux->poke_tab[j];
13673 if (poke->insn_idx < subprog_end &&
13674 poke->insn_idx >= subprog_start)
13675 poke->aux = func[i]->aux;
13678 func[i]->aux->name[0] = 'F';
13679 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13680 func[i]->jit_requested = 1;
13681 func[i]->blinding_requested = prog->blinding_requested;
13682 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13683 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13684 func[i]->aux->linfo = prog->aux->linfo;
13685 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13686 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13687 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13689 insn = func[i]->insnsi;
13690 for (j = 0; j < func[i]->len; j++, insn++) {
13691 if (BPF_CLASS(insn->code) == BPF_LDX &&
13692 BPF_MODE(insn->code) == BPF_PROBE_MEM)
13695 func[i]->aux->num_exentries = num_exentries;
13696 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13697 func[i] = bpf_int_jit_compile(func[i]);
13698 if (!func[i]->jited) {
13705 /* at this point all bpf functions were successfully JITed
13706 * now populate all bpf_calls with correct addresses and
13707 * run last pass of JIT
13709 for (i = 0; i < env->subprog_cnt; i++) {
13710 insn = func[i]->insnsi;
13711 for (j = 0; j < func[i]->len; j++, insn++) {
13712 if (bpf_pseudo_func(insn)) {
13713 subprog = insn->off;
13714 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13715 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13718 if (!bpf_pseudo_call(insn))
13720 subprog = insn->off;
13721 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13724 /* we use the aux data to keep a list of the start addresses
13725 * of the JITed images for each function in the program
13727 * for some architectures, such as powerpc64, the imm field
13728 * might not be large enough to hold the offset of the start
13729 * address of the callee's JITed image from __bpf_call_base
13731 * in such cases, we can lookup the start address of a callee
13732 * by using its subprog id, available from the off field of
13733 * the call instruction, as an index for this list
13735 func[i]->aux->func = func;
13736 func[i]->aux->func_cnt = env->subprog_cnt;
13738 for (i = 0; i < env->subprog_cnt; i++) {
13739 old_bpf_func = func[i]->bpf_func;
13740 tmp = bpf_int_jit_compile(func[i]);
13741 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13742 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13749 /* finally lock prog and jit images for all functions and
13750 * populate kallsysm
13752 for (i = 0; i < env->subprog_cnt; i++) {
13753 bpf_prog_lock_ro(func[i]);
13754 bpf_prog_kallsyms_add(func[i]);
13757 /* Last step: make now unused interpreter insns from main
13758 * prog consistent for later dump requests, so they can
13759 * later look the same as if they were interpreted only.
13761 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13762 if (bpf_pseudo_func(insn)) {
13763 insn[0].imm = env->insn_aux_data[i].call_imm;
13764 insn[1].imm = insn->off;
13768 if (!bpf_pseudo_call(insn))
13770 insn->off = env->insn_aux_data[i].call_imm;
13771 subprog = find_subprog(env, i + insn->off + 1);
13772 insn->imm = subprog;
13776 prog->bpf_func = func[0]->bpf_func;
13777 prog->jited_len = func[0]->jited_len;
13778 prog->aux->func = func;
13779 prog->aux->func_cnt = env->subprog_cnt;
13780 bpf_prog_jit_attempt_done(prog);
13783 /* We failed JIT'ing, so at this point we need to unregister poke
13784 * descriptors from subprogs, so that kernel is not attempting to
13785 * patch it anymore as we're freeing the subprog JIT memory.
13787 for (i = 0; i < prog->aux->size_poke_tab; i++) {
13788 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13789 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13791 /* At this point we're guaranteed that poke descriptors are not
13792 * live anymore. We can just unlink its descriptor table as it's
13793 * released with the main prog.
13795 for (i = 0; i < env->subprog_cnt; i++) {
13798 func[i]->aux->poke_tab = NULL;
13799 bpf_jit_free(func[i]);
13803 /* cleanup main prog to be interpreted */
13804 prog->jit_requested = 0;
13805 prog->blinding_requested = 0;
13806 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13807 if (!bpf_pseudo_call(insn))
13810 insn->imm = env->insn_aux_data[i].call_imm;
13812 bpf_prog_jit_attempt_done(prog);
13816 static int fixup_call_args(struct bpf_verifier_env *env)
13818 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13819 struct bpf_prog *prog = env->prog;
13820 struct bpf_insn *insn = prog->insnsi;
13821 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13826 if (env->prog->jit_requested &&
13827 !bpf_prog_is_dev_bound(env->prog->aux)) {
13828 err = jit_subprogs(env);
13831 if (err == -EFAULT)
13834 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13835 if (has_kfunc_call) {
13836 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13839 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13840 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13841 * have to be rejected, since interpreter doesn't support them yet.
13843 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13846 for (i = 0; i < prog->len; i++, insn++) {
13847 if (bpf_pseudo_func(insn)) {
13848 /* When JIT fails the progs with callback calls
13849 * have to be rejected, since interpreter doesn't support them yet.
13851 verbose(env, "callbacks are not allowed in non-JITed programs\n");
13855 if (!bpf_pseudo_call(insn))
13857 depth = get_callee_stack_depth(env, insn, i);
13860 bpf_patch_call_args(insn, depth);
13867 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13868 struct bpf_insn *insn)
13870 const struct bpf_kfunc_desc *desc;
13873 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13877 /* insn->imm has the btf func_id. Replace it with
13878 * an address (relative to __bpf_base_call).
13880 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13882 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13887 insn->imm = desc->imm;
13892 /* Do various post-verification rewrites in a single program pass.
13893 * These rewrites simplify JIT and interpreter implementations.
13895 static int do_misc_fixups(struct bpf_verifier_env *env)
13897 struct bpf_prog *prog = env->prog;
13898 enum bpf_attach_type eatype = prog->expected_attach_type;
13899 enum bpf_prog_type prog_type = resolve_prog_type(prog);
13900 struct bpf_insn *insn = prog->insnsi;
13901 const struct bpf_func_proto *fn;
13902 const int insn_cnt = prog->len;
13903 const struct bpf_map_ops *ops;
13904 struct bpf_insn_aux_data *aux;
13905 struct bpf_insn insn_buf[16];
13906 struct bpf_prog *new_prog;
13907 struct bpf_map *map_ptr;
13908 int i, ret, cnt, delta = 0;
13910 for (i = 0; i < insn_cnt; i++, insn++) {
13911 /* Make divide-by-zero exceptions impossible. */
13912 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13913 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13914 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13915 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13916 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13917 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13918 struct bpf_insn *patchlet;
13919 struct bpf_insn chk_and_div[] = {
13920 /* [R,W]x div 0 -> 0 */
13921 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13922 BPF_JNE | BPF_K, insn->src_reg,
13924 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13925 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13928 struct bpf_insn chk_and_mod[] = {
13929 /* [R,W]x mod 0 -> [R,W]x */
13930 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13931 BPF_JEQ | BPF_K, insn->src_reg,
13932 0, 1 + (is64 ? 0 : 1), 0),
13934 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13935 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13938 patchlet = isdiv ? chk_and_div : chk_and_mod;
13939 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13940 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
13942 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
13947 env->prog = prog = new_prog;
13948 insn = new_prog->insnsi + i + delta;
13952 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
13953 if (BPF_CLASS(insn->code) == BPF_LD &&
13954 (BPF_MODE(insn->code) == BPF_ABS ||
13955 BPF_MODE(insn->code) == BPF_IND)) {
13956 cnt = env->ops->gen_ld_abs(insn, insn_buf);
13957 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13958 verbose(env, "bpf verifier is misconfigured\n");
13962 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13967 env->prog = prog = new_prog;
13968 insn = new_prog->insnsi + i + delta;
13972 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
13973 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13974 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13975 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13976 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
13977 struct bpf_insn *patch = &insn_buf[0];
13978 bool issrc, isneg, isimm;
13981 aux = &env->insn_aux_data[i + delta];
13982 if (!aux->alu_state ||
13983 aux->alu_state == BPF_ALU_NON_POINTER)
13986 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
13987 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
13988 BPF_ALU_SANITIZE_SRC;
13989 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
13991 off_reg = issrc ? insn->src_reg : insn->dst_reg;
13993 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13996 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13997 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13998 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
13999 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14000 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14001 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14002 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14005 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14006 insn->src_reg = BPF_REG_AX;
14008 insn->code = insn->code == code_add ?
14009 code_sub : code_add;
14011 if (issrc && isneg && !isimm)
14012 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14013 cnt = patch - insn_buf;
14015 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14020 env->prog = prog = new_prog;
14021 insn = new_prog->insnsi + i + delta;
14025 if (insn->code != (BPF_JMP | BPF_CALL))
14027 if (insn->src_reg == BPF_PSEUDO_CALL)
14029 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14030 ret = fixup_kfunc_call(env, insn);
14036 if (insn->imm == BPF_FUNC_get_route_realm)
14037 prog->dst_needed = 1;
14038 if (insn->imm == BPF_FUNC_get_prandom_u32)
14039 bpf_user_rnd_init_once();
14040 if (insn->imm == BPF_FUNC_override_return)
14041 prog->kprobe_override = 1;
14042 if (insn->imm == BPF_FUNC_tail_call) {
14043 /* If we tail call into other programs, we
14044 * cannot make any assumptions since they can
14045 * be replaced dynamically during runtime in
14046 * the program array.
14048 prog->cb_access = 1;
14049 if (!allow_tail_call_in_subprogs(env))
14050 prog->aux->stack_depth = MAX_BPF_STACK;
14051 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14053 /* mark bpf_tail_call as different opcode to avoid
14054 * conditional branch in the interpreter for every normal
14055 * call and to prevent accidental JITing by JIT compiler
14056 * that doesn't support bpf_tail_call yet
14059 insn->code = BPF_JMP | BPF_TAIL_CALL;
14061 aux = &env->insn_aux_data[i + delta];
14062 if (env->bpf_capable && !prog->blinding_requested &&
14063 prog->jit_requested &&
14064 !bpf_map_key_poisoned(aux) &&
14065 !bpf_map_ptr_poisoned(aux) &&
14066 !bpf_map_ptr_unpriv(aux)) {
14067 struct bpf_jit_poke_descriptor desc = {
14068 .reason = BPF_POKE_REASON_TAIL_CALL,
14069 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14070 .tail_call.key = bpf_map_key_immediate(aux),
14071 .insn_idx = i + delta,
14074 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14076 verbose(env, "adding tail call poke descriptor failed\n");
14080 insn->imm = ret + 1;
14084 if (!bpf_map_ptr_unpriv(aux))
14087 /* instead of changing every JIT dealing with tail_call
14088 * emit two extra insns:
14089 * if (index >= max_entries) goto out;
14090 * index &= array->index_mask;
14091 * to avoid out-of-bounds cpu speculation
14093 if (bpf_map_ptr_poisoned(aux)) {
14094 verbose(env, "tail_call abusing map_ptr\n");
14098 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14099 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14100 map_ptr->max_entries, 2);
14101 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14102 container_of(map_ptr,
14105 insn_buf[2] = *insn;
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->imm == BPF_FUNC_timer_set_callback) {
14118 /* The verifier will process callback_fn as many times as necessary
14119 * with different maps and the register states prepared by
14120 * set_timer_callback_state will be accurate.
14122 * The following use case is valid:
14123 * map1 is shared by prog1, prog2, prog3.
14124 * prog1 calls bpf_timer_init for some map1 elements
14125 * prog2 calls bpf_timer_set_callback for some map1 elements.
14126 * Those that were not bpf_timer_init-ed will return -EINVAL.
14127 * prog3 calls bpf_timer_start for some map1 elements.
14128 * Those that were not both bpf_timer_init-ed and
14129 * bpf_timer_set_callback-ed will return -EINVAL.
14131 struct bpf_insn ld_addrs[2] = {
14132 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14135 insn_buf[0] = ld_addrs[0];
14136 insn_buf[1] = ld_addrs[1];
14137 insn_buf[2] = *insn;
14140 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14145 env->prog = prog = new_prog;
14146 insn = new_prog->insnsi + i + delta;
14147 goto patch_call_imm;
14150 if (insn->imm == BPF_FUNC_task_storage_get ||
14151 insn->imm == BPF_FUNC_sk_storage_get ||
14152 insn->imm == BPF_FUNC_inode_storage_get) {
14153 if (env->prog->aux->sleepable)
14154 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14156 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14157 insn_buf[1] = *insn;
14160 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14165 env->prog = prog = new_prog;
14166 insn = new_prog->insnsi + i + delta;
14167 goto patch_call_imm;
14170 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14171 * and other inlining handlers are currently limited to 64 bit
14174 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14175 (insn->imm == BPF_FUNC_map_lookup_elem ||
14176 insn->imm == BPF_FUNC_map_update_elem ||
14177 insn->imm == BPF_FUNC_map_delete_elem ||
14178 insn->imm == BPF_FUNC_map_push_elem ||
14179 insn->imm == BPF_FUNC_map_pop_elem ||
14180 insn->imm == BPF_FUNC_map_peek_elem ||
14181 insn->imm == BPF_FUNC_redirect_map ||
14182 insn->imm == BPF_FUNC_for_each_map_elem ||
14183 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14184 aux = &env->insn_aux_data[i + delta];
14185 if (bpf_map_ptr_poisoned(aux))
14186 goto patch_call_imm;
14188 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14189 ops = map_ptr->ops;
14190 if (insn->imm == BPF_FUNC_map_lookup_elem &&
14191 ops->map_gen_lookup) {
14192 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14193 if (cnt == -EOPNOTSUPP)
14194 goto patch_map_ops_generic;
14195 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14196 verbose(env, "bpf verifier is misconfigured\n");
14200 new_prog = bpf_patch_insn_data(env, i + delta,
14206 env->prog = prog = new_prog;
14207 insn = new_prog->insnsi + i + delta;
14211 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14212 (void *(*)(struct bpf_map *map, void *key))NULL));
14213 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14214 (int (*)(struct bpf_map *map, void *key))NULL));
14215 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14216 (int (*)(struct bpf_map *map, void *key, void *value,
14218 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14219 (int (*)(struct bpf_map *map, void *value,
14221 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14222 (int (*)(struct bpf_map *map, void *value))NULL));
14223 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14224 (int (*)(struct bpf_map *map, void *value))NULL));
14225 BUILD_BUG_ON(!__same_type(ops->map_redirect,
14226 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14227 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14228 (int (*)(struct bpf_map *map,
14229 bpf_callback_t callback_fn,
14230 void *callback_ctx,
14232 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14233 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14235 patch_map_ops_generic:
14236 switch (insn->imm) {
14237 case BPF_FUNC_map_lookup_elem:
14238 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14240 case BPF_FUNC_map_update_elem:
14241 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14243 case BPF_FUNC_map_delete_elem:
14244 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14246 case BPF_FUNC_map_push_elem:
14247 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14249 case BPF_FUNC_map_pop_elem:
14250 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14252 case BPF_FUNC_map_peek_elem:
14253 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14255 case BPF_FUNC_redirect_map:
14256 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14258 case BPF_FUNC_for_each_map_elem:
14259 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14261 case BPF_FUNC_map_lookup_percpu_elem:
14262 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14266 goto patch_call_imm;
14269 /* Implement bpf_jiffies64 inline. */
14270 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14271 insn->imm == BPF_FUNC_jiffies64) {
14272 struct bpf_insn ld_jiffies_addr[2] = {
14273 BPF_LD_IMM64(BPF_REG_0,
14274 (unsigned long)&jiffies),
14277 insn_buf[0] = ld_jiffies_addr[0];
14278 insn_buf[1] = ld_jiffies_addr[1];
14279 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14283 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14289 env->prog = prog = new_prog;
14290 insn = new_prog->insnsi + i + delta;
14294 /* Implement bpf_get_func_arg inline. */
14295 if (prog_type == BPF_PROG_TYPE_TRACING &&
14296 insn->imm == BPF_FUNC_get_func_arg) {
14297 /* Load nr_args from ctx - 8 */
14298 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14299 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14300 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14301 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14302 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14303 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14304 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14305 insn_buf[7] = BPF_JMP_A(1);
14306 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14309 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14314 env->prog = prog = new_prog;
14315 insn = new_prog->insnsi + i + delta;
14319 /* Implement bpf_get_func_ret inline. */
14320 if (prog_type == BPF_PROG_TYPE_TRACING &&
14321 insn->imm == BPF_FUNC_get_func_ret) {
14322 if (eatype == BPF_TRACE_FEXIT ||
14323 eatype == BPF_MODIFY_RETURN) {
14324 /* Load nr_args from ctx - 8 */
14325 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14326 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14327 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14328 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14329 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14330 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14333 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14337 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14342 env->prog = prog = new_prog;
14343 insn = new_prog->insnsi + i + delta;
14347 /* Implement get_func_arg_cnt inline. */
14348 if (prog_type == BPF_PROG_TYPE_TRACING &&
14349 insn->imm == BPF_FUNC_get_func_arg_cnt) {
14350 /* Load nr_args from ctx - 8 */
14351 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14353 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14357 env->prog = prog = new_prog;
14358 insn = new_prog->insnsi + i + delta;
14362 /* Implement bpf_get_func_ip inline. */
14363 if (prog_type == BPF_PROG_TYPE_TRACING &&
14364 insn->imm == BPF_FUNC_get_func_ip) {
14365 /* Load IP address from ctx - 16 */
14366 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14368 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14372 env->prog = prog = new_prog;
14373 insn = new_prog->insnsi + i + delta;
14378 fn = env->ops->get_func_proto(insn->imm, env->prog);
14379 /* all functions that have prototype and verifier allowed
14380 * programs to call them, must be real in-kernel functions
14384 "kernel subsystem misconfigured func %s#%d\n",
14385 func_id_name(insn->imm), insn->imm);
14388 insn->imm = fn->func - __bpf_call_base;
14391 /* Since poke tab is now finalized, publish aux to tracker. */
14392 for (i = 0; i < prog->aux->size_poke_tab; i++) {
14393 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14394 if (!map_ptr->ops->map_poke_track ||
14395 !map_ptr->ops->map_poke_untrack ||
14396 !map_ptr->ops->map_poke_run) {
14397 verbose(env, "bpf verifier is misconfigured\n");
14401 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14403 verbose(env, "tracking tail call prog failed\n");
14408 sort_kfunc_descs_by_imm(env->prog);
14413 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14416 u32 callback_subprogno,
14419 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14420 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14421 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14422 int reg_loop_max = BPF_REG_6;
14423 int reg_loop_cnt = BPF_REG_7;
14424 int reg_loop_ctx = BPF_REG_8;
14426 struct bpf_prog *new_prog;
14427 u32 callback_start;
14428 u32 call_insn_offset;
14429 s32 callback_offset;
14431 /* This represents an inlined version of bpf_iter.c:bpf_loop,
14432 * be careful to modify this code in sync.
14434 struct bpf_insn insn_buf[] = {
14435 /* Return error and jump to the end of the patch if
14436 * expected number of iterations is too big.
14438 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14439 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14440 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14441 /* spill R6, R7, R8 to use these as loop vars */
14442 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14443 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14444 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14445 /* initialize loop vars */
14446 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14447 BPF_MOV32_IMM(reg_loop_cnt, 0),
14448 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14450 * if reg_loop_cnt >= reg_loop_max skip the loop body
14452 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14454 * correct callback offset would be set after patching
14456 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14457 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14459 /* increment loop counter */
14460 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14461 /* jump to loop header if callback returned 0 */
14462 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14463 /* return value of bpf_loop,
14464 * set R0 to the number of iterations
14466 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14467 /* restore original values of R6, R7, R8 */
14468 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14469 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14470 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14473 *cnt = ARRAY_SIZE(insn_buf);
14474 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14478 /* callback start is known only after patching */
14479 callback_start = env->subprog_info[callback_subprogno].start;
14480 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14481 call_insn_offset = position + 12;
14482 callback_offset = callback_start - call_insn_offset - 1;
14483 new_prog->insnsi[call_insn_offset].imm = callback_offset;
14488 static bool is_bpf_loop_call(struct bpf_insn *insn)
14490 return insn->code == (BPF_JMP | BPF_CALL) &&
14491 insn->src_reg == 0 &&
14492 insn->imm == BPF_FUNC_loop;
14495 /* For all sub-programs in the program (including main) check
14496 * insn_aux_data to see if there are bpf_loop calls that require
14497 * inlining. If such calls are found the calls are replaced with a
14498 * sequence of instructions produced by `inline_bpf_loop` function and
14499 * subprog stack_depth is increased by the size of 3 registers.
14500 * This stack space is used to spill values of the R6, R7, R8. These
14501 * registers are used to store the loop bound, counter and context
14504 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14506 struct bpf_subprog_info *subprogs = env->subprog_info;
14507 int i, cur_subprog = 0, cnt, delta = 0;
14508 struct bpf_insn *insn = env->prog->insnsi;
14509 int insn_cnt = env->prog->len;
14510 u16 stack_depth = subprogs[cur_subprog].stack_depth;
14511 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14512 u16 stack_depth_extra = 0;
14514 for (i = 0; i < insn_cnt; i++, insn++) {
14515 struct bpf_loop_inline_state *inline_state =
14516 &env->insn_aux_data[i + delta].loop_inline_state;
14518 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14519 struct bpf_prog *new_prog;
14521 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14522 new_prog = inline_bpf_loop(env,
14524 -(stack_depth + stack_depth_extra),
14525 inline_state->callback_subprogno,
14531 env->prog = new_prog;
14532 insn = new_prog->insnsi + i + delta;
14535 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14536 subprogs[cur_subprog].stack_depth += stack_depth_extra;
14538 stack_depth = subprogs[cur_subprog].stack_depth;
14539 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14540 stack_depth_extra = 0;
14544 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14549 static void free_states(struct bpf_verifier_env *env)
14551 struct bpf_verifier_state_list *sl, *sln;
14554 sl = env->free_list;
14557 free_verifier_state(&sl->state, false);
14561 env->free_list = NULL;
14563 if (!env->explored_states)
14566 for (i = 0; i < state_htab_size(env); i++) {
14567 sl = env->explored_states[i];
14571 free_verifier_state(&sl->state, false);
14575 env->explored_states[i] = NULL;
14579 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14581 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14582 struct bpf_verifier_state *state;
14583 struct bpf_reg_state *regs;
14586 env->prev_linfo = NULL;
14589 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14592 state->curframe = 0;
14593 state->speculative = false;
14594 state->branches = 1;
14595 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14596 if (!state->frame[0]) {
14600 env->cur_state = state;
14601 init_func_state(env, state->frame[0],
14602 BPF_MAIN_FUNC /* callsite */,
14606 regs = state->frame[state->curframe]->regs;
14607 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14608 ret = btf_prepare_func_args(env, subprog, regs);
14611 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14612 if (regs[i].type == PTR_TO_CTX)
14613 mark_reg_known_zero(env, regs, i);
14614 else if (regs[i].type == SCALAR_VALUE)
14615 mark_reg_unknown(env, regs, i);
14616 else if (base_type(regs[i].type) == PTR_TO_MEM) {
14617 const u32 mem_size = regs[i].mem_size;
14619 mark_reg_known_zero(env, regs, i);
14620 regs[i].mem_size = mem_size;
14621 regs[i].id = ++env->id_gen;
14625 /* 1st arg to a function */
14626 regs[BPF_REG_1].type = PTR_TO_CTX;
14627 mark_reg_known_zero(env, regs, BPF_REG_1);
14628 ret = btf_check_subprog_arg_match(env, subprog, regs);
14629 if (ret == -EFAULT)
14630 /* unlikely verifier bug. abort.
14631 * ret == 0 and ret < 0 are sadly acceptable for
14632 * main() function due to backward compatibility.
14633 * Like socket filter program may be written as:
14634 * int bpf_prog(struct pt_regs *ctx)
14635 * and never dereference that ctx in the program.
14636 * 'struct pt_regs' is a type mismatch for socket
14637 * filter that should be using 'struct __sk_buff'.
14642 ret = do_check(env);
14644 /* check for NULL is necessary, since cur_state can be freed inside
14645 * do_check() under memory pressure.
14647 if (env->cur_state) {
14648 free_verifier_state(env->cur_state, true);
14649 env->cur_state = NULL;
14651 while (!pop_stack(env, NULL, NULL, false));
14652 if (!ret && pop_log)
14653 bpf_vlog_reset(&env->log, 0);
14658 /* Verify all global functions in a BPF program one by one based on their BTF.
14659 * All global functions must pass verification. Otherwise the whole program is rejected.
14670 * foo() will be verified first for R1=any_scalar_value. During verification it
14671 * will be assumed that bar() already verified successfully and call to bar()
14672 * from foo() will be checked for type match only. Later bar() will be verified
14673 * independently to check that it's safe for R1=any_scalar_value.
14675 static int do_check_subprogs(struct bpf_verifier_env *env)
14677 struct bpf_prog_aux *aux = env->prog->aux;
14680 if (!aux->func_info)
14683 for (i = 1; i < env->subprog_cnt; i++) {
14684 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14686 env->insn_idx = env->subprog_info[i].start;
14687 WARN_ON_ONCE(env->insn_idx == 0);
14688 ret = do_check_common(env, i);
14691 } else if (env->log.level & BPF_LOG_LEVEL) {
14693 "Func#%d is safe for any args that match its prototype\n",
14700 static int do_check_main(struct bpf_verifier_env *env)
14705 ret = do_check_common(env, 0);
14707 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14712 static void print_verification_stats(struct bpf_verifier_env *env)
14716 if (env->log.level & BPF_LOG_STATS) {
14717 verbose(env, "verification time %lld usec\n",
14718 div_u64(env->verification_time, 1000));
14719 verbose(env, "stack depth ");
14720 for (i = 0; i < env->subprog_cnt; i++) {
14721 u32 depth = env->subprog_info[i].stack_depth;
14723 verbose(env, "%d", depth);
14724 if (i + 1 < env->subprog_cnt)
14727 verbose(env, "\n");
14729 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14730 "total_states %d peak_states %d mark_read %d\n",
14731 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14732 env->max_states_per_insn, env->total_states,
14733 env->peak_states, env->longest_mark_read_walk);
14736 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14738 const struct btf_type *t, *func_proto;
14739 const struct bpf_struct_ops *st_ops;
14740 const struct btf_member *member;
14741 struct bpf_prog *prog = env->prog;
14742 u32 btf_id, member_idx;
14745 if (!prog->gpl_compatible) {
14746 verbose(env, "struct ops programs must have a GPL compatible license\n");
14750 btf_id = prog->aux->attach_btf_id;
14751 st_ops = bpf_struct_ops_find(btf_id);
14753 verbose(env, "attach_btf_id %u is not a supported struct\n",
14759 member_idx = prog->expected_attach_type;
14760 if (member_idx >= btf_type_vlen(t)) {
14761 verbose(env, "attach to invalid member idx %u of struct %s\n",
14762 member_idx, st_ops->name);
14766 member = &btf_type_member(t)[member_idx];
14767 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14768 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14771 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14772 mname, member_idx, st_ops->name);
14776 if (st_ops->check_member) {
14777 int err = st_ops->check_member(t, member);
14780 verbose(env, "attach to unsupported member %s of struct %s\n",
14781 mname, st_ops->name);
14786 prog->aux->attach_func_proto = func_proto;
14787 prog->aux->attach_func_name = mname;
14788 env->ops = st_ops->verifier_ops;
14792 #define SECURITY_PREFIX "security_"
14794 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14796 if (within_error_injection_list(addr) ||
14797 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14803 /* list of non-sleepable functions that are otherwise on
14804 * ALLOW_ERROR_INJECTION list
14806 BTF_SET_START(btf_non_sleepable_error_inject)
14807 /* Three functions below can be called from sleepable and non-sleepable context.
14808 * Assume non-sleepable from bpf safety point of view.
14810 BTF_ID(func, __filemap_add_folio)
14811 BTF_ID(func, should_fail_alloc_page)
14812 BTF_ID(func, should_failslab)
14813 BTF_SET_END(btf_non_sleepable_error_inject)
14815 static int check_non_sleepable_error_inject(u32 btf_id)
14817 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14820 int bpf_check_attach_target(struct bpf_verifier_log *log,
14821 const struct bpf_prog *prog,
14822 const struct bpf_prog *tgt_prog,
14824 struct bpf_attach_target_info *tgt_info)
14826 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14827 const char prefix[] = "btf_trace_";
14828 int ret = 0, subprog = -1, i;
14829 const struct btf_type *t;
14830 bool conservative = true;
14836 bpf_log(log, "Tracing programs must provide btf_id\n");
14839 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14842 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14845 t = btf_type_by_id(btf, btf_id);
14847 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14850 tname = btf_name_by_offset(btf, t->name_off);
14852 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14856 struct bpf_prog_aux *aux = tgt_prog->aux;
14858 for (i = 0; i < aux->func_info_cnt; i++)
14859 if (aux->func_info[i].type_id == btf_id) {
14863 if (subprog == -1) {
14864 bpf_log(log, "Subprog %s doesn't exist\n", tname);
14867 conservative = aux->func_info_aux[subprog].unreliable;
14868 if (prog_extension) {
14869 if (conservative) {
14871 "Cannot replace static functions\n");
14874 if (!prog->jit_requested) {
14876 "Extension programs should be JITed\n");
14880 if (!tgt_prog->jited) {
14881 bpf_log(log, "Can attach to only JITed progs\n");
14884 if (tgt_prog->type == prog->type) {
14885 /* Cannot fentry/fexit another fentry/fexit program.
14886 * Cannot attach program extension to another extension.
14887 * It's ok to attach fentry/fexit to extension program.
14889 bpf_log(log, "Cannot recursively attach\n");
14892 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14894 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14895 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14896 /* Program extensions can extend all program types
14897 * except fentry/fexit. The reason is the following.
14898 * The fentry/fexit programs are used for performance
14899 * analysis, stats and can be attached to any program
14900 * type except themselves. When extension program is
14901 * replacing XDP function it is necessary to allow
14902 * performance analysis of all functions. Both original
14903 * XDP program and its program extension. Hence
14904 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14905 * allowed. If extending of fentry/fexit was allowed it
14906 * would be possible to create long call chain
14907 * fentry->extension->fentry->extension beyond
14908 * reasonable stack size. Hence extending fentry is not
14911 bpf_log(log, "Cannot extend fentry/fexit\n");
14915 if (prog_extension) {
14916 bpf_log(log, "Cannot replace kernel functions\n");
14921 switch (prog->expected_attach_type) {
14922 case BPF_TRACE_RAW_TP:
14925 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14928 if (!btf_type_is_typedef(t)) {
14929 bpf_log(log, "attach_btf_id %u is not a typedef\n",
14933 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
14934 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
14938 tname += sizeof(prefix) - 1;
14939 t = btf_type_by_id(btf, t->type);
14940 if (!btf_type_is_ptr(t))
14941 /* should never happen in valid vmlinux build */
14943 t = btf_type_by_id(btf, t->type);
14944 if (!btf_type_is_func_proto(t))
14945 /* should never happen in valid vmlinux build */
14949 case BPF_TRACE_ITER:
14950 if (!btf_type_is_func(t)) {
14951 bpf_log(log, "attach_btf_id %u is not a function\n",
14955 t = btf_type_by_id(btf, t->type);
14956 if (!btf_type_is_func_proto(t))
14958 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14963 if (!prog_extension)
14966 case BPF_MODIFY_RETURN:
14968 case BPF_LSM_CGROUP:
14969 case BPF_TRACE_FENTRY:
14970 case BPF_TRACE_FEXIT:
14971 if (!btf_type_is_func(t)) {
14972 bpf_log(log, "attach_btf_id %u is not a function\n",
14976 if (prog_extension &&
14977 btf_check_type_match(log, prog, btf, t))
14979 t = btf_type_by_id(btf, t->type);
14980 if (!btf_type_is_func_proto(t))
14983 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
14984 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
14985 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
14988 if (tgt_prog && conservative)
14991 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14997 addr = (long) tgt_prog->bpf_func;
14999 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15001 addr = kallsyms_lookup_name(tname);
15004 "The address of function %s cannot be found\n",
15010 if (prog->aux->sleepable) {
15012 switch (prog->type) {
15013 case BPF_PROG_TYPE_TRACING:
15014 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
15015 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15017 if (!check_non_sleepable_error_inject(btf_id) &&
15018 within_error_injection_list(addr))
15021 case BPF_PROG_TYPE_LSM:
15022 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
15023 * Only some of them are sleepable.
15025 if (bpf_lsm_is_sleepable_hook(btf_id))
15032 bpf_log(log, "%s is not sleepable\n", tname);
15035 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15037 bpf_log(log, "can't modify return codes of BPF programs\n");
15040 ret = check_attach_modify_return(addr, tname);
15042 bpf_log(log, "%s() is not modifiable\n", tname);
15049 tgt_info->tgt_addr = addr;
15050 tgt_info->tgt_name = tname;
15051 tgt_info->tgt_type = t;
15055 BTF_SET_START(btf_id_deny)
15058 BTF_ID(func, migrate_disable)
15059 BTF_ID(func, migrate_enable)
15061 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15062 BTF_ID(func, rcu_read_unlock_strict)
15064 BTF_SET_END(btf_id_deny)
15066 static int check_attach_btf_id(struct bpf_verifier_env *env)
15068 struct bpf_prog *prog = env->prog;
15069 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15070 struct bpf_attach_target_info tgt_info = {};
15071 u32 btf_id = prog->aux->attach_btf_id;
15072 struct bpf_trampoline *tr;
15076 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15077 if (prog->aux->sleepable)
15078 /* attach_btf_id checked to be zero already */
15080 verbose(env, "Syscall programs can only be sleepable\n");
15084 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15085 prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15086 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15090 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15091 return check_struct_ops_btf_id(env);
15093 if (prog->type != BPF_PROG_TYPE_TRACING &&
15094 prog->type != BPF_PROG_TYPE_LSM &&
15095 prog->type != BPF_PROG_TYPE_EXT)
15098 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15102 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15103 /* to make freplace equivalent to their targets, they need to
15104 * inherit env->ops and expected_attach_type for the rest of the
15107 env->ops = bpf_verifier_ops[tgt_prog->type];
15108 prog->expected_attach_type = tgt_prog->expected_attach_type;
15111 /* store info about the attachment target that will be used later */
15112 prog->aux->attach_func_proto = tgt_info.tgt_type;
15113 prog->aux->attach_func_name = tgt_info.tgt_name;
15116 prog->aux->saved_dst_prog_type = tgt_prog->type;
15117 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15120 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15121 prog->aux->attach_btf_trace = true;
15123 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15124 if (!bpf_iter_prog_supported(prog))
15129 if (prog->type == BPF_PROG_TYPE_LSM) {
15130 ret = bpf_lsm_verify_prog(&env->log, prog);
15133 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15134 btf_id_set_contains(&btf_id_deny, btf_id)) {
15138 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15139 tr = bpf_trampoline_get(key, &tgt_info);
15143 prog->aux->dst_trampoline = tr;
15147 struct btf *bpf_get_btf_vmlinux(void)
15149 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15150 mutex_lock(&bpf_verifier_lock);
15152 btf_vmlinux = btf_parse_vmlinux();
15153 mutex_unlock(&bpf_verifier_lock);
15155 return btf_vmlinux;
15158 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15160 u64 start_time = ktime_get_ns();
15161 struct bpf_verifier_env *env;
15162 struct bpf_verifier_log *log;
15163 int i, len, ret = -EINVAL;
15166 /* no program is valid */
15167 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15170 /* 'struct bpf_verifier_env' can be global, but since it's not small,
15171 * allocate/free it every time bpf_check() is called
15173 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15178 len = (*prog)->len;
15179 env->insn_aux_data =
15180 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15182 if (!env->insn_aux_data)
15184 for (i = 0; i < len; i++)
15185 env->insn_aux_data[i].orig_idx = i;
15187 env->ops = bpf_verifier_ops[env->prog->type];
15188 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15189 is_priv = bpf_capable();
15191 bpf_get_btf_vmlinux();
15193 /* grab the mutex to protect few globals used by verifier */
15195 mutex_lock(&bpf_verifier_lock);
15197 if (attr->log_level || attr->log_buf || attr->log_size) {
15198 /* user requested verbose verifier output
15199 * and supplied buffer to store the verification trace
15201 log->level = attr->log_level;
15202 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15203 log->len_total = attr->log_size;
15205 /* log attributes have to be sane */
15206 if (!bpf_verifier_log_attr_valid(log)) {
15212 mark_verifier_state_clean(env);
15214 if (IS_ERR(btf_vmlinux)) {
15215 /* Either gcc or pahole or kernel are broken. */
15216 verbose(env, "in-kernel BTF is malformed\n");
15217 ret = PTR_ERR(btf_vmlinux);
15218 goto skip_full_check;
15221 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15222 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15223 env->strict_alignment = true;
15224 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15225 env->strict_alignment = false;
15227 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15228 env->allow_uninit_stack = bpf_allow_uninit_stack();
15229 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15230 env->bypass_spec_v1 = bpf_bypass_spec_v1();
15231 env->bypass_spec_v4 = bpf_bypass_spec_v4();
15232 env->bpf_capable = bpf_capable();
15235 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15237 env->explored_states = kvcalloc(state_htab_size(env),
15238 sizeof(struct bpf_verifier_state_list *),
15241 if (!env->explored_states)
15242 goto skip_full_check;
15244 ret = add_subprog_and_kfunc(env);
15246 goto skip_full_check;
15248 ret = check_subprogs(env);
15250 goto skip_full_check;
15252 ret = check_btf_info(env, attr, uattr);
15254 goto skip_full_check;
15256 ret = check_attach_btf_id(env);
15258 goto skip_full_check;
15260 ret = resolve_pseudo_ldimm64(env);
15262 goto skip_full_check;
15264 if (bpf_prog_is_dev_bound(env->prog->aux)) {
15265 ret = bpf_prog_offload_verifier_prep(env->prog);
15267 goto skip_full_check;
15270 ret = check_cfg(env);
15272 goto skip_full_check;
15274 ret = do_check_subprogs(env);
15275 ret = ret ?: do_check_main(env);
15277 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15278 ret = bpf_prog_offload_finalize(env);
15281 kvfree(env->explored_states);
15284 ret = check_max_stack_depth(env);
15286 /* instruction rewrites happen after this point */
15288 ret = optimize_bpf_loop(env);
15292 opt_hard_wire_dead_code_branches(env);
15294 ret = opt_remove_dead_code(env);
15296 ret = opt_remove_nops(env);
15299 sanitize_dead_code(env);
15303 /* program is valid, convert *(u32*)(ctx + off) accesses */
15304 ret = convert_ctx_accesses(env);
15307 ret = do_misc_fixups(env);
15309 /* do 32-bit optimization after insn patching has done so those patched
15310 * insns could be handled correctly.
15312 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15313 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15314 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15319 ret = fixup_call_args(env);
15321 env->verification_time = ktime_get_ns() - start_time;
15322 print_verification_stats(env);
15323 env->prog->aux->verified_insns = env->insn_processed;
15325 if (log->level && bpf_verifier_log_full(log))
15327 if (log->level && !log->ubuf) {
15329 goto err_release_maps;
15333 goto err_release_maps;
15335 if (env->used_map_cnt) {
15336 /* if program passed verifier, update used_maps in bpf_prog_info */
15337 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15338 sizeof(env->used_maps[0]),
15341 if (!env->prog->aux->used_maps) {
15343 goto err_release_maps;
15346 memcpy(env->prog->aux->used_maps, env->used_maps,
15347 sizeof(env->used_maps[0]) * env->used_map_cnt);
15348 env->prog->aux->used_map_cnt = env->used_map_cnt;
15350 if (env->used_btf_cnt) {
15351 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15352 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15353 sizeof(env->used_btfs[0]),
15355 if (!env->prog->aux->used_btfs) {
15357 goto err_release_maps;
15360 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15361 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15362 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15364 if (env->used_map_cnt || env->used_btf_cnt) {
15365 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15366 * bpf_ld_imm64 instructions
15368 convert_pseudo_ld_imm64(env);
15371 adjust_btf_func(env);
15374 if (!env->prog->aux->used_maps)
15375 /* if we didn't copy map pointers into bpf_prog_info, release
15376 * them now. Otherwise free_used_maps() will release them.
15379 if (!env->prog->aux->used_btfs)
15382 /* extension progs temporarily inherit the attach_type of their targets
15383 for verification purposes, so set it back to zero before returning
15385 if (env->prog->type == BPF_PROG_TYPE_EXT)
15386 env->prog->expected_attach_type = 0;
15391 mutex_unlock(&bpf_verifier_lock);
15392 vfree(env->insn_aux_data);