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)
1032 if (!new_n || old_n == new_n)
1035 new_arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
1043 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1046 return arr ? arr : ZERO_SIZE_PTR;
1049 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1051 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1052 sizeof(struct bpf_reference_state), GFP_KERNEL);
1056 dst->acquired_refs = src->acquired_refs;
1060 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1062 size_t n = src->allocated_stack / BPF_REG_SIZE;
1064 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1069 dst->allocated_stack = src->allocated_stack;
1073 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1075 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1076 sizeof(struct bpf_reference_state));
1080 state->acquired_refs = n;
1084 static int grow_stack_state(struct bpf_func_state *state, int size)
1086 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1091 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1095 state->allocated_stack = size;
1099 /* Acquire a pointer id from the env and update the state->refs to include
1100 * this new pointer reference.
1101 * On success, returns a valid pointer id to associate with the register
1102 * On failure, returns a negative errno.
1104 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1106 struct bpf_func_state *state = cur_func(env);
1107 int new_ofs = state->acquired_refs;
1110 err = resize_reference_state(state, state->acquired_refs + 1);
1114 state->refs[new_ofs].id = id;
1115 state->refs[new_ofs].insn_idx = insn_idx;
1116 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1121 /* release function corresponding to acquire_reference_state(). Idempotent. */
1122 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1126 last_idx = state->acquired_refs - 1;
1127 for (i = 0; i < state->acquired_refs; i++) {
1128 if (state->refs[i].id == ptr_id) {
1129 /* Cannot release caller references in callbacks */
1130 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1132 if (last_idx && i != last_idx)
1133 memcpy(&state->refs[i], &state->refs[last_idx],
1134 sizeof(*state->refs));
1135 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1136 state->acquired_refs--;
1143 static void free_func_state(struct bpf_func_state *state)
1148 kfree(state->stack);
1152 static void clear_jmp_history(struct bpf_verifier_state *state)
1154 kfree(state->jmp_history);
1155 state->jmp_history = NULL;
1156 state->jmp_history_cnt = 0;
1159 static void free_verifier_state(struct bpf_verifier_state *state,
1164 for (i = 0; i <= state->curframe; i++) {
1165 free_func_state(state->frame[i]);
1166 state->frame[i] = NULL;
1168 clear_jmp_history(state);
1173 /* copy verifier state from src to dst growing dst stack space
1174 * when necessary to accommodate larger src stack
1176 static int copy_func_state(struct bpf_func_state *dst,
1177 const struct bpf_func_state *src)
1181 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1182 err = copy_reference_state(dst, src);
1185 return copy_stack_state(dst, src);
1188 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1189 const struct bpf_verifier_state *src)
1191 struct bpf_func_state *dst;
1194 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1195 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1197 if (!dst_state->jmp_history)
1199 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1201 /* if dst has more stack frames then src frame, free them */
1202 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1203 free_func_state(dst_state->frame[i]);
1204 dst_state->frame[i] = NULL;
1206 dst_state->speculative = src->speculative;
1207 dst_state->curframe = src->curframe;
1208 dst_state->active_spin_lock = src->active_spin_lock;
1209 dst_state->branches = src->branches;
1210 dst_state->parent = src->parent;
1211 dst_state->first_insn_idx = src->first_insn_idx;
1212 dst_state->last_insn_idx = src->last_insn_idx;
1213 for (i = 0; i <= src->curframe; i++) {
1214 dst = dst_state->frame[i];
1216 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1219 dst_state->frame[i] = dst;
1221 err = copy_func_state(dst, src->frame[i]);
1228 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1231 u32 br = --st->branches;
1233 /* WARN_ON(br > 1) technically makes sense here,
1234 * but see comment in push_stack(), hence:
1236 WARN_ONCE((int)br < 0,
1237 "BUG update_branch_counts:branches_to_explore=%d\n",
1245 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1246 int *insn_idx, bool pop_log)
1248 struct bpf_verifier_state *cur = env->cur_state;
1249 struct bpf_verifier_stack_elem *elem, *head = env->head;
1252 if (env->head == NULL)
1256 err = copy_verifier_state(cur, &head->st);
1261 bpf_vlog_reset(&env->log, head->log_pos);
1263 *insn_idx = head->insn_idx;
1265 *prev_insn_idx = head->prev_insn_idx;
1267 free_verifier_state(&head->st, false);
1274 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1275 int insn_idx, int prev_insn_idx,
1278 struct bpf_verifier_state *cur = env->cur_state;
1279 struct bpf_verifier_stack_elem *elem;
1282 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1286 elem->insn_idx = insn_idx;
1287 elem->prev_insn_idx = prev_insn_idx;
1288 elem->next = env->head;
1289 elem->log_pos = env->log.len_used;
1292 err = copy_verifier_state(&elem->st, cur);
1295 elem->st.speculative |= speculative;
1296 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1297 verbose(env, "The sequence of %d jumps is too complex.\n",
1301 if (elem->st.parent) {
1302 ++elem->st.parent->branches;
1303 /* WARN_ON(branches > 2) technically makes sense here,
1305 * 1. speculative states will bump 'branches' for non-branch
1307 * 2. is_state_visited() heuristics may decide not to create
1308 * a new state for a sequence of branches and all such current
1309 * and cloned states will be pointing to a single parent state
1310 * which might have large 'branches' count.
1315 free_verifier_state(env->cur_state, true);
1316 env->cur_state = NULL;
1317 /* pop all elements and return */
1318 while (!pop_stack(env, NULL, NULL, false));
1322 #define CALLER_SAVED_REGS 6
1323 static const int caller_saved[CALLER_SAVED_REGS] = {
1324 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1327 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1328 struct bpf_reg_state *reg);
1330 /* This helper doesn't clear reg->id */
1331 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1333 reg->var_off = tnum_const(imm);
1334 reg->smin_value = (s64)imm;
1335 reg->smax_value = (s64)imm;
1336 reg->umin_value = imm;
1337 reg->umax_value = imm;
1339 reg->s32_min_value = (s32)imm;
1340 reg->s32_max_value = (s32)imm;
1341 reg->u32_min_value = (u32)imm;
1342 reg->u32_max_value = (u32)imm;
1345 /* Mark the unknown part of a register (variable offset or scalar value) as
1346 * known to have the value @imm.
1348 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1350 /* Clear id, off, and union(map_ptr, range) */
1351 memset(((u8 *)reg) + sizeof(reg->type), 0,
1352 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1353 ___mark_reg_known(reg, imm);
1356 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1358 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1359 reg->s32_min_value = (s32)imm;
1360 reg->s32_max_value = (s32)imm;
1361 reg->u32_min_value = (u32)imm;
1362 reg->u32_max_value = (u32)imm;
1365 /* Mark the 'variable offset' part of a register as zero. This should be
1366 * used only on registers holding a pointer type.
1368 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1370 __mark_reg_known(reg, 0);
1373 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1375 __mark_reg_known(reg, 0);
1376 reg->type = SCALAR_VALUE;
1379 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1380 struct bpf_reg_state *regs, u32 regno)
1382 if (WARN_ON(regno >= MAX_BPF_REG)) {
1383 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1384 /* Something bad happened, let's kill all regs */
1385 for (regno = 0; regno < MAX_BPF_REG; regno++)
1386 __mark_reg_not_init(env, regs + regno);
1389 __mark_reg_known_zero(regs + regno);
1392 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1394 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1395 const struct bpf_map *map = reg->map_ptr;
1397 if (map->inner_map_meta) {
1398 reg->type = CONST_PTR_TO_MAP;
1399 reg->map_ptr = map->inner_map_meta;
1400 /* transfer reg's id which is unique for every map_lookup_elem
1401 * as UID of the inner map.
1403 if (map_value_has_timer(map->inner_map_meta))
1404 reg->map_uid = reg->id;
1405 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1406 reg->type = PTR_TO_XDP_SOCK;
1407 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1408 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1409 reg->type = PTR_TO_SOCKET;
1411 reg->type = PTR_TO_MAP_VALUE;
1416 reg->type &= ~PTR_MAYBE_NULL;
1419 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1421 return type_is_pkt_pointer(reg->type);
1424 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1426 return reg_is_pkt_pointer(reg) ||
1427 reg->type == PTR_TO_PACKET_END;
1430 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1431 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1432 enum bpf_reg_type which)
1434 /* The register can already have a range from prior markings.
1435 * This is fine as long as it hasn't been advanced from its
1438 return reg->type == which &&
1441 tnum_equals_const(reg->var_off, 0);
1444 /* Reset the min/max bounds of a register */
1445 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1447 reg->smin_value = S64_MIN;
1448 reg->smax_value = S64_MAX;
1449 reg->umin_value = 0;
1450 reg->umax_value = U64_MAX;
1452 reg->s32_min_value = S32_MIN;
1453 reg->s32_max_value = S32_MAX;
1454 reg->u32_min_value = 0;
1455 reg->u32_max_value = U32_MAX;
1458 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1460 reg->smin_value = S64_MIN;
1461 reg->smax_value = S64_MAX;
1462 reg->umin_value = 0;
1463 reg->umax_value = U64_MAX;
1466 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1468 reg->s32_min_value = S32_MIN;
1469 reg->s32_max_value = S32_MAX;
1470 reg->u32_min_value = 0;
1471 reg->u32_max_value = U32_MAX;
1474 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1476 struct tnum var32_off = tnum_subreg(reg->var_off);
1478 /* min signed is max(sign bit) | min(other bits) */
1479 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1480 var32_off.value | (var32_off.mask & S32_MIN));
1481 /* max signed is min(sign bit) | max(other bits) */
1482 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1483 var32_off.value | (var32_off.mask & S32_MAX));
1484 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1485 reg->u32_max_value = min(reg->u32_max_value,
1486 (u32)(var32_off.value | var32_off.mask));
1489 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1491 /* min signed is max(sign bit) | min(other bits) */
1492 reg->smin_value = max_t(s64, reg->smin_value,
1493 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1494 /* max signed is min(sign bit) | max(other bits) */
1495 reg->smax_value = min_t(s64, reg->smax_value,
1496 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1497 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1498 reg->umax_value = min(reg->umax_value,
1499 reg->var_off.value | reg->var_off.mask);
1502 static void __update_reg_bounds(struct bpf_reg_state *reg)
1504 __update_reg32_bounds(reg);
1505 __update_reg64_bounds(reg);
1508 /* Uses signed min/max values to inform unsigned, and vice-versa */
1509 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1511 /* Learn sign from signed bounds.
1512 * If we cannot cross the sign boundary, then signed and unsigned bounds
1513 * are the same, so combine. This works even in the negative case, e.g.
1514 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1516 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1517 reg->s32_min_value = reg->u32_min_value =
1518 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1519 reg->s32_max_value = reg->u32_max_value =
1520 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1523 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1524 * boundary, so we must be careful.
1526 if ((s32)reg->u32_max_value >= 0) {
1527 /* Positive. We can't learn anything from the smin, but smax
1528 * is positive, hence safe.
1530 reg->s32_min_value = reg->u32_min_value;
1531 reg->s32_max_value = reg->u32_max_value =
1532 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1533 } else if ((s32)reg->u32_min_value < 0) {
1534 /* Negative. We can't learn anything from the smax, but smin
1535 * is negative, hence safe.
1537 reg->s32_min_value = reg->u32_min_value =
1538 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1539 reg->s32_max_value = reg->u32_max_value;
1543 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1545 /* Learn sign from signed bounds.
1546 * If we cannot cross the sign boundary, then signed and unsigned bounds
1547 * are the same, so combine. This works even in the negative case, e.g.
1548 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1550 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1551 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1553 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1557 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1558 * boundary, so we must be careful.
1560 if ((s64)reg->umax_value >= 0) {
1561 /* Positive. We can't learn anything from the smin, but smax
1562 * is positive, hence safe.
1564 reg->smin_value = reg->umin_value;
1565 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1567 } else if ((s64)reg->umin_value < 0) {
1568 /* Negative. We can't learn anything from the smax, but smin
1569 * is negative, hence safe.
1571 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1573 reg->smax_value = reg->umax_value;
1577 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1579 __reg32_deduce_bounds(reg);
1580 __reg64_deduce_bounds(reg);
1583 /* Attempts to improve var_off based on unsigned min/max information */
1584 static void __reg_bound_offset(struct bpf_reg_state *reg)
1586 struct tnum var64_off = tnum_intersect(reg->var_off,
1587 tnum_range(reg->umin_value,
1589 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1590 tnum_range(reg->u32_min_value,
1591 reg->u32_max_value));
1593 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1596 static void reg_bounds_sync(struct bpf_reg_state *reg)
1598 /* We might have learned new bounds from the var_off. */
1599 __update_reg_bounds(reg);
1600 /* We might have learned something about the sign bit. */
1601 __reg_deduce_bounds(reg);
1602 /* We might have learned some bits from the bounds. */
1603 __reg_bound_offset(reg);
1604 /* Intersecting with the old var_off might have improved our bounds
1605 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1606 * then new var_off is (0; 0x7f...fc) which improves our umax.
1608 __update_reg_bounds(reg);
1611 static bool __reg32_bound_s64(s32 a)
1613 return a >= 0 && a <= S32_MAX;
1616 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1618 reg->umin_value = reg->u32_min_value;
1619 reg->umax_value = reg->u32_max_value;
1621 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1622 * be positive otherwise set to worse case bounds and refine later
1625 if (__reg32_bound_s64(reg->s32_min_value) &&
1626 __reg32_bound_s64(reg->s32_max_value)) {
1627 reg->smin_value = reg->s32_min_value;
1628 reg->smax_value = reg->s32_max_value;
1630 reg->smin_value = 0;
1631 reg->smax_value = U32_MAX;
1635 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1637 /* special case when 64-bit register has upper 32-bit register
1638 * zeroed. Typically happens after zext or <<32, >>32 sequence
1639 * allowing us to use 32-bit bounds directly,
1641 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1642 __reg_assign_32_into_64(reg);
1644 /* Otherwise the best we can do is push lower 32bit known and
1645 * unknown bits into register (var_off set from jmp logic)
1646 * then learn as much as possible from the 64-bit tnum
1647 * known and unknown bits. The previous smin/smax bounds are
1648 * invalid here because of jmp32 compare so mark them unknown
1649 * so they do not impact tnum bounds calculation.
1651 __mark_reg64_unbounded(reg);
1653 reg_bounds_sync(reg);
1656 static bool __reg64_bound_s32(s64 a)
1658 return a >= S32_MIN && a <= S32_MAX;
1661 static bool __reg64_bound_u32(u64 a)
1663 return a >= U32_MIN && a <= U32_MAX;
1666 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1668 __mark_reg32_unbounded(reg);
1669 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1670 reg->s32_min_value = (s32)reg->smin_value;
1671 reg->s32_max_value = (s32)reg->smax_value;
1673 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1674 reg->u32_min_value = (u32)reg->umin_value;
1675 reg->u32_max_value = (u32)reg->umax_value;
1677 reg_bounds_sync(reg);
1680 /* Mark a register as having a completely unknown (scalar) value. */
1681 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1682 struct bpf_reg_state *reg)
1685 * Clear type, id, off, and union(map_ptr, range) and
1686 * padding between 'type' and union
1688 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1689 reg->type = SCALAR_VALUE;
1690 reg->var_off = tnum_unknown;
1692 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1693 __mark_reg_unbounded(reg);
1696 static void mark_reg_unknown(struct bpf_verifier_env *env,
1697 struct bpf_reg_state *regs, u32 regno)
1699 if (WARN_ON(regno >= MAX_BPF_REG)) {
1700 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1701 /* Something bad happened, let's kill all regs except FP */
1702 for (regno = 0; regno < BPF_REG_FP; regno++)
1703 __mark_reg_not_init(env, regs + regno);
1706 __mark_reg_unknown(env, regs + regno);
1709 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1710 struct bpf_reg_state *reg)
1712 __mark_reg_unknown(env, reg);
1713 reg->type = NOT_INIT;
1716 static void mark_reg_not_init(struct bpf_verifier_env *env,
1717 struct bpf_reg_state *regs, u32 regno)
1719 if (WARN_ON(regno >= MAX_BPF_REG)) {
1720 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1721 /* Something bad happened, let's kill all regs except FP */
1722 for (regno = 0; regno < BPF_REG_FP; regno++)
1723 __mark_reg_not_init(env, regs + regno);
1726 __mark_reg_not_init(env, regs + regno);
1729 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1730 struct bpf_reg_state *regs, u32 regno,
1731 enum bpf_reg_type reg_type,
1732 struct btf *btf, u32 btf_id,
1733 enum bpf_type_flag flag)
1735 if (reg_type == SCALAR_VALUE) {
1736 mark_reg_unknown(env, regs, regno);
1739 mark_reg_known_zero(env, regs, regno);
1740 regs[regno].type = PTR_TO_BTF_ID | flag;
1741 regs[regno].btf = btf;
1742 regs[regno].btf_id = btf_id;
1745 #define DEF_NOT_SUBREG (0)
1746 static void init_reg_state(struct bpf_verifier_env *env,
1747 struct bpf_func_state *state)
1749 struct bpf_reg_state *regs = state->regs;
1752 for (i = 0; i < MAX_BPF_REG; i++) {
1753 mark_reg_not_init(env, regs, i);
1754 regs[i].live = REG_LIVE_NONE;
1755 regs[i].parent = NULL;
1756 regs[i].subreg_def = DEF_NOT_SUBREG;
1760 regs[BPF_REG_FP].type = PTR_TO_STACK;
1761 mark_reg_known_zero(env, regs, BPF_REG_FP);
1762 regs[BPF_REG_FP].frameno = state->frameno;
1765 #define BPF_MAIN_FUNC (-1)
1766 static void init_func_state(struct bpf_verifier_env *env,
1767 struct bpf_func_state *state,
1768 int callsite, int frameno, int subprogno)
1770 state->callsite = callsite;
1771 state->frameno = frameno;
1772 state->subprogno = subprogno;
1773 state->callback_ret_range = tnum_range(0, 0);
1774 init_reg_state(env, state);
1775 mark_verifier_state_scratched(env);
1778 /* Similar to push_stack(), but for async callbacks */
1779 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1780 int insn_idx, int prev_insn_idx,
1783 struct bpf_verifier_stack_elem *elem;
1784 struct bpf_func_state *frame;
1786 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1790 elem->insn_idx = insn_idx;
1791 elem->prev_insn_idx = prev_insn_idx;
1792 elem->next = env->head;
1793 elem->log_pos = env->log.len_used;
1796 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1798 "The sequence of %d jumps is too complex for async cb.\n",
1802 /* Unlike push_stack() do not copy_verifier_state().
1803 * The caller state doesn't matter.
1804 * This is async callback. It starts in a fresh stack.
1805 * Initialize it similar to do_check_common().
1807 elem->st.branches = 1;
1808 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1811 init_func_state(env, frame,
1812 BPF_MAIN_FUNC /* callsite */,
1813 0 /* frameno within this callchain */,
1814 subprog /* subprog number within this prog */);
1815 elem->st.frame[0] = frame;
1818 free_verifier_state(env->cur_state, true);
1819 env->cur_state = NULL;
1820 /* pop all elements and return */
1821 while (!pop_stack(env, NULL, NULL, false));
1827 SRC_OP, /* register is used as source operand */
1828 DST_OP, /* register is used as destination operand */
1829 DST_OP_NO_MARK /* same as above, check only, don't mark */
1832 static int cmp_subprogs(const void *a, const void *b)
1834 return ((struct bpf_subprog_info *)a)->start -
1835 ((struct bpf_subprog_info *)b)->start;
1838 static int find_subprog(struct bpf_verifier_env *env, int off)
1840 struct bpf_subprog_info *p;
1842 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1843 sizeof(env->subprog_info[0]), cmp_subprogs);
1846 return p - env->subprog_info;
1850 static int add_subprog(struct bpf_verifier_env *env, int off)
1852 int insn_cnt = env->prog->len;
1855 if (off >= insn_cnt || off < 0) {
1856 verbose(env, "call to invalid destination\n");
1859 ret = find_subprog(env, off);
1862 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1863 verbose(env, "too many subprograms\n");
1866 /* determine subprog starts. The end is one before the next starts */
1867 env->subprog_info[env->subprog_cnt++].start = off;
1868 sort(env->subprog_info, env->subprog_cnt,
1869 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1870 return env->subprog_cnt - 1;
1873 #define MAX_KFUNC_DESCS 256
1874 #define MAX_KFUNC_BTFS 256
1876 struct bpf_kfunc_desc {
1877 struct btf_func_model func_model;
1883 struct bpf_kfunc_btf {
1885 struct module *module;
1889 struct bpf_kfunc_desc_tab {
1890 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1894 struct bpf_kfunc_btf_tab {
1895 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1899 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1901 const struct bpf_kfunc_desc *d0 = a;
1902 const struct bpf_kfunc_desc *d1 = b;
1904 /* func_id is not greater than BTF_MAX_TYPE */
1905 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1908 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1910 const struct bpf_kfunc_btf *d0 = a;
1911 const struct bpf_kfunc_btf *d1 = b;
1913 return d0->offset - d1->offset;
1916 static const struct bpf_kfunc_desc *
1917 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1919 struct bpf_kfunc_desc desc = {
1923 struct bpf_kfunc_desc_tab *tab;
1925 tab = prog->aux->kfunc_tab;
1926 return bsearch(&desc, tab->descs, tab->nr_descs,
1927 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1930 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1933 struct bpf_kfunc_btf kf_btf = { .offset = offset };
1934 struct bpf_kfunc_btf_tab *tab;
1935 struct bpf_kfunc_btf *b;
1940 tab = env->prog->aux->kfunc_btf_tab;
1941 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1942 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1944 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1945 verbose(env, "too many different module BTFs\n");
1946 return ERR_PTR(-E2BIG);
1949 if (bpfptr_is_null(env->fd_array)) {
1950 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1951 return ERR_PTR(-EPROTO);
1954 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1955 offset * sizeof(btf_fd),
1957 return ERR_PTR(-EFAULT);
1959 btf = btf_get_by_fd(btf_fd);
1961 verbose(env, "invalid module BTF fd specified\n");
1965 if (!btf_is_module(btf)) {
1966 verbose(env, "BTF fd for kfunc is not a module BTF\n");
1968 return ERR_PTR(-EINVAL);
1971 mod = btf_try_get_module(btf);
1974 return ERR_PTR(-ENXIO);
1977 b = &tab->descs[tab->nr_descs++];
1982 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1983 kfunc_btf_cmp_by_off, NULL);
1988 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1993 while (tab->nr_descs--) {
1994 module_put(tab->descs[tab->nr_descs].module);
1995 btf_put(tab->descs[tab->nr_descs].btf);
2000 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2004 /* In the future, this can be allowed to increase limit
2005 * of fd index into fd_array, interpreted as u16.
2007 verbose(env, "negative offset disallowed for kernel module function call\n");
2008 return ERR_PTR(-EINVAL);
2011 return __find_kfunc_desc_btf(env, offset);
2013 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2016 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2018 const struct btf_type *func, *func_proto;
2019 struct bpf_kfunc_btf_tab *btf_tab;
2020 struct bpf_kfunc_desc_tab *tab;
2021 struct bpf_prog_aux *prog_aux;
2022 struct bpf_kfunc_desc *desc;
2023 const char *func_name;
2024 struct btf *desc_btf;
2025 unsigned long call_imm;
2029 prog_aux = env->prog->aux;
2030 tab = prog_aux->kfunc_tab;
2031 btf_tab = prog_aux->kfunc_btf_tab;
2034 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2038 if (!env->prog->jit_requested) {
2039 verbose(env, "JIT is required for calling kernel function\n");
2043 if (!bpf_jit_supports_kfunc_call()) {
2044 verbose(env, "JIT does not support calling kernel function\n");
2048 if (!env->prog->gpl_compatible) {
2049 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2053 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2056 prog_aux->kfunc_tab = tab;
2059 /* func_id == 0 is always invalid, but instead of returning an error, be
2060 * conservative and wait until the code elimination pass before returning
2061 * error, so that invalid calls that get pruned out can be in BPF programs
2062 * loaded from userspace. It is also required that offset be untouched
2065 if (!func_id && !offset)
2068 if (!btf_tab && offset) {
2069 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2072 prog_aux->kfunc_btf_tab = btf_tab;
2075 desc_btf = find_kfunc_desc_btf(env, offset);
2076 if (IS_ERR(desc_btf)) {
2077 verbose(env, "failed to find BTF for kernel function\n");
2078 return PTR_ERR(desc_btf);
2081 if (find_kfunc_desc(env->prog, func_id, offset))
2084 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2085 verbose(env, "too many different kernel function calls\n");
2089 func = btf_type_by_id(desc_btf, func_id);
2090 if (!func || !btf_type_is_func(func)) {
2091 verbose(env, "kernel btf_id %u is not a function\n",
2095 func_proto = btf_type_by_id(desc_btf, func->type);
2096 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2097 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2102 func_name = btf_name_by_offset(desc_btf, func->name_off);
2103 addr = kallsyms_lookup_name(func_name);
2105 verbose(env, "cannot find address for kernel function %s\n",
2110 call_imm = BPF_CALL_IMM(addr);
2111 /* Check whether or not the relative offset overflows desc->imm */
2112 if ((unsigned long)(s32)call_imm != call_imm) {
2113 verbose(env, "address of kernel function %s is out of range\n",
2118 desc = &tab->descs[tab->nr_descs++];
2119 desc->func_id = func_id;
2120 desc->imm = call_imm;
2121 desc->offset = offset;
2122 err = btf_distill_func_proto(&env->log, desc_btf,
2123 func_proto, func_name,
2126 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2127 kfunc_desc_cmp_by_id_off, NULL);
2131 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2133 const struct bpf_kfunc_desc *d0 = a;
2134 const struct bpf_kfunc_desc *d1 = b;
2136 if (d0->imm > d1->imm)
2138 else if (d0->imm < d1->imm)
2143 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2145 struct bpf_kfunc_desc_tab *tab;
2147 tab = prog->aux->kfunc_tab;
2151 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2152 kfunc_desc_cmp_by_imm, NULL);
2155 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2157 return !!prog->aux->kfunc_tab;
2160 const struct btf_func_model *
2161 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2162 const struct bpf_insn *insn)
2164 const struct bpf_kfunc_desc desc = {
2167 const struct bpf_kfunc_desc *res;
2168 struct bpf_kfunc_desc_tab *tab;
2170 tab = prog->aux->kfunc_tab;
2171 res = bsearch(&desc, tab->descs, tab->nr_descs,
2172 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2174 return res ? &res->func_model : NULL;
2177 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2179 struct bpf_subprog_info *subprog = env->subprog_info;
2180 struct bpf_insn *insn = env->prog->insnsi;
2181 int i, ret, insn_cnt = env->prog->len;
2183 /* Add entry function. */
2184 ret = add_subprog(env, 0);
2188 for (i = 0; i < insn_cnt; i++, insn++) {
2189 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2190 !bpf_pseudo_kfunc_call(insn))
2193 if (!env->bpf_capable) {
2194 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2198 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2199 ret = add_subprog(env, i + insn->imm + 1);
2201 ret = add_kfunc_call(env, insn->imm, insn->off);
2207 /* Add a fake 'exit' subprog which could simplify subprog iteration
2208 * logic. 'subprog_cnt' should not be increased.
2210 subprog[env->subprog_cnt].start = insn_cnt;
2212 if (env->log.level & BPF_LOG_LEVEL2)
2213 for (i = 0; i < env->subprog_cnt; i++)
2214 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2219 static int check_subprogs(struct bpf_verifier_env *env)
2221 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2222 struct bpf_subprog_info *subprog = env->subprog_info;
2223 struct bpf_insn *insn = env->prog->insnsi;
2224 int insn_cnt = env->prog->len;
2226 /* now check that all jumps are within the same subprog */
2227 subprog_start = subprog[cur_subprog].start;
2228 subprog_end = subprog[cur_subprog + 1].start;
2229 for (i = 0; i < insn_cnt; i++) {
2230 u8 code = insn[i].code;
2232 if (code == (BPF_JMP | BPF_CALL) &&
2233 insn[i].imm == BPF_FUNC_tail_call &&
2234 insn[i].src_reg != BPF_PSEUDO_CALL)
2235 subprog[cur_subprog].has_tail_call = true;
2236 if (BPF_CLASS(code) == BPF_LD &&
2237 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2238 subprog[cur_subprog].has_ld_abs = true;
2239 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2241 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2243 off = i + insn[i].off + 1;
2244 if (off < subprog_start || off >= subprog_end) {
2245 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2249 if (i == subprog_end - 1) {
2250 /* to avoid fall-through from one subprog into another
2251 * the last insn of the subprog should be either exit
2252 * or unconditional jump back
2254 if (code != (BPF_JMP | BPF_EXIT) &&
2255 code != (BPF_JMP | BPF_JA)) {
2256 verbose(env, "last insn is not an exit or jmp\n");
2259 subprog_start = subprog_end;
2261 if (cur_subprog < env->subprog_cnt)
2262 subprog_end = subprog[cur_subprog + 1].start;
2268 /* Parentage chain of this register (or stack slot) should take care of all
2269 * issues like callee-saved registers, stack slot allocation time, etc.
2271 static int mark_reg_read(struct bpf_verifier_env *env,
2272 const struct bpf_reg_state *state,
2273 struct bpf_reg_state *parent, u8 flag)
2275 bool writes = parent == state->parent; /* Observe write marks */
2279 /* if read wasn't screened by an earlier write ... */
2280 if (writes && state->live & REG_LIVE_WRITTEN)
2282 if (parent->live & REG_LIVE_DONE) {
2283 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2284 reg_type_str(env, parent->type),
2285 parent->var_off.value, parent->off);
2288 /* The first condition is more likely to be true than the
2289 * second, checked it first.
2291 if ((parent->live & REG_LIVE_READ) == flag ||
2292 parent->live & REG_LIVE_READ64)
2293 /* The parentage chain never changes and
2294 * this parent was already marked as LIVE_READ.
2295 * There is no need to keep walking the chain again and
2296 * keep re-marking all parents as LIVE_READ.
2297 * This case happens when the same register is read
2298 * multiple times without writes into it in-between.
2299 * Also, if parent has the stronger REG_LIVE_READ64 set,
2300 * then no need to set the weak REG_LIVE_READ32.
2303 /* ... then we depend on parent's value */
2304 parent->live |= flag;
2305 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2306 if (flag == REG_LIVE_READ64)
2307 parent->live &= ~REG_LIVE_READ32;
2309 parent = state->parent;
2314 if (env->longest_mark_read_walk < cnt)
2315 env->longest_mark_read_walk = cnt;
2319 /* This function is supposed to be used by the following 32-bit optimization
2320 * code only. It returns TRUE if the source or destination register operates
2321 * on 64-bit, otherwise return FALSE.
2323 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2324 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2329 class = BPF_CLASS(code);
2331 if (class == BPF_JMP) {
2332 /* BPF_EXIT for "main" will reach here. Return TRUE
2337 if (op == BPF_CALL) {
2338 /* BPF to BPF call will reach here because of marking
2339 * caller saved clobber with DST_OP_NO_MARK for which we
2340 * don't care the register def because they are anyway
2341 * marked as NOT_INIT already.
2343 if (insn->src_reg == BPF_PSEUDO_CALL)
2345 /* Helper call will reach here because of arg type
2346 * check, conservatively return TRUE.
2355 if (class == BPF_ALU64 || class == BPF_JMP ||
2356 /* BPF_END always use BPF_ALU class. */
2357 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2360 if (class == BPF_ALU || class == BPF_JMP32)
2363 if (class == BPF_LDX) {
2365 return BPF_SIZE(code) == BPF_DW;
2366 /* LDX source must be ptr. */
2370 if (class == BPF_STX) {
2371 /* BPF_STX (including atomic variants) has multiple source
2372 * operands, one of which is a ptr. Check whether the caller is
2375 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2377 return BPF_SIZE(code) == BPF_DW;
2380 if (class == BPF_LD) {
2381 u8 mode = BPF_MODE(code);
2384 if (mode == BPF_IMM)
2387 /* Both LD_IND and LD_ABS return 32-bit data. */
2391 /* Implicit ctx ptr. */
2392 if (regno == BPF_REG_6)
2395 /* Explicit source could be any width. */
2399 if (class == BPF_ST)
2400 /* The only source register for BPF_ST is a ptr. */
2403 /* Conservatively return true at default. */
2407 /* Return the regno defined by the insn, or -1. */
2408 static int insn_def_regno(const struct bpf_insn *insn)
2410 switch (BPF_CLASS(insn->code)) {
2416 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2417 (insn->imm & BPF_FETCH)) {
2418 if (insn->imm == BPF_CMPXCHG)
2421 return insn->src_reg;
2426 return insn->dst_reg;
2430 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2431 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2433 int dst_reg = insn_def_regno(insn);
2438 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2441 static void mark_insn_zext(struct bpf_verifier_env *env,
2442 struct bpf_reg_state *reg)
2444 s32 def_idx = reg->subreg_def;
2446 if (def_idx == DEF_NOT_SUBREG)
2449 env->insn_aux_data[def_idx - 1].zext_dst = true;
2450 /* The dst will be zero extended, so won't be sub-register anymore. */
2451 reg->subreg_def = DEF_NOT_SUBREG;
2454 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2455 enum reg_arg_type t)
2457 struct bpf_verifier_state *vstate = env->cur_state;
2458 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2459 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2460 struct bpf_reg_state *reg, *regs = state->regs;
2463 if (regno >= MAX_BPF_REG) {
2464 verbose(env, "R%d is invalid\n", regno);
2468 mark_reg_scratched(env, regno);
2471 rw64 = is_reg64(env, insn, regno, reg, t);
2473 /* check whether register used as source operand can be read */
2474 if (reg->type == NOT_INIT) {
2475 verbose(env, "R%d !read_ok\n", regno);
2478 /* We don't need to worry about FP liveness because it's read-only */
2479 if (regno == BPF_REG_FP)
2483 mark_insn_zext(env, reg);
2485 return mark_reg_read(env, reg, reg->parent,
2486 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2488 /* check whether register used as dest operand can be written to */
2489 if (regno == BPF_REG_FP) {
2490 verbose(env, "frame pointer is read only\n");
2493 reg->live |= REG_LIVE_WRITTEN;
2494 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2496 mark_reg_unknown(env, regs, regno);
2501 /* for any branch, call, exit record the history of jmps in the given state */
2502 static int push_jmp_history(struct bpf_verifier_env *env,
2503 struct bpf_verifier_state *cur)
2505 u32 cnt = cur->jmp_history_cnt;
2506 struct bpf_idx_pair *p;
2509 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2512 p[cnt - 1].idx = env->insn_idx;
2513 p[cnt - 1].prev_idx = env->prev_insn_idx;
2514 cur->jmp_history = p;
2515 cur->jmp_history_cnt = cnt;
2519 /* Backtrack one insn at a time. If idx is not at the top of recorded
2520 * history then previous instruction came from straight line execution.
2522 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2527 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2528 i = st->jmp_history[cnt - 1].prev_idx;
2536 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2538 const struct btf_type *func;
2539 struct btf *desc_btf;
2541 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2544 desc_btf = find_kfunc_desc_btf(data, insn->off);
2545 if (IS_ERR(desc_btf))
2548 func = btf_type_by_id(desc_btf, insn->imm);
2549 return btf_name_by_offset(desc_btf, func->name_off);
2552 /* For given verifier state backtrack_insn() is called from the last insn to
2553 * the first insn. Its purpose is to compute a bitmask of registers and
2554 * stack slots that needs precision in the parent verifier state.
2556 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2557 u32 *reg_mask, u64 *stack_mask)
2559 const struct bpf_insn_cbs cbs = {
2560 .cb_call = disasm_kfunc_name,
2561 .cb_print = verbose,
2562 .private_data = env,
2564 struct bpf_insn *insn = env->prog->insnsi + idx;
2565 u8 class = BPF_CLASS(insn->code);
2566 u8 opcode = BPF_OP(insn->code);
2567 u8 mode = BPF_MODE(insn->code);
2568 u32 dreg = 1u << insn->dst_reg;
2569 u32 sreg = 1u << insn->src_reg;
2572 if (insn->code == 0)
2574 if (env->log.level & BPF_LOG_LEVEL2) {
2575 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2576 verbose(env, "%d: ", idx);
2577 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2580 if (class == BPF_ALU || class == BPF_ALU64) {
2581 if (!(*reg_mask & dreg))
2583 if (opcode == BPF_MOV) {
2584 if (BPF_SRC(insn->code) == BPF_X) {
2586 * dreg needs precision after this insn
2587 * sreg needs precision before this insn
2593 * dreg needs precision after this insn.
2594 * Corresponding register is already marked
2595 * as precise=true in this verifier state.
2596 * No further markings in parent are necessary
2601 if (BPF_SRC(insn->code) == BPF_X) {
2603 * both dreg and sreg need precision
2608 * dreg still needs precision before this insn
2611 } else if (class == BPF_LDX) {
2612 if (!(*reg_mask & dreg))
2616 /* scalars can only be spilled into stack w/o losing precision.
2617 * Load from any other memory can be zero extended.
2618 * The desire to keep that precision is already indicated
2619 * by 'precise' mark in corresponding register of this state.
2620 * No further tracking necessary.
2622 if (insn->src_reg != BPF_REG_FP)
2625 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2626 * that [fp - off] slot contains scalar that needs to be
2627 * tracked with precision
2629 spi = (-insn->off - 1) / BPF_REG_SIZE;
2631 verbose(env, "BUG spi %d\n", spi);
2632 WARN_ONCE(1, "verifier backtracking bug");
2635 *stack_mask |= 1ull << spi;
2636 } else if (class == BPF_STX || class == BPF_ST) {
2637 if (*reg_mask & dreg)
2638 /* stx & st shouldn't be using _scalar_ dst_reg
2639 * to access memory. It means backtracking
2640 * encountered a case of pointer subtraction.
2643 /* scalars can only be spilled into stack */
2644 if (insn->dst_reg != BPF_REG_FP)
2646 spi = (-insn->off - 1) / BPF_REG_SIZE;
2648 verbose(env, "BUG spi %d\n", spi);
2649 WARN_ONCE(1, "verifier backtracking bug");
2652 if (!(*stack_mask & (1ull << spi)))
2654 *stack_mask &= ~(1ull << spi);
2655 if (class == BPF_STX)
2657 } else if (class == BPF_JMP || class == BPF_JMP32) {
2658 if (opcode == BPF_CALL) {
2659 if (insn->src_reg == BPF_PSEUDO_CALL)
2661 /* regular helper call sets R0 */
2663 if (*reg_mask & 0x3f) {
2664 /* if backtracing was looking for registers R1-R5
2665 * they should have been found already.
2667 verbose(env, "BUG regs %x\n", *reg_mask);
2668 WARN_ONCE(1, "verifier backtracking bug");
2671 } else if (opcode == BPF_EXIT) {
2674 } else if (class == BPF_LD) {
2675 if (!(*reg_mask & dreg))
2678 /* It's ld_imm64 or ld_abs or ld_ind.
2679 * For ld_imm64 no further tracking of precision
2680 * into parent is necessary
2682 if (mode == BPF_IND || mode == BPF_ABS)
2683 /* to be analyzed */
2689 /* the scalar precision tracking algorithm:
2690 * . at the start all registers have precise=false.
2691 * . scalar ranges are tracked as normal through alu and jmp insns.
2692 * . once precise value of the scalar register is used in:
2693 * . ptr + scalar alu
2694 * . if (scalar cond K|scalar)
2695 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2696 * backtrack through the verifier states and mark all registers and
2697 * stack slots with spilled constants that these scalar regisers
2698 * should be precise.
2699 * . during state pruning two registers (or spilled stack slots)
2700 * are equivalent if both are not precise.
2702 * Note the verifier cannot simply walk register parentage chain,
2703 * since many different registers and stack slots could have been
2704 * used to compute single precise scalar.
2706 * The approach of starting with precise=true for all registers and then
2707 * backtrack to mark a register as not precise when the verifier detects
2708 * that program doesn't care about specific value (e.g., when helper
2709 * takes register as ARG_ANYTHING parameter) is not safe.
2711 * It's ok to walk single parentage chain of the verifier states.
2712 * It's possible that this backtracking will go all the way till 1st insn.
2713 * All other branches will be explored for needing precision later.
2715 * The backtracking needs to deal with cases like:
2716 * 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)
2719 * if r5 > 0x79f goto pc+7
2720 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2723 * call bpf_perf_event_output#25
2724 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2728 * call foo // uses callee's r6 inside to compute r0
2732 * to track above reg_mask/stack_mask needs to be independent for each frame.
2734 * Also if parent's curframe > frame where backtracking started,
2735 * the verifier need to mark registers in both frames, otherwise callees
2736 * may incorrectly prune callers. This is similar to
2737 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2739 * For now backtracking falls back into conservative marking.
2741 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2742 struct bpf_verifier_state *st)
2744 struct bpf_func_state *func;
2745 struct bpf_reg_state *reg;
2748 /* big hammer: mark all scalars precise in this path.
2749 * pop_stack may still get !precise scalars.
2751 for (; st; st = st->parent)
2752 for (i = 0; i <= st->curframe; i++) {
2753 func = st->frame[i];
2754 for (j = 0; j < BPF_REG_FP; j++) {
2755 reg = &func->regs[j];
2756 if (reg->type != SCALAR_VALUE)
2758 reg->precise = true;
2760 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2761 if (!is_spilled_reg(&func->stack[j]))
2763 reg = &func->stack[j].spilled_ptr;
2764 if (reg->type != SCALAR_VALUE)
2766 reg->precise = true;
2771 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2774 struct bpf_verifier_state *st = env->cur_state;
2775 int first_idx = st->first_insn_idx;
2776 int last_idx = env->insn_idx;
2777 struct bpf_func_state *func;
2778 struct bpf_reg_state *reg;
2779 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2780 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2781 bool skip_first = true;
2782 bool new_marks = false;
2785 if (!env->bpf_capable)
2788 func = st->frame[st->curframe];
2790 reg = &func->regs[regno];
2791 if (reg->type != SCALAR_VALUE) {
2792 WARN_ONCE(1, "backtracing misuse");
2799 reg->precise = true;
2803 if (!is_spilled_reg(&func->stack[spi])) {
2807 reg = &func->stack[spi].spilled_ptr;
2808 if (reg->type != SCALAR_VALUE) {
2816 reg->precise = true;
2822 if (!reg_mask && !stack_mask)
2825 DECLARE_BITMAP(mask, 64);
2826 u32 history = st->jmp_history_cnt;
2828 if (env->log.level & BPF_LOG_LEVEL2)
2829 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2830 for (i = last_idx;;) {
2835 err = backtrack_insn(env, i, ®_mask, &stack_mask);
2837 if (err == -ENOTSUPP) {
2838 mark_all_scalars_precise(env, st);
2843 if (!reg_mask && !stack_mask)
2844 /* Found assignment(s) into tracked register in this state.
2845 * Since this state is already marked, just return.
2846 * Nothing to be tracked further in the parent state.
2851 i = get_prev_insn_idx(st, i, &history);
2852 if (i >= env->prog->len) {
2853 /* This can happen if backtracking reached insn 0
2854 * and there are still reg_mask or stack_mask
2856 * It means the backtracking missed the spot where
2857 * particular register was initialized with a constant.
2859 verbose(env, "BUG backtracking idx %d\n", i);
2860 WARN_ONCE(1, "verifier backtracking bug");
2869 func = st->frame[st->curframe];
2870 bitmap_from_u64(mask, reg_mask);
2871 for_each_set_bit(i, mask, 32) {
2872 reg = &func->regs[i];
2873 if (reg->type != SCALAR_VALUE) {
2874 reg_mask &= ~(1u << i);
2879 reg->precise = true;
2882 bitmap_from_u64(mask, stack_mask);
2883 for_each_set_bit(i, mask, 64) {
2884 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2885 /* the sequence of instructions:
2887 * 3: (7b) *(u64 *)(r3 -8) = r0
2888 * 4: (79) r4 = *(u64 *)(r10 -8)
2889 * doesn't contain jmps. It's backtracked
2890 * as a single block.
2891 * During backtracking insn 3 is not recognized as
2892 * stack access, so at the end of backtracking
2893 * stack slot fp-8 is still marked in stack_mask.
2894 * However the parent state may not have accessed
2895 * fp-8 and it's "unallocated" stack space.
2896 * In such case fallback to conservative.
2898 mark_all_scalars_precise(env, st);
2902 if (!is_spilled_reg(&func->stack[i])) {
2903 stack_mask &= ~(1ull << i);
2906 reg = &func->stack[i].spilled_ptr;
2907 if (reg->type != SCALAR_VALUE) {
2908 stack_mask &= ~(1ull << i);
2913 reg->precise = true;
2915 if (env->log.level & BPF_LOG_LEVEL2) {
2916 verbose(env, "parent %s regs=%x stack=%llx marks:",
2917 new_marks ? "didn't have" : "already had",
2918 reg_mask, stack_mask);
2919 print_verifier_state(env, func, true);
2922 if (!reg_mask && !stack_mask)
2927 last_idx = st->last_insn_idx;
2928 first_idx = st->first_insn_idx;
2933 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2935 return __mark_chain_precision(env, regno, -1);
2938 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2940 return __mark_chain_precision(env, -1, spi);
2943 static bool is_spillable_regtype(enum bpf_reg_type type)
2945 switch (base_type(type)) {
2946 case PTR_TO_MAP_VALUE:
2950 case PTR_TO_PACKET_META:
2951 case PTR_TO_PACKET_END:
2952 case PTR_TO_FLOW_KEYS:
2953 case CONST_PTR_TO_MAP:
2955 case PTR_TO_SOCK_COMMON:
2956 case PTR_TO_TCP_SOCK:
2957 case PTR_TO_XDP_SOCK:
2962 case PTR_TO_MAP_KEY:
2969 /* Does this register contain a constant zero? */
2970 static bool register_is_null(struct bpf_reg_state *reg)
2972 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2975 static bool register_is_const(struct bpf_reg_state *reg)
2977 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2980 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2982 return tnum_is_unknown(reg->var_off) &&
2983 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2984 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2985 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2986 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2989 static bool register_is_bounded(struct bpf_reg_state *reg)
2991 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2994 static bool __is_pointer_value(bool allow_ptr_leaks,
2995 const struct bpf_reg_state *reg)
2997 if (allow_ptr_leaks)
3000 return reg->type != SCALAR_VALUE;
3003 static void save_register_state(struct bpf_func_state *state,
3004 int spi, struct bpf_reg_state *reg,
3009 state->stack[spi].spilled_ptr = *reg;
3010 if (size == BPF_REG_SIZE)
3011 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3013 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3014 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3016 /* size < 8 bytes spill */
3018 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3021 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3022 * stack boundary and alignment are checked in check_mem_access()
3024 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3025 /* stack frame we're writing to */
3026 struct bpf_func_state *state,
3027 int off, int size, int value_regno,
3030 struct bpf_func_state *cur; /* state of the current function */
3031 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3032 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3033 struct bpf_reg_state *reg = NULL;
3035 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3038 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3039 * so it's aligned access and [off, off + size) are within stack limits
3041 if (!env->allow_ptr_leaks &&
3042 state->stack[spi].slot_type[0] == STACK_SPILL &&
3043 size != BPF_REG_SIZE) {
3044 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3048 cur = env->cur_state->frame[env->cur_state->curframe];
3049 if (value_regno >= 0)
3050 reg = &cur->regs[value_regno];
3051 if (!env->bypass_spec_v4) {
3052 bool sanitize = reg && is_spillable_regtype(reg->type);
3054 for (i = 0; i < size; i++) {
3055 if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3062 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3065 mark_stack_slot_scratched(env, spi);
3066 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3067 !register_is_null(reg) && env->bpf_capable) {
3068 if (dst_reg != BPF_REG_FP) {
3069 /* The backtracking logic can only recognize explicit
3070 * stack slot address like [fp - 8]. Other spill of
3071 * scalar via different register has to be conservative.
3072 * Backtrack from here and mark all registers as precise
3073 * that contributed into 'reg' being a constant.
3075 err = mark_chain_precision(env, value_regno);
3079 save_register_state(state, spi, reg, size);
3080 } else if (reg && is_spillable_regtype(reg->type)) {
3081 /* register containing pointer is being spilled into stack */
3082 if (size != BPF_REG_SIZE) {
3083 verbose_linfo(env, insn_idx, "; ");
3084 verbose(env, "invalid size of register spill\n");
3087 if (state != cur && reg->type == PTR_TO_STACK) {
3088 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3091 save_register_state(state, spi, reg, size);
3093 u8 type = STACK_MISC;
3095 /* regular write of data into stack destroys any spilled ptr */
3096 state->stack[spi].spilled_ptr.type = NOT_INIT;
3097 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3098 if (is_spilled_reg(&state->stack[spi]))
3099 for (i = 0; i < BPF_REG_SIZE; i++)
3100 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3102 /* only mark the slot as written if all 8 bytes were written
3103 * otherwise read propagation may incorrectly stop too soon
3104 * when stack slots are partially written.
3105 * This heuristic means that read propagation will be
3106 * conservative, since it will add reg_live_read marks
3107 * to stack slots all the way to first state when programs
3108 * writes+reads less than 8 bytes
3110 if (size == BPF_REG_SIZE)
3111 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3113 /* when we zero initialize stack slots mark them as such */
3114 if (reg && register_is_null(reg)) {
3115 /* backtracking doesn't work for STACK_ZERO yet. */
3116 err = mark_chain_precision(env, value_regno);
3122 /* Mark slots affected by this stack write. */
3123 for (i = 0; i < size; i++)
3124 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3130 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3131 * known to contain a variable offset.
3132 * This function checks whether the write is permitted and conservatively
3133 * tracks the effects of the write, considering that each stack slot in the
3134 * dynamic range is potentially written to.
3136 * 'off' includes 'regno->off'.
3137 * 'value_regno' can be -1, meaning that an unknown value is being written to
3140 * Spilled pointers in range are not marked as written because we don't know
3141 * what's going to be actually written. This means that read propagation for
3142 * future reads cannot be terminated by this write.
3144 * For privileged programs, uninitialized stack slots are considered
3145 * initialized by this write (even though we don't know exactly what offsets
3146 * are going to be written to). The idea is that we don't want the verifier to
3147 * reject future reads that access slots written to through variable offsets.
3149 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3150 /* func where register points to */
3151 struct bpf_func_state *state,
3152 int ptr_regno, int off, int size,
3153 int value_regno, int insn_idx)
3155 struct bpf_func_state *cur; /* state of the current function */
3156 int min_off, max_off;
3158 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3159 bool writing_zero = false;
3160 /* set if the fact that we're writing a zero is used to let any
3161 * stack slots remain STACK_ZERO
3163 bool zero_used = false;
3165 cur = env->cur_state->frame[env->cur_state->curframe];
3166 ptr_reg = &cur->regs[ptr_regno];
3167 min_off = ptr_reg->smin_value + off;
3168 max_off = ptr_reg->smax_value + off + size;
3169 if (value_regno >= 0)
3170 value_reg = &cur->regs[value_regno];
3171 if (value_reg && register_is_null(value_reg))
3172 writing_zero = true;
3174 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3179 /* Variable offset writes destroy any spilled pointers in range. */
3180 for (i = min_off; i < max_off; i++) {
3181 u8 new_type, *stype;
3185 spi = slot / BPF_REG_SIZE;
3186 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3187 mark_stack_slot_scratched(env, spi);
3189 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3190 /* Reject the write if range we may write to has not
3191 * been initialized beforehand. If we didn't reject
3192 * here, the ptr status would be erased below (even
3193 * though not all slots are actually overwritten),
3194 * possibly opening the door to leaks.
3196 * We do however catch STACK_INVALID case below, and
3197 * only allow reading possibly uninitialized memory
3198 * later for CAP_PERFMON, as the write may not happen to
3201 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3206 /* Erase all spilled pointers. */
3207 state->stack[spi].spilled_ptr.type = NOT_INIT;
3209 /* Update the slot type. */
3210 new_type = STACK_MISC;
3211 if (writing_zero && *stype == STACK_ZERO) {
3212 new_type = STACK_ZERO;
3215 /* If the slot is STACK_INVALID, we check whether it's OK to
3216 * pretend that it will be initialized by this write. The slot
3217 * might not actually be written to, and so if we mark it as
3218 * initialized future reads might leak uninitialized memory.
3219 * For privileged programs, we will accept such reads to slots
3220 * that may or may not be written because, if we're reject
3221 * them, the error would be too confusing.
3223 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3224 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3231 /* backtracking doesn't work for STACK_ZERO yet. */
3232 err = mark_chain_precision(env, value_regno);
3239 /* When register 'dst_regno' is assigned some values from stack[min_off,
3240 * max_off), we set the register's type according to the types of the
3241 * respective stack slots. If all the stack values are known to be zeros, then
3242 * so is the destination reg. Otherwise, the register is considered to be
3243 * SCALAR. This function does not deal with register filling; the caller must
3244 * ensure that all spilled registers in the stack range have been marked as
3247 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3248 /* func where src register points to */
3249 struct bpf_func_state *ptr_state,
3250 int min_off, int max_off, int dst_regno)
3252 struct bpf_verifier_state *vstate = env->cur_state;
3253 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3258 for (i = min_off; i < max_off; i++) {
3260 spi = slot / BPF_REG_SIZE;
3261 stype = ptr_state->stack[spi].slot_type;
3262 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3266 if (zeros == max_off - min_off) {
3267 /* any access_size read into register is zero extended,
3268 * so the whole register == const_zero
3270 __mark_reg_const_zero(&state->regs[dst_regno]);
3271 /* backtracking doesn't support STACK_ZERO yet,
3272 * so mark it precise here, so that later
3273 * backtracking can stop here.
3274 * Backtracking may not need this if this register
3275 * doesn't participate in pointer adjustment.
3276 * Forward propagation of precise flag is not
3277 * necessary either. This mark is only to stop
3278 * backtracking. Any register that contributed
3279 * to const 0 was marked precise before spill.
3281 state->regs[dst_regno].precise = true;
3283 /* have read misc data from the stack */
3284 mark_reg_unknown(env, state->regs, dst_regno);
3286 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3289 /* Read the stack at 'off' and put the results into the register indicated by
3290 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3293 * 'dst_regno' can be -1, meaning that the read value is not going to a
3296 * The access is assumed to be within the current stack bounds.
3298 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3299 /* func where src register points to */
3300 struct bpf_func_state *reg_state,
3301 int off, int size, int dst_regno)
3303 struct bpf_verifier_state *vstate = env->cur_state;
3304 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3305 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3306 struct bpf_reg_state *reg;
3309 stype = reg_state->stack[spi].slot_type;
3310 reg = ®_state->stack[spi].spilled_ptr;
3312 if (is_spilled_reg(®_state->stack[spi])) {
3315 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3318 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3319 if (reg->type != SCALAR_VALUE) {
3320 verbose_linfo(env, env->insn_idx, "; ");
3321 verbose(env, "invalid size of register fill\n");
3325 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3329 if (!(off % BPF_REG_SIZE) && size == spill_size) {
3330 /* The earlier check_reg_arg() has decided the
3331 * subreg_def for this insn. Save it first.
3333 s32 subreg_def = state->regs[dst_regno].subreg_def;
3335 state->regs[dst_regno] = *reg;
3336 state->regs[dst_regno].subreg_def = subreg_def;
3338 for (i = 0; i < size; i++) {
3339 type = stype[(slot - i) % BPF_REG_SIZE];
3340 if (type == STACK_SPILL)
3342 if (type == STACK_MISC)
3344 verbose(env, "invalid read from stack off %d+%d size %d\n",
3348 mark_reg_unknown(env, state->regs, dst_regno);
3350 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3354 if (dst_regno >= 0) {
3355 /* restore register state from stack */
3356 state->regs[dst_regno] = *reg;
3357 /* mark reg as written since spilled pointer state likely
3358 * has its liveness marks cleared by is_state_visited()
3359 * which resets stack/reg liveness for state transitions
3361 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3362 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3363 /* If dst_regno==-1, the caller is asking us whether
3364 * it is acceptable to use this value as a SCALAR_VALUE
3366 * We must not allow unprivileged callers to do that
3367 * with spilled pointers.
3369 verbose(env, "leaking pointer from stack off %d\n",
3373 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3375 for (i = 0; i < size; i++) {
3376 type = stype[(slot - i) % BPF_REG_SIZE];
3377 if (type == STACK_MISC)
3379 if (type == STACK_ZERO)
3381 verbose(env, "invalid read from stack off %d+%d size %d\n",
3385 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3387 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3392 enum bpf_access_src {
3393 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
3394 ACCESS_HELPER = 2, /* the access is performed by a helper */
3397 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3398 int regno, int off, int access_size,
3399 bool zero_size_allowed,
3400 enum bpf_access_src type,
3401 struct bpf_call_arg_meta *meta);
3403 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3405 return cur_regs(env) + regno;
3408 /* Read the stack at 'ptr_regno + off' and put the result into the register
3410 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3411 * but not its variable offset.
3412 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3414 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3415 * filling registers (i.e. reads of spilled register cannot be detected when
3416 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3417 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3418 * offset; for a fixed offset check_stack_read_fixed_off should be used
3421 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3422 int ptr_regno, int off, int size, int dst_regno)
3424 /* The state of the source register. */
3425 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3426 struct bpf_func_state *ptr_state = func(env, reg);
3428 int min_off, max_off;
3430 /* Note that we pass a NULL meta, so raw access will not be permitted.
3432 err = check_stack_range_initialized(env, ptr_regno, off, size,
3433 false, ACCESS_DIRECT, NULL);
3437 min_off = reg->smin_value + off;
3438 max_off = reg->smax_value + off;
3439 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3443 /* check_stack_read dispatches to check_stack_read_fixed_off or
3444 * check_stack_read_var_off.
3446 * The caller must ensure that the offset falls within the allocated stack
3449 * 'dst_regno' is a register which will receive the value from the stack. It
3450 * can be -1, meaning that the read value is not going to a register.
3452 static int check_stack_read(struct bpf_verifier_env *env,
3453 int ptr_regno, int off, int size,
3456 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3457 struct bpf_func_state *state = func(env, reg);
3459 /* Some accesses are only permitted with a static offset. */
3460 bool var_off = !tnum_is_const(reg->var_off);
3462 /* The offset is required to be static when reads don't go to a
3463 * register, in order to not leak pointers (see
3464 * check_stack_read_fixed_off).
3466 if (dst_regno < 0 && var_off) {
3469 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3470 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3474 /* Variable offset is prohibited for unprivileged mode for simplicity
3475 * since it requires corresponding support in Spectre masking for stack
3476 * ALU. See also retrieve_ptr_limit().
3478 if (!env->bypass_spec_v1 && var_off) {
3481 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3482 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3488 off += reg->var_off.value;
3489 err = check_stack_read_fixed_off(env, state, off, size,
3492 /* Variable offset stack reads need more conservative handling
3493 * than fixed offset ones. Note that dst_regno >= 0 on this
3496 err = check_stack_read_var_off(env, ptr_regno, off, size,
3503 /* check_stack_write dispatches to check_stack_write_fixed_off or
3504 * check_stack_write_var_off.
3506 * 'ptr_regno' is the register used as a pointer into the stack.
3507 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3508 * 'value_regno' is the register whose value we're writing to the stack. It can
3509 * be -1, meaning that we're not writing from a register.
3511 * The caller must ensure that the offset falls within the maximum stack size.
3513 static int check_stack_write(struct bpf_verifier_env *env,
3514 int ptr_regno, int off, int size,
3515 int value_regno, int insn_idx)
3517 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3518 struct bpf_func_state *state = func(env, reg);
3521 if (tnum_is_const(reg->var_off)) {
3522 off += reg->var_off.value;
3523 err = check_stack_write_fixed_off(env, state, off, size,
3524 value_regno, insn_idx);
3526 /* Variable offset stack reads need more conservative handling
3527 * than fixed offset ones.
3529 err = check_stack_write_var_off(env, state,
3530 ptr_regno, off, size,
3531 value_regno, insn_idx);
3536 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3537 int off, int size, enum bpf_access_type type)
3539 struct bpf_reg_state *regs = cur_regs(env);
3540 struct bpf_map *map = regs[regno].map_ptr;
3541 u32 cap = bpf_map_flags_to_cap(map);
3543 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3544 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3545 map->value_size, off, size);
3549 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3550 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3551 map->value_size, off, size);
3558 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3559 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3560 int off, int size, u32 mem_size,
3561 bool zero_size_allowed)
3563 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3564 struct bpf_reg_state *reg;
3566 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3569 reg = &cur_regs(env)[regno];
3570 switch (reg->type) {
3571 case PTR_TO_MAP_KEY:
3572 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3573 mem_size, off, size);
3575 case PTR_TO_MAP_VALUE:
3576 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3577 mem_size, off, size);
3580 case PTR_TO_PACKET_META:
3581 case PTR_TO_PACKET_END:
3582 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3583 off, size, regno, reg->id, off, mem_size);
3587 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3588 mem_size, off, size);
3594 /* check read/write into a memory region with possible variable offset */
3595 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3596 int off, int size, u32 mem_size,
3597 bool zero_size_allowed)
3599 struct bpf_verifier_state *vstate = env->cur_state;
3600 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3601 struct bpf_reg_state *reg = &state->regs[regno];
3604 /* We may have adjusted the register pointing to memory region, so we
3605 * need to try adding each of min_value and max_value to off
3606 * to make sure our theoretical access will be safe.
3608 * The minimum value is only important with signed
3609 * comparisons where we can't assume the floor of a
3610 * value is 0. If we are using signed variables for our
3611 * index'es we need to make sure that whatever we use
3612 * will have a set floor within our range.
3614 if (reg->smin_value < 0 &&
3615 (reg->smin_value == S64_MIN ||
3616 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3617 reg->smin_value + off < 0)) {
3618 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3622 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3623 mem_size, zero_size_allowed);
3625 verbose(env, "R%d min value is outside of the allowed memory range\n",
3630 /* If we haven't set a max value then we need to bail since we can't be
3631 * sure we won't do bad things.
3632 * If reg->umax_value + off could overflow, treat that as unbounded too.
3634 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3635 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3639 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3640 mem_size, zero_size_allowed);
3642 verbose(env, "R%d max value is outside of the allowed memory range\n",
3650 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3651 const struct bpf_reg_state *reg, int regno,
3654 /* Access to this pointer-typed register or passing it to a helper
3655 * is only allowed in its original, unmodified form.
3659 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3660 reg_type_str(env, reg->type), regno, reg->off);
3664 if (!fixed_off_ok && reg->off) {
3665 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3666 reg_type_str(env, reg->type), regno, reg->off);
3670 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3673 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3674 verbose(env, "variable %s access var_off=%s disallowed\n",
3675 reg_type_str(env, reg->type), tn_buf);
3682 int check_ptr_off_reg(struct bpf_verifier_env *env,
3683 const struct bpf_reg_state *reg, int regno)
3685 return __check_ptr_off_reg(env, reg, regno, false);
3688 static int map_kptr_match_type(struct bpf_verifier_env *env,
3689 struct bpf_map_value_off_desc *off_desc,
3690 struct bpf_reg_state *reg, u32 regno)
3692 const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3693 int perm_flags = PTR_MAYBE_NULL;
3694 const char *reg_name = "";
3696 /* Only unreferenced case accepts untrusted pointers */
3697 if (off_desc->type == BPF_KPTR_UNREF)
3698 perm_flags |= PTR_UNTRUSTED;
3700 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3703 if (!btf_is_kernel(reg->btf)) {
3704 verbose(env, "R%d must point to kernel BTF\n", regno);
3707 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3708 reg_name = kernel_type_name(reg->btf, reg->btf_id);
3710 /* For ref_ptr case, release function check should ensure we get one
3711 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3712 * normal store of unreferenced kptr, we must ensure var_off is zero.
3713 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3714 * reg->off and reg->ref_obj_id are not needed here.
3716 if (__check_ptr_off_reg(env, reg, regno, true))
3719 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3720 * we also need to take into account the reg->off.
3722 * We want to support cases like:
3730 * v = func(); // PTR_TO_BTF_ID
3731 * val->foo = v; // reg->off is zero, btf and btf_id match type
3732 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3733 * // first member type of struct after comparison fails
3734 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3737 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3738 * is zero. We must also ensure that btf_struct_ids_match does not walk
3739 * the struct to match type against first member of struct, i.e. reject
3740 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3741 * strict mode to true for type match.
3743 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3744 off_desc->kptr.btf, off_desc->kptr.btf_id,
3745 off_desc->type == BPF_KPTR_REF))
3749 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3750 reg_type_str(env, reg->type), reg_name);
3751 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3752 if (off_desc->type == BPF_KPTR_UNREF)
3753 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3760 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3761 int value_regno, int insn_idx,
3762 struct bpf_map_value_off_desc *off_desc)
3764 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3765 int class = BPF_CLASS(insn->code);
3766 struct bpf_reg_state *val_reg;
3768 /* Things we already checked for in check_map_access and caller:
3769 * - Reject cases where variable offset may touch kptr
3770 * - size of access (must be BPF_DW)
3771 * - tnum_is_const(reg->var_off)
3772 * - off_desc->offset == off + reg->var_off.value
3774 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3775 if (BPF_MODE(insn->code) != BPF_MEM) {
3776 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3780 /* We only allow loading referenced kptr, since it will be marked as
3781 * untrusted, similar to unreferenced kptr.
3783 if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3784 verbose(env, "store to referenced kptr disallowed\n");
3788 if (class == BPF_LDX) {
3789 val_reg = reg_state(env, value_regno);
3790 /* We can simply mark the value_regno receiving the pointer
3791 * value from map as PTR_TO_BTF_ID, with the correct type.
3793 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3794 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3795 /* For mark_ptr_or_null_reg */
3796 val_reg->id = ++env->id_gen;
3797 } else if (class == BPF_STX) {
3798 val_reg = reg_state(env, value_regno);
3799 if (!register_is_null(val_reg) &&
3800 map_kptr_match_type(env, off_desc, val_reg, value_regno))
3802 } else if (class == BPF_ST) {
3804 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3809 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3815 /* check read/write into a map element with possible variable offset */
3816 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3817 int off, int size, bool zero_size_allowed,
3818 enum bpf_access_src src)
3820 struct bpf_verifier_state *vstate = env->cur_state;
3821 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3822 struct bpf_reg_state *reg = &state->regs[regno];
3823 struct bpf_map *map = reg->map_ptr;
3826 err = check_mem_region_access(env, regno, off, size, map->value_size,
3831 if (map_value_has_spin_lock(map)) {
3832 u32 lock = map->spin_lock_off;
3834 /* if any part of struct bpf_spin_lock can be touched by
3835 * load/store reject this program.
3836 * To check that [x1, x2) overlaps with [y1, y2)
3837 * it is sufficient to check x1 < y2 && y1 < x2.
3839 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3840 lock < reg->umax_value + off + size) {
3841 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3845 if (map_value_has_timer(map)) {
3846 u32 t = map->timer_off;
3848 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3849 t < reg->umax_value + off + size) {
3850 verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3854 if (map_value_has_kptrs(map)) {
3855 struct bpf_map_value_off *tab = map->kptr_off_tab;
3858 for (i = 0; i < tab->nr_off; i++) {
3859 u32 p = tab->off[i].offset;
3861 if (reg->smin_value + off < p + sizeof(u64) &&
3862 p < reg->umax_value + off + size) {
3863 if (src != ACCESS_DIRECT) {
3864 verbose(env, "kptr cannot be accessed indirectly by helper\n");
3867 if (!tnum_is_const(reg->var_off)) {
3868 verbose(env, "kptr access cannot have variable offset\n");
3871 if (p != off + reg->var_off.value) {
3872 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3873 p, off + reg->var_off.value);
3876 if (size != bpf_size_to_bytes(BPF_DW)) {
3877 verbose(env, "kptr access size must be BPF_DW\n");
3887 #define MAX_PACKET_OFF 0xffff
3889 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3890 const struct bpf_call_arg_meta *meta,
3891 enum bpf_access_type t)
3893 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3895 switch (prog_type) {
3896 /* Program types only with direct read access go here! */
3897 case BPF_PROG_TYPE_LWT_IN:
3898 case BPF_PROG_TYPE_LWT_OUT:
3899 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3900 case BPF_PROG_TYPE_SK_REUSEPORT:
3901 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3902 case BPF_PROG_TYPE_CGROUP_SKB:
3907 /* Program types with direct read + write access go here! */
3908 case BPF_PROG_TYPE_SCHED_CLS:
3909 case BPF_PROG_TYPE_SCHED_ACT:
3910 case BPF_PROG_TYPE_XDP:
3911 case BPF_PROG_TYPE_LWT_XMIT:
3912 case BPF_PROG_TYPE_SK_SKB:
3913 case BPF_PROG_TYPE_SK_MSG:
3915 return meta->pkt_access;
3917 env->seen_direct_write = true;
3920 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3922 env->seen_direct_write = true;
3931 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3932 int size, bool zero_size_allowed)
3934 struct bpf_reg_state *regs = cur_regs(env);
3935 struct bpf_reg_state *reg = ®s[regno];
3938 /* We may have added a variable offset to the packet pointer; but any
3939 * reg->range we have comes after that. We are only checking the fixed
3943 /* We don't allow negative numbers, because we aren't tracking enough
3944 * detail to prove they're safe.
3946 if (reg->smin_value < 0) {
3947 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3952 err = reg->range < 0 ? -EINVAL :
3953 __check_mem_access(env, regno, off, size, reg->range,
3956 verbose(env, "R%d offset is outside of the packet\n", regno);
3960 /* __check_mem_access has made sure "off + size - 1" is within u16.
3961 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3962 * otherwise find_good_pkt_pointers would have refused to set range info
3963 * that __check_mem_access would have rejected this pkt access.
3964 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3966 env->prog->aux->max_pkt_offset =
3967 max_t(u32, env->prog->aux->max_pkt_offset,
3968 off + reg->umax_value + size - 1);
3973 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
3974 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3975 enum bpf_access_type t, enum bpf_reg_type *reg_type,
3976 struct btf **btf, u32 *btf_id)
3978 struct bpf_insn_access_aux info = {
3979 .reg_type = *reg_type,
3983 if (env->ops->is_valid_access &&
3984 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3985 /* A non zero info.ctx_field_size indicates that this field is a
3986 * candidate for later verifier transformation to load the whole
3987 * field and then apply a mask when accessed with a narrower
3988 * access than actual ctx access size. A zero info.ctx_field_size
3989 * will only allow for whole field access and rejects any other
3990 * type of narrower access.
3992 *reg_type = info.reg_type;
3994 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3996 *btf_id = info.btf_id;
3998 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4000 /* remember the offset of last byte accessed in ctx */
4001 if (env->prog->aux->max_ctx_offset < off + size)
4002 env->prog->aux->max_ctx_offset = off + size;
4006 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4010 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4013 if (size < 0 || off < 0 ||
4014 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4015 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4022 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4023 u32 regno, int off, int size,
4024 enum bpf_access_type t)
4026 struct bpf_reg_state *regs = cur_regs(env);
4027 struct bpf_reg_state *reg = ®s[regno];
4028 struct bpf_insn_access_aux info = {};
4031 if (reg->smin_value < 0) {
4032 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4037 switch (reg->type) {
4038 case PTR_TO_SOCK_COMMON:
4039 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4042 valid = bpf_sock_is_valid_access(off, size, t, &info);
4044 case PTR_TO_TCP_SOCK:
4045 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4047 case PTR_TO_XDP_SOCK:
4048 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4056 env->insn_aux_data[insn_idx].ctx_field_size =
4057 info.ctx_field_size;
4061 verbose(env, "R%d invalid %s access off=%d size=%d\n",
4062 regno, reg_type_str(env, reg->type), off, size);
4067 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4069 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4072 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4074 const struct bpf_reg_state *reg = reg_state(env, regno);
4076 return reg->type == PTR_TO_CTX;
4079 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4081 const struct bpf_reg_state *reg = reg_state(env, regno);
4083 return type_is_sk_pointer(reg->type);
4086 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4088 const struct bpf_reg_state *reg = reg_state(env, regno);
4090 return type_is_pkt_pointer(reg->type);
4093 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4095 const struct bpf_reg_state *reg = reg_state(env, regno);
4097 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4098 return reg->type == PTR_TO_FLOW_KEYS;
4101 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4102 const struct bpf_reg_state *reg,
4103 int off, int size, bool strict)
4105 struct tnum reg_off;
4108 /* Byte size accesses are always allowed. */
4109 if (!strict || size == 1)
4112 /* For platforms that do not have a Kconfig enabling
4113 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4114 * NET_IP_ALIGN is universally set to '2'. And on platforms
4115 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4116 * to this code only in strict mode where we want to emulate
4117 * the NET_IP_ALIGN==2 checking. Therefore use an
4118 * unconditional IP align value of '2'.
4122 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4123 if (!tnum_is_aligned(reg_off, size)) {
4126 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4128 "misaligned packet access off %d+%s+%d+%d size %d\n",
4129 ip_align, tn_buf, reg->off, off, size);
4136 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4137 const struct bpf_reg_state *reg,
4138 const char *pointer_desc,
4139 int off, int size, bool strict)
4141 struct tnum reg_off;
4143 /* Byte size accesses are always allowed. */
4144 if (!strict || size == 1)
4147 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4148 if (!tnum_is_aligned(reg_off, size)) {
4151 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4152 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4153 pointer_desc, tn_buf, reg->off, off, size);
4160 static int check_ptr_alignment(struct bpf_verifier_env *env,
4161 const struct bpf_reg_state *reg, int off,
4162 int size, bool strict_alignment_once)
4164 bool strict = env->strict_alignment || strict_alignment_once;
4165 const char *pointer_desc = "";
4167 switch (reg->type) {
4169 case PTR_TO_PACKET_META:
4170 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4171 * right in front, treat it the very same way.
4173 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4174 case PTR_TO_FLOW_KEYS:
4175 pointer_desc = "flow keys ";
4177 case PTR_TO_MAP_KEY:
4178 pointer_desc = "key ";
4180 case PTR_TO_MAP_VALUE:
4181 pointer_desc = "value ";
4184 pointer_desc = "context ";
4187 pointer_desc = "stack ";
4188 /* The stack spill tracking logic in check_stack_write_fixed_off()
4189 * and check_stack_read_fixed_off() relies on stack accesses being
4195 pointer_desc = "sock ";
4197 case PTR_TO_SOCK_COMMON:
4198 pointer_desc = "sock_common ";
4200 case PTR_TO_TCP_SOCK:
4201 pointer_desc = "tcp_sock ";
4203 case PTR_TO_XDP_SOCK:
4204 pointer_desc = "xdp_sock ";
4209 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4213 static int update_stack_depth(struct bpf_verifier_env *env,
4214 const struct bpf_func_state *func,
4217 u16 stack = env->subprog_info[func->subprogno].stack_depth;
4222 /* update known max for given subprogram */
4223 env->subprog_info[func->subprogno].stack_depth = -off;
4227 /* starting from main bpf function walk all instructions of the function
4228 * and recursively walk all callees that given function can call.
4229 * Ignore jump and exit insns.
4230 * Since recursion is prevented by check_cfg() this algorithm
4231 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4233 static int check_max_stack_depth(struct bpf_verifier_env *env)
4235 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4236 struct bpf_subprog_info *subprog = env->subprog_info;
4237 struct bpf_insn *insn = env->prog->insnsi;
4238 bool tail_call_reachable = false;
4239 int ret_insn[MAX_CALL_FRAMES];
4240 int ret_prog[MAX_CALL_FRAMES];
4244 /* protect against potential stack overflow that might happen when
4245 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4246 * depth for such case down to 256 so that the worst case scenario
4247 * would result in 8k stack size (32 which is tailcall limit * 256 =
4250 * To get the idea what might happen, see an example:
4251 * func1 -> sub rsp, 128
4252 * subfunc1 -> sub rsp, 256
4253 * tailcall1 -> add rsp, 256
4254 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4255 * subfunc2 -> sub rsp, 64
4256 * subfunc22 -> sub rsp, 128
4257 * tailcall2 -> add rsp, 128
4258 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4260 * tailcall will unwind the current stack frame but it will not get rid
4261 * of caller's stack as shown on the example above.
4263 if (idx && subprog[idx].has_tail_call && depth >= 256) {
4265 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4269 /* round up to 32-bytes, since this is granularity
4270 * of interpreter stack size
4272 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4273 if (depth > MAX_BPF_STACK) {
4274 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4279 subprog_end = subprog[idx + 1].start;
4280 for (; i < subprog_end; i++) {
4283 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4285 /* remember insn and function to return to */
4286 ret_insn[frame] = i + 1;
4287 ret_prog[frame] = idx;
4289 /* find the callee */
4290 next_insn = i + insn[i].imm + 1;
4291 idx = find_subprog(env, next_insn);
4293 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4297 if (subprog[idx].is_async_cb) {
4298 if (subprog[idx].has_tail_call) {
4299 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4302 /* async callbacks don't increase bpf prog stack size */
4307 if (subprog[idx].has_tail_call)
4308 tail_call_reachable = true;
4311 if (frame >= MAX_CALL_FRAMES) {
4312 verbose(env, "the call stack of %d frames is too deep !\n",
4318 /* if tail call got detected across bpf2bpf calls then mark each of the
4319 * currently present subprog frames as tail call reachable subprogs;
4320 * this info will be utilized by JIT so that we will be preserving the
4321 * tail call counter throughout bpf2bpf calls combined with tailcalls
4323 if (tail_call_reachable)
4324 for (j = 0; j < frame; j++)
4325 subprog[ret_prog[j]].tail_call_reachable = true;
4326 if (subprog[0].tail_call_reachable)
4327 env->prog->aux->tail_call_reachable = true;
4329 /* end of for() loop means the last insn of the 'subprog'
4330 * was reached. Doesn't matter whether it was JA or EXIT
4334 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4336 i = ret_insn[frame];
4337 idx = ret_prog[frame];
4341 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4342 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4343 const struct bpf_insn *insn, int idx)
4345 int start = idx + insn->imm + 1, subprog;
4347 subprog = find_subprog(env, start);
4349 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4353 return env->subprog_info[subprog].stack_depth;
4357 static int __check_buffer_access(struct bpf_verifier_env *env,
4358 const char *buf_info,
4359 const struct bpf_reg_state *reg,
4360 int regno, int off, int size)
4364 "R%d invalid %s buffer access: off=%d, size=%d\n",
4365 regno, buf_info, off, size);
4368 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4371 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4373 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4374 regno, off, tn_buf);
4381 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4382 const struct bpf_reg_state *reg,
4383 int regno, int off, int size)
4387 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4391 if (off + size > env->prog->aux->max_tp_access)
4392 env->prog->aux->max_tp_access = off + size;
4397 static int check_buffer_access(struct bpf_verifier_env *env,
4398 const struct bpf_reg_state *reg,
4399 int regno, int off, int size,
4400 bool zero_size_allowed,
4403 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4406 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4410 if (off + size > *max_access)
4411 *max_access = off + size;
4416 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4417 static void zext_32_to_64(struct bpf_reg_state *reg)
4419 reg->var_off = tnum_subreg(reg->var_off);
4420 __reg_assign_32_into_64(reg);
4423 /* truncate register to smaller size (in bytes)
4424 * must be called with size < BPF_REG_SIZE
4426 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4430 /* clear high bits in bit representation */
4431 reg->var_off = tnum_cast(reg->var_off, size);
4433 /* fix arithmetic bounds */
4434 mask = ((u64)1 << (size * 8)) - 1;
4435 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4436 reg->umin_value &= mask;
4437 reg->umax_value &= mask;
4439 reg->umin_value = 0;
4440 reg->umax_value = mask;
4442 reg->smin_value = reg->umin_value;
4443 reg->smax_value = reg->umax_value;
4445 /* If size is smaller than 32bit register the 32bit register
4446 * values are also truncated so we push 64-bit bounds into
4447 * 32-bit bounds. Above were truncated < 32-bits already.
4451 __reg_combine_64_into_32(reg);
4454 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4456 /* A map is considered read-only if the following condition are true:
4458 * 1) BPF program side cannot change any of the map content. The
4459 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4460 * and was set at map creation time.
4461 * 2) The map value(s) have been initialized from user space by a
4462 * loader and then "frozen", such that no new map update/delete
4463 * operations from syscall side are possible for the rest of
4464 * the map's lifetime from that point onwards.
4465 * 3) Any parallel/pending map update/delete operations from syscall
4466 * side have been completed. Only after that point, it's safe to
4467 * assume that map value(s) are immutable.
4469 return (map->map_flags & BPF_F_RDONLY_PROG) &&
4470 READ_ONCE(map->frozen) &&
4471 !bpf_map_write_active(map);
4474 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4480 err = map->ops->map_direct_value_addr(map, &addr, off);
4483 ptr = (void *)(long)addr + off;
4487 *val = (u64)*(u8 *)ptr;
4490 *val = (u64)*(u16 *)ptr;
4493 *val = (u64)*(u32 *)ptr;
4504 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4505 struct bpf_reg_state *regs,
4506 int regno, int off, int size,
4507 enum bpf_access_type atype,
4510 struct bpf_reg_state *reg = regs + regno;
4511 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4512 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4513 enum bpf_type_flag flag = 0;
4519 "R%d is ptr_%s invalid negative access: off=%d\n",
4523 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4526 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4528 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4529 regno, tname, off, tn_buf);
4533 if (reg->type & MEM_USER) {
4535 "R%d is ptr_%s access user memory: off=%d\n",
4540 if (reg->type & MEM_PERCPU) {
4542 "R%d is ptr_%s access percpu memory: off=%d\n",
4547 if (env->ops->btf_struct_access) {
4548 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4549 off, size, atype, &btf_id, &flag);
4551 if (atype != BPF_READ) {
4552 verbose(env, "only read is supported\n");
4556 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4557 atype, &btf_id, &flag);
4563 /* If this is an untrusted pointer, all pointers formed by walking it
4564 * also inherit the untrusted flag.
4566 if (type_flag(reg->type) & PTR_UNTRUSTED)
4567 flag |= PTR_UNTRUSTED;
4569 if (atype == BPF_READ && value_regno >= 0)
4570 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4575 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4576 struct bpf_reg_state *regs,
4577 int regno, int off, int size,
4578 enum bpf_access_type atype,
4581 struct bpf_reg_state *reg = regs + regno;
4582 struct bpf_map *map = reg->map_ptr;
4583 enum bpf_type_flag flag = 0;
4584 const struct btf_type *t;
4590 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4594 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4595 verbose(env, "map_ptr access not supported for map type %d\n",
4600 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4601 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4603 if (!env->allow_ptr_to_map_access) {
4605 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4611 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4616 if (atype != BPF_READ) {
4617 verbose(env, "only read from %s is supported\n", tname);
4621 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4625 if (value_regno >= 0)
4626 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4631 /* Check that the stack access at the given offset is within bounds. The
4632 * maximum valid offset is -1.
4634 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4635 * -state->allocated_stack for reads.
4637 static int check_stack_slot_within_bounds(int off,
4638 struct bpf_func_state *state,
4639 enum bpf_access_type t)
4644 min_valid_off = -MAX_BPF_STACK;
4646 min_valid_off = -state->allocated_stack;
4648 if (off < min_valid_off || off > -1)
4653 /* Check that the stack access at 'regno + off' falls within the maximum stack
4656 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4658 static int check_stack_access_within_bounds(
4659 struct bpf_verifier_env *env,
4660 int regno, int off, int access_size,
4661 enum bpf_access_src src, enum bpf_access_type type)
4663 struct bpf_reg_state *regs = cur_regs(env);
4664 struct bpf_reg_state *reg = regs + regno;
4665 struct bpf_func_state *state = func(env, reg);
4666 int min_off, max_off;
4670 if (src == ACCESS_HELPER)
4671 /* We don't know if helpers are reading or writing (or both). */
4672 err_extra = " indirect access to";
4673 else if (type == BPF_READ)
4674 err_extra = " read from";
4676 err_extra = " write to";
4678 if (tnum_is_const(reg->var_off)) {
4679 min_off = reg->var_off.value + off;
4680 if (access_size > 0)
4681 max_off = min_off + access_size - 1;
4685 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4686 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4687 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4691 min_off = reg->smin_value + off;
4692 if (access_size > 0)
4693 max_off = reg->smax_value + off + access_size - 1;
4698 err = check_stack_slot_within_bounds(min_off, state, type);
4700 err = check_stack_slot_within_bounds(max_off, state, type);
4703 if (tnum_is_const(reg->var_off)) {
4704 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4705 err_extra, regno, off, access_size);
4709 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4710 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4711 err_extra, regno, tn_buf, access_size);
4717 /* check whether memory at (regno + off) is accessible for t = (read | write)
4718 * if t==write, value_regno is a register which value is stored into memory
4719 * if t==read, value_regno is a register which will receive the value from memory
4720 * if t==write && value_regno==-1, some unknown value is stored into memory
4721 * if t==read && value_regno==-1, don't care what we read from memory
4723 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4724 int off, int bpf_size, enum bpf_access_type t,
4725 int value_regno, bool strict_alignment_once)
4727 struct bpf_reg_state *regs = cur_regs(env);
4728 struct bpf_reg_state *reg = regs + regno;
4729 struct bpf_func_state *state;
4732 size = bpf_size_to_bytes(bpf_size);
4736 /* alignment checks will add in reg->off themselves */
4737 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4741 /* for access checks, reg->off is just part of off */
4744 if (reg->type == PTR_TO_MAP_KEY) {
4745 if (t == BPF_WRITE) {
4746 verbose(env, "write to change key R%d not allowed\n", regno);
4750 err = check_mem_region_access(env, regno, off, size,
4751 reg->map_ptr->key_size, false);
4754 if (value_regno >= 0)
4755 mark_reg_unknown(env, regs, value_regno);
4756 } else if (reg->type == PTR_TO_MAP_VALUE) {
4757 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4759 if (t == BPF_WRITE && value_regno >= 0 &&
4760 is_pointer_value(env, value_regno)) {
4761 verbose(env, "R%d leaks addr into map\n", value_regno);
4764 err = check_map_access_type(env, regno, off, size, t);
4767 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4770 if (tnum_is_const(reg->var_off))
4771 kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4772 off + reg->var_off.value);
4773 if (kptr_off_desc) {
4774 err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4776 } else if (t == BPF_READ && value_regno >= 0) {
4777 struct bpf_map *map = reg->map_ptr;
4779 /* if map is read-only, track its contents as scalars */
4780 if (tnum_is_const(reg->var_off) &&
4781 bpf_map_is_rdonly(map) &&
4782 map->ops->map_direct_value_addr) {
4783 int map_off = off + reg->var_off.value;
4786 err = bpf_map_direct_read(map, map_off, size,
4791 regs[value_regno].type = SCALAR_VALUE;
4792 __mark_reg_known(®s[value_regno], val);
4794 mark_reg_unknown(env, regs, value_regno);
4797 } else if (base_type(reg->type) == PTR_TO_MEM) {
4798 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4800 if (type_may_be_null(reg->type)) {
4801 verbose(env, "R%d invalid mem access '%s'\n", regno,
4802 reg_type_str(env, reg->type));
4806 if (t == BPF_WRITE && rdonly_mem) {
4807 verbose(env, "R%d cannot write into %s\n",
4808 regno, reg_type_str(env, reg->type));
4812 if (t == BPF_WRITE && value_regno >= 0 &&
4813 is_pointer_value(env, value_regno)) {
4814 verbose(env, "R%d leaks addr into mem\n", value_regno);
4818 err = check_mem_region_access(env, regno, off, size,
4819 reg->mem_size, false);
4820 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4821 mark_reg_unknown(env, regs, value_regno);
4822 } else if (reg->type == PTR_TO_CTX) {
4823 enum bpf_reg_type reg_type = SCALAR_VALUE;
4824 struct btf *btf = NULL;
4827 if (t == BPF_WRITE && value_regno >= 0 &&
4828 is_pointer_value(env, value_regno)) {
4829 verbose(env, "R%d leaks addr into ctx\n", value_regno);
4833 err = check_ptr_off_reg(env, reg, regno);
4837 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
4840 verbose_linfo(env, insn_idx, "; ");
4841 if (!err && t == BPF_READ && value_regno >= 0) {
4842 /* ctx access returns either a scalar, or a
4843 * PTR_TO_PACKET[_META,_END]. In the latter
4844 * case, we know the offset is zero.
4846 if (reg_type == SCALAR_VALUE) {
4847 mark_reg_unknown(env, regs, value_regno);
4849 mark_reg_known_zero(env, regs,
4851 if (type_may_be_null(reg_type))
4852 regs[value_regno].id = ++env->id_gen;
4853 /* A load of ctx field could have different
4854 * actual load size with the one encoded in the
4855 * insn. When the dst is PTR, it is for sure not
4858 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4859 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4860 regs[value_regno].btf = btf;
4861 regs[value_regno].btf_id = btf_id;
4864 regs[value_regno].type = reg_type;
4867 } else if (reg->type == PTR_TO_STACK) {
4868 /* Basic bounds checks. */
4869 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4873 state = func(env, reg);
4874 err = update_stack_depth(env, state, off);
4879 err = check_stack_read(env, regno, off, size,
4882 err = check_stack_write(env, regno, off, size,
4883 value_regno, insn_idx);
4884 } else if (reg_is_pkt_pointer(reg)) {
4885 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4886 verbose(env, "cannot write into packet\n");
4889 if (t == BPF_WRITE && value_regno >= 0 &&
4890 is_pointer_value(env, value_regno)) {
4891 verbose(env, "R%d leaks addr into packet\n",
4895 err = check_packet_access(env, regno, off, size, false);
4896 if (!err && t == BPF_READ && value_regno >= 0)
4897 mark_reg_unknown(env, regs, value_regno);
4898 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4899 if (t == BPF_WRITE && value_regno >= 0 &&
4900 is_pointer_value(env, value_regno)) {
4901 verbose(env, "R%d leaks addr into flow keys\n",
4906 err = check_flow_keys_access(env, off, size);
4907 if (!err && t == BPF_READ && value_regno >= 0)
4908 mark_reg_unknown(env, regs, value_regno);
4909 } else if (type_is_sk_pointer(reg->type)) {
4910 if (t == BPF_WRITE) {
4911 verbose(env, "R%d cannot write into %s\n",
4912 regno, reg_type_str(env, reg->type));
4915 err = check_sock_access(env, insn_idx, regno, off, size, t);
4916 if (!err && value_regno >= 0)
4917 mark_reg_unknown(env, regs, value_regno);
4918 } else if (reg->type == PTR_TO_TP_BUFFER) {
4919 err = check_tp_buffer_access(env, reg, regno, off, size);
4920 if (!err && t == BPF_READ && value_regno >= 0)
4921 mark_reg_unknown(env, regs, value_regno);
4922 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4923 !type_may_be_null(reg->type)) {
4924 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4926 } else if (reg->type == CONST_PTR_TO_MAP) {
4927 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4929 } else if (base_type(reg->type) == PTR_TO_BUF) {
4930 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4934 if (t == BPF_WRITE) {
4935 verbose(env, "R%d cannot write into %s\n",
4936 regno, reg_type_str(env, reg->type));
4939 max_access = &env->prog->aux->max_rdonly_access;
4941 max_access = &env->prog->aux->max_rdwr_access;
4944 err = check_buffer_access(env, reg, regno, off, size, false,
4947 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4948 mark_reg_unknown(env, regs, value_regno);
4950 verbose(env, "R%d invalid mem access '%s'\n", regno,
4951 reg_type_str(env, reg->type));
4955 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4956 regs[value_regno].type == SCALAR_VALUE) {
4957 /* b/h/w load zero-extends, mark upper bits as known 0 */
4958 coerce_reg_to_size(®s[value_regno], size);
4963 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4968 switch (insn->imm) {
4970 case BPF_ADD | BPF_FETCH:
4972 case BPF_AND | BPF_FETCH:
4974 case BPF_OR | BPF_FETCH:
4976 case BPF_XOR | BPF_FETCH:
4981 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4985 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4986 verbose(env, "invalid atomic operand size\n");
4990 /* check src1 operand */
4991 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4995 /* check src2 operand */
4996 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5000 if (insn->imm == BPF_CMPXCHG) {
5001 /* Check comparison of R0 with memory location */
5002 const u32 aux_reg = BPF_REG_0;
5004 err = check_reg_arg(env, aux_reg, SRC_OP);
5008 if (is_pointer_value(env, aux_reg)) {
5009 verbose(env, "R%d leaks addr into mem\n", aux_reg);
5014 if (is_pointer_value(env, insn->src_reg)) {
5015 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5019 if (is_ctx_reg(env, insn->dst_reg) ||
5020 is_pkt_reg(env, insn->dst_reg) ||
5021 is_flow_key_reg(env, insn->dst_reg) ||
5022 is_sk_reg(env, insn->dst_reg)) {
5023 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5025 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5029 if (insn->imm & BPF_FETCH) {
5030 if (insn->imm == BPF_CMPXCHG)
5031 load_reg = BPF_REG_0;
5033 load_reg = insn->src_reg;
5035 /* check and record load of old value */
5036 err = check_reg_arg(env, load_reg, DST_OP);
5040 /* This instruction accesses a memory location but doesn't
5041 * actually load it into a register.
5046 /* Check whether we can read the memory, with second call for fetch
5047 * case to simulate the register fill.
5049 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5050 BPF_SIZE(insn->code), BPF_READ, -1, true);
5051 if (!err && load_reg >= 0)
5052 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5053 BPF_SIZE(insn->code), BPF_READ, load_reg,
5058 /* Check whether we can write into the same memory. */
5059 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5060 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5067 /* When register 'regno' is used to read the stack (either directly or through
5068 * a helper function) make sure that it's within stack boundary and, depending
5069 * on the access type, that all elements of the stack are initialized.
5071 * 'off' includes 'regno->off', but not its dynamic part (if any).
5073 * All registers that have been spilled on the stack in the slots within the
5074 * read offsets are marked as read.
5076 static int check_stack_range_initialized(
5077 struct bpf_verifier_env *env, int regno, int off,
5078 int access_size, bool zero_size_allowed,
5079 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5081 struct bpf_reg_state *reg = reg_state(env, regno);
5082 struct bpf_func_state *state = func(env, reg);
5083 int err, min_off, max_off, i, j, slot, spi;
5084 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5085 enum bpf_access_type bounds_check_type;
5086 /* Some accesses can write anything into the stack, others are
5089 bool clobber = false;
5091 if (access_size == 0 && !zero_size_allowed) {
5092 verbose(env, "invalid zero-sized read\n");
5096 if (type == ACCESS_HELPER) {
5097 /* The bounds checks for writes are more permissive than for
5098 * reads. However, if raw_mode is not set, we'll do extra
5101 bounds_check_type = BPF_WRITE;
5104 bounds_check_type = BPF_READ;
5106 err = check_stack_access_within_bounds(env, regno, off, access_size,
5107 type, bounds_check_type);
5112 if (tnum_is_const(reg->var_off)) {
5113 min_off = max_off = reg->var_off.value + off;
5115 /* Variable offset is prohibited for unprivileged mode for
5116 * simplicity since it requires corresponding support in
5117 * Spectre masking for stack ALU.
5118 * See also retrieve_ptr_limit().
5120 if (!env->bypass_spec_v1) {
5123 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5124 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5125 regno, err_extra, tn_buf);
5128 /* Only initialized buffer on stack is allowed to be accessed
5129 * with variable offset. With uninitialized buffer it's hard to
5130 * guarantee that whole memory is marked as initialized on
5131 * helper return since specific bounds are unknown what may
5132 * cause uninitialized stack leaking.
5134 if (meta && meta->raw_mode)
5137 min_off = reg->smin_value + off;
5138 max_off = reg->smax_value + off;
5141 if (meta && meta->raw_mode) {
5142 meta->access_size = access_size;
5143 meta->regno = regno;
5147 for (i = min_off; i < max_off + access_size; i++) {
5151 spi = slot / BPF_REG_SIZE;
5152 if (state->allocated_stack <= slot)
5154 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5155 if (*stype == STACK_MISC)
5157 if (*stype == STACK_ZERO) {
5159 /* helper can write anything into the stack */
5160 *stype = STACK_MISC;
5165 if (is_spilled_reg(&state->stack[spi]) &&
5166 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5167 env->allow_ptr_leaks)) {
5169 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5170 for (j = 0; j < BPF_REG_SIZE; j++)
5171 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5177 if (tnum_is_const(reg->var_off)) {
5178 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5179 err_extra, regno, min_off, i - min_off, access_size);
5183 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5184 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5185 err_extra, regno, tn_buf, i - min_off, access_size);
5189 /* reading any byte out of 8-byte 'spill_slot' will cause
5190 * the whole slot to be marked as 'read'
5192 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5193 state->stack[spi].spilled_ptr.parent,
5195 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5196 * be sure that whether stack slot is written to or not. Hence,
5197 * we must still conservatively propagate reads upwards even if
5198 * helper may write to the entire memory range.
5201 return update_stack_depth(env, state, min_off);
5204 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5205 int access_size, bool zero_size_allowed,
5206 struct bpf_call_arg_meta *meta)
5208 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5211 switch (base_type(reg->type)) {
5213 case PTR_TO_PACKET_META:
5214 return check_packet_access(env, regno, reg->off, access_size,
5216 case PTR_TO_MAP_KEY:
5217 if (meta && meta->raw_mode) {
5218 verbose(env, "R%d cannot write into %s\n", regno,
5219 reg_type_str(env, reg->type));
5222 return check_mem_region_access(env, regno, reg->off, access_size,
5223 reg->map_ptr->key_size, false);
5224 case PTR_TO_MAP_VALUE:
5225 if (check_map_access_type(env, regno, reg->off, access_size,
5226 meta && meta->raw_mode ? BPF_WRITE :
5229 return check_map_access(env, regno, reg->off, access_size,
5230 zero_size_allowed, ACCESS_HELPER);
5232 if (type_is_rdonly_mem(reg->type)) {
5233 if (meta && meta->raw_mode) {
5234 verbose(env, "R%d cannot write into %s\n", regno,
5235 reg_type_str(env, reg->type));
5239 return check_mem_region_access(env, regno, reg->off,
5240 access_size, reg->mem_size,
5243 if (type_is_rdonly_mem(reg->type)) {
5244 if (meta && meta->raw_mode) {
5245 verbose(env, "R%d cannot write into %s\n", regno,
5246 reg_type_str(env, reg->type));
5250 max_access = &env->prog->aux->max_rdonly_access;
5252 max_access = &env->prog->aux->max_rdwr_access;
5254 return check_buffer_access(env, reg, regno, reg->off,
5255 access_size, zero_size_allowed,
5258 return check_stack_range_initialized(
5260 regno, reg->off, access_size,
5261 zero_size_allowed, ACCESS_HELPER, meta);
5263 /* in case the function doesn't know how to access the context,
5264 * (because we are in a program of type SYSCALL for example), we
5265 * can not statically check its size.
5266 * Dynamically check it now.
5268 if (!env->ops->convert_ctx_access) {
5269 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5270 int offset = access_size - 1;
5272 /* Allow zero-byte read from PTR_TO_CTX */
5273 if (access_size == 0)
5274 return zero_size_allowed ? 0 : -EACCES;
5276 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5281 default: /* scalar_value or invalid ptr */
5282 /* Allow zero-byte read from NULL, regardless of pointer type */
5283 if (zero_size_allowed && access_size == 0 &&
5284 register_is_null(reg))
5287 verbose(env, "R%d type=%s ", regno,
5288 reg_type_str(env, reg->type));
5289 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5294 static int check_mem_size_reg(struct bpf_verifier_env *env,
5295 struct bpf_reg_state *reg, u32 regno,
5296 bool zero_size_allowed,
5297 struct bpf_call_arg_meta *meta)
5301 /* This is used to refine r0 return value bounds for helpers
5302 * that enforce this value as an upper bound on return values.
5303 * See do_refine_retval_range() for helpers that can refine
5304 * the return value. C type of helper is u32 so we pull register
5305 * bound from umax_value however, if negative verifier errors
5306 * out. Only upper bounds can be learned because retval is an
5307 * int type and negative retvals are allowed.
5309 meta->msize_max_value = reg->umax_value;
5311 /* The register is SCALAR_VALUE; the access check
5312 * happens using its boundaries.
5314 if (!tnum_is_const(reg->var_off))
5315 /* For unprivileged variable accesses, disable raw
5316 * mode so that the program is required to
5317 * initialize all the memory that the helper could
5318 * just partially fill up.
5322 if (reg->smin_value < 0) {
5323 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5328 if (reg->umin_value == 0) {
5329 err = check_helper_mem_access(env, regno - 1, 0,
5336 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5337 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5341 err = check_helper_mem_access(env, regno - 1,
5343 zero_size_allowed, meta);
5345 err = mark_chain_precision(env, regno);
5349 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5350 u32 regno, u32 mem_size)
5352 bool may_be_null = type_may_be_null(reg->type);
5353 struct bpf_reg_state saved_reg;
5354 struct bpf_call_arg_meta meta;
5357 if (register_is_null(reg))
5360 memset(&meta, 0, sizeof(meta));
5361 /* Assuming that the register contains a value check if the memory
5362 * access is safe. Temporarily save and restore the register's state as
5363 * the conversion shouldn't be visible to a caller.
5367 mark_ptr_not_null_reg(reg);
5370 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5371 /* Check access for BPF_WRITE */
5372 meta.raw_mode = true;
5373 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5381 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5384 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5385 bool may_be_null = type_may_be_null(mem_reg->type);
5386 struct bpf_reg_state saved_reg;
5387 struct bpf_call_arg_meta meta;
5390 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5392 memset(&meta, 0, sizeof(meta));
5395 saved_reg = *mem_reg;
5396 mark_ptr_not_null_reg(mem_reg);
5399 err = check_mem_size_reg(env, reg, regno, true, &meta);
5400 /* Check access for BPF_WRITE */
5401 meta.raw_mode = true;
5402 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5405 *mem_reg = saved_reg;
5409 /* Implementation details:
5410 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5411 * Two bpf_map_lookups (even with the same key) will have different reg->id.
5412 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5413 * value_or_null->value transition, since the verifier only cares about
5414 * the range of access to valid map value pointer and doesn't care about actual
5415 * address of the map element.
5416 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5417 * reg->id > 0 after value_or_null->value transition. By doing so
5418 * two bpf_map_lookups will be considered two different pointers that
5419 * point to different bpf_spin_locks.
5420 * The verifier allows taking only one bpf_spin_lock at a time to avoid
5422 * Since only one bpf_spin_lock is allowed the checks are simpler than
5423 * reg_is_refcounted() logic. The verifier needs to remember only
5424 * one spin_lock instead of array of acquired_refs.
5425 * cur_state->active_spin_lock remembers which map value element got locked
5426 * and clears it after bpf_spin_unlock.
5428 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5431 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5432 struct bpf_verifier_state *cur = env->cur_state;
5433 bool is_const = tnum_is_const(reg->var_off);
5434 struct bpf_map *map = reg->map_ptr;
5435 u64 val = reg->var_off.value;
5439 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5445 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5449 if (!map_value_has_spin_lock(map)) {
5450 if (map->spin_lock_off == -E2BIG)
5452 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5454 else if (map->spin_lock_off == -ENOENT)
5456 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5460 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5464 if (map->spin_lock_off != val + reg->off) {
5465 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5470 if (cur->active_spin_lock) {
5472 "Locking two bpf_spin_locks are not allowed\n");
5475 cur->active_spin_lock = reg->id;
5477 if (!cur->active_spin_lock) {
5478 verbose(env, "bpf_spin_unlock without taking a lock\n");
5481 if (cur->active_spin_lock != reg->id) {
5482 verbose(env, "bpf_spin_unlock of different lock\n");
5485 cur->active_spin_lock = 0;
5490 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5491 struct bpf_call_arg_meta *meta)
5493 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5494 bool is_const = tnum_is_const(reg->var_off);
5495 struct bpf_map *map = reg->map_ptr;
5496 u64 val = reg->var_off.value;
5500 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5505 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5509 if (!map_value_has_timer(map)) {
5510 if (map->timer_off == -E2BIG)
5512 "map '%s' has more than one 'struct bpf_timer'\n",
5514 else if (map->timer_off == -ENOENT)
5516 "map '%s' doesn't have 'struct bpf_timer'\n",
5520 "map '%s' is not a struct type or bpf_timer is mangled\n",
5524 if (map->timer_off != val + reg->off) {
5525 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5526 val + reg->off, map->timer_off);
5529 if (meta->map_ptr) {
5530 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5533 meta->map_uid = reg->map_uid;
5534 meta->map_ptr = map;
5538 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5539 struct bpf_call_arg_meta *meta)
5541 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5542 struct bpf_map_value_off_desc *off_desc;
5543 struct bpf_map *map_ptr = reg->map_ptr;
5547 if (!tnum_is_const(reg->var_off)) {
5549 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5553 if (!map_ptr->btf) {
5554 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5558 if (!map_value_has_kptrs(map_ptr)) {
5559 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5561 verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5562 BPF_MAP_VALUE_OFF_MAX);
5563 else if (ret == -EEXIST)
5564 verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5566 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5570 meta->map_ptr = map_ptr;
5571 kptr_off = reg->off + reg->var_off.value;
5572 off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5574 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5577 if (off_desc->type != BPF_KPTR_REF) {
5578 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5581 meta->kptr_off_desc = off_desc;
5585 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5587 return type == ARG_CONST_SIZE ||
5588 type == ARG_CONST_SIZE_OR_ZERO;
5591 static bool arg_type_is_release(enum bpf_arg_type type)
5593 return type & OBJ_RELEASE;
5596 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5598 return base_type(type) == ARG_PTR_TO_DYNPTR;
5601 static int int_ptr_type_to_size(enum bpf_arg_type type)
5603 if (type == ARG_PTR_TO_INT)
5605 else if (type == ARG_PTR_TO_LONG)
5611 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5612 const struct bpf_call_arg_meta *meta,
5613 enum bpf_arg_type *arg_type)
5615 if (!meta->map_ptr) {
5616 /* kernel subsystem misconfigured verifier */
5617 verbose(env, "invalid map_ptr to access map->type\n");
5621 switch (meta->map_ptr->map_type) {
5622 case BPF_MAP_TYPE_SOCKMAP:
5623 case BPF_MAP_TYPE_SOCKHASH:
5624 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5625 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5627 verbose(env, "invalid arg_type for sockmap/sockhash\n");
5631 case BPF_MAP_TYPE_BLOOM_FILTER:
5632 if (meta->func_id == BPF_FUNC_map_peek_elem)
5633 *arg_type = ARG_PTR_TO_MAP_VALUE;
5641 struct bpf_reg_types {
5642 const enum bpf_reg_type types[10];
5646 static const struct bpf_reg_types map_key_value_types = {
5656 static const struct bpf_reg_types sock_types = {
5666 static const struct bpf_reg_types btf_id_sock_common_types = {
5674 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5678 static const struct bpf_reg_types mem_types = {
5686 PTR_TO_MEM | MEM_ALLOC,
5691 static const struct bpf_reg_types int_ptr_types = {
5701 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5702 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5703 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5704 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5705 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5706 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5707 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5708 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5709 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5710 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5711 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5712 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5713 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5714 static const struct bpf_reg_types dynptr_types = {
5717 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5721 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5722 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
5723 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
5724 [ARG_CONST_SIZE] = &scalar_types,
5725 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
5726 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
5727 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
5728 [ARG_PTR_TO_CTX] = &context_types,
5729 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
5731 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5733 [ARG_PTR_TO_SOCKET] = &fullsock_types,
5734 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
5735 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
5736 [ARG_PTR_TO_MEM] = &mem_types,
5737 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
5738 [ARG_PTR_TO_INT] = &int_ptr_types,
5739 [ARG_PTR_TO_LONG] = &int_ptr_types,
5740 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
5741 [ARG_PTR_TO_FUNC] = &func_ptr_types,
5742 [ARG_PTR_TO_STACK] = &stack_ptr_types,
5743 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
5744 [ARG_PTR_TO_TIMER] = &timer_types,
5745 [ARG_PTR_TO_KPTR] = &kptr_types,
5746 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
5749 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5750 enum bpf_arg_type arg_type,
5751 const u32 *arg_btf_id,
5752 struct bpf_call_arg_meta *meta)
5754 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5755 enum bpf_reg_type expected, type = reg->type;
5756 const struct bpf_reg_types *compatible;
5759 compatible = compatible_reg_types[base_type(arg_type)];
5761 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5765 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5766 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5768 * Same for MAYBE_NULL:
5770 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5771 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5773 * Therefore we fold these flags depending on the arg_type before comparison.
5775 if (arg_type & MEM_RDONLY)
5776 type &= ~MEM_RDONLY;
5777 if (arg_type & PTR_MAYBE_NULL)
5778 type &= ~PTR_MAYBE_NULL;
5780 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5781 expected = compatible->types[i];
5782 if (expected == NOT_INIT)
5785 if (type == expected)
5789 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5790 for (j = 0; j + 1 < i; j++)
5791 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5792 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5796 if (reg->type == PTR_TO_BTF_ID) {
5797 /* For bpf_sk_release, it needs to match against first member
5798 * 'struct sock_common', hence make an exception for it. This
5799 * allows bpf_sk_release to work for multiple socket types.
5801 bool strict_type_match = arg_type_is_release(arg_type) &&
5802 meta->func_id != BPF_FUNC_sk_release;
5805 if (!compatible->btf_id) {
5806 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5809 arg_btf_id = compatible->btf_id;
5812 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5813 if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5816 if (arg_btf_id == BPF_PTR_POISON) {
5817 verbose(env, "verifier internal error:");
5818 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5823 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5824 btf_vmlinux, *arg_btf_id,
5825 strict_type_match)) {
5826 verbose(env, "R%d is of type %s but %s is expected\n",
5827 regno, kernel_type_name(reg->btf, reg->btf_id),
5828 kernel_type_name(btf_vmlinux, *arg_btf_id));
5837 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5838 const struct bpf_reg_state *reg, int regno,
5839 enum bpf_arg_type arg_type)
5841 enum bpf_reg_type type = reg->type;
5842 bool fixed_off_ok = false;
5844 switch ((u32)type) {
5845 /* Pointer types where reg offset is explicitly allowed: */
5847 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5848 verbose(env, "cannot pass in dynptr at an offset\n");
5853 case PTR_TO_PACKET_META:
5854 case PTR_TO_MAP_KEY:
5855 case PTR_TO_MAP_VALUE:
5857 case PTR_TO_MEM | MEM_RDONLY:
5858 case PTR_TO_MEM | MEM_ALLOC:
5860 case PTR_TO_BUF | MEM_RDONLY:
5862 /* Some of the argument types nevertheless require a
5863 * zero register offset.
5865 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5868 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5872 /* When referenced PTR_TO_BTF_ID is passed to release function,
5873 * it's fixed offset must be 0. In the other cases, fixed offset
5876 if (arg_type_is_release(arg_type) && reg->off) {
5877 verbose(env, "R%d must have zero offset when passed to release func\n",
5881 /* For arg is release pointer, fixed_off_ok must be false, but
5882 * we already checked and rejected reg->off != 0 above, so set
5883 * to true to allow fixed offset for all other cases.
5885 fixed_off_ok = true;
5890 return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5893 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5895 struct bpf_func_state *state = func(env, reg);
5896 int spi = get_spi(reg->off);
5898 return state->stack[spi].spilled_ptr.id;
5901 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5902 struct bpf_call_arg_meta *meta,
5903 const struct bpf_func_proto *fn)
5905 u32 regno = BPF_REG_1 + arg;
5906 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5907 enum bpf_arg_type arg_type = fn->arg_type[arg];
5908 enum bpf_reg_type type = reg->type;
5909 u32 *arg_btf_id = NULL;
5912 if (arg_type == ARG_DONTCARE)
5915 err = check_reg_arg(env, regno, SRC_OP);
5919 if (arg_type == ARG_ANYTHING) {
5920 if (is_pointer_value(env, regno)) {
5921 verbose(env, "R%d leaks addr into helper function\n",
5928 if (type_is_pkt_pointer(type) &&
5929 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5930 verbose(env, "helper access to the packet is not allowed\n");
5934 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5935 err = resolve_map_arg_type(env, meta, &arg_type);
5940 if (register_is_null(reg) && type_may_be_null(arg_type))
5941 /* A NULL register has a SCALAR_VALUE type, so skip
5944 goto skip_type_check;
5946 /* arg_btf_id and arg_size are in a union. */
5947 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5948 arg_btf_id = fn->arg_btf_id[arg];
5950 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5954 err = check_func_arg_reg_off(env, reg, regno, arg_type);
5959 if (arg_type_is_release(arg_type)) {
5960 if (arg_type_is_dynptr(arg_type)) {
5961 struct bpf_func_state *state = func(env, reg);
5962 int spi = get_spi(reg->off);
5964 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
5965 !state->stack[spi].spilled_ptr.id) {
5966 verbose(env, "arg %d is an unacquired reference\n", regno);
5969 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
5970 verbose(env, "R%d must be referenced when passed to release function\n",
5974 if (meta->release_regno) {
5975 verbose(env, "verifier internal error: more than one release argument\n");
5978 meta->release_regno = regno;
5981 if (reg->ref_obj_id) {
5982 if (meta->ref_obj_id) {
5983 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5984 regno, reg->ref_obj_id,
5988 meta->ref_obj_id = reg->ref_obj_id;
5991 switch (base_type(arg_type)) {
5992 case ARG_CONST_MAP_PTR:
5993 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5994 if (meta->map_ptr) {
5995 /* Use map_uid (which is unique id of inner map) to reject:
5996 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5997 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5998 * if (inner_map1 && inner_map2) {
5999 * timer = bpf_map_lookup_elem(inner_map1);
6001 * // mismatch would have been allowed
6002 * bpf_timer_init(timer, inner_map2);
6005 * Comparing map_ptr is enough to distinguish normal and outer maps.
6007 if (meta->map_ptr != reg->map_ptr ||
6008 meta->map_uid != reg->map_uid) {
6010 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6011 meta->map_uid, reg->map_uid);
6015 meta->map_ptr = reg->map_ptr;
6016 meta->map_uid = reg->map_uid;
6018 case ARG_PTR_TO_MAP_KEY:
6019 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6020 * check that [key, key + map->key_size) are within
6021 * stack limits and initialized
6023 if (!meta->map_ptr) {
6024 /* in function declaration map_ptr must come before
6025 * map_key, so that it's verified and known before
6026 * we have to check map_key here. Otherwise it means
6027 * that kernel subsystem misconfigured verifier
6029 verbose(env, "invalid map_ptr to access map->key\n");
6032 err = check_helper_mem_access(env, regno,
6033 meta->map_ptr->key_size, false,
6036 case ARG_PTR_TO_MAP_VALUE:
6037 if (type_may_be_null(arg_type) && register_is_null(reg))
6040 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6041 * check [value, value + map->value_size) validity
6043 if (!meta->map_ptr) {
6044 /* kernel subsystem misconfigured verifier */
6045 verbose(env, "invalid map_ptr to access map->value\n");
6048 meta->raw_mode = arg_type & MEM_UNINIT;
6049 err = check_helper_mem_access(env, regno,
6050 meta->map_ptr->value_size, false,
6053 case ARG_PTR_TO_PERCPU_BTF_ID:
6055 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6058 meta->ret_btf = reg->btf;
6059 meta->ret_btf_id = reg->btf_id;
6061 case ARG_PTR_TO_SPIN_LOCK:
6062 if (meta->func_id == BPF_FUNC_spin_lock) {
6063 if (process_spin_lock(env, regno, true))
6065 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6066 if (process_spin_lock(env, regno, false))
6069 verbose(env, "verifier internal error\n");
6073 case ARG_PTR_TO_TIMER:
6074 if (process_timer_func(env, regno, meta))
6077 case ARG_PTR_TO_FUNC:
6078 meta->subprogno = reg->subprogno;
6080 case ARG_PTR_TO_MEM:
6081 /* The access to this pointer is only checked when we hit the
6082 * next is_mem_size argument below.
6084 meta->raw_mode = arg_type & MEM_UNINIT;
6085 if (arg_type & MEM_FIXED_SIZE) {
6086 err = check_helper_mem_access(env, regno,
6087 fn->arg_size[arg], false,
6091 case ARG_CONST_SIZE:
6092 err = check_mem_size_reg(env, reg, regno, false, meta);
6094 case ARG_CONST_SIZE_OR_ZERO:
6095 err = check_mem_size_reg(env, reg, regno, true, meta);
6097 case ARG_PTR_TO_DYNPTR:
6098 /* We only need to check for initialized / uninitialized helper
6099 * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6100 * assumption is that if it is, that a helper function
6101 * initialized the dynptr on behalf of the BPF program.
6103 if (base_type(reg->type) == PTR_TO_DYNPTR)
6105 if (arg_type & MEM_UNINIT) {
6106 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6107 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6111 /* We only support one dynptr being uninitialized at the moment,
6112 * which is sufficient for the helper functions we have right now.
6114 if (meta->uninit_dynptr_regno) {
6115 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6119 meta->uninit_dynptr_regno = regno;
6120 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6122 "Expected an initialized dynptr as arg #%d\n",
6125 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6126 const char *err_extra = "";
6128 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6129 case DYNPTR_TYPE_LOCAL:
6130 err_extra = "local";
6132 case DYNPTR_TYPE_RINGBUF:
6133 err_extra = "ringbuf";
6136 err_extra = "<unknown>";
6140 "Expected a dynptr of type %s as arg #%d\n",
6141 err_extra, arg + 1);
6145 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6146 if (!tnum_is_const(reg->var_off)) {
6147 verbose(env, "R%d is not a known constant'\n",
6151 meta->mem_size = reg->var_off.value;
6152 err = mark_chain_precision(env, regno);
6156 case ARG_PTR_TO_INT:
6157 case ARG_PTR_TO_LONG:
6159 int size = int_ptr_type_to_size(arg_type);
6161 err = check_helper_mem_access(env, regno, size, false, meta);
6164 err = check_ptr_alignment(env, reg, 0, size, true);
6167 case ARG_PTR_TO_CONST_STR:
6169 struct bpf_map *map = reg->map_ptr;
6174 if (!bpf_map_is_rdonly(map)) {
6175 verbose(env, "R%d does not point to a readonly map'\n", regno);
6179 if (!tnum_is_const(reg->var_off)) {
6180 verbose(env, "R%d is not a constant address'\n", regno);
6184 if (!map->ops->map_direct_value_addr) {
6185 verbose(env, "no direct value access support for this map type\n");
6189 err = check_map_access(env, regno, reg->off,
6190 map->value_size - reg->off, false,
6195 map_off = reg->off + reg->var_off.value;
6196 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6198 verbose(env, "direct value access on string failed\n");
6202 str_ptr = (char *)(long)(map_addr);
6203 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6204 verbose(env, "string is not zero-terminated\n");
6209 case ARG_PTR_TO_KPTR:
6210 if (process_kptr_func(env, regno, meta))
6218 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6220 enum bpf_attach_type eatype = env->prog->expected_attach_type;
6221 enum bpf_prog_type type = resolve_prog_type(env->prog);
6223 if (func_id != BPF_FUNC_map_update_elem)
6226 /* It's not possible to get access to a locked struct sock in these
6227 * contexts, so updating is safe.
6230 case BPF_PROG_TYPE_TRACING:
6231 if (eatype == BPF_TRACE_ITER)
6234 case BPF_PROG_TYPE_SOCKET_FILTER:
6235 case BPF_PROG_TYPE_SCHED_CLS:
6236 case BPF_PROG_TYPE_SCHED_ACT:
6237 case BPF_PROG_TYPE_XDP:
6238 case BPF_PROG_TYPE_SK_REUSEPORT:
6239 case BPF_PROG_TYPE_FLOW_DISSECTOR:
6240 case BPF_PROG_TYPE_SK_LOOKUP:
6246 verbose(env, "cannot update sockmap in this context\n");
6250 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6252 return env->prog->jit_requested &&
6253 bpf_jit_supports_subprog_tailcalls();
6256 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6257 struct bpf_map *map, int func_id)
6262 /* We need a two way check, first is from map perspective ... */
6263 switch (map->map_type) {
6264 case BPF_MAP_TYPE_PROG_ARRAY:
6265 if (func_id != BPF_FUNC_tail_call)
6268 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6269 if (func_id != BPF_FUNC_perf_event_read &&
6270 func_id != BPF_FUNC_perf_event_output &&
6271 func_id != BPF_FUNC_skb_output &&
6272 func_id != BPF_FUNC_perf_event_read_value &&
6273 func_id != BPF_FUNC_xdp_output)
6276 case BPF_MAP_TYPE_RINGBUF:
6277 if (func_id != BPF_FUNC_ringbuf_output &&
6278 func_id != BPF_FUNC_ringbuf_reserve &&
6279 func_id != BPF_FUNC_ringbuf_query &&
6280 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6281 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6282 func_id != BPF_FUNC_ringbuf_discard_dynptr)
6285 case BPF_MAP_TYPE_USER_RINGBUF:
6286 if (func_id != BPF_FUNC_user_ringbuf_drain)
6289 case BPF_MAP_TYPE_STACK_TRACE:
6290 if (func_id != BPF_FUNC_get_stackid)
6293 case BPF_MAP_TYPE_CGROUP_ARRAY:
6294 if (func_id != BPF_FUNC_skb_under_cgroup &&
6295 func_id != BPF_FUNC_current_task_under_cgroup)
6298 case BPF_MAP_TYPE_CGROUP_STORAGE:
6299 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6300 if (func_id != BPF_FUNC_get_local_storage)
6303 case BPF_MAP_TYPE_DEVMAP:
6304 case BPF_MAP_TYPE_DEVMAP_HASH:
6305 if (func_id != BPF_FUNC_redirect_map &&
6306 func_id != BPF_FUNC_map_lookup_elem)
6309 /* Restrict bpf side of cpumap and xskmap, open when use-cases
6312 case BPF_MAP_TYPE_CPUMAP:
6313 if (func_id != BPF_FUNC_redirect_map)
6316 case BPF_MAP_TYPE_XSKMAP:
6317 if (func_id != BPF_FUNC_redirect_map &&
6318 func_id != BPF_FUNC_map_lookup_elem)
6321 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6322 case BPF_MAP_TYPE_HASH_OF_MAPS:
6323 if (func_id != BPF_FUNC_map_lookup_elem)
6326 case BPF_MAP_TYPE_SOCKMAP:
6327 if (func_id != BPF_FUNC_sk_redirect_map &&
6328 func_id != BPF_FUNC_sock_map_update &&
6329 func_id != BPF_FUNC_map_delete_elem &&
6330 func_id != BPF_FUNC_msg_redirect_map &&
6331 func_id != BPF_FUNC_sk_select_reuseport &&
6332 func_id != BPF_FUNC_map_lookup_elem &&
6333 !may_update_sockmap(env, func_id))
6336 case BPF_MAP_TYPE_SOCKHASH:
6337 if (func_id != BPF_FUNC_sk_redirect_hash &&
6338 func_id != BPF_FUNC_sock_hash_update &&
6339 func_id != BPF_FUNC_map_delete_elem &&
6340 func_id != BPF_FUNC_msg_redirect_hash &&
6341 func_id != BPF_FUNC_sk_select_reuseport &&
6342 func_id != BPF_FUNC_map_lookup_elem &&
6343 !may_update_sockmap(env, func_id))
6346 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6347 if (func_id != BPF_FUNC_sk_select_reuseport)
6350 case BPF_MAP_TYPE_QUEUE:
6351 case BPF_MAP_TYPE_STACK:
6352 if (func_id != BPF_FUNC_map_peek_elem &&
6353 func_id != BPF_FUNC_map_pop_elem &&
6354 func_id != BPF_FUNC_map_push_elem)
6357 case BPF_MAP_TYPE_SK_STORAGE:
6358 if (func_id != BPF_FUNC_sk_storage_get &&
6359 func_id != BPF_FUNC_sk_storage_delete)
6362 case BPF_MAP_TYPE_INODE_STORAGE:
6363 if (func_id != BPF_FUNC_inode_storage_get &&
6364 func_id != BPF_FUNC_inode_storage_delete)
6367 case BPF_MAP_TYPE_TASK_STORAGE:
6368 if (func_id != BPF_FUNC_task_storage_get &&
6369 func_id != BPF_FUNC_task_storage_delete)
6372 case BPF_MAP_TYPE_BLOOM_FILTER:
6373 if (func_id != BPF_FUNC_map_peek_elem &&
6374 func_id != BPF_FUNC_map_push_elem)
6381 /* ... and second from the function itself. */
6383 case BPF_FUNC_tail_call:
6384 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6386 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6387 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6391 case BPF_FUNC_perf_event_read:
6392 case BPF_FUNC_perf_event_output:
6393 case BPF_FUNC_perf_event_read_value:
6394 case BPF_FUNC_skb_output:
6395 case BPF_FUNC_xdp_output:
6396 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6399 case BPF_FUNC_ringbuf_output:
6400 case BPF_FUNC_ringbuf_reserve:
6401 case BPF_FUNC_ringbuf_query:
6402 case BPF_FUNC_ringbuf_reserve_dynptr:
6403 case BPF_FUNC_ringbuf_submit_dynptr:
6404 case BPF_FUNC_ringbuf_discard_dynptr:
6405 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6408 case BPF_FUNC_user_ringbuf_drain:
6409 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6412 case BPF_FUNC_get_stackid:
6413 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6416 case BPF_FUNC_current_task_under_cgroup:
6417 case BPF_FUNC_skb_under_cgroup:
6418 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6421 case BPF_FUNC_redirect_map:
6422 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6423 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6424 map->map_type != BPF_MAP_TYPE_CPUMAP &&
6425 map->map_type != BPF_MAP_TYPE_XSKMAP)
6428 case BPF_FUNC_sk_redirect_map:
6429 case BPF_FUNC_msg_redirect_map:
6430 case BPF_FUNC_sock_map_update:
6431 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6434 case BPF_FUNC_sk_redirect_hash:
6435 case BPF_FUNC_msg_redirect_hash:
6436 case BPF_FUNC_sock_hash_update:
6437 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6440 case BPF_FUNC_get_local_storage:
6441 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6442 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6445 case BPF_FUNC_sk_select_reuseport:
6446 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6447 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6448 map->map_type != BPF_MAP_TYPE_SOCKHASH)
6451 case BPF_FUNC_map_pop_elem:
6452 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6453 map->map_type != BPF_MAP_TYPE_STACK)
6456 case BPF_FUNC_map_peek_elem:
6457 case BPF_FUNC_map_push_elem:
6458 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6459 map->map_type != BPF_MAP_TYPE_STACK &&
6460 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6463 case BPF_FUNC_map_lookup_percpu_elem:
6464 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6465 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6466 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6469 case BPF_FUNC_sk_storage_get:
6470 case BPF_FUNC_sk_storage_delete:
6471 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6474 case BPF_FUNC_inode_storage_get:
6475 case BPF_FUNC_inode_storage_delete:
6476 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6479 case BPF_FUNC_task_storage_get:
6480 case BPF_FUNC_task_storage_delete:
6481 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6490 verbose(env, "cannot pass map_type %d into func %s#%d\n",
6491 map->map_type, func_id_name(func_id), func_id);
6495 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6499 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6501 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6503 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6505 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6507 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6510 /* We only support one arg being in raw mode at the moment,
6511 * which is sufficient for the helper functions we have
6517 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6519 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6520 bool has_size = fn->arg_size[arg] != 0;
6521 bool is_next_size = false;
6523 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6524 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6526 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6527 return is_next_size;
6529 return has_size == is_next_size || is_next_size == is_fixed;
6532 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6534 /* bpf_xxx(..., buf, len) call will access 'len'
6535 * bytes from memory 'buf'. Both arg types need
6536 * to be paired, so make sure there's no buggy
6537 * helper function specification.
6539 if (arg_type_is_mem_size(fn->arg1_type) ||
6540 check_args_pair_invalid(fn, 0) ||
6541 check_args_pair_invalid(fn, 1) ||
6542 check_args_pair_invalid(fn, 2) ||
6543 check_args_pair_invalid(fn, 3) ||
6544 check_args_pair_invalid(fn, 4))
6550 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6554 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6555 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6558 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6559 /* arg_btf_id and arg_size are in a union. */
6560 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6561 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6568 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6570 return check_raw_mode_ok(fn) &&
6571 check_arg_pair_ok(fn) &&
6572 check_btf_id_ok(fn) ? 0 : -EINVAL;
6575 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6576 * are now invalid, so turn them into unknown SCALAR_VALUE.
6578 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6580 struct bpf_func_state *state;
6581 struct bpf_reg_state *reg;
6583 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6584 if (reg_is_pkt_pointer_any(reg))
6585 __mark_reg_unknown(env, reg);
6591 BEYOND_PKT_END = -2,
6594 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6596 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6597 struct bpf_reg_state *reg = &state->regs[regn];
6599 if (reg->type != PTR_TO_PACKET)
6600 /* PTR_TO_PACKET_META is not supported yet */
6603 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6604 * How far beyond pkt_end it goes is unknown.
6605 * if (!range_open) it's the case of pkt >= pkt_end
6606 * if (range_open) it's the case of pkt > pkt_end
6607 * hence this pointer is at least 1 byte bigger than pkt_end
6610 reg->range = BEYOND_PKT_END;
6612 reg->range = AT_PKT_END;
6615 /* The pointer with the specified id has released its reference to kernel
6616 * resources. Identify all copies of the same pointer and clear the reference.
6618 static int release_reference(struct bpf_verifier_env *env,
6621 struct bpf_func_state *state;
6622 struct bpf_reg_state *reg;
6625 err = release_reference_state(cur_func(env), ref_obj_id);
6629 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6630 if (reg->ref_obj_id == ref_obj_id) {
6631 if (!env->allow_ptr_leaks)
6632 __mark_reg_not_init(env, reg);
6634 __mark_reg_unknown(env, reg);
6641 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6642 struct bpf_reg_state *regs)
6646 /* after the call registers r0 - r5 were scratched */
6647 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6648 mark_reg_not_init(env, regs, caller_saved[i]);
6649 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6653 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6654 struct bpf_func_state *caller,
6655 struct bpf_func_state *callee,
6658 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6659 int *insn_idx, int subprog,
6660 set_callee_state_fn set_callee_state_cb)
6662 struct bpf_verifier_state *state = env->cur_state;
6663 struct bpf_func_info_aux *func_info_aux;
6664 struct bpf_func_state *caller, *callee;
6666 bool is_global = false;
6668 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6669 verbose(env, "the call stack of %d frames is too deep\n",
6670 state->curframe + 2);
6674 caller = state->frame[state->curframe];
6675 if (state->frame[state->curframe + 1]) {
6676 verbose(env, "verifier bug. Frame %d already allocated\n",
6677 state->curframe + 1);
6681 func_info_aux = env->prog->aux->func_info_aux;
6683 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6684 err = btf_check_subprog_call(env, subprog, caller->regs);
6689 verbose(env, "Caller passes invalid args into func#%d\n",
6693 if (env->log.level & BPF_LOG_LEVEL)
6695 "Func#%d is global and valid. Skipping.\n",
6697 clear_caller_saved_regs(env, caller->regs);
6699 /* All global functions return a 64-bit SCALAR_VALUE */
6700 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6701 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6703 /* continue with next insn after call */
6708 if (insn->code == (BPF_JMP | BPF_CALL) &&
6709 insn->src_reg == 0 &&
6710 insn->imm == BPF_FUNC_timer_set_callback) {
6711 struct bpf_verifier_state *async_cb;
6713 /* there is no real recursion here. timer callbacks are async */
6714 env->subprog_info[subprog].is_async_cb = true;
6715 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6716 *insn_idx, subprog);
6719 callee = async_cb->frame[0];
6720 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6722 /* Convert bpf_timer_set_callback() args into timer callback args */
6723 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6727 clear_caller_saved_regs(env, caller->regs);
6728 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6729 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6730 /* continue with next insn after call */
6734 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6737 state->frame[state->curframe + 1] = callee;
6739 /* callee cannot access r0, r6 - r9 for reading and has to write
6740 * into its own stack before reading from it.
6741 * callee can read/write into caller's stack
6743 init_func_state(env, callee,
6744 /* remember the callsite, it will be used by bpf_exit */
6745 *insn_idx /* callsite */,
6746 state->curframe + 1 /* frameno within this callchain */,
6747 subprog /* subprog number within this prog */);
6749 /* Transfer references to the callee */
6750 err = copy_reference_state(callee, caller);
6754 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6758 clear_caller_saved_regs(env, caller->regs);
6760 /* only increment it after check_reg_arg() finished */
6763 /* and go analyze first insn of the callee */
6764 *insn_idx = env->subprog_info[subprog].start - 1;
6766 if (env->log.level & BPF_LOG_LEVEL) {
6767 verbose(env, "caller:\n");
6768 print_verifier_state(env, caller, true);
6769 verbose(env, "callee:\n");
6770 print_verifier_state(env, callee, true);
6775 free_func_state(callee);
6776 state->frame[state->curframe + 1] = NULL;
6780 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6781 struct bpf_func_state *caller,
6782 struct bpf_func_state *callee)
6784 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6785 * void *callback_ctx, u64 flags);
6786 * callback_fn(struct bpf_map *map, void *key, void *value,
6787 * void *callback_ctx);
6789 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6791 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6792 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6793 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6795 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6796 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6797 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6799 /* pointer to stack or null */
6800 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6803 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6807 static int set_callee_state(struct bpf_verifier_env *env,
6808 struct bpf_func_state *caller,
6809 struct bpf_func_state *callee, int insn_idx)
6813 /* copy r1 - r5 args that callee can access. The copy includes parent
6814 * pointers, which connects us up to the liveness chain
6816 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6817 callee->regs[i] = caller->regs[i];
6821 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6824 int subprog, target_insn;
6826 target_insn = *insn_idx + insn->imm + 1;
6827 subprog = find_subprog(env, target_insn);
6829 verbose(env, "verifier bug. No program starts at insn %d\n",
6834 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6837 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6838 struct bpf_func_state *caller,
6839 struct bpf_func_state *callee,
6842 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6843 struct bpf_map *map;
6846 if (bpf_map_ptr_poisoned(insn_aux)) {
6847 verbose(env, "tail_call abusing map_ptr\n");
6851 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6852 if (!map->ops->map_set_for_each_callback_args ||
6853 !map->ops->map_for_each_callback) {
6854 verbose(env, "callback function not allowed for map\n");
6858 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6862 callee->in_callback_fn = true;
6863 callee->callback_ret_range = tnum_range(0, 1);
6867 static int set_loop_callback_state(struct bpf_verifier_env *env,
6868 struct bpf_func_state *caller,
6869 struct bpf_func_state *callee,
6872 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6874 * callback_fn(u32 index, void *callback_ctx);
6876 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6877 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6880 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6881 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6882 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6884 callee->in_callback_fn = true;
6885 callee->callback_ret_range = tnum_range(0, 1);
6889 static int set_timer_callback_state(struct bpf_verifier_env *env,
6890 struct bpf_func_state *caller,
6891 struct bpf_func_state *callee,
6894 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6896 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6897 * callback_fn(struct bpf_map *map, void *key, void *value);
6899 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6900 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6901 callee->regs[BPF_REG_1].map_ptr = map_ptr;
6903 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6904 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6905 callee->regs[BPF_REG_2].map_ptr = map_ptr;
6907 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6908 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6909 callee->regs[BPF_REG_3].map_ptr = map_ptr;
6912 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6913 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6914 callee->in_async_callback_fn = true;
6915 callee->callback_ret_range = tnum_range(0, 1);
6919 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6920 struct bpf_func_state *caller,
6921 struct bpf_func_state *callee,
6924 /* bpf_find_vma(struct task_struct *task, u64 addr,
6925 * void *callback_fn, void *callback_ctx, u64 flags)
6926 * (callback_fn)(struct task_struct *task,
6927 * struct vm_area_struct *vma, void *callback_ctx);
6929 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6931 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6932 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6933 callee->regs[BPF_REG_2].btf = btf_vmlinux;
6934 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6936 /* pointer to stack or null */
6937 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6940 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6941 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6942 callee->in_callback_fn = true;
6943 callee->callback_ret_range = tnum_range(0, 1);
6947 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
6948 struct bpf_func_state *caller,
6949 struct bpf_func_state *callee,
6952 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
6953 * callback_ctx, u64 flags);
6954 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
6956 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
6957 callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
6958 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6959 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6962 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6963 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6964 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6966 callee->in_callback_fn = true;
6967 callee->callback_ret_range = tnum_range(0, 1);
6971 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6973 struct bpf_verifier_state *state = env->cur_state;
6974 struct bpf_func_state *caller, *callee;
6975 struct bpf_reg_state *r0;
6978 callee = state->frame[state->curframe];
6979 r0 = &callee->regs[BPF_REG_0];
6980 if (r0->type == PTR_TO_STACK) {
6981 /* technically it's ok to return caller's stack pointer
6982 * (or caller's caller's pointer) back to the caller,
6983 * since these pointers are valid. Only current stack
6984 * pointer will be invalid as soon as function exits,
6985 * but let's be conservative
6987 verbose(env, "cannot return stack pointer to the caller\n");
6991 caller = state->frame[state->curframe - 1];
6992 if (callee->in_callback_fn) {
6993 /* enforce R0 return value range [0, 1]. */
6994 struct tnum range = callee->callback_ret_range;
6996 if (r0->type != SCALAR_VALUE) {
6997 verbose(env, "R0 not a scalar value\n");
7000 if (!tnum_in(range, r0->var_off)) {
7001 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7005 /* return to the caller whatever r0 had in the callee */
7006 caller->regs[BPF_REG_0] = *r0;
7009 /* callback_fn frame should have released its own additions to parent's
7010 * reference state at this point, or check_reference_leak would
7011 * complain, hence it must be the same as the caller. There is no need
7014 if (!callee->in_callback_fn) {
7015 /* Transfer references to the caller */
7016 err = copy_reference_state(caller, callee);
7021 *insn_idx = callee->callsite + 1;
7022 if (env->log.level & BPF_LOG_LEVEL) {
7023 verbose(env, "returning from callee:\n");
7024 print_verifier_state(env, callee, true);
7025 verbose(env, "to caller at %d:\n", *insn_idx);
7026 print_verifier_state(env, caller, true);
7028 /* clear everything in the callee */
7029 free_func_state(callee);
7030 state->frame[state->curframe--] = NULL;
7034 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7036 struct bpf_call_arg_meta *meta)
7038 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
7040 if (ret_type != RET_INTEGER ||
7041 (func_id != BPF_FUNC_get_stack &&
7042 func_id != BPF_FUNC_get_task_stack &&
7043 func_id != BPF_FUNC_probe_read_str &&
7044 func_id != BPF_FUNC_probe_read_kernel_str &&
7045 func_id != BPF_FUNC_probe_read_user_str))
7048 ret_reg->smax_value = meta->msize_max_value;
7049 ret_reg->s32_max_value = meta->msize_max_value;
7050 ret_reg->smin_value = -MAX_ERRNO;
7051 ret_reg->s32_min_value = -MAX_ERRNO;
7052 reg_bounds_sync(ret_reg);
7056 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7057 int func_id, int insn_idx)
7059 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7060 struct bpf_map *map = meta->map_ptr;
7062 if (func_id != BPF_FUNC_tail_call &&
7063 func_id != BPF_FUNC_map_lookup_elem &&
7064 func_id != BPF_FUNC_map_update_elem &&
7065 func_id != BPF_FUNC_map_delete_elem &&
7066 func_id != BPF_FUNC_map_push_elem &&
7067 func_id != BPF_FUNC_map_pop_elem &&
7068 func_id != BPF_FUNC_map_peek_elem &&
7069 func_id != BPF_FUNC_for_each_map_elem &&
7070 func_id != BPF_FUNC_redirect_map &&
7071 func_id != BPF_FUNC_map_lookup_percpu_elem)
7075 verbose(env, "kernel subsystem misconfigured verifier\n");
7079 /* In case of read-only, some additional restrictions
7080 * need to be applied in order to prevent altering the
7081 * state of the map from program side.
7083 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7084 (func_id == BPF_FUNC_map_delete_elem ||
7085 func_id == BPF_FUNC_map_update_elem ||
7086 func_id == BPF_FUNC_map_push_elem ||
7087 func_id == BPF_FUNC_map_pop_elem)) {
7088 verbose(env, "write into map forbidden\n");
7092 if (!BPF_MAP_PTR(aux->map_ptr_state))
7093 bpf_map_ptr_store(aux, meta->map_ptr,
7094 !meta->map_ptr->bypass_spec_v1);
7095 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7096 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7097 !meta->map_ptr->bypass_spec_v1);
7102 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7103 int func_id, int insn_idx)
7105 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7106 struct bpf_reg_state *regs = cur_regs(env), *reg;
7107 struct bpf_map *map = meta->map_ptr;
7111 if (func_id != BPF_FUNC_tail_call)
7113 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7114 verbose(env, "kernel subsystem misconfigured verifier\n");
7118 reg = ®s[BPF_REG_3];
7119 val = reg->var_off.value;
7120 max = map->max_entries;
7122 if (!(register_is_const(reg) && val < max)) {
7123 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7127 err = mark_chain_precision(env, BPF_REG_3);
7130 if (bpf_map_key_unseen(aux))
7131 bpf_map_key_store(aux, val);
7132 else if (!bpf_map_key_poisoned(aux) &&
7133 bpf_map_key_immediate(aux) != val)
7134 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7138 static int check_reference_leak(struct bpf_verifier_env *env)
7140 struct bpf_func_state *state = cur_func(env);
7141 bool refs_lingering = false;
7144 if (state->frameno && !state->in_callback_fn)
7147 for (i = 0; i < state->acquired_refs; i++) {
7148 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7150 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7151 state->refs[i].id, state->refs[i].insn_idx);
7152 refs_lingering = true;
7154 return refs_lingering ? -EINVAL : 0;
7157 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7158 struct bpf_reg_state *regs)
7160 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
7161 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
7162 struct bpf_map *fmt_map = fmt_reg->map_ptr;
7163 int err, fmt_map_off, num_args;
7167 /* data must be an array of u64 */
7168 if (data_len_reg->var_off.value % 8)
7170 num_args = data_len_reg->var_off.value / 8;
7172 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7173 * and map_direct_value_addr is set.
7175 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7176 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7179 verbose(env, "verifier bug\n");
7182 fmt = (char *)(long)fmt_addr + fmt_map_off;
7184 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7185 * can focus on validating the format specifiers.
7187 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7189 verbose(env, "Invalid format string\n");
7194 static int check_get_func_ip(struct bpf_verifier_env *env)
7196 enum bpf_prog_type type = resolve_prog_type(env->prog);
7197 int func_id = BPF_FUNC_get_func_ip;
7199 if (type == BPF_PROG_TYPE_TRACING) {
7200 if (!bpf_prog_has_trampoline(env->prog)) {
7201 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7202 func_id_name(func_id), func_id);
7206 } else if (type == BPF_PROG_TYPE_KPROBE) {
7210 verbose(env, "func %s#%d not supported for program type %d\n",
7211 func_id_name(func_id), func_id, type);
7215 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7217 return &env->insn_aux_data[env->insn_idx];
7220 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7222 struct bpf_reg_state *regs = cur_regs(env);
7223 struct bpf_reg_state *reg = ®s[BPF_REG_4];
7224 bool reg_is_null = register_is_null(reg);
7227 mark_chain_precision(env, BPF_REG_4);
7232 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7234 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7236 if (!state->initialized) {
7237 state->initialized = 1;
7238 state->fit_for_inline = loop_flag_is_zero(env);
7239 state->callback_subprogno = subprogno;
7243 if (!state->fit_for_inline)
7246 state->fit_for_inline = (loop_flag_is_zero(env) &&
7247 state->callback_subprogno == subprogno);
7250 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7253 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7254 const struct bpf_func_proto *fn = NULL;
7255 enum bpf_return_type ret_type;
7256 enum bpf_type_flag ret_flag;
7257 struct bpf_reg_state *regs;
7258 struct bpf_call_arg_meta meta;
7259 int insn_idx = *insn_idx_p;
7261 int i, err, func_id;
7263 /* find function prototype */
7264 func_id = insn->imm;
7265 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7266 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7271 if (env->ops->get_func_proto)
7272 fn = env->ops->get_func_proto(func_id, env->prog);
7274 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7279 /* eBPF programs must be GPL compatible to use GPL-ed functions */
7280 if (!env->prog->gpl_compatible && fn->gpl_only) {
7281 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7285 if (fn->allowed && !fn->allowed(env->prog)) {
7286 verbose(env, "helper call is not allowed in probe\n");
7290 /* With LD_ABS/IND some JITs save/restore skb from r1. */
7291 changes_data = bpf_helper_changes_pkt_data(fn->func);
7292 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7293 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7294 func_id_name(func_id), func_id);
7298 memset(&meta, 0, sizeof(meta));
7299 meta.pkt_access = fn->pkt_access;
7301 err = check_func_proto(fn, func_id);
7303 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7304 func_id_name(func_id), func_id);
7308 meta.func_id = func_id;
7310 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7311 err = check_func_arg(env, i, &meta, fn);
7316 err = record_func_map(env, &meta, func_id, insn_idx);
7320 err = record_func_key(env, &meta, func_id, insn_idx);
7324 /* Mark slots with STACK_MISC in case of raw mode, stack offset
7325 * is inferred from register state.
7327 for (i = 0; i < meta.access_size; i++) {
7328 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7329 BPF_WRITE, -1, false);
7334 regs = cur_regs(env);
7336 if (meta.uninit_dynptr_regno) {
7337 /* we write BPF_DW bits (8 bytes) at a time */
7338 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7339 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7340 i, BPF_DW, BPF_WRITE, -1, false);
7345 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno],
7346 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7352 if (meta.release_regno) {
7354 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7355 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
7356 else if (meta.ref_obj_id)
7357 err = release_reference(env, meta.ref_obj_id);
7358 /* meta.ref_obj_id can only be 0 if register that is meant to be
7359 * released is NULL, which must be > R0.
7361 else if (register_is_null(®s[meta.release_regno]))
7364 verbose(env, "func %s#%d reference has not been acquired before\n",
7365 func_id_name(func_id), func_id);
7371 case BPF_FUNC_tail_call:
7372 err = check_reference_leak(env);
7374 verbose(env, "tail_call would lead to reference leak\n");
7378 case BPF_FUNC_get_local_storage:
7379 /* check that flags argument in get_local_storage(map, flags) is 0,
7380 * this is required because get_local_storage() can't return an error.
7382 if (!register_is_null(®s[BPF_REG_2])) {
7383 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7387 case BPF_FUNC_for_each_map_elem:
7388 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7389 set_map_elem_callback_state);
7391 case BPF_FUNC_timer_set_callback:
7392 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7393 set_timer_callback_state);
7395 case BPF_FUNC_find_vma:
7396 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7397 set_find_vma_callback_state);
7399 case BPF_FUNC_snprintf:
7400 err = check_bpf_snprintf_call(env, regs);
7403 update_loop_inline_state(env, meta.subprogno);
7404 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7405 set_loop_callback_state);
7407 case BPF_FUNC_dynptr_from_mem:
7408 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7409 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7410 reg_type_str(env, regs[BPF_REG_1].type));
7414 case BPF_FUNC_set_retval:
7415 if (prog_type == BPF_PROG_TYPE_LSM &&
7416 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7417 if (!env->prog->aux->attach_func_proto->type) {
7418 /* Make sure programs that attach to void
7419 * hooks don't try to modify return value.
7421 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7426 case BPF_FUNC_dynptr_data:
7427 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7428 if (arg_type_is_dynptr(fn->arg_type[i])) {
7429 struct bpf_reg_state *reg = ®s[BPF_REG_1 + i];
7431 if (meta.ref_obj_id) {
7432 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7436 if (base_type(reg->type) != PTR_TO_DYNPTR)
7437 /* Find the id of the dynptr we're
7438 * tracking the reference of
7440 meta.ref_obj_id = stack_slot_get_id(env, reg);
7444 if (i == MAX_BPF_FUNC_REG_ARGS) {
7445 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7449 case BPF_FUNC_user_ringbuf_drain:
7450 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7451 set_user_ringbuf_callback_state);
7458 /* reset caller saved regs */
7459 for (i = 0; i < CALLER_SAVED_REGS; i++) {
7460 mark_reg_not_init(env, regs, caller_saved[i]);
7461 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7464 /* helper call returns 64-bit value. */
7465 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7467 /* update return register (already marked as written above) */
7468 ret_type = fn->ret_type;
7469 ret_flag = type_flag(ret_type);
7471 switch (base_type(ret_type)) {
7473 /* sets type to SCALAR_VALUE */
7474 mark_reg_unknown(env, regs, BPF_REG_0);
7477 regs[BPF_REG_0].type = NOT_INIT;
7479 case RET_PTR_TO_MAP_VALUE:
7480 /* There is no offset yet applied, variable or fixed */
7481 mark_reg_known_zero(env, regs, BPF_REG_0);
7482 /* remember map_ptr, so that check_map_access()
7483 * can check 'value_size' boundary of memory access
7484 * to map element returned from bpf_map_lookup_elem()
7486 if (meta.map_ptr == NULL) {
7488 "kernel subsystem misconfigured verifier\n");
7491 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7492 regs[BPF_REG_0].map_uid = meta.map_uid;
7493 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7494 if (!type_may_be_null(ret_type) &&
7495 map_value_has_spin_lock(meta.map_ptr)) {
7496 regs[BPF_REG_0].id = ++env->id_gen;
7499 case RET_PTR_TO_SOCKET:
7500 mark_reg_known_zero(env, regs, BPF_REG_0);
7501 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7503 case RET_PTR_TO_SOCK_COMMON:
7504 mark_reg_known_zero(env, regs, BPF_REG_0);
7505 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7507 case RET_PTR_TO_TCP_SOCK:
7508 mark_reg_known_zero(env, regs, BPF_REG_0);
7509 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7511 case RET_PTR_TO_ALLOC_MEM:
7512 mark_reg_known_zero(env, regs, BPF_REG_0);
7513 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7514 regs[BPF_REG_0].mem_size = meta.mem_size;
7516 case RET_PTR_TO_MEM_OR_BTF_ID:
7518 const struct btf_type *t;
7520 mark_reg_known_zero(env, regs, BPF_REG_0);
7521 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7522 if (!btf_type_is_struct(t)) {
7524 const struct btf_type *ret;
7527 /* resolve the type size of ksym. */
7528 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7530 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7531 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7532 tname, PTR_ERR(ret));
7535 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7536 regs[BPF_REG_0].mem_size = tsize;
7538 /* MEM_RDONLY may be carried from ret_flag, but it
7539 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7540 * it will confuse the check of PTR_TO_BTF_ID in
7541 * check_mem_access().
7543 ret_flag &= ~MEM_RDONLY;
7545 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7546 regs[BPF_REG_0].btf = meta.ret_btf;
7547 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7551 case RET_PTR_TO_BTF_ID:
7553 struct btf *ret_btf;
7556 mark_reg_known_zero(env, regs, BPF_REG_0);
7557 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7558 if (func_id == BPF_FUNC_kptr_xchg) {
7559 ret_btf = meta.kptr_off_desc->kptr.btf;
7560 ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7562 if (fn->ret_btf_id == BPF_PTR_POISON) {
7563 verbose(env, "verifier internal error:");
7564 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7565 func_id_name(func_id));
7568 ret_btf = btf_vmlinux;
7569 ret_btf_id = *fn->ret_btf_id;
7571 if (ret_btf_id == 0) {
7572 verbose(env, "invalid return type %u of func %s#%d\n",
7573 base_type(ret_type), func_id_name(func_id),
7577 regs[BPF_REG_0].btf = ret_btf;
7578 regs[BPF_REG_0].btf_id = ret_btf_id;
7582 verbose(env, "unknown return type %u of func %s#%d\n",
7583 base_type(ret_type), func_id_name(func_id), func_id);
7587 if (type_may_be_null(regs[BPF_REG_0].type))
7588 regs[BPF_REG_0].id = ++env->id_gen;
7590 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7591 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7592 func_id_name(func_id), func_id);
7596 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7597 /* For release_reference() */
7598 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7599 } else if (is_acquire_function(func_id, meta.map_ptr)) {
7600 int id = acquire_reference_state(env, insn_idx);
7604 /* For mark_ptr_or_null_reg() */
7605 regs[BPF_REG_0].id = id;
7606 /* For release_reference() */
7607 regs[BPF_REG_0].ref_obj_id = id;
7610 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7612 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7616 if ((func_id == BPF_FUNC_get_stack ||
7617 func_id == BPF_FUNC_get_task_stack) &&
7618 !env->prog->has_callchain_buf) {
7619 const char *err_str;
7621 #ifdef CONFIG_PERF_EVENTS
7622 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7623 err_str = "cannot get callchain buffer for func %s#%d\n";
7626 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7629 verbose(env, err_str, func_id_name(func_id), func_id);
7633 env->prog->has_callchain_buf = true;
7636 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7637 env->prog->call_get_stack = true;
7639 if (func_id == BPF_FUNC_get_func_ip) {
7640 if (check_get_func_ip(env))
7642 env->prog->call_get_func_ip = true;
7646 clear_all_pkt_pointers(env);
7650 /* mark_btf_func_reg_size() is used when the reg size is determined by
7651 * the BTF func_proto's return value size and argument.
7653 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7656 struct bpf_reg_state *reg = &cur_regs(env)[regno];
7658 if (regno == BPF_REG_0) {
7659 /* Function return value */
7660 reg->live |= REG_LIVE_WRITTEN;
7661 reg->subreg_def = reg_size == sizeof(u64) ?
7662 DEF_NOT_SUBREG : env->insn_idx + 1;
7664 /* Function argument */
7665 if (reg_size == sizeof(u64)) {
7666 mark_insn_zext(env, reg);
7667 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7669 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7674 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7677 const struct btf_type *t, *func, *func_proto, *ptr_type;
7678 struct bpf_reg_state *regs = cur_regs(env);
7679 struct bpf_kfunc_arg_meta meta = { 0 };
7680 const char *func_name, *ptr_type_name;
7681 u32 i, nargs, func_id, ptr_type_id;
7682 int err, insn_idx = *insn_idx_p;
7683 const struct btf_param *args;
7684 struct btf *desc_btf;
7688 /* skip for now, but return error when we find this in fixup_kfunc_call */
7692 desc_btf = find_kfunc_desc_btf(env, insn->off);
7693 if (IS_ERR(desc_btf))
7694 return PTR_ERR(desc_btf);
7696 func_id = insn->imm;
7697 func = btf_type_by_id(desc_btf, func_id);
7698 func_name = btf_name_by_offset(desc_btf, func->name_off);
7699 func_proto = btf_type_by_id(desc_btf, func->type);
7701 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7703 verbose(env, "calling kernel function %s is not allowed\n",
7707 if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7708 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7712 acq = *kfunc_flags & KF_ACQUIRE;
7714 meta.flags = *kfunc_flags;
7716 /* Check the arguments */
7717 err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7720 /* In case of release function, we get register number of refcounted
7721 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7724 err = release_reference(env, regs[err].ref_obj_id);
7726 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7727 func_name, func_id);
7732 for (i = 0; i < CALLER_SAVED_REGS; i++)
7733 mark_reg_not_init(env, regs, caller_saved[i]);
7735 /* Check return type */
7736 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7738 if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7739 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7743 if (btf_type_is_scalar(t)) {
7744 mark_reg_unknown(env, regs, BPF_REG_0);
7745 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7746 } else if (btf_type_is_ptr(t)) {
7747 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7749 if (!btf_type_is_struct(ptr_type)) {
7750 if (!meta.r0_size) {
7751 ptr_type_name = btf_name_by_offset(desc_btf,
7752 ptr_type->name_off);
7754 "kernel function %s returns pointer type %s %s is not supported\n",
7756 btf_type_str(ptr_type),
7761 mark_reg_known_zero(env, regs, BPF_REG_0);
7762 regs[BPF_REG_0].type = PTR_TO_MEM;
7763 regs[BPF_REG_0].mem_size = meta.r0_size;
7766 regs[BPF_REG_0].type |= MEM_RDONLY;
7768 /* Ensures we don't access the memory after a release_reference() */
7769 if (meta.ref_obj_id)
7770 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7772 mark_reg_known_zero(env, regs, BPF_REG_0);
7773 regs[BPF_REG_0].btf = desc_btf;
7774 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7775 regs[BPF_REG_0].btf_id = ptr_type_id;
7777 if (*kfunc_flags & KF_RET_NULL) {
7778 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7779 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7780 regs[BPF_REG_0].id = ++env->id_gen;
7782 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7784 int id = acquire_reference_state(env, insn_idx);
7788 regs[BPF_REG_0].id = id;
7789 regs[BPF_REG_0].ref_obj_id = id;
7791 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7793 nargs = btf_type_vlen(func_proto);
7794 args = (const struct btf_param *)(func_proto + 1);
7795 for (i = 0; i < nargs; i++) {
7798 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7799 if (btf_type_is_ptr(t))
7800 mark_btf_func_reg_size(env, regno, sizeof(void *));
7802 /* scalar. ensured by btf_check_kfunc_arg_match() */
7803 mark_btf_func_reg_size(env, regno, t->size);
7809 static bool signed_add_overflows(s64 a, s64 b)
7811 /* Do the add in u64, where overflow is well-defined */
7812 s64 res = (s64)((u64)a + (u64)b);
7819 static bool signed_add32_overflows(s32 a, s32 b)
7821 /* Do the add in u32, where overflow is well-defined */
7822 s32 res = (s32)((u32)a + (u32)b);
7829 static bool signed_sub_overflows(s64 a, s64 b)
7831 /* Do the sub in u64, where overflow is well-defined */
7832 s64 res = (s64)((u64)a - (u64)b);
7839 static bool signed_sub32_overflows(s32 a, s32 b)
7841 /* Do the sub in u32, where overflow is well-defined */
7842 s32 res = (s32)((u32)a - (u32)b);
7849 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7850 const struct bpf_reg_state *reg,
7851 enum bpf_reg_type type)
7853 bool known = tnum_is_const(reg->var_off);
7854 s64 val = reg->var_off.value;
7855 s64 smin = reg->smin_value;
7857 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7858 verbose(env, "math between %s pointer and %lld is not allowed\n",
7859 reg_type_str(env, type), val);
7863 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7864 verbose(env, "%s pointer offset %d is not allowed\n",
7865 reg_type_str(env, type), reg->off);
7869 if (smin == S64_MIN) {
7870 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7871 reg_type_str(env, type));
7875 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7876 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7877 smin, reg_type_str(env, type));
7892 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7893 u32 *alu_limit, bool mask_to_left)
7895 u32 max = 0, ptr_limit = 0;
7897 switch (ptr_reg->type) {
7899 /* Offset 0 is out-of-bounds, but acceptable start for the
7900 * left direction, see BPF_REG_FP. Also, unknown scalar
7901 * offset where we would need to deal with min/max bounds is
7902 * currently prohibited for unprivileged.
7904 max = MAX_BPF_STACK + mask_to_left;
7905 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7907 case PTR_TO_MAP_VALUE:
7908 max = ptr_reg->map_ptr->value_size;
7909 ptr_limit = (mask_to_left ?
7910 ptr_reg->smin_value :
7911 ptr_reg->umax_value) + ptr_reg->off;
7917 if (ptr_limit >= max)
7918 return REASON_LIMIT;
7919 *alu_limit = ptr_limit;
7923 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7924 const struct bpf_insn *insn)
7926 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7929 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7930 u32 alu_state, u32 alu_limit)
7932 /* If we arrived here from different branches with different
7933 * state or limits to sanitize, then this won't work.
7935 if (aux->alu_state &&
7936 (aux->alu_state != alu_state ||
7937 aux->alu_limit != alu_limit))
7938 return REASON_PATHS;
7940 /* Corresponding fixup done in do_misc_fixups(). */
7941 aux->alu_state = alu_state;
7942 aux->alu_limit = alu_limit;
7946 static int sanitize_val_alu(struct bpf_verifier_env *env,
7947 struct bpf_insn *insn)
7949 struct bpf_insn_aux_data *aux = cur_aux(env);
7951 if (can_skip_alu_sanitation(env, insn))
7954 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7957 static bool sanitize_needed(u8 opcode)
7959 return opcode == BPF_ADD || opcode == BPF_SUB;
7962 struct bpf_sanitize_info {
7963 struct bpf_insn_aux_data aux;
7967 static struct bpf_verifier_state *
7968 sanitize_speculative_path(struct bpf_verifier_env *env,
7969 const struct bpf_insn *insn,
7970 u32 next_idx, u32 curr_idx)
7972 struct bpf_verifier_state *branch;
7973 struct bpf_reg_state *regs;
7975 branch = push_stack(env, next_idx, curr_idx, true);
7976 if (branch && insn) {
7977 regs = branch->frame[branch->curframe]->regs;
7978 if (BPF_SRC(insn->code) == BPF_K) {
7979 mark_reg_unknown(env, regs, insn->dst_reg);
7980 } else if (BPF_SRC(insn->code) == BPF_X) {
7981 mark_reg_unknown(env, regs, insn->dst_reg);
7982 mark_reg_unknown(env, regs, insn->src_reg);
7988 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7989 struct bpf_insn *insn,
7990 const struct bpf_reg_state *ptr_reg,
7991 const struct bpf_reg_state *off_reg,
7992 struct bpf_reg_state *dst_reg,
7993 struct bpf_sanitize_info *info,
7994 const bool commit_window)
7996 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7997 struct bpf_verifier_state *vstate = env->cur_state;
7998 bool off_is_imm = tnum_is_const(off_reg->var_off);
7999 bool off_is_neg = off_reg->smin_value < 0;
8000 bool ptr_is_dst_reg = ptr_reg == dst_reg;
8001 u8 opcode = BPF_OP(insn->code);
8002 u32 alu_state, alu_limit;
8003 struct bpf_reg_state tmp;
8007 if (can_skip_alu_sanitation(env, insn))
8010 /* We already marked aux for masking from non-speculative
8011 * paths, thus we got here in the first place. We only care
8012 * to explore bad access from here.
8014 if (vstate->speculative)
8017 if (!commit_window) {
8018 if (!tnum_is_const(off_reg->var_off) &&
8019 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8020 return REASON_BOUNDS;
8022 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
8023 (opcode == BPF_SUB && !off_is_neg);
8026 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8030 if (commit_window) {
8031 /* In commit phase we narrow the masking window based on
8032 * the observed pointer move after the simulated operation.
8034 alu_state = info->aux.alu_state;
8035 alu_limit = abs(info->aux.alu_limit - alu_limit);
8037 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8038 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8039 alu_state |= ptr_is_dst_reg ?
8040 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8042 /* Limit pruning on unknown scalars to enable deep search for
8043 * potential masking differences from other program paths.
8046 env->explore_alu_limits = true;
8049 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8053 /* If we're in commit phase, we're done here given we already
8054 * pushed the truncated dst_reg into the speculative verification
8057 * Also, when register is a known constant, we rewrite register-based
8058 * operation to immediate-based, and thus do not need masking (and as
8059 * a consequence, do not need to simulate the zero-truncation either).
8061 if (commit_window || off_is_imm)
8064 /* Simulate and find potential out-of-bounds access under
8065 * speculative execution from truncation as a result of
8066 * masking when off was not within expected range. If off
8067 * sits in dst, then we temporarily need to move ptr there
8068 * to simulate dst (== 0) +/-= ptr. Needed, for example,
8069 * for cases where we use K-based arithmetic in one direction
8070 * and truncated reg-based in the other in order to explore
8073 if (!ptr_is_dst_reg) {
8075 *dst_reg = *ptr_reg;
8077 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8079 if (!ptr_is_dst_reg && ret)
8081 return !ret ? REASON_STACK : 0;
8084 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8086 struct bpf_verifier_state *vstate = env->cur_state;
8088 /* If we simulate paths under speculation, we don't update the
8089 * insn as 'seen' such that when we verify unreachable paths in
8090 * the non-speculative domain, sanitize_dead_code() can still
8091 * rewrite/sanitize them.
8093 if (!vstate->speculative)
8094 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8097 static int sanitize_err(struct bpf_verifier_env *env,
8098 const struct bpf_insn *insn, int reason,
8099 const struct bpf_reg_state *off_reg,
8100 const struct bpf_reg_state *dst_reg)
8102 static const char *err = "pointer arithmetic with it prohibited for !root";
8103 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8104 u32 dst = insn->dst_reg, src = insn->src_reg;
8108 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8109 off_reg == dst_reg ? dst : src, err);
8112 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8113 off_reg == dst_reg ? src : dst, err);
8116 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8120 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8124 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8128 verbose(env, "verifier internal error: unknown reason (%d)\n",
8136 /* check that stack access falls within stack limits and that 'reg' doesn't
8137 * have a variable offset.
8139 * Variable offset is prohibited for unprivileged mode for simplicity since it
8140 * requires corresponding support in Spectre masking for stack ALU. See also
8141 * retrieve_ptr_limit().
8144 * 'off' includes 'reg->off'.
8146 static int check_stack_access_for_ptr_arithmetic(
8147 struct bpf_verifier_env *env,
8149 const struct bpf_reg_state *reg,
8152 if (!tnum_is_const(reg->var_off)) {
8155 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8156 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8157 regno, tn_buf, off);
8161 if (off >= 0 || off < -MAX_BPF_STACK) {
8162 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8163 "prohibited for !root; off=%d\n", regno, off);
8170 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8171 const struct bpf_insn *insn,
8172 const struct bpf_reg_state *dst_reg)
8174 u32 dst = insn->dst_reg;
8176 /* For unprivileged we require that resulting offset must be in bounds
8177 * in order to be able to sanitize access later on.
8179 if (env->bypass_spec_v1)
8182 switch (dst_reg->type) {
8184 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8185 dst_reg->off + dst_reg->var_off.value))
8188 case PTR_TO_MAP_VALUE:
8189 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8190 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8191 "prohibited for !root\n", dst);
8202 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8203 * Caller should also handle BPF_MOV case separately.
8204 * If we return -EACCES, caller may want to try again treating pointer as a
8205 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
8207 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8208 struct bpf_insn *insn,
8209 const struct bpf_reg_state *ptr_reg,
8210 const struct bpf_reg_state *off_reg)
8212 struct bpf_verifier_state *vstate = env->cur_state;
8213 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8214 struct bpf_reg_state *regs = state->regs, *dst_reg;
8215 bool known = tnum_is_const(off_reg->var_off);
8216 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8217 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8218 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8219 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8220 struct bpf_sanitize_info info = {};
8221 u8 opcode = BPF_OP(insn->code);
8222 u32 dst = insn->dst_reg;
8225 dst_reg = ®s[dst];
8227 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8228 smin_val > smax_val || umin_val > umax_val) {
8229 /* Taint dst register if offset had invalid bounds derived from
8230 * e.g. dead branches.
8232 __mark_reg_unknown(env, dst_reg);
8236 if (BPF_CLASS(insn->code) != BPF_ALU64) {
8237 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8238 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8239 __mark_reg_unknown(env, dst_reg);
8244 "R%d 32-bit pointer arithmetic prohibited\n",
8249 if (ptr_reg->type & PTR_MAYBE_NULL) {
8250 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8251 dst, reg_type_str(env, ptr_reg->type));
8255 switch (base_type(ptr_reg->type)) {
8256 case CONST_PTR_TO_MAP:
8257 /* smin_val represents the known value */
8258 if (known && smin_val == 0 && opcode == BPF_ADD)
8261 case PTR_TO_PACKET_END:
8263 case PTR_TO_SOCK_COMMON:
8264 case PTR_TO_TCP_SOCK:
8265 case PTR_TO_XDP_SOCK:
8266 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8267 dst, reg_type_str(env, ptr_reg->type));
8273 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8274 * The id may be overwritten later if we create a new variable offset.
8276 dst_reg->type = ptr_reg->type;
8277 dst_reg->id = ptr_reg->id;
8279 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8280 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8283 /* pointer types do not carry 32-bit bounds at the moment. */
8284 __mark_reg32_unbounded(dst_reg);
8286 if (sanitize_needed(opcode)) {
8287 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8290 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8295 /* We can take a fixed offset as long as it doesn't overflow
8296 * the s32 'off' field
8298 if (known && (ptr_reg->off + smin_val ==
8299 (s64)(s32)(ptr_reg->off + smin_val))) {
8300 /* pointer += K. Accumulate it into fixed offset */
8301 dst_reg->smin_value = smin_ptr;
8302 dst_reg->smax_value = smax_ptr;
8303 dst_reg->umin_value = umin_ptr;
8304 dst_reg->umax_value = umax_ptr;
8305 dst_reg->var_off = ptr_reg->var_off;
8306 dst_reg->off = ptr_reg->off + smin_val;
8307 dst_reg->raw = ptr_reg->raw;
8310 /* A new variable offset is created. Note that off_reg->off
8311 * == 0, since it's a scalar.
8312 * dst_reg gets the pointer type and since some positive
8313 * integer value was added to the pointer, give it a new 'id'
8314 * if it's a PTR_TO_PACKET.
8315 * this creates a new 'base' pointer, off_reg (variable) gets
8316 * added into the variable offset, and we copy the fixed offset
8319 if (signed_add_overflows(smin_ptr, smin_val) ||
8320 signed_add_overflows(smax_ptr, smax_val)) {
8321 dst_reg->smin_value = S64_MIN;
8322 dst_reg->smax_value = S64_MAX;
8324 dst_reg->smin_value = smin_ptr + smin_val;
8325 dst_reg->smax_value = smax_ptr + smax_val;
8327 if (umin_ptr + umin_val < umin_ptr ||
8328 umax_ptr + umax_val < umax_ptr) {
8329 dst_reg->umin_value = 0;
8330 dst_reg->umax_value = U64_MAX;
8332 dst_reg->umin_value = umin_ptr + umin_val;
8333 dst_reg->umax_value = umax_ptr + umax_val;
8335 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8336 dst_reg->off = ptr_reg->off;
8337 dst_reg->raw = ptr_reg->raw;
8338 if (reg_is_pkt_pointer(ptr_reg)) {
8339 dst_reg->id = ++env->id_gen;
8340 /* something was added to pkt_ptr, set range to zero */
8341 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8345 if (dst_reg == off_reg) {
8346 /* scalar -= pointer. Creates an unknown scalar */
8347 verbose(env, "R%d tried to subtract pointer from scalar\n",
8351 /* We don't allow subtraction from FP, because (according to
8352 * test_verifier.c test "invalid fp arithmetic", JITs might not
8353 * be able to deal with it.
8355 if (ptr_reg->type == PTR_TO_STACK) {
8356 verbose(env, "R%d subtraction from stack pointer prohibited\n",
8360 if (known && (ptr_reg->off - smin_val ==
8361 (s64)(s32)(ptr_reg->off - smin_val))) {
8362 /* pointer -= K. Subtract it from fixed offset */
8363 dst_reg->smin_value = smin_ptr;
8364 dst_reg->smax_value = smax_ptr;
8365 dst_reg->umin_value = umin_ptr;
8366 dst_reg->umax_value = umax_ptr;
8367 dst_reg->var_off = ptr_reg->var_off;
8368 dst_reg->id = ptr_reg->id;
8369 dst_reg->off = ptr_reg->off - smin_val;
8370 dst_reg->raw = ptr_reg->raw;
8373 /* A new variable offset is created. If the subtrahend is known
8374 * nonnegative, then any reg->range we had before is still good.
8376 if (signed_sub_overflows(smin_ptr, smax_val) ||
8377 signed_sub_overflows(smax_ptr, smin_val)) {
8378 /* Overflow possible, we know nothing */
8379 dst_reg->smin_value = S64_MIN;
8380 dst_reg->smax_value = S64_MAX;
8382 dst_reg->smin_value = smin_ptr - smax_val;
8383 dst_reg->smax_value = smax_ptr - smin_val;
8385 if (umin_ptr < umax_val) {
8386 /* Overflow possible, we know nothing */
8387 dst_reg->umin_value = 0;
8388 dst_reg->umax_value = U64_MAX;
8390 /* Cannot overflow (as long as bounds are consistent) */
8391 dst_reg->umin_value = umin_ptr - umax_val;
8392 dst_reg->umax_value = umax_ptr - umin_val;
8394 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8395 dst_reg->off = ptr_reg->off;
8396 dst_reg->raw = ptr_reg->raw;
8397 if (reg_is_pkt_pointer(ptr_reg)) {
8398 dst_reg->id = ++env->id_gen;
8399 /* something was added to pkt_ptr, set range to zero */
8401 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8407 /* bitwise ops on pointers are troublesome, prohibit. */
8408 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8409 dst, bpf_alu_string[opcode >> 4]);
8412 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8413 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8414 dst, bpf_alu_string[opcode >> 4]);
8418 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8420 reg_bounds_sync(dst_reg);
8421 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8423 if (sanitize_needed(opcode)) {
8424 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8427 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8433 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8434 struct bpf_reg_state *src_reg)
8436 s32 smin_val = src_reg->s32_min_value;
8437 s32 smax_val = src_reg->s32_max_value;
8438 u32 umin_val = src_reg->u32_min_value;
8439 u32 umax_val = src_reg->u32_max_value;
8441 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8442 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8443 dst_reg->s32_min_value = S32_MIN;
8444 dst_reg->s32_max_value = S32_MAX;
8446 dst_reg->s32_min_value += smin_val;
8447 dst_reg->s32_max_value += smax_val;
8449 if (dst_reg->u32_min_value + umin_val < umin_val ||
8450 dst_reg->u32_max_value + umax_val < umax_val) {
8451 dst_reg->u32_min_value = 0;
8452 dst_reg->u32_max_value = U32_MAX;
8454 dst_reg->u32_min_value += umin_val;
8455 dst_reg->u32_max_value += umax_val;
8459 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8460 struct bpf_reg_state *src_reg)
8462 s64 smin_val = src_reg->smin_value;
8463 s64 smax_val = src_reg->smax_value;
8464 u64 umin_val = src_reg->umin_value;
8465 u64 umax_val = src_reg->umax_value;
8467 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8468 signed_add_overflows(dst_reg->smax_value, smax_val)) {
8469 dst_reg->smin_value = S64_MIN;
8470 dst_reg->smax_value = S64_MAX;
8472 dst_reg->smin_value += smin_val;
8473 dst_reg->smax_value += smax_val;
8475 if (dst_reg->umin_value + umin_val < umin_val ||
8476 dst_reg->umax_value + umax_val < umax_val) {
8477 dst_reg->umin_value = 0;
8478 dst_reg->umax_value = U64_MAX;
8480 dst_reg->umin_value += umin_val;
8481 dst_reg->umax_value += umax_val;
8485 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8486 struct bpf_reg_state *src_reg)
8488 s32 smin_val = src_reg->s32_min_value;
8489 s32 smax_val = src_reg->s32_max_value;
8490 u32 umin_val = src_reg->u32_min_value;
8491 u32 umax_val = src_reg->u32_max_value;
8493 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8494 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8495 /* Overflow possible, we know nothing */
8496 dst_reg->s32_min_value = S32_MIN;
8497 dst_reg->s32_max_value = S32_MAX;
8499 dst_reg->s32_min_value -= smax_val;
8500 dst_reg->s32_max_value -= smin_val;
8502 if (dst_reg->u32_min_value < umax_val) {
8503 /* Overflow possible, we know nothing */
8504 dst_reg->u32_min_value = 0;
8505 dst_reg->u32_max_value = U32_MAX;
8507 /* Cannot overflow (as long as bounds are consistent) */
8508 dst_reg->u32_min_value -= umax_val;
8509 dst_reg->u32_max_value -= umin_val;
8513 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8514 struct bpf_reg_state *src_reg)
8516 s64 smin_val = src_reg->smin_value;
8517 s64 smax_val = src_reg->smax_value;
8518 u64 umin_val = src_reg->umin_value;
8519 u64 umax_val = src_reg->umax_value;
8521 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8522 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8523 /* Overflow possible, we know nothing */
8524 dst_reg->smin_value = S64_MIN;
8525 dst_reg->smax_value = S64_MAX;
8527 dst_reg->smin_value -= smax_val;
8528 dst_reg->smax_value -= smin_val;
8530 if (dst_reg->umin_value < umax_val) {
8531 /* Overflow possible, we know nothing */
8532 dst_reg->umin_value = 0;
8533 dst_reg->umax_value = U64_MAX;
8535 /* Cannot overflow (as long as bounds are consistent) */
8536 dst_reg->umin_value -= umax_val;
8537 dst_reg->umax_value -= umin_val;
8541 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8542 struct bpf_reg_state *src_reg)
8544 s32 smin_val = src_reg->s32_min_value;
8545 u32 umin_val = src_reg->u32_min_value;
8546 u32 umax_val = src_reg->u32_max_value;
8548 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8549 /* Ain't nobody got time to multiply that sign */
8550 __mark_reg32_unbounded(dst_reg);
8553 /* Both values are positive, so we can work with unsigned and
8554 * copy the result to signed (unless it exceeds S32_MAX).
8556 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8557 /* Potential overflow, we know nothing */
8558 __mark_reg32_unbounded(dst_reg);
8561 dst_reg->u32_min_value *= umin_val;
8562 dst_reg->u32_max_value *= umax_val;
8563 if (dst_reg->u32_max_value > S32_MAX) {
8564 /* Overflow possible, we know nothing */
8565 dst_reg->s32_min_value = S32_MIN;
8566 dst_reg->s32_max_value = S32_MAX;
8568 dst_reg->s32_min_value = dst_reg->u32_min_value;
8569 dst_reg->s32_max_value = dst_reg->u32_max_value;
8573 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8574 struct bpf_reg_state *src_reg)
8576 s64 smin_val = src_reg->smin_value;
8577 u64 umin_val = src_reg->umin_value;
8578 u64 umax_val = src_reg->umax_value;
8580 if (smin_val < 0 || dst_reg->smin_value < 0) {
8581 /* Ain't nobody got time to multiply that sign */
8582 __mark_reg64_unbounded(dst_reg);
8585 /* Both values are positive, so we can work with unsigned and
8586 * copy the result to signed (unless it exceeds S64_MAX).
8588 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8589 /* Potential overflow, we know nothing */
8590 __mark_reg64_unbounded(dst_reg);
8593 dst_reg->umin_value *= umin_val;
8594 dst_reg->umax_value *= umax_val;
8595 if (dst_reg->umax_value > S64_MAX) {
8596 /* Overflow possible, we know nothing */
8597 dst_reg->smin_value = S64_MIN;
8598 dst_reg->smax_value = S64_MAX;
8600 dst_reg->smin_value = dst_reg->umin_value;
8601 dst_reg->smax_value = dst_reg->umax_value;
8605 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8606 struct bpf_reg_state *src_reg)
8608 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8609 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8610 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8611 s32 smin_val = src_reg->s32_min_value;
8612 u32 umax_val = src_reg->u32_max_value;
8614 if (src_known && dst_known) {
8615 __mark_reg32_known(dst_reg, var32_off.value);
8619 /* We get our minimum from the var_off, since that's inherently
8620 * bitwise. Our maximum is the minimum of the operands' maxima.
8622 dst_reg->u32_min_value = var32_off.value;
8623 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8624 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8625 /* Lose signed bounds when ANDing negative numbers,
8626 * ain't nobody got time for that.
8628 dst_reg->s32_min_value = S32_MIN;
8629 dst_reg->s32_max_value = S32_MAX;
8631 /* ANDing two positives gives a positive, so safe to
8632 * cast result into s64.
8634 dst_reg->s32_min_value = dst_reg->u32_min_value;
8635 dst_reg->s32_max_value = dst_reg->u32_max_value;
8639 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8640 struct bpf_reg_state *src_reg)
8642 bool src_known = tnum_is_const(src_reg->var_off);
8643 bool dst_known = tnum_is_const(dst_reg->var_off);
8644 s64 smin_val = src_reg->smin_value;
8645 u64 umax_val = src_reg->umax_value;
8647 if (src_known && dst_known) {
8648 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8652 /* We get our minimum from the var_off, since that's inherently
8653 * bitwise. Our maximum is the minimum of the operands' maxima.
8655 dst_reg->umin_value = dst_reg->var_off.value;
8656 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8657 if (dst_reg->smin_value < 0 || smin_val < 0) {
8658 /* Lose signed bounds when ANDing negative numbers,
8659 * ain't nobody got time for that.
8661 dst_reg->smin_value = S64_MIN;
8662 dst_reg->smax_value = S64_MAX;
8664 /* ANDing two positives gives a positive, so safe to
8665 * cast result into s64.
8667 dst_reg->smin_value = dst_reg->umin_value;
8668 dst_reg->smax_value = dst_reg->umax_value;
8670 /* We may learn something more from the var_off */
8671 __update_reg_bounds(dst_reg);
8674 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8675 struct bpf_reg_state *src_reg)
8677 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8678 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8679 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8680 s32 smin_val = src_reg->s32_min_value;
8681 u32 umin_val = src_reg->u32_min_value;
8683 if (src_known && dst_known) {
8684 __mark_reg32_known(dst_reg, var32_off.value);
8688 /* We get our maximum from the var_off, and our minimum is the
8689 * maximum of the operands' minima
8691 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8692 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8693 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8694 /* Lose signed bounds when ORing negative numbers,
8695 * ain't nobody got time for that.
8697 dst_reg->s32_min_value = S32_MIN;
8698 dst_reg->s32_max_value = S32_MAX;
8700 /* ORing two positives gives a positive, so safe to
8701 * cast result into s64.
8703 dst_reg->s32_min_value = dst_reg->u32_min_value;
8704 dst_reg->s32_max_value = dst_reg->u32_max_value;
8708 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8709 struct bpf_reg_state *src_reg)
8711 bool src_known = tnum_is_const(src_reg->var_off);
8712 bool dst_known = tnum_is_const(dst_reg->var_off);
8713 s64 smin_val = src_reg->smin_value;
8714 u64 umin_val = src_reg->umin_value;
8716 if (src_known && dst_known) {
8717 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8721 /* We get our maximum from the var_off, and our minimum is the
8722 * maximum of the operands' minima
8724 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8725 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8726 if (dst_reg->smin_value < 0 || smin_val < 0) {
8727 /* Lose signed bounds when ORing negative numbers,
8728 * ain't nobody got time for that.
8730 dst_reg->smin_value = S64_MIN;
8731 dst_reg->smax_value = S64_MAX;
8733 /* ORing two positives gives a positive, so safe to
8734 * cast result into s64.
8736 dst_reg->smin_value = dst_reg->umin_value;
8737 dst_reg->smax_value = dst_reg->umax_value;
8739 /* We may learn something more from the var_off */
8740 __update_reg_bounds(dst_reg);
8743 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8744 struct bpf_reg_state *src_reg)
8746 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8747 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8748 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8749 s32 smin_val = src_reg->s32_min_value;
8751 if (src_known && dst_known) {
8752 __mark_reg32_known(dst_reg, var32_off.value);
8756 /* We get both minimum and maximum from the var32_off. */
8757 dst_reg->u32_min_value = var32_off.value;
8758 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8760 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8761 /* XORing two positive sign numbers gives a positive,
8762 * so safe to cast u32 result into s32.
8764 dst_reg->s32_min_value = dst_reg->u32_min_value;
8765 dst_reg->s32_max_value = dst_reg->u32_max_value;
8767 dst_reg->s32_min_value = S32_MIN;
8768 dst_reg->s32_max_value = S32_MAX;
8772 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8773 struct bpf_reg_state *src_reg)
8775 bool src_known = tnum_is_const(src_reg->var_off);
8776 bool dst_known = tnum_is_const(dst_reg->var_off);
8777 s64 smin_val = src_reg->smin_value;
8779 if (src_known && dst_known) {
8780 /* dst_reg->var_off.value has been updated earlier */
8781 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8785 /* We get both minimum and maximum from the var_off. */
8786 dst_reg->umin_value = dst_reg->var_off.value;
8787 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8789 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8790 /* XORing two positive sign numbers gives a positive,
8791 * so safe to cast u64 result into s64.
8793 dst_reg->smin_value = dst_reg->umin_value;
8794 dst_reg->smax_value = dst_reg->umax_value;
8796 dst_reg->smin_value = S64_MIN;
8797 dst_reg->smax_value = S64_MAX;
8800 __update_reg_bounds(dst_reg);
8803 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8804 u64 umin_val, u64 umax_val)
8806 /* We lose all sign bit information (except what we can pick
8809 dst_reg->s32_min_value = S32_MIN;
8810 dst_reg->s32_max_value = S32_MAX;
8811 /* If we might shift our top bit out, then we know nothing */
8812 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8813 dst_reg->u32_min_value = 0;
8814 dst_reg->u32_max_value = U32_MAX;
8816 dst_reg->u32_min_value <<= umin_val;
8817 dst_reg->u32_max_value <<= umax_val;
8821 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8822 struct bpf_reg_state *src_reg)
8824 u32 umax_val = src_reg->u32_max_value;
8825 u32 umin_val = src_reg->u32_min_value;
8826 /* u32 alu operation will zext upper bits */
8827 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8829 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8830 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8831 /* Not required but being careful mark reg64 bounds as unknown so
8832 * that we are forced to pick them up from tnum and zext later and
8833 * if some path skips this step we are still safe.
8835 __mark_reg64_unbounded(dst_reg);
8836 __update_reg32_bounds(dst_reg);
8839 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8840 u64 umin_val, u64 umax_val)
8842 /* Special case <<32 because it is a common compiler pattern to sign
8843 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8844 * positive we know this shift will also be positive so we can track
8845 * bounds correctly. Otherwise we lose all sign bit information except
8846 * what we can pick up from var_off. Perhaps we can generalize this
8847 * later to shifts of any length.
8849 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8850 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8852 dst_reg->smax_value = S64_MAX;
8854 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8855 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8857 dst_reg->smin_value = S64_MIN;
8859 /* If we might shift our top bit out, then we know nothing */
8860 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8861 dst_reg->umin_value = 0;
8862 dst_reg->umax_value = U64_MAX;
8864 dst_reg->umin_value <<= umin_val;
8865 dst_reg->umax_value <<= umax_val;
8869 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8870 struct bpf_reg_state *src_reg)
8872 u64 umax_val = src_reg->umax_value;
8873 u64 umin_val = src_reg->umin_value;
8875 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8876 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8877 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8879 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8880 /* We may learn something more from the var_off */
8881 __update_reg_bounds(dst_reg);
8884 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8885 struct bpf_reg_state *src_reg)
8887 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8888 u32 umax_val = src_reg->u32_max_value;
8889 u32 umin_val = src_reg->u32_min_value;
8891 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8892 * be negative, then either:
8893 * 1) src_reg might be zero, so the sign bit of the result is
8894 * unknown, so we lose our signed bounds
8895 * 2) it's known negative, thus the unsigned bounds capture the
8897 * 3) the signed bounds cross zero, so they tell us nothing
8899 * If the value in dst_reg is known nonnegative, then again the
8900 * unsigned bounds capture the signed bounds.
8901 * Thus, in all cases it suffices to blow away our signed bounds
8902 * and rely on inferring new ones from the unsigned bounds and
8903 * var_off of the result.
8905 dst_reg->s32_min_value = S32_MIN;
8906 dst_reg->s32_max_value = S32_MAX;
8908 dst_reg->var_off = tnum_rshift(subreg, umin_val);
8909 dst_reg->u32_min_value >>= umax_val;
8910 dst_reg->u32_max_value >>= umin_val;
8912 __mark_reg64_unbounded(dst_reg);
8913 __update_reg32_bounds(dst_reg);
8916 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8917 struct bpf_reg_state *src_reg)
8919 u64 umax_val = src_reg->umax_value;
8920 u64 umin_val = src_reg->umin_value;
8922 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8923 * be negative, then either:
8924 * 1) src_reg might be zero, so the sign bit of the result is
8925 * unknown, so we lose our signed bounds
8926 * 2) it's known negative, thus the unsigned bounds capture the
8928 * 3) the signed bounds cross zero, so they tell us nothing
8930 * If the value in dst_reg is known nonnegative, then again the
8931 * unsigned bounds capture the signed bounds.
8932 * Thus, in all cases it suffices to blow away our signed bounds
8933 * and rely on inferring new ones from the unsigned bounds and
8934 * var_off of the result.
8936 dst_reg->smin_value = S64_MIN;
8937 dst_reg->smax_value = S64_MAX;
8938 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8939 dst_reg->umin_value >>= umax_val;
8940 dst_reg->umax_value >>= umin_val;
8942 /* Its not easy to operate on alu32 bounds here because it depends
8943 * on bits being shifted in. Take easy way out and mark unbounded
8944 * so we can recalculate later from tnum.
8946 __mark_reg32_unbounded(dst_reg);
8947 __update_reg_bounds(dst_reg);
8950 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8951 struct bpf_reg_state *src_reg)
8953 u64 umin_val = src_reg->u32_min_value;
8955 /* Upon reaching here, src_known is true and
8956 * umax_val is equal to umin_val.
8958 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8959 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8961 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8963 /* blow away the dst_reg umin_value/umax_value and rely on
8964 * dst_reg var_off to refine the result.
8966 dst_reg->u32_min_value = 0;
8967 dst_reg->u32_max_value = U32_MAX;
8969 __mark_reg64_unbounded(dst_reg);
8970 __update_reg32_bounds(dst_reg);
8973 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8974 struct bpf_reg_state *src_reg)
8976 u64 umin_val = src_reg->umin_value;
8978 /* Upon reaching here, src_known is true and umax_val is equal
8981 dst_reg->smin_value >>= umin_val;
8982 dst_reg->smax_value >>= umin_val;
8984 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8986 /* blow away the dst_reg umin_value/umax_value and rely on
8987 * dst_reg var_off to refine the result.
8989 dst_reg->umin_value = 0;
8990 dst_reg->umax_value = U64_MAX;
8992 /* Its not easy to operate on alu32 bounds here because it depends
8993 * on bits being shifted in from upper 32-bits. Take easy way out
8994 * and mark unbounded so we can recalculate later from tnum.
8996 __mark_reg32_unbounded(dst_reg);
8997 __update_reg_bounds(dst_reg);
9000 /* WARNING: This function does calculations on 64-bit values, but the actual
9001 * execution may occur on 32-bit values. Therefore, things like bitshifts
9002 * need extra checks in the 32-bit case.
9004 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9005 struct bpf_insn *insn,
9006 struct bpf_reg_state *dst_reg,
9007 struct bpf_reg_state src_reg)
9009 struct bpf_reg_state *regs = cur_regs(env);
9010 u8 opcode = BPF_OP(insn->code);
9012 s64 smin_val, smax_val;
9013 u64 umin_val, umax_val;
9014 s32 s32_min_val, s32_max_val;
9015 u32 u32_min_val, u32_max_val;
9016 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9017 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9020 smin_val = src_reg.smin_value;
9021 smax_val = src_reg.smax_value;
9022 umin_val = src_reg.umin_value;
9023 umax_val = src_reg.umax_value;
9025 s32_min_val = src_reg.s32_min_value;
9026 s32_max_val = src_reg.s32_max_value;
9027 u32_min_val = src_reg.u32_min_value;
9028 u32_max_val = src_reg.u32_max_value;
9031 src_known = tnum_subreg_is_const(src_reg.var_off);
9033 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9034 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9035 /* Taint dst register if offset had invalid bounds
9036 * derived from e.g. dead branches.
9038 __mark_reg_unknown(env, dst_reg);
9042 src_known = tnum_is_const(src_reg.var_off);
9044 (smin_val != smax_val || umin_val != umax_val)) ||
9045 smin_val > smax_val || umin_val > umax_val) {
9046 /* Taint dst register if offset had invalid bounds
9047 * derived from e.g. dead branches.
9049 __mark_reg_unknown(env, dst_reg);
9055 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9056 __mark_reg_unknown(env, dst_reg);
9060 if (sanitize_needed(opcode)) {
9061 ret = sanitize_val_alu(env, insn);
9063 return sanitize_err(env, insn, ret, NULL, NULL);
9066 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9067 * There are two classes of instructions: The first class we track both
9068 * alu32 and alu64 sign/unsigned bounds independently this provides the
9069 * greatest amount of precision when alu operations are mixed with jmp32
9070 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9071 * and BPF_OR. This is possible because these ops have fairly easy to
9072 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9073 * See alu32 verifier tests for examples. The second class of
9074 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9075 * with regards to tracking sign/unsigned bounds because the bits may
9076 * cross subreg boundaries in the alu64 case. When this happens we mark
9077 * the reg unbounded in the subreg bound space and use the resulting
9078 * tnum to calculate an approximation of the sign/unsigned bounds.
9082 scalar32_min_max_add(dst_reg, &src_reg);
9083 scalar_min_max_add(dst_reg, &src_reg);
9084 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9087 scalar32_min_max_sub(dst_reg, &src_reg);
9088 scalar_min_max_sub(dst_reg, &src_reg);
9089 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9092 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9093 scalar32_min_max_mul(dst_reg, &src_reg);
9094 scalar_min_max_mul(dst_reg, &src_reg);
9097 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9098 scalar32_min_max_and(dst_reg, &src_reg);
9099 scalar_min_max_and(dst_reg, &src_reg);
9102 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9103 scalar32_min_max_or(dst_reg, &src_reg);
9104 scalar_min_max_or(dst_reg, &src_reg);
9107 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9108 scalar32_min_max_xor(dst_reg, &src_reg);
9109 scalar_min_max_xor(dst_reg, &src_reg);
9112 if (umax_val >= insn_bitness) {
9113 /* Shifts greater than 31 or 63 are undefined.
9114 * This includes shifts by a negative number.
9116 mark_reg_unknown(env, regs, insn->dst_reg);
9120 scalar32_min_max_lsh(dst_reg, &src_reg);
9122 scalar_min_max_lsh(dst_reg, &src_reg);
9125 if (umax_val >= insn_bitness) {
9126 /* Shifts greater than 31 or 63 are undefined.
9127 * This includes shifts by a negative number.
9129 mark_reg_unknown(env, regs, insn->dst_reg);
9133 scalar32_min_max_rsh(dst_reg, &src_reg);
9135 scalar_min_max_rsh(dst_reg, &src_reg);
9138 if (umax_val >= insn_bitness) {
9139 /* Shifts greater than 31 or 63 are undefined.
9140 * This includes shifts by a negative number.
9142 mark_reg_unknown(env, regs, insn->dst_reg);
9146 scalar32_min_max_arsh(dst_reg, &src_reg);
9148 scalar_min_max_arsh(dst_reg, &src_reg);
9151 mark_reg_unknown(env, regs, insn->dst_reg);
9155 /* ALU32 ops are zero extended into 64bit register */
9157 zext_32_to_64(dst_reg);
9158 reg_bounds_sync(dst_reg);
9162 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9165 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9166 struct bpf_insn *insn)
9168 struct bpf_verifier_state *vstate = env->cur_state;
9169 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9170 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9171 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9172 u8 opcode = BPF_OP(insn->code);
9175 dst_reg = ®s[insn->dst_reg];
9177 if (dst_reg->type != SCALAR_VALUE)
9180 /* Make sure ID is cleared otherwise dst_reg min/max could be
9181 * incorrectly propagated into other registers by find_equal_scalars()
9184 if (BPF_SRC(insn->code) == BPF_X) {
9185 src_reg = ®s[insn->src_reg];
9186 if (src_reg->type != SCALAR_VALUE) {
9187 if (dst_reg->type != SCALAR_VALUE) {
9188 /* Combining two pointers by any ALU op yields
9189 * an arbitrary scalar. Disallow all math except
9190 * pointer subtraction
9192 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9193 mark_reg_unknown(env, regs, insn->dst_reg);
9196 verbose(env, "R%d pointer %s pointer prohibited\n",
9198 bpf_alu_string[opcode >> 4]);
9201 /* scalar += pointer
9202 * This is legal, but we have to reverse our
9203 * src/dest handling in computing the range
9205 err = mark_chain_precision(env, insn->dst_reg);
9208 return adjust_ptr_min_max_vals(env, insn,
9211 } else if (ptr_reg) {
9212 /* pointer += scalar */
9213 err = mark_chain_precision(env, insn->src_reg);
9216 return adjust_ptr_min_max_vals(env, insn,
9220 /* Pretend the src is a reg with a known value, since we only
9221 * need to be able to read from this state.
9223 off_reg.type = SCALAR_VALUE;
9224 __mark_reg_known(&off_reg, insn->imm);
9226 if (ptr_reg) /* pointer += K */
9227 return adjust_ptr_min_max_vals(env, insn,
9231 /* Got here implies adding two SCALAR_VALUEs */
9232 if (WARN_ON_ONCE(ptr_reg)) {
9233 print_verifier_state(env, state, true);
9234 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9237 if (WARN_ON(!src_reg)) {
9238 print_verifier_state(env, state, true);
9239 verbose(env, "verifier internal error: no src_reg\n");
9242 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9245 /* check validity of 32-bit and 64-bit arithmetic operations */
9246 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9248 struct bpf_reg_state *regs = cur_regs(env);
9249 u8 opcode = BPF_OP(insn->code);
9252 if (opcode == BPF_END || opcode == BPF_NEG) {
9253 if (opcode == BPF_NEG) {
9254 if (BPF_SRC(insn->code) != BPF_K ||
9255 insn->src_reg != BPF_REG_0 ||
9256 insn->off != 0 || insn->imm != 0) {
9257 verbose(env, "BPF_NEG uses reserved fields\n");
9261 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9262 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9263 BPF_CLASS(insn->code) == BPF_ALU64) {
9264 verbose(env, "BPF_END uses reserved fields\n");
9269 /* check src operand */
9270 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9274 if (is_pointer_value(env, insn->dst_reg)) {
9275 verbose(env, "R%d pointer arithmetic prohibited\n",
9280 /* check dest operand */
9281 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9285 } else if (opcode == BPF_MOV) {
9287 if (BPF_SRC(insn->code) == BPF_X) {
9288 if (insn->imm != 0 || insn->off != 0) {
9289 verbose(env, "BPF_MOV uses reserved fields\n");
9293 /* check src operand */
9294 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9298 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9299 verbose(env, "BPF_MOV uses reserved fields\n");
9304 /* check dest operand, mark as required later */
9305 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9309 if (BPF_SRC(insn->code) == BPF_X) {
9310 struct bpf_reg_state *src_reg = regs + insn->src_reg;
9311 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9313 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9315 * copy register state to dest reg
9317 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9318 /* Assign src and dst registers the same ID
9319 * that will be used by find_equal_scalars()
9320 * to propagate min/max range.
9322 src_reg->id = ++env->id_gen;
9323 *dst_reg = *src_reg;
9324 dst_reg->live |= REG_LIVE_WRITTEN;
9325 dst_reg->subreg_def = DEF_NOT_SUBREG;
9328 if (is_pointer_value(env, insn->src_reg)) {
9330 "R%d partial copy of pointer\n",
9333 } else if (src_reg->type == SCALAR_VALUE) {
9334 *dst_reg = *src_reg;
9335 /* Make sure ID is cleared otherwise
9336 * dst_reg min/max could be incorrectly
9337 * propagated into src_reg by find_equal_scalars()
9340 dst_reg->live |= REG_LIVE_WRITTEN;
9341 dst_reg->subreg_def = env->insn_idx + 1;
9343 mark_reg_unknown(env, regs,
9346 zext_32_to_64(dst_reg);
9347 reg_bounds_sync(dst_reg);
9351 * remember the value we stored into this reg
9353 /* clear any state __mark_reg_known doesn't set */
9354 mark_reg_unknown(env, regs, insn->dst_reg);
9355 regs[insn->dst_reg].type = SCALAR_VALUE;
9356 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9357 __mark_reg_known(regs + insn->dst_reg,
9360 __mark_reg_known(regs + insn->dst_reg,
9365 } else if (opcode > BPF_END) {
9366 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9369 } else { /* all other ALU ops: and, sub, xor, add, ... */
9371 if (BPF_SRC(insn->code) == BPF_X) {
9372 if (insn->imm != 0 || insn->off != 0) {
9373 verbose(env, "BPF_ALU uses reserved fields\n");
9376 /* check src1 operand */
9377 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9381 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9382 verbose(env, "BPF_ALU uses reserved fields\n");
9387 /* check src2 operand */
9388 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9392 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9393 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9394 verbose(env, "div by zero\n");
9398 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9399 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9400 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9402 if (insn->imm < 0 || insn->imm >= size) {
9403 verbose(env, "invalid shift %d\n", insn->imm);
9408 /* check dest operand */
9409 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9413 return adjust_reg_min_max_vals(env, insn);
9419 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9420 struct bpf_reg_state *dst_reg,
9421 enum bpf_reg_type type,
9422 bool range_right_open)
9424 struct bpf_func_state *state;
9425 struct bpf_reg_state *reg;
9428 if (dst_reg->off < 0 ||
9429 (dst_reg->off == 0 && range_right_open))
9430 /* This doesn't give us any range */
9433 if (dst_reg->umax_value > MAX_PACKET_OFF ||
9434 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9435 /* Risk of overflow. For instance, ptr + (1<<63) may be less
9436 * than pkt_end, but that's because it's also less than pkt.
9440 new_range = dst_reg->off;
9441 if (range_right_open)
9444 /* Examples for register markings:
9446 * pkt_data in dst register:
9450 * if (r2 > pkt_end) goto <handle exception>
9455 * if (r2 < pkt_end) goto <access okay>
9456 * <handle exception>
9459 * r2 == dst_reg, pkt_end == src_reg
9460 * r2=pkt(id=n,off=8,r=0)
9461 * r3=pkt(id=n,off=0,r=0)
9463 * pkt_data in src register:
9467 * if (pkt_end >= r2) goto <access okay>
9468 * <handle exception>
9472 * if (pkt_end <= r2) goto <handle exception>
9476 * pkt_end == dst_reg, r2 == src_reg
9477 * r2=pkt(id=n,off=8,r=0)
9478 * r3=pkt(id=n,off=0,r=0)
9480 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9481 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9482 * and [r3, r3 + 8-1) respectively is safe to access depending on
9486 /* If our ids match, then we must have the same max_value. And we
9487 * don't care about the other reg's fixed offset, since if it's too big
9488 * the range won't allow anything.
9489 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9491 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9492 if (reg->type == type && reg->id == dst_reg->id)
9493 /* keep the maximum range already checked */
9494 reg->range = max(reg->range, new_range);
9498 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9500 struct tnum subreg = tnum_subreg(reg->var_off);
9501 s32 sval = (s32)val;
9505 if (tnum_is_const(subreg))
9506 return !!tnum_equals_const(subreg, val);
9509 if (tnum_is_const(subreg))
9510 return !tnum_equals_const(subreg, val);
9513 if ((~subreg.mask & subreg.value) & val)
9515 if (!((subreg.mask | subreg.value) & val))
9519 if (reg->u32_min_value > val)
9521 else if (reg->u32_max_value <= val)
9525 if (reg->s32_min_value > sval)
9527 else if (reg->s32_max_value <= sval)
9531 if (reg->u32_max_value < val)
9533 else if (reg->u32_min_value >= val)
9537 if (reg->s32_max_value < sval)
9539 else if (reg->s32_min_value >= sval)
9543 if (reg->u32_min_value >= val)
9545 else if (reg->u32_max_value < val)
9549 if (reg->s32_min_value >= sval)
9551 else if (reg->s32_max_value < sval)
9555 if (reg->u32_max_value <= val)
9557 else if (reg->u32_min_value > val)
9561 if (reg->s32_max_value <= sval)
9563 else if (reg->s32_min_value > sval)
9572 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9574 s64 sval = (s64)val;
9578 if (tnum_is_const(reg->var_off))
9579 return !!tnum_equals_const(reg->var_off, val);
9582 if (tnum_is_const(reg->var_off))
9583 return !tnum_equals_const(reg->var_off, val);
9586 if ((~reg->var_off.mask & reg->var_off.value) & val)
9588 if (!((reg->var_off.mask | reg->var_off.value) & val))
9592 if (reg->umin_value > val)
9594 else if (reg->umax_value <= val)
9598 if (reg->smin_value > sval)
9600 else if (reg->smax_value <= sval)
9604 if (reg->umax_value < val)
9606 else if (reg->umin_value >= val)
9610 if (reg->smax_value < sval)
9612 else if (reg->smin_value >= sval)
9616 if (reg->umin_value >= val)
9618 else if (reg->umax_value < val)
9622 if (reg->smin_value >= sval)
9624 else if (reg->smax_value < sval)
9628 if (reg->umax_value <= val)
9630 else if (reg->umin_value > val)
9634 if (reg->smax_value <= sval)
9636 else if (reg->smin_value > sval)
9644 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9646 * 1 - branch will be taken and "goto target" will be executed
9647 * 0 - branch will not be taken and fall-through to next insn
9648 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9651 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9654 if (__is_pointer_value(false, reg)) {
9655 if (!reg_type_not_null(reg->type))
9658 /* If pointer is valid tests against zero will fail so we can
9659 * use this to direct branch taken.
9675 return is_branch32_taken(reg, val, opcode);
9676 return is_branch64_taken(reg, val, opcode);
9679 static int flip_opcode(u32 opcode)
9681 /* How can we transform "a <op> b" into "b <op> a"? */
9682 static const u8 opcode_flip[16] = {
9683 /* these stay the same */
9684 [BPF_JEQ >> 4] = BPF_JEQ,
9685 [BPF_JNE >> 4] = BPF_JNE,
9686 [BPF_JSET >> 4] = BPF_JSET,
9687 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9688 [BPF_JGE >> 4] = BPF_JLE,
9689 [BPF_JGT >> 4] = BPF_JLT,
9690 [BPF_JLE >> 4] = BPF_JGE,
9691 [BPF_JLT >> 4] = BPF_JGT,
9692 [BPF_JSGE >> 4] = BPF_JSLE,
9693 [BPF_JSGT >> 4] = BPF_JSLT,
9694 [BPF_JSLE >> 4] = BPF_JSGE,
9695 [BPF_JSLT >> 4] = BPF_JSGT
9697 return opcode_flip[opcode >> 4];
9700 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9701 struct bpf_reg_state *src_reg,
9704 struct bpf_reg_state *pkt;
9706 if (src_reg->type == PTR_TO_PACKET_END) {
9708 } else if (dst_reg->type == PTR_TO_PACKET_END) {
9710 opcode = flip_opcode(opcode);
9715 if (pkt->range >= 0)
9720 /* pkt <= pkt_end */
9724 if (pkt->range == BEYOND_PKT_END)
9725 /* pkt has at last one extra byte beyond pkt_end */
9726 return opcode == BPF_JGT;
9732 /* pkt >= pkt_end */
9733 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9734 return opcode == BPF_JGE;
9740 /* Adjusts the register min/max values in the case that the dst_reg is the
9741 * variable register that we are working on, and src_reg is a constant or we're
9742 * simply doing a BPF_K check.
9743 * In JEQ/JNE cases we also adjust the var_off values.
9745 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9746 struct bpf_reg_state *false_reg,
9748 u8 opcode, bool is_jmp32)
9750 struct tnum false_32off = tnum_subreg(false_reg->var_off);
9751 struct tnum false_64off = false_reg->var_off;
9752 struct tnum true_32off = tnum_subreg(true_reg->var_off);
9753 struct tnum true_64off = true_reg->var_off;
9754 s64 sval = (s64)val;
9755 s32 sval32 = (s32)val32;
9757 /* If the dst_reg is a pointer, we can't learn anything about its
9758 * variable offset from the compare (unless src_reg were a pointer into
9759 * the same object, but we don't bother with that.
9760 * Since false_reg and true_reg have the same type by construction, we
9761 * only need to check one of them for pointerness.
9763 if (__is_pointer_value(false, false_reg))
9767 /* JEQ/JNE comparison doesn't change the register equivalence.
9770 * if (r1 == 42) goto label;
9772 * label: // here both r1 and r2 are known to be 42.
9774 * Hence when marking register as known preserve it's ID.
9778 __mark_reg32_known(true_reg, val32);
9779 true_32off = tnum_subreg(true_reg->var_off);
9781 ___mark_reg_known(true_reg, val);
9782 true_64off = true_reg->var_off;
9787 __mark_reg32_known(false_reg, val32);
9788 false_32off = tnum_subreg(false_reg->var_off);
9790 ___mark_reg_known(false_reg, val);
9791 false_64off = false_reg->var_off;
9796 false_32off = tnum_and(false_32off, tnum_const(~val32));
9797 if (is_power_of_2(val32))
9798 true_32off = tnum_or(true_32off,
9801 false_64off = tnum_and(false_64off, tnum_const(~val));
9802 if (is_power_of_2(val))
9803 true_64off = tnum_or(true_64off,
9811 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
9812 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9814 false_reg->u32_max_value = min(false_reg->u32_max_value,
9816 true_reg->u32_min_value = max(true_reg->u32_min_value,
9819 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
9820 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9822 false_reg->umax_value = min(false_reg->umax_value, false_umax);
9823 true_reg->umin_value = max(true_reg->umin_value, true_umin);
9831 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
9832 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9834 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9835 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9837 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
9838 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9840 false_reg->smax_value = min(false_reg->smax_value, false_smax);
9841 true_reg->smin_value = max(true_reg->smin_value, true_smin);
9849 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
9850 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9852 false_reg->u32_min_value = max(false_reg->u32_min_value,
9854 true_reg->u32_max_value = min(true_reg->u32_max_value,
9857 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
9858 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9860 false_reg->umin_value = max(false_reg->umin_value, false_umin);
9861 true_reg->umax_value = min(true_reg->umax_value, true_umax);
9869 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
9870 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9872 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9873 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9875 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
9876 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9878 false_reg->smin_value = max(false_reg->smin_value, false_smin);
9879 true_reg->smax_value = min(true_reg->smax_value, true_smax);
9888 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9889 tnum_subreg(false_32off));
9890 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9891 tnum_subreg(true_32off));
9892 __reg_combine_32_into_64(false_reg);
9893 __reg_combine_32_into_64(true_reg);
9895 false_reg->var_off = false_64off;
9896 true_reg->var_off = true_64off;
9897 __reg_combine_64_into_32(false_reg);
9898 __reg_combine_64_into_32(true_reg);
9902 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9905 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9906 struct bpf_reg_state *false_reg,
9908 u8 opcode, bool is_jmp32)
9910 opcode = flip_opcode(opcode);
9911 /* This uses zero as "not present in table"; luckily the zero opcode,
9912 * BPF_JA, can't get here.
9915 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9918 /* Regs are known to be equal, so intersect their min/max/var_off */
9919 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9920 struct bpf_reg_state *dst_reg)
9922 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9923 dst_reg->umin_value);
9924 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9925 dst_reg->umax_value);
9926 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9927 dst_reg->smin_value);
9928 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9929 dst_reg->smax_value);
9930 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9932 reg_bounds_sync(src_reg);
9933 reg_bounds_sync(dst_reg);
9936 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9937 struct bpf_reg_state *true_dst,
9938 struct bpf_reg_state *false_src,
9939 struct bpf_reg_state *false_dst,
9944 __reg_combine_min_max(true_src, true_dst);
9947 __reg_combine_min_max(false_src, false_dst);
9952 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9953 struct bpf_reg_state *reg, u32 id,
9956 if (type_may_be_null(reg->type) && reg->id == id &&
9957 !WARN_ON_ONCE(!reg->id)) {
9958 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9959 !tnum_equals_const(reg->var_off, 0) ||
9961 /* Old offset (both fixed and variable parts) should
9962 * have been known-zero, because we don't allow pointer
9963 * arithmetic on pointers that might be NULL. If we
9964 * see this happening, don't convert the register.
9969 reg->type = SCALAR_VALUE;
9970 /* We don't need id and ref_obj_id from this point
9971 * onwards anymore, thus we should better reset it,
9972 * so that state pruning has chances to take effect.
9975 reg->ref_obj_id = 0;
9980 mark_ptr_not_null_reg(reg);
9982 if (!reg_may_point_to_spin_lock(reg)) {
9983 /* For not-NULL ptr, reg->ref_obj_id will be reset
9984 * in release_reference().
9986 * reg->id is still used by spin_lock ptr. Other
9987 * than spin_lock ptr type, reg->id can be reset.
9994 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9995 * be folded together at some point.
9997 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
10000 struct bpf_func_state *state = vstate->frame[vstate->curframe];
10001 struct bpf_reg_state *regs = state->regs, *reg;
10002 u32 ref_obj_id = regs[regno].ref_obj_id;
10003 u32 id = regs[regno].id;
10005 if (ref_obj_id && ref_obj_id == id && is_null)
10006 /* regs[regno] is in the " == NULL" branch.
10007 * No one could have freed the reference state before
10008 * doing the NULL check.
10010 WARN_ON_ONCE(release_reference_state(state, id));
10012 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10013 mark_ptr_or_null_reg(state, reg, id, is_null);
10017 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10018 struct bpf_reg_state *dst_reg,
10019 struct bpf_reg_state *src_reg,
10020 struct bpf_verifier_state *this_branch,
10021 struct bpf_verifier_state *other_branch)
10023 if (BPF_SRC(insn->code) != BPF_X)
10026 /* Pointers are always 64-bit. */
10027 if (BPF_CLASS(insn->code) == BPF_JMP32)
10030 switch (BPF_OP(insn->code)) {
10032 if ((dst_reg->type == PTR_TO_PACKET &&
10033 src_reg->type == PTR_TO_PACKET_END) ||
10034 (dst_reg->type == PTR_TO_PACKET_META &&
10035 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10036 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10037 find_good_pkt_pointers(this_branch, dst_reg,
10038 dst_reg->type, false);
10039 mark_pkt_end(other_branch, insn->dst_reg, true);
10040 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10041 src_reg->type == PTR_TO_PACKET) ||
10042 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10043 src_reg->type == PTR_TO_PACKET_META)) {
10044 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
10045 find_good_pkt_pointers(other_branch, src_reg,
10046 src_reg->type, true);
10047 mark_pkt_end(this_branch, insn->src_reg, false);
10053 if ((dst_reg->type == PTR_TO_PACKET &&
10054 src_reg->type == PTR_TO_PACKET_END) ||
10055 (dst_reg->type == PTR_TO_PACKET_META &&
10056 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10057 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10058 find_good_pkt_pointers(other_branch, dst_reg,
10059 dst_reg->type, true);
10060 mark_pkt_end(this_branch, insn->dst_reg, false);
10061 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10062 src_reg->type == PTR_TO_PACKET) ||
10063 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10064 src_reg->type == PTR_TO_PACKET_META)) {
10065 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
10066 find_good_pkt_pointers(this_branch, src_reg,
10067 src_reg->type, false);
10068 mark_pkt_end(other_branch, insn->src_reg, true);
10074 if ((dst_reg->type == PTR_TO_PACKET &&
10075 src_reg->type == PTR_TO_PACKET_END) ||
10076 (dst_reg->type == PTR_TO_PACKET_META &&
10077 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10078 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10079 find_good_pkt_pointers(this_branch, dst_reg,
10080 dst_reg->type, true);
10081 mark_pkt_end(other_branch, insn->dst_reg, false);
10082 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10083 src_reg->type == PTR_TO_PACKET) ||
10084 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10085 src_reg->type == PTR_TO_PACKET_META)) {
10086 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10087 find_good_pkt_pointers(other_branch, src_reg,
10088 src_reg->type, false);
10089 mark_pkt_end(this_branch, insn->src_reg, true);
10095 if ((dst_reg->type == PTR_TO_PACKET &&
10096 src_reg->type == PTR_TO_PACKET_END) ||
10097 (dst_reg->type == PTR_TO_PACKET_META &&
10098 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10099 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10100 find_good_pkt_pointers(other_branch, dst_reg,
10101 dst_reg->type, false);
10102 mark_pkt_end(this_branch, insn->dst_reg, true);
10103 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10104 src_reg->type == PTR_TO_PACKET) ||
10105 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10106 src_reg->type == PTR_TO_PACKET_META)) {
10107 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10108 find_good_pkt_pointers(this_branch, src_reg,
10109 src_reg->type, true);
10110 mark_pkt_end(other_branch, insn->src_reg, false);
10122 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10123 struct bpf_reg_state *known_reg)
10125 struct bpf_func_state *state;
10126 struct bpf_reg_state *reg;
10128 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10129 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10134 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10135 struct bpf_insn *insn, int *insn_idx)
10137 struct bpf_verifier_state *this_branch = env->cur_state;
10138 struct bpf_verifier_state *other_branch;
10139 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10140 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10141 u8 opcode = BPF_OP(insn->code);
10146 /* Only conditional jumps are expected to reach here. */
10147 if (opcode == BPF_JA || opcode > BPF_JSLE) {
10148 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10152 if (BPF_SRC(insn->code) == BPF_X) {
10153 if (insn->imm != 0) {
10154 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10158 /* check src1 operand */
10159 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10163 if (is_pointer_value(env, insn->src_reg)) {
10164 verbose(env, "R%d pointer comparison prohibited\n",
10168 src_reg = ®s[insn->src_reg];
10170 if (insn->src_reg != BPF_REG_0) {
10171 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10176 /* check src2 operand */
10177 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10181 dst_reg = ®s[insn->dst_reg];
10182 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10184 if (BPF_SRC(insn->code) == BPF_K) {
10185 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10186 } else if (src_reg->type == SCALAR_VALUE &&
10187 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10188 pred = is_branch_taken(dst_reg,
10189 tnum_subreg(src_reg->var_off).value,
10192 } else if (src_reg->type == SCALAR_VALUE &&
10193 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10194 pred = is_branch_taken(dst_reg,
10195 src_reg->var_off.value,
10198 } else if (reg_is_pkt_pointer_any(dst_reg) &&
10199 reg_is_pkt_pointer_any(src_reg) &&
10201 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10205 /* If we get here with a dst_reg pointer type it is because
10206 * above is_branch_taken() special cased the 0 comparison.
10208 if (!__is_pointer_value(false, dst_reg))
10209 err = mark_chain_precision(env, insn->dst_reg);
10210 if (BPF_SRC(insn->code) == BPF_X && !err &&
10211 !__is_pointer_value(false, src_reg))
10212 err = mark_chain_precision(env, insn->src_reg);
10218 /* Only follow the goto, ignore fall-through. If needed, push
10219 * the fall-through branch for simulation under speculative
10222 if (!env->bypass_spec_v1 &&
10223 !sanitize_speculative_path(env, insn, *insn_idx + 1,
10226 *insn_idx += insn->off;
10228 } else if (pred == 0) {
10229 /* Only follow the fall-through branch, since that's where the
10230 * program will go. If needed, push the goto branch for
10231 * simulation under speculative execution.
10233 if (!env->bypass_spec_v1 &&
10234 !sanitize_speculative_path(env, insn,
10235 *insn_idx + insn->off + 1,
10241 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10245 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10247 /* detect if we are comparing against a constant value so we can adjust
10248 * our min/max values for our dst register.
10249 * this is only legit if both are scalars (or pointers to the same
10250 * object, I suppose, but we don't support that right now), because
10251 * otherwise the different base pointers mean the offsets aren't
10254 if (BPF_SRC(insn->code) == BPF_X) {
10255 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
10257 if (dst_reg->type == SCALAR_VALUE &&
10258 src_reg->type == SCALAR_VALUE) {
10259 if (tnum_is_const(src_reg->var_off) ||
10261 tnum_is_const(tnum_subreg(src_reg->var_off))))
10262 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10264 src_reg->var_off.value,
10265 tnum_subreg(src_reg->var_off).value,
10267 else if (tnum_is_const(dst_reg->var_off) ||
10269 tnum_is_const(tnum_subreg(dst_reg->var_off))))
10270 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10272 dst_reg->var_off.value,
10273 tnum_subreg(dst_reg->var_off).value,
10275 else if (!is_jmp32 &&
10276 (opcode == BPF_JEQ || opcode == BPF_JNE))
10277 /* Comparing for equality, we can combine knowledge */
10278 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10279 &other_branch_regs[insn->dst_reg],
10280 src_reg, dst_reg, opcode);
10282 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10283 find_equal_scalars(this_branch, src_reg);
10284 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10288 } else if (dst_reg->type == SCALAR_VALUE) {
10289 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10290 dst_reg, insn->imm, (u32)insn->imm,
10294 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10295 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10296 find_equal_scalars(this_branch, dst_reg);
10297 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10300 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10301 * NOTE: these optimizations below are related with pointer comparison
10302 * which will never be JMP32.
10304 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10305 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10306 type_may_be_null(dst_reg->type)) {
10307 /* Mark all identical registers in each branch as either
10308 * safe or unknown depending R == 0 or R != 0 conditional.
10310 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10311 opcode == BPF_JNE);
10312 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10313 opcode == BPF_JEQ);
10314 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
10315 this_branch, other_branch) &&
10316 is_pointer_value(env, insn->dst_reg)) {
10317 verbose(env, "R%d pointer comparison prohibited\n",
10321 if (env->log.level & BPF_LOG_LEVEL)
10322 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10326 /* verify BPF_LD_IMM64 instruction */
10327 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10329 struct bpf_insn_aux_data *aux = cur_aux(env);
10330 struct bpf_reg_state *regs = cur_regs(env);
10331 struct bpf_reg_state *dst_reg;
10332 struct bpf_map *map;
10335 if (BPF_SIZE(insn->code) != BPF_DW) {
10336 verbose(env, "invalid BPF_LD_IMM insn\n");
10339 if (insn->off != 0) {
10340 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10344 err = check_reg_arg(env, insn->dst_reg, DST_OP);
10348 dst_reg = ®s[insn->dst_reg];
10349 if (insn->src_reg == 0) {
10350 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10352 dst_reg->type = SCALAR_VALUE;
10353 __mark_reg_known(®s[insn->dst_reg], imm);
10357 /* All special src_reg cases are listed below. From this point onwards
10358 * we either succeed and assign a corresponding dst_reg->type after
10359 * zeroing the offset, or fail and reject the program.
10361 mark_reg_known_zero(env, regs, insn->dst_reg);
10363 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10364 dst_reg->type = aux->btf_var.reg_type;
10365 switch (base_type(dst_reg->type)) {
10367 dst_reg->mem_size = aux->btf_var.mem_size;
10369 case PTR_TO_BTF_ID:
10370 dst_reg->btf = aux->btf_var.btf;
10371 dst_reg->btf_id = aux->btf_var.btf_id;
10374 verbose(env, "bpf verifier is misconfigured\n");
10380 if (insn->src_reg == BPF_PSEUDO_FUNC) {
10381 struct bpf_prog_aux *aux = env->prog->aux;
10382 u32 subprogno = find_subprog(env,
10383 env->insn_idx + insn->imm + 1);
10385 if (!aux->func_info) {
10386 verbose(env, "missing btf func_info\n");
10389 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10390 verbose(env, "callback function not static\n");
10394 dst_reg->type = PTR_TO_FUNC;
10395 dst_reg->subprogno = subprogno;
10399 map = env->used_maps[aux->map_index];
10400 dst_reg->map_ptr = map;
10402 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10403 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10404 dst_reg->type = PTR_TO_MAP_VALUE;
10405 dst_reg->off = aux->map_off;
10406 if (map_value_has_spin_lock(map))
10407 dst_reg->id = ++env->id_gen;
10408 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10409 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10410 dst_reg->type = CONST_PTR_TO_MAP;
10412 verbose(env, "bpf verifier is misconfigured\n");
10419 static bool may_access_skb(enum bpf_prog_type type)
10422 case BPF_PROG_TYPE_SOCKET_FILTER:
10423 case BPF_PROG_TYPE_SCHED_CLS:
10424 case BPF_PROG_TYPE_SCHED_ACT:
10431 /* verify safety of LD_ABS|LD_IND instructions:
10432 * - they can only appear in the programs where ctx == skb
10433 * - since they are wrappers of function calls, they scratch R1-R5 registers,
10434 * preserve R6-R9, and store return value into R0
10437 * ctx == skb == R6 == CTX
10440 * SRC == any register
10441 * IMM == 32-bit immediate
10444 * R0 - 8/16/32-bit skb data converted to cpu endianness
10446 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10448 struct bpf_reg_state *regs = cur_regs(env);
10449 static const int ctx_reg = BPF_REG_6;
10450 u8 mode = BPF_MODE(insn->code);
10453 if (!may_access_skb(resolve_prog_type(env->prog))) {
10454 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10458 if (!env->ops->gen_ld_abs) {
10459 verbose(env, "bpf verifier is misconfigured\n");
10463 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10464 BPF_SIZE(insn->code) == BPF_DW ||
10465 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10466 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10470 /* check whether implicit source operand (register R6) is readable */
10471 err = check_reg_arg(env, ctx_reg, SRC_OP);
10475 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10476 * gen_ld_abs() may terminate the program at runtime, leading to
10479 err = check_reference_leak(env);
10481 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10485 if (env->cur_state->active_spin_lock) {
10486 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10490 if (regs[ctx_reg].type != PTR_TO_CTX) {
10492 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10496 if (mode == BPF_IND) {
10497 /* check explicit source operand */
10498 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10503 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
10507 /* reset caller saved regs to unreadable */
10508 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10509 mark_reg_not_init(env, regs, caller_saved[i]);
10510 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10513 /* mark destination R0 register as readable, since it contains
10514 * the value fetched from the packet.
10515 * Already marked as written above.
10517 mark_reg_unknown(env, regs, BPF_REG_0);
10518 /* ld_abs load up to 32-bit skb data. */
10519 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10523 static int check_return_code(struct bpf_verifier_env *env)
10525 struct tnum enforce_attach_type_range = tnum_unknown;
10526 const struct bpf_prog *prog = env->prog;
10527 struct bpf_reg_state *reg;
10528 struct tnum range = tnum_range(0, 1);
10529 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10531 struct bpf_func_state *frame = env->cur_state->frame[0];
10532 const bool is_subprog = frame->subprogno;
10534 /* LSM and struct_ops func-ptr's return type could be "void" */
10536 switch (prog_type) {
10537 case BPF_PROG_TYPE_LSM:
10538 if (prog->expected_attach_type == BPF_LSM_CGROUP)
10539 /* See below, can be 0 or 0-1 depending on hook. */
10542 case BPF_PROG_TYPE_STRUCT_OPS:
10543 if (!prog->aux->attach_func_proto->type)
10551 /* eBPF calling convention is such that R0 is used
10552 * to return the value from eBPF program.
10553 * Make sure that it's readable at this time
10554 * of bpf_exit, which means that program wrote
10555 * something into it earlier
10557 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10561 if (is_pointer_value(env, BPF_REG_0)) {
10562 verbose(env, "R0 leaks addr as return value\n");
10566 reg = cur_regs(env) + BPF_REG_0;
10568 if (frame->in_async_callback_fn) {
10569 /* enforce return zero from async callbacks like timer */
10570 if (reg->type != SCALAR_VALUE) {
10571 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10572 reg_type_str(env, reg->type));
10576 if (!tnum_in(tnum_const(0), reg->var_off)) {
10577 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10584 if (reg->type != SCALAR_VALUE) {
10585 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10586 reg_type_str(env, reg->type));
10592 switch (prog_type) {
10593 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10594 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10595 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10596 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10597 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10598 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10599 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10600 range = tnum_range(1, 1);
10601 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10602 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10603 range = tnum_range(0, 3);
10605 case BPF_PROG_TYPE_CGROUP_SKB:
10606 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10607 range = tnum_range(0, 3);
10608 enforce_attach_type_range = tnum_range(2, 3);
10611 case BPF_PROG_TYPE_CGROUP_SOCK:
10612 case BPF_PROG_TYPE_SOCK_OPS:
10613 case BPF_PROG_TYPE_CGROUP_DEVICE:
10614 case BPF_PROG_TYPE_CGROUP_SYSCTL:
10615 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10617 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10618 if (!env->prog->aux->attach_btf_id)
10620 range = tnum_const(0);
10622 case BPF_PROG_TYPE_TRACING:
10623 switch (env->prog->expected_attach_type) {
10624 case BPF_TRACE_FENTRY:
10625 case BPF_TRACE_FEXIT:
10626 range = tnum_const(0);
10628 case BPF_TRACE_RAW_TP:
10629 case BPF_MODIFY_RETURN:
10631 case BPF_TRACE_ITER:
10637 case BPF_PROG_TYPE_SK_LOOKUP:
10638 range = tnum_range(SK_DROP, SK_PASS);
10641 case BPF_PROG_TYPE_LSM:
10642 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10643 /* Regular BPF_PROG_TYPE_LSM programs can return
10648 if (!env->prog->aux->attach_func_proto->type) {
10649 /* Make sure programs that attach to void
10650 * hooks don't try to modify return value.
10652 range = tnum_range(1, 1);
10656 case BPF_PROG_TYPE_EXT:
10657 /* freplace program can return anything as its return value
10658 * depends on the to-be-replaced kernel func or bpf program.
10664 if (reg->type != SCALAR_VALUE) {
10665 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10666 reg_type_str(env, reg->type));
10670 if (!tnum_in(range, reg->var_off)) {
10671 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10672 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10673 prog_type == BPF_PROG_TYPE_LSM &&
10674 !prog->aux->attach_func_proto->type)
10675 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10679 if (!tnum_is_unknown(enforce_attach_type_range) &&
10680 tnum_in(enforce_attach_type_range, reg->var_off))
10681 env->prog->enforce_expected_attach_type = 1;
10685 /* non-recursive DFS pseudo code
10686 * 1 procedure DFS-iterative(G,v):
10687 * 2 label v as discovered
10688 * 3 let S be a stack
10690 * 5 while S is not empty
10692 * 7 if t is what we're looking for:
10694 * 9 for all edges e in G.adjacentEdges(t) do
10695 * 10 if edge e is already labelled
10696 * 11 continue with the next edge
10697 * 12 w <- G.adjacentVertex(t,e)
10698 * 13 if vertex w is not discovered and not explored
10699 * 14 label e as tree-edge
10700 * 15 label w as discovered
10703 * 18 else if vertex w is discovered
10704 * 19 label e as back-edge
10706 * 21 // vertex w is explored
10707 * 22 label e as forward- or cross-edge
10708 * 23 label t as explored
10712 * 0x10 - discovered
10713 * 0x11 - discovered and fall-through edge labelled
10714 * 0x12 - discovered and fall-through and branch edges labelled
10725 static u32 state_htab_size(struct bpf_verifier_env *env)
10727 return env->prog->len;
10730 static struct bpf_verifier_state_list **explored_state(
10731 struct bpf_verifier_env *env,
10734 struct bpf_verifier_state *cur = env->cur_state;
10735 struct bpf_func_state *state = cur->frame[cur->curframe];
10737 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10740 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10742 env->insn_aux_data[idx].prune_point = true;
10746 DONE_EXPLORING = 0,
10747 KEEP_EXPLORING = 1,
10750 /* t, w, e - match pseudo-code above:
10751 * t - index of current instruction
10752 * w - next instruction
10755 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10758 int *insn_stack = env->cfg.insn_stack;
10759 int *insn_state = env->cfg.insn_state;
10761 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10762 return DONE_EXPLORING;
10764 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10765 return DONE_EXPLORING;
10767 if (w < 0 || w >= env->prog->len) {
10768 verbose_linfo(env, t, "%d: ", t);
10769 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10774 /* mark branch target for state pruning */
10775 init_explored_state(env, w);
10777 if (insn_state[w] == 0) {
10779 insn_state[t] = DISCOVERED | e;
10780 insn_state[w] = DISCOVERED;
10781 if (env->cfg.cur_stack >= env->prog->len)
10783 insn_stack[env->cfg.cur_stack++] = w;
10784 return KEEP_EXPLORING;
10785 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10786 if (loop_ok && env->bpf_capable)
10787 return DONE_EXPLORING;
10788 verbose_linfo(env, t, "%d: ", t);
10789 verbose_linfo(env, w, "%d: ", w);
10790 verbose(env, "back-edge from insn %d to %d\n", t, w);
10792 } else if (insn_state[w] == EXPLORED) {
10793 /* forward- or cross-edge */
10794 insn_state[t] = DISCOVERED | e;
10796 verbose(env, "insn state internal bug\n");
10799 return DONE_EXPLORING;
10802 static int visit_func_call_insn(int t, int insn_cnt,
10803 struct bpf_insn *insns,
10804 struct bpf_verifier_env *env,
10809 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10813 if (t + 1 < insn_cnt)
10814 init_explored_state(env, t + 1);
10815 if (visit_callee) {
10816 init_explored_state(env, t);
10817 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10818 /* It's ok to allow recursion from CFG point of
10819 * view. __check_func_call() will do the actual
10822 bpf_pseudo_func(insns + t));
10827 /* Visits the instruction at index t and returns one of the following:
10828 * < 0 - an error occurred
10829 * DONE_EXPLORING - the instruction was fully explored
10830 * KEEP_EXPLORING - there is still work to be done before it is fully explored
10832 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10834 struct bpf_insn *insns = env->prog->insnsi;
10837 if (bpf_pseudo_func(insns + t))
10838 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10840 /* All non-branch instructions have a single fall-through edge. */
10841 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10842 BPF_CLASS(insns[t].code) != BPF_JMP32)
10843 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10845 switch (BPF_OP(insns[t].code)) {
10847 return DONE_EXPLORING;
10850 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10851 /* Mark this call insn to trigger is_state_visited() check
10852 * before call itself is processed by __check_func_call().
10853 * Otherwise new async state will be pushed for further
10856 init_explored_state(env, t);
10857 return visit_func_call_insn(t, insn_cnt, insns, env,
10858 insns[t].src_reg == BPF_PSEUDO_CALL);
10861 if (BPF_SRC(insns[t].code) != BPF_K)
10864 /* unconditional jump with single edge */
10865 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10870 /* unconditional jmp is not a good pruning point,
10871 * but it's marked, since backtracking needs
10872 * to record jmp history in is_state_visited().
10874 init_explored_state(env, t + insns[t].off + 1);
10875 /* tell verifier to check for equivalent states
10876 * after every call and jump
10878 if (t + 1 < insn_cnt)
10879 init_explored_state(env, t + 1);
10884 /* conditional jump with two edges */
10885 init_explored_state(env, t);
10886 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10890 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10894 /* non-recursive depth-first-search to detect loops in BPF program
10895 * loop == back-edge in directed graph
10897 static int check_cfg(struct bpf_verifier_env *env)
10899 int insn_cnt = env->prog->len;
10900 int *insn_stack, *insn_state;
10904 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10908 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10910 kvfree(insn_state);
10914 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10915 insn_stack[0] = 0; /* 0 is the first instruction */
10916 env->cfg.cur_stack = 1;
10918 while (env->cfg.cur_stack > 0) {
10919 int t = insn_stack[env->cfg.cur_stack - 1];
10921 ret = visit_insn(t, insn_cnt, env);
10923 case DONE_EXPLORING:
10924 insn_state[t] = EXPLORED;
10925 env->cfg.cur_stack--;
10927 case KEEP_EXPLORING:
10931 verbose(env, "visit_insn internal bug\n");
10938 if (env->cfg.cur_stack < 0) {
10939 verbose(env, "pop stack internal bug\n");
10944 for (i = 0; i < insn_cnt; i++) {
10945 if (insn_state[i] != EXPLORED) {
10946 verbose(env, "unreachable insn %d\n", i);
10951 ret = 0; /* cfg looks good */
10954 kvfree(insn_state);
10955 kvfree(insn_stack);
10956 env->cfg.insn_state = env->cfg.insn_stack = NULL;
10960 static int check_abnormal_return(struct bpf_verifier_env *env)
10964 for (i = 1; i < env->subprog_cnt; i++) {
10965 if (env->subprog_info[i].has_ld_abs) {
10966 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10969 if (env->subprog_info[i].has_tail_call) {
10970 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10977 /* The minimum supported BTF func info size */
10978 #define MIN_BPF_FUNCINFO_SIZE 8
10979 #define MAX_FUNCINFO_REC_SIZE 252
10981 static int check_btf_func(struct bpf_verifier_env *env,
10982 const union bpf_attr *attr,
10985 const struct btf_type *type, *func_proto, *ret_type;
10986 u32 i, nfuncs, urec_size, min_size;
10987 u32 krec_size = sizeof(struct bpf_func_info);
10988 struct bpf_func_info *krecord;
10989 struct bpf_func_info_aux *info_aux = NULL;
10990 struct bpf_prog *prog;
10991 const struct btf *btf;
10993 u32 prev_offset = 0;
10994 bool scalar_return;
10997 nfuncs = attr->func_info_cnt;
10999 if (check_abnormal_return(env))
11004 if (nfuncs != env->subprog_cnt) {
11005 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11009 urec_size = attr->func_info_rec_size;
11010 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11011 urec_size > MAX_FUNCINFO_REC_SIZE ||
11012 urec_size % sizeof(u32)) {
11013 verbose(env, "invalid func info rec size %u\n", urec_size);
11018 btf = prog->aux->btf;
11020 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11021 min_size = min_t(u32, krec_size, urec_size);
11023 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11026 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11030 for (i = 0; i < nfuncs; i++) {
11031 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11033 if (ret == -E2BIG) {
11034 verbose(env, "nonzero tailing record in func info");
11035 /* set the size kernel expects so loader can zero
11036 * out the rest of the record.
11038 if (copy_to_bpfptr_offset(uattr,
11039 offsetof(union bpf_attr, func_info_rec_size),
11040 &min_size, sizeof(min_size)))
11046 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11051 /* check insn_off */
11054 if (krecord[i].insn_off) {
11056 "nonzero insn_off %u for the first func info record",
11057 krecord[i].insn_off);
11060 } else if (krecord[i].insn_off <= prev_offset) {
11062 "same or smaller insn offset (%u) than previous func info record (%u)",
11063 krecord[i].insn_off, prev_offset);
11067 if (env->subprog_info[i].start != krecord[i].insn_off) {
11068 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11072 /* check type_id */
11073 type = btf_type_by_id(btf, krecord[i].type_id);
11074 if (!type || !btf_type_is_func(type)) {
11075 verbose(env, "invalid type id %d in func info",
11076 krecord[i].type_id);
11079 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11081 func_proto = btf_type_by_id(btf, type->type);
11082 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11083 /* btf_func_check() already verified it during BTF load */
11085 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11087 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11088 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11089 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11092 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11093 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11097 prev_offset = krecord[i].insn_off;
11098 bpfptr_add(&urecord, urec_size);
11101 prog->aux->func_info = krecord;
11102 prog->aux->func_info_cnt = nfuncs;
11103 prog->aux->func_info_aux = info_aux;
11112 static void adjust_btf_func(struct bpf_verifier_env *env)
11114 struct bpf_prog_aux *aux = env->prog->aux;
11117 if (!aux->func_info)
11120 for (i = 0; i < env->subprog_cnt; i++)
11121 aux->func_info[i].insn_off = env->subprog_info[i].start;
11124 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
11125 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
11127 static int check_btf_line(struct bpf_verifier_env *env,
11128 const union bpf_attr *attr,
11131 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11132 struct bpf_subprog_info *sub;
11133 struct bpf_line_info *linfo;
11134 struct bpf_prog *prog;
11135 const struct btf *btf;
11139 nr_linfo = attr->line_info_cnt;
11142 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11145 rec_size = attr->line_info_rec_size;
11146 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11147 rec_size > MAX_LINEINFO_REC_SIZE ||
11148 rec_size & (sizeof(u32) - 1))
11151 /* Need to zero it in case the userspace may
11152 * pass in a smaller bpf_line_info object.
11154 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11155 GFP_KERNEL | __GFP_NOWARN);
11160 btf = prog->aux->btf;
11163 sub = env->subprog_info;
11164 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11165 expected_size = sizeof(struct bpf_line_info);
11166 ncopy = min_t(u32, expected_size, rec_size);
11167 for (i = 0; i < nr_linfo; i++) {
11168 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11170 if (err == -E2BIG) {
11171 verbose(env, "nonzero tailing record in line_info");
11172 if (copy_to_bpfptr_offset(uattr,
11173 offsetof(union bpf_attr, line_info_rec_size),
11174 &expected_size, sizeof(expected_size)))
11180 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11186 * Check insn_off to ensure
11187 * 1) strictly increasing AND
11188 * 2) bounded by prog->len
11190 * The linfo[0].insn_off == 0 check logically falls into
11191 * the later "missing bpf_line_info for func..." case
11192 * because the first linfo[0].insn_off must be the
11193 * first sub also and the first sub must have
11194 * subprog_info[0].start == 0.
11196 if ((i && linfo[i].insn_off <= prev_offset) ||
11197 linfo[i].insn_off >= prog->len) {
11198 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11199 i, linfo[i].insn_off, prev_offset,
11205 if (!prog->insnsi[linfo[i].insn_off].code) {
11207 "Invalid insn code at line_info[%u].insn_off\n",
11213 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11214 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11215 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11220 if (s != env->subprog_cnt) {
11221 if (linfo[i].insn_off == sub[s].start) {
11222 sub[s].linfo_idx = i;
11224 } else if (sub[s].start < linfo[i].insn_off) {
11225 verbose(env, "missing bpf_line_info for func#%u\n", s);
11231 prev_offset = linfo[i].insn_off;
11232 bpfptr_add(&ulinfo, rec_size);
11235 if (s != env->subprog_cnt) {
11236 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11237 env->subprog_cnt - s, s);
11242 prog->aux->linfo = linfo;
11243 prog->aux->nr_linfo = nr_linfo;
11252 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
11253 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
11255 static int check_core_relo(struct bpf_verifier_env *env,
11256 const union bpf_attr *attr,
11259 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11260 struct bpf_core_relo core_relo = {};
11261 struct bpf_prog *prog = env->prog;
11262 const struct btf *btf = prog->aux->btf;
11263 struct bpf_core_ctx ctx = {
11267 bpfptr_t u_core_relo;
11270 nr_core_relo = attr->core_relo_cnt;
11273 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11276 rec_size = attr->core_relo_rec_size;
11277 if (rec_size < MIN_CORE_RELO_SIZE ||
11278 rec_size > MAX_CORE_RELO_SIZE ||
11279 rec_size % sizeof(u32))
11282 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11283 expected_size = sizeof(struct bpf_core_relo);
11284 ncopy = min_t(u32, expected_size, rec_size);
11286 /* Unlike func_info and line_info, copy and apply each CO-RE
11287 * relocation record one at a time.
11289 for (i = 0; i < nr_core_relo; i++) {
11290 /* future proofing when sizeof(bpf_core_relo) changes */
11291 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11293 if (err == -E2BIG) {
11294 verbose(env, "nonzero tailing record in core_relo");
11295 if (copy_to_bpfptr_offset(uattr,
11296 offsetof(union bpf_attr, core_relo_rec_size),
11297 &expected_size, sizeof(expected_size)))
11303 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11308 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11309 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11310 i, core_relo.insn_off, prog->len);
11315 err = bpf_core_apply(&ctx, &core_relo, i,
11316 &prog->insnsi[core_relo.insn_off / 8]);
11319 bpfptr_add(&u_core_relo, rec_size);
11324 static int check_btf_info(struct bpf_verifier_env *env,
11325 const union bpf_attr *attr,
11331 if (!attr->func_info_cnt && !attr->line_info_cnt) {
11332 if (check_abnormal_return(env))
11337 btf = btf_get_by_fd(attr->prog_btf_fd);
11339 return PTR_ERR(btf);
11340 if (btf_is_kernel(btf)) {
11344 env->prog->aux->btf = btf;
11346 err = check_btf_func(env, attr, uattr);
11350 err = check_btf_line(env, attr, uattr);
11354 err = check_core_relo(env, attr, uattr);
11361 /* check %cur's range satisfies %old's */
11362 static bool range_within(struct bpf_reg_state *old,
11363 struct bpf_reg_state *cur)
11365 return old->umin_value <= cur->umin_value &&
11366 old->umax_value >= cur->umax_value &&
11367 old->smin_value <= cur->smin_value &&
11368 old->smax_value >= cur->smax_value &&
11369 old->u32_min_value <= cur->u32_min_value &&
11370 old->u32_max_value >= cur->u32_max_value &&
11371 old->s32_min_value <= cur->s32_min_value &&
11372 old->s32_max_value >= cur->s32_max_value;
11375 /* If in the old state two registers had the same id, then they need to have
11376 * the same id in the new state as well. But that id could be different from
11377 * the old state, so we need to track the mapping from old to new ids.
11378 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11379 * regs with old id 5 must also have new id 9 for the new state to be safe. But
11380 * regs with a different old id could still have new id 9, we don't care about
11382 * So we look through our idmap to see if this old id has been seen before. If
11383 * so, we require the new id to match; otherwise, we add the id pair to the map.
11385 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11389 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11390 if (!idmap[i].old) {
11391 /* Reached an empty slot; haven't seen this id before */
11392 idmap[i].old = old_id;
11393 idmap[i].cur = cur_id;
11396 if (idmap[i].old == old_id)
11397 return idmap[i].cur == cur_id;
11399 /* We ran out of idmap slots, which should be impossible */
11404 static void clean_func_state(struct bpf_verifier_env *env,
11405 struct bpf_func_state *st)
11407 enum bpf_reg_liveness live;
11410 for (i = 0; i < BPF_REG_FP; i++) {
11411 live = st->regs[i].live;
11412 /* liveness must not touch this register anymore */
11413 st->regs[i].live |= REG_LIVE_DONE;
11414 if (!(live & REG_LIVE_READ))
11415 /* since the register is unused, clear its state
11416 * to make further comparison simpler
11418 __mark_reg_not_init(env, &st->regs[i]);
11421 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11422 live = st->stack[i].spilled_ptr.live;
11423 /* liveness must not touch this stack slot anymore */
11424 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11425 if (!(live & REG_LIVE_READ)) {
11426 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11427 for (j = 0; j < BPF_REG_SIZE; j++)
11428 st->stack[i].slot_type[j] = STACK_INVALID;
11433 static void clean_verifier_state(struct bpf_verifier_env *env,
11434 struct bpf_verifier_state *st)
11438 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11439 /* all regs in this state in all frames were already marked */
11442 for (i = 0; i <= st->curframe; i++)
11443 clean_func_state(env, st->frame[i]);
11446 /* the parentage chains form a tree.
11447 * the verifier states are added to state lists at given insn and
11448 * pushed into state stack for future exploration.
11449 * when the verifier reaches bpf_exit insn some of the verifer states
11450 * stored in the state lists have their final liveness state already,
11451 * but a lot of states will get revised from liveness point of view when
11452 * the verifier explores other branches.
11455 * 2: if r1 == 100 goto pc+1
11458 * when the verifier reaches exit insn the register r0 in the state list of
11459 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11460 * of insn 2 and goes exploring further. At the insn 4 it will walk the
11461 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11463 * Since the verifier pushes the branch states as it sees them while exploring
11464 * the program the condition of walking the branch instruction for the second
11465 * time means that all states below this branch were already explored and
11466 * their final liveness marks are already propagated.
11467 * Hence when the verifier completes the search of state list in is_state_visited()
11468 * we can call this clean_live_states() function to mark all liveness states
11469 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11470 * will not be used.
11471 * This function also clears the registers and stack for states that !READ
11472 * to simplify state merging.
11474 * Important note here that walking the same branch instruction in the callee
11475 * doesn't meant that the states are DONE. The verifier has to compare
11478 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11479 struct bpf_verifier_state *cur)
11481 struct bpf_verifier_state_list *sl;
11484 sl = *explored_state(env, insn);
11486 if (sl->state.branches)
11488 if (sl->state.insn_idx != insn ||
11489 sl->state.curframe != cur->curframe)
11491 for (i = 0; i <= cur->curframe; i++)
11492 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11494 clean_verifier_state(env, &sl->state);
11500 /* Returns true if (rold safe implies rcur safe) */
11501 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11502 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11506 if (!(rold->live & REG_LIVE_READ))
11507 /* explored state didn't use this */
11510 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11512 if (rold->type == PTR_TO_STACK)
11513 /* two stack pointers are equal only if they're pointing to
11514 * the same stack frame, since fp-8 in foo != fp-8 in bar
11516 return equal && rold->frameno == rcur->frameno;
11521 if (rold->type == NOT_INIT)
11522 /* explored state can't have used this */
11524 if (rcur->type == NOT_INIT)
11526 switch (base_type(rold->type)) {
11528 if (env->explore_alu_limits)
11530 if (rcur->type == SCALAR_VALUE) {
11531 if (!rold->precise && !rcur->precise)
11533 /* new val must satisfy old val knowledge */
11534 return range_within(rold, rcur) &&
11535 tnum_in(rold->var_off, rcur->var_off);
11537 /* We're trying to use a pointer in place of a scalar.
11538 * Even if the scalar was unbounded, this could lead to
11539 * pointer leaks because scalars are allowed to leak
11540 * while pointers are not. We could make this safe in
11541 * special cases if root is calling us, but it's
11542 * probably not worth the hassle.
11546 case PTR_TO_MAP_KEY:
11547 case PTR_TO_MAP_VALUE:
11548 /* a PTR_TO_MAP_VALUE could be safe to use as a
11549 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11550 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11551 * checked, doing so could have affected others with the same
11552 * id, and we can't check for that because we lost the id when
11553 * we converted to a PTR_TO_MAP_VALUE.
11555 if (type_may_be_null(rold->type)) {
11556 if (!type_may_be_null(rcur->type))
11558 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11560 /* Check our ids match any regs they're supposed to */
11561 return check_ids(rold->id, rcur->id, idmap);
11564 /* If the new min/max/var_off satisfy the old ones and
11565 * everything else matches, we are OK.
11566 * 'id' is not compared, since it's only used for maps with
11567 * bpf_spin_lock inside map element and in such cases if
11568 * the rest of the prog is valid for one map element then
11569 * it's valid for all map elements regardless of the key
11570 * used in bpf_map_lookup()
11572 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11573 range_within(rold, rcur) &&
11574 tnum_in(rold->var_off, rcur->var_off);
11575 case PTR_TO_PACKET_META:
11576 case PTR_TO_PACKET:
11577 if (rcur->type != rold->type)
11579 /* We must have at least as much range as the old ptr
11580 * did, so that any accesses which were safe before are
11581 * still safe. This is true even if old range < old off,
11582 * since someone could have accessed through (ptr - k), or
11583 * even done ptr -= k in a register, to get a safe access.
11585 if (rold->range > rcur->range)
11587 /* If the offsets don't match, we can't trust our alignment;
11588 * nor can we be sure that we won't fall out of range.
11590 if (rold->off != rcur->off)
11592 /* id relations must be preserved */
11593 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11595 /* new val must satisfy old val knowledge */
11596 return range_within(rold, rcur) &&
11597 tnum_in(rold->var_off, rcur->var_off);
11599 case CONST_PTR_TO_MAP:
11600 case PTR_TO_PACKET_END:
11601 case PTR_TO_FLOW_KEYS:
11602 case PTR_TO_SOCKET:
11603 case PTR_TO_SOCK_COMMON:
11604 case PTR_TO_TCP_SOCK:
11605 case PTR_TO_XDP_SOCK:
11606 /* Only valid matches are exact, which memcmp() above
11607 * would have accepted
11610 /* Don't know what's going on, just say it's not safe */
11614 /* Shouldn't get here; if we do, say it's not safe */
11619 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11620 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11624 /* walk slots of the explored stack and ignore any additional
11625 * slots in the current stack, since explored(safe) state
11628 for (i = 0; i < old->allocated_stack; i++) {
11629 spi = i / BPF_REG_SIZE;
11631 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11632 i += BPF_REG_SIZE - 1;
11633 /* explored state didn't use this */
11637 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11640 /* explored stack has more populated slots than current stack
11641 * and these slots were used
11643 if (i >= cur->allocated_stack)
11646 /* if old state was safe with misc data in the stack
11647 * it will be safe with zero-initialized stack.
11648 * The opposite is not true
11650 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11651 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11653 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11654 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11655 /* Ex: old explored (safe) state has STACK_SPILL in
11656 * this stack slot, but current has STACK_MISC ->
11657 * this verifier states are not equivalent,
11658 * return false to continue verification of this path
11661 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11663 if (!is_spilled_reg(&old->stack[spi]))
11665 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11666 &cur->stack[spi].spilled_ptr, idmap))
11667 /* when explored and current stack slot are both storing
11668 * spilled registers, check that stored pointers types
11669 * are the same as well.
11670 * Ex: explored safe path could have stored
11671 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11672 * but current path has stored:
11673 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11674 * such verifier states are not equivalent.
11675 * return false to continue verification of this path
11682 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11684 if (old->acquired_refs != cur->acquired_refs)
11686 return !memcmp(old->refs, cur->refs,
11687 sizeof(*old->refs) * old->acquired_refs);
11690 /* compare two verifier states
11692 * all states stored in state_list are known to be valid, since
11693 * verifier reached 'bpf_exit' instruction through them
11695 * this function is called when verifier exploring different branches of
11696 * execution popped from the state stack. If it sees an old state that has
11697 * more strict register state and more strict stack state then this execution
11698 * branch doesn't need to be explored further, since verifier already
11699 * concluded that more strict state leads to valid finish.
11701 * Therefore two states are equivalent if register state is more conservative
11702 * and explored stack state is more conservative than the current one.
11705 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11706 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11708 * In other words if current stack state (one being explored) has more
11709 * valid slots than old one that already passed validation, it means
11710 * the verifier can stop exploring and conclude that current state is valid too
11712 * Similarly with registers. If explored state has register type as invalid
11713 * whereas register type in current state is meaningful, it means that
11714 * the current state will reach 'bpf_exit' instruction safely
11716 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11717 struct bpf_func_state *cur)
11721 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11722 for (i = 0; i < MAX_BPF_REG; i++)
11723 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11724 env->idmap_scratch))
11727 if (!stacksafe(env, old, cur, env->idmap_scratch))
11730 if (!refsafe(old, cur))
11736 static bool states_equal(struct bpf_verifier_env *env,
11737 struct bpf_verifier_state *old,
11738 struct bpf_verifier_state *cur)
11742 if (old->curframe != cur->curframe)
11745 /* Verification state from speculative execution simulation
11746 * must never prune a non-speculative execution one.
11748 if (old->speculative && !cur->speculative)
11751 if (old->active_spin_lock != cur->active_spin_lock)
11754 /* for states to be equal callsites have to be the same
11755 * and all frame states need to be equivalent
11757 for (i = 0; i <= old->curframe; i++) {
11758 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11760 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11766 /* Return 0 if no propagation happened. Return negative error code if error
11767 * happened. Otherwise, return the propagated bit.
11769 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11770 struct bpf_reg_state *reg,
11771 struct bpf_reg_state *parent_reg)
11773 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11774 u8 flag = reg->live & REG_LIVE_READ;
11777 /* When comes here, read flags of PARENT_REG or REG could be any of
11778 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11779 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11781 if (parent_flag == REG_LIVE_READ64 ||
11782 /* Or if there is no read flag from REG. */
11784 /* Or if the read flag from REG is the same as PARENT_REG. */
11785 parent_flag == flag)
11788 err = mark_reg_read(env, reg, parent_reg, flag);
11795 /* A write screens off any subsequent reads; but write marks come from the
11796 * straight-line code between a state and its parent. When we arrive at an
11797 * equivalent state (jump target or such) we didn't arrive by the straight-line
11798 * code, so read marks in the state must propagate to the parent regardless
11799 * of the state's write marks. That's what 'parent == state->parent' comparison
11800 * in mark_reg_read() is for.
11802 static int propagate_liveness(struct bpf_verifier_env *env,
11803 const struct bpf_verifier_state *vstate,
11804 struct bpf_verifier_state *vparent)
11806 struct bpf_reg_state *state_reg, *parent_reg;
11807 struct bpf_func_state *state, *parent;
11808 int i, frame, err = 0;
11810 if (vparent->curframe != vstate->curframe) {
11811 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11812 vparent->curframe, vstate->curframe);
11815 /* Propagate read liveness of registers... */
11816 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11817 for (frame = 0; frame <= vstate->curframe; frame++) {
11818 parent = vparent->frame[frame];
11819 state = vstate->frame[frame];
11820 parent_reg = parent->regs;
11821 state_reg = state->regs;
11822 /* We don't need to worry about FP liveness, it's read-only */
11823 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11824 err = propagate_liveness_reg(env, &state_reg[i],
11828 if (err == REG_LIVE_READ64)
11829 mark_insn_zext(env, &parent_reg[i]);
11832 /* Propagate stack slots. */
11833 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11834 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11835 parent_reg = &parent->stack[i].spilled_ptr;
11836 state_reg = &state->stack[i].spilled_ptr;
11837 err = propagate_liveness_reg(env, state_reg,
11846 /* find precise scalars in the previous equivalent state and
11847 * propagate them into the current state
11849 static int propagate_precision(struct bpf_verifier_env *env,
11850 const struct bpf_verifier_state *old)
11852 struct bpf_reg_state *state_reg;
11853 struct bpf_func_state *state;
11856 state = old->frame[old->curframe];
11857 state_reg = state->regs;
11858 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11859 if (state_reg->type != SCALAR_VALUE ||
11860 !state_reg->precise)
11862 if (env->log.level & BPF_LOG_LEVEL2)
11863 verbose(env, "propagating r%d\n", i);
11864 err = mark_chain_precision(env, i);
11869 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11870 if (!is_spilled_reg(&state->stack[i]))
11872 state_reg = &state->stack[i].spilled_ptr;
11873 if (state_reg->type != SCALAR_VALUE ||
11874 !state_reg->precise)
11876 if (env->log.level & BPF_LOG_LEVEL2)
11877 verbose(env, "propagating fp%d\n",
11878 (-i - 1) * BPF_REG_SIZE);
11879 err = mark_chain_precision_stack(env, i);
11886 static bool states_maybe_looping(struct bpf_verifier_state *old,
11887 struct bpf_verifier_state *cur)
11889 struct bpf_func_state *fold, *fcur;
11890 int i, fr = cur->curframe;
11892 if (old->curframe != fr)
11895 fold = old->frame[fr];
11896 fcur = cur->frame[fr];
11897 for (i = 0; i < MAX_BPF_REG; i++)
11898 if (memcmp(&fold->regs[i], &fcur->regs[i],
11899 offsetof(struct bpf_reg_state, parent)))
11905 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11907 struct bpf_verifier_state_list *new_sl;
11908 struct bpf_verifier_state_list *sl, **pprev;
11909 struct bpf_verifier_state *cur = env->cur_state, *new;
11910 int i, j, err, states_cnt = 0;
11911 bool add_new_state = env->test_state_freq ? true : false;
11913 cur->last_insn_idx = env->prev_insn_idx;
11914 if (!env->insn_aux_data[insn_idx].prune_point)
11915 /* this 'insn_idx' instruction wasn't marked, so we will not
11916 * be doing state search here
11920 /* bpf progs typically have pruning point every 4 instructions
11921 * http://vger.kernel.org/bpfconf2019.html#session-1
11922 * Do not add new state for future pruning if the verifier hasn't seen
11923 * at least 2 jumps and at least 8 instructions.
11924 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11925 * In tests that amounts to up to 50% reduction into total verifier
11926 * memory consumption and 20% verifier time speedup.
11928 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11929 env->insn_processed - env->prev_insn_processed >= 8)
11930 add_new_state = true;
11932 pprev = explored_state(env, insn_idx);
11935 clean_live_states(env, insn_idx, cur);
11939 if (sl->state.insn_idx != insn_idx)
11942 if (sl->state.branches) {
11943 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11945 if (frame->in_async_callback_fn &&
11946 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11947 /* Different async_entry_cnt means that the verifier is
11948 * processing another entry into async callback.
11949 * Seeing the same state is not an indication of infinite
11950 * loop or infinite recursion.
11951 * But finding the same state doesn't mean that it's safe
11952 * to stop processing the current state. The previous state
11953 * hasn't yet reached bpf_exit, since state.branches > 0.
11954 * Checking in_async_callback_fn alone is not enough either.
11955 * Since the verifier still needs to catch infinite loops
11956 * inside async callbacks.
11958 } else if (states_maybe_looping(&sl->state, cur) &&
11959 states_equal(env, &sl->state, cur)) {
11960 verbose_linfo(env, insn_idx, "; ");
11961 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11964 /* if the verifier is processing a loop, avoid adding new state
11965 * too often, since different loop iterations have distinct
11966 * states and may not help future pruning.
11967 * This threshold shouldn't be too low to make sure that
11968 * a loop with large bound will be rejected quickly.
11969 * The most abusive loop will be:
11971 * if r1 < 1000000 goto pc-2
11972 * 1M insn_procssed limit / 100 == 10k peak states.
11973 * This threshold shouldn't be too high either, since states
11974 * at the end of the loop are likely to be useful in pruning.
11976 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11977 env->insn_processed - env->prev_insn_processed < 100)
11978 add_new_state = false;
11981 if (states_equal(env, &sl->state, cur)) {
11983 /* reached equivalent register/stack state,
11984 * prune the search.
11985 * Registers read by the continuation are read by us.
11986 * If we have any write marks in env->cur_state, they
11987 * will prevent corresponding reads in the continuation
11988 * from reaching our parent (an explored_state). Our
11989 * own state will get the read marks recorded, but
11990 * they'll be immediately forgotten as we're pruning
11991 * this state and will pop a new one.
11993 err = propagate_liveness(env, &sl->state, cur);
11995 /* if previous state reached the exit with precision and
11996 * current state is equivalent to it (except precsion marks)
11997 * the precision needs to be propagated back in
11998 * the current state.
12000 err = err ? : push_jmp_history(env, cur);
12001 err = err ? : propagate_precision(env, &sl->state);
12007 /* when new state is not going to be added do not increase miss count.
12008 * Otherwise several loop iterations will remove the state
12009 * recorded earlier. The goal of these heuristics is to have
12010 * states from some iterations of the loop (some in the beginning
12011 * and some at the end) to help pruning.
12015 /* heuristic to determine whether this state is beneficial
12016 * to keep checking from state equivalence point of view.
12017 * Higher numbers increase max_states_per_insn and verification time,
12018 * but do not meaningfully decrease insn_processed.
12020 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12021 /* the state is unlikely to be useful. Remove it to
12022 * speed up verification
12025 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12026 u32 br = sl->state.branches;
12029 "BUG live_done but branches_to_explore %d\n",
12031 free_verifier_state(&sl->state, false);
12033 env->peak_states--;
12035 /* cannot free this state, since parentage chain may
12036 * walk it later. Add it for free_list instead to
12037 * be freed at the end of verification
12039 sl->next = env->free_list;
12040 env->free_list = sl;
12050 if (env->max_states_per_insn < states_cnt)
12051 env->max_states_per_insn = states_cnt;
12053 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12054 return push_jmp_history(env, cur);
12056 if (!add_new_state)
12057 return push_jmp_history(env, cur);
12059 /* There were no equivalent states, remember the current one.
12060 * Technically the current state is not proven to be safe yet,
12061 * but it will either reach outer most bpf_exit (which means it's safe)
12062 * or it will be rejected. When there are no loops the verifier won't be
12063 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12064 * again on the way to bpf_exit.
12065 * When looping the sl->state.branches will be > 0 and this state
12066 * will not be considered for equivalence until branches == 0.
12068 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12071 env->total_states++;
12072 env->peak_states++;
12073 env->prev_jmps_processed = env->jmps_processed;
12074 env->prev_insn_processed = env->insn_processed;
12076 /* add new state to the head of linked list */
12077 new = &new_sl->state;
12078 err = copy_verifier_state(new, cur);
12080 free_verifier_state(new, false);
12084 new->insn_idx = insn_idx;
12085 WARN_ONCE(new->branches != 1,
12086 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12089 cur->first_insn_idx = insn_idx;
12090 clear_jmp_history(cur);
12091 new_sl->next = *explored_state(env, insn_idx);
12092 *explored_state(env, insn_idx) = new_sl;
12093 /* connect new state to parentage chain. Current frame needs all
12094 * registers connected. Only r6 - r9 of the callers are alive (pushed
12095 * to the stack implicitly by JITs) so in callers' frames connect just
12096 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12097 * the state of the call instruction (with WRITTEN set), and r0 comes
12098 * from callee with its full parentage chain, anyway.
12100 /* clear write marks in current state: the writes we did are not writes
12101 * our child did, so they don't screen off its reads from us.
12102 * (There are no read marks in current state, because reads always mark
12103 * their parent and current state never has children yet. Only
12104 * explored_states can get read marks.)
12106 for (j = 0; j <= cur->curframe; j++) {
12107 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12108 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12109 for (i = 0; i < BPF_REG_FP; i++)
12110 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12113 /* all stack frames are accessible from callee, clear them all */
12114 for (j = 0; j <= cur->curframe; j++) {
12115 struct bpf_func_state *frame = cur->frame[j];
12116 struct bpf_func_state *newframe = new->frame[j];
12118 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12119 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12120 frame->stack[i].spilled_ptr.parent =
12121 &newframe->stack[i].spilled_ptr;
12127 /* Return true if it's OK to have the same insn return a different type. */
12128 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12130 switch (base_type(type)) {
12132 case PTR_TO_SOCKET:
12133 case PTR_TO_SOCK_COMMON:
12134 case PTR_TO_TCP_SOCK:
12135 case PTR_TO_XDP_SOCK:
12136 case PTR_TO_BTF_ID:
12143 /* If an instruction was previously used with particular pointer types, then we
12144 * need to be careful to avoid cases such as the below, where it may be ok
12145 * for one branch accessing the pointer, but not ok for the other branch:
12150 * R1 = some_other_valid_ptr;
12153 * R2 = *(u32 *)(R1 + 0);
12155 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12157 return src != prev && (!reg_type_mismatch_ok(src) ||
12158 !reg_type_mismatch_ok(prev));
12161 static int do_check(struct bpf_verifier_env *env)
12163 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12164 struct bpf_verifier_state *state = env->cur_state;
12165 struct bpf_insn *insns = env->prog->insnsi;
12166 struct bpf_reg_state *regs;
12167 int insn_cnt = env->prog->len;
12168 bool do_print_state = false;
12169 int prev_insn_idx = -1;
12172 struct bpf_insn *insn;
12176 env->prev_insn_idx = prev_insn_idx;
12177 if (env->insn_idx >= insn_cnt) {
12178 verbose(env, "invalid insn idx %d insn_cnt %d\n",
12179 env->insn_idx, insn_cnt);
12183 insn = &insns[env->insn_idx];
12184 class = BPF_CLASS(insn->code);
12186 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12188 "BPF program is too large. Processed %d insn\n",
12189 env->insn_processed);
12193 err = is_state_visited(env, env->insn_idx);
12197 /* found equivalent state, can prune the search */
12198 if (env->log.level & BPF_LOG_LEVEL) {
12199 if (do_print_state)
12200 verbose(env, "\nfrom %d to %d%s: safe\n",
12201 env->prev_insn_idx, env->insn_idx,
12202 env->cur_state->speculative ?
12203 " (speculative execution)" : "");
12205 verbose(env, "%d: safe\n", env->insn_idx);
12207 goto process_bpf_exit;
12210 if (signal_pending(current))
12213 if (need_resched())
12216 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12217 verbose(env, "\nfrom %d to %d%s:",
12218 env->prev_insn_idx, env->insn_idx,
12219 env->cur_state->speculative ?
12220 " (speculative execution)" : "");
12221 print_verifier_state(env, state->frame[state->curframe], true);
12222 do_print_state = false;
12225 if (env->log.level & BPF_LOG_LEVEL) {
12226 const struct bpf_insn_cbs cbs = {
12227 .cb_call = disasm_kfunc_name,
12228 .cb_print = verbose,
12229 .private_data = env,
12232 if (verifier_state_scratched(env))
12233 print_insn_state(env, state->frame[state->curframe]);
12235 verbose_linfo(env, env->insn_idx, "; ");
12236 env->prev_log_len = env->log.len_used;
12237 verbose(env, "%d: ", env->insn_idx);
12238 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12239 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12240 env->prev_log_len = env->log.len_used;
12243 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12244 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12245 env->prev_insn_idx);
12250 regs = cur_regs(env);
12251 sanitize_mark_insn_seen(env);
12252 prev_insn_idx = env->insn_idx;
12254 if (class == BPF_ALU || class == BPF_ALU64) {
12255 err = check_alu_op(env, insn);
12259 } else if (class == BPF_LDX) {
12260 enum bpf_reg_type *prev_src_type, src_reg_type;
12262 /* check for reserved fields is already done */
12264 /* check src operand */
12265 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12269 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12273 src_reg_type = regs[insn->src_reg].type;
12275 /* check that memory (src_reg + off) is readable,
12276 * the state of dst_reg will be updated by this func
12278 err = check_mem_access(env, env->insn_idx, insn->src_reg,
12279 insn->off, BPF_SIZE(insn->code),
12280 BPF_READ, insn->dst_reg, false);
12284 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12286 if (*prev_src_type == NOT_INIT) {
12287 /* saw a valid insn
12288 * dst_reg = *(u32 *)(src_reg + off)
12289 * save type to validate intersecting paths
12291 *prev_src_type = src_reg_type;
12293 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12294 /* ABuser program is trying to use the same insn
12295 * dst_reg = *(u32*) (src_reg + off)
12296 * with different pointer types:
12297 * src_reg == ctx in one branch and
12298 * src_reg == stack|map in some other branch.
12301 verbose(env, "same insn cannot be used with different pointers\n");
12305 } else if (class == BPF_STX) {
12306 enum bpf_reg_type *prev_dst_type, dst_reg_type;
12308 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12309 err = check_atomic(env, env->insn_idx, insn);
12316 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12317 verbose(env, "BPF_STX uses reserved fields\n");
12321 /* check src1 operand */
12322 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12325 /* check src2 operand */
12326 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12330 dst_reg_type = regs[insn->dst_reg].type;
12332 /* check that memory (dst_reg + off) is writeable */
12333 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12334 insn->off, BPF_SIZE(insn->code),
12335 BPF_WRITE, insn->src_reg, false);
12339 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12341 if (*prev_dst_type == NOT_INIT) {
12342 *prev_dst_type = dst_reg_type;
12343 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12344 verbose(env, "same insn cannot be used with different pointers\n");
12348 } else if (class == BPF_ST) {
12349 if (BPF_MODE(insn->code) != BPF_MEM ||
12350 insn->src_reg != BPF_REG_0) {
12351 verbose(env, "BPF_ST uses reserved fields\n");
12354 /* check src operand */
12355 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12359 if (is_ctx_reg(env, insn->dst_reg)) {
12360 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12362 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12366 /* check that memory (dst_reg + off) is writeable */
12367 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12368 insn->off, BPF_SIZE(insn->code),
12369 BPF_WRITE, -1, false);
12373 } else if (class == BPF_JMP || class == BPF_JMP32) {
12374 u8 opcode = BPF_OP(insn->code);
12376 env->jmps_processed++;
12377 if (opcode == BPF_CALL) {
12378 if (BPF_SRC(insn->code) != BPF_K ||
12379 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12380 && insn->off != 0) ||
12381 (insn->src_reg != BPF_REG_0 &&
12382 insn->src_reg != BPF_PSEUDO_CALL &&
12383 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12384 insn->dst_reg != BPF_REG_0 ||
12385 class == BPF_JMP32) {
12386 verbose(env, "BPF_CALL uses reserved fields\n");
12390 if (env->cur_state->active_spin_lock &&
12391 (insn->src_reg == BPF_PSEUDO_CALL ||
12392 insn->imm != BPF_FUNC_spin_unlock)) {
12393 verbose(env, "function calls are not allowed while holding a lock\n");
12396 if (insn->src_reg == BPF_PSEUDO_CALL)
12397 err = check_func_call(env, insn, &env->insn_idx);
12398 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12399 err = check_kfunc_call(env, insn, &env->insn_idx);
12401 err = check_helper_call(env, insn, &env->insn_idx);
12404 } else if (opcode == BPF_JA) {
12405 if (BPF_SRC(insn->code) != BPF_K ||
12407 insn->src_reg != BPF_REG_0 ||
12408 insn->dst_reg != BPF_REG_0 ||
12409 class == BPF_JMP32) {
12410 verbose(env, "BPF_JA uses reserved fields\n");
12414 env->insn_idx += insn->off + 1;
12417 } else if (opcode == BPF_EXIT) {
12418 if (BPF_SRC(insn->code) != BPF_K ||
12420 insn->src_reg != BPF_REG_0 ||
12421 insn->dst_reg != BPF_REG_0 ||
12422 class == BPF_JMP32) {
12423 verbose(env, "BPF_EXIT uses reserved fields\n");
12427 if (env->cur_state->active_spin_lock) {
12428 verbose(env, "bpf_spin_unlock is missing\n");
12432 /* We must do check_reference_leak here before
12433 * prepare_func_exit to handle the case when
12434 * state->curframe > 0, it may be a callback
12435 * function, for which reference_state must
12436 * match caller reference state when it exits.
12438 err = check_reference_leak(env);
12442 if (state->curframe) {
12443 /* exit from nested function */
12444 err = prepare_func_exit(env, &env->insn_idx);
12447 do_print_state = true;
12451 err = check_return_code(env);
12455 mark_verifier_state_scratched(env);
12456 update_branch_counts(env, env->cur_state);
12457 err = pop_stack(env, &prev_insn_idx,
12458 &env->insn_idx, pop_log);
12460 if (err != -ENOENT)
12464 do_print_state = true;
12468 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12472 } else if (class == BPF_LD) {
12473 u8 mode = BPF_MODE(insn->code);
12475 if (mode == BPF_ABS || mode == BPF_IND) {
12476 err = check_ld_abs(env, insn);
12480 } else if (mode == BPF_IMM) {
12481 err = check_ld_imm(env, insn);
12486 sanitize_mark_insn_seen(env);
12488 verbose(env, "invalid BPF_LD mode\n");
12492 verbose(env, "unknown insn class %d\n", class);
12502 static int find_btf_percpu_datasec(struct btf *btf)
12504 const struct btf_type *t;
12509 * Both vmlinux and module each have their own ".data..percpu"
12510 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12511 * types to look at only module's own BTF types.
12513 n = btf_nr_types(btf);
12514 if (btf_is_module(btf))
12515 i = btf_nr_types(btf_vmlinux);
12519 for(; i < n; i++) {
12520 t = btf_type_by_id(btf, i);
12521 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12524 tname = btf_name_by_offset(btf, t->name_off);
12525 if (!strcmp(tname, ".data..percpu"))
12532 /* replace pseudo btf_id with kernel symbol address */
12533 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12534 struct bpf_insn *insn,
12535 struct bpf_insn_aux_data *aux)
12537 const struct btf_var_secinfo *vsi;
12538 const struct btf_type *datasec;
12539 struct btf_mod_pair *btf_mod;
12540 const struct btf_type *t;
12541 const char *sym_name;
12542 bool percpu = false;
12543 u32 type, id = insn->imm;
12547 int i, btf_fd, err;
12549 btf_fd = insn[1].imm;
12551 btf = btf_get_by_fd(btf_fd);
12553 verbose(env, "invalid module BTF object FD specified.\n");
12557 if (!btf_vmlinux) {
12558 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12565 t = btf_type_by_id(btf, id);
12567 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12572 if (!btf_type_is_var(t)) {
12573 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12578 sym_name = btf_name_by_offset(btf, t->name_off);
12579 addr = kallsyms_lookup_name(sym_name);
12581 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12587 datasec_id = find_btf_percpu_datasec(btf);
12588 if (datasec_id > 0) {
12589 datasec = btf_type_by_id(btf, datasec_id);
12590 for_each_vsi(i, datasec, vsi) {
12591 if (vsi->type == id) {
12598 insn[0].imm = (u32)addr;
12599 insn[1].imm = addr >> 32;
12602 t = btf_type_skip_modifiers(btf, type, NULL);
12604 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12605 aux->btf_var.btf = btf;
12606 aux->btf_var.btf_id = type;
12607 } else if (!btf_type_is_struct(t)) {
12608 const struct btf_type *ret;
12612 /* resolve the type size of ksym. */
12613 ret = btf_resolve_size(btf, t, &tsize);
12615 tname = btf_name_by_offset(btf, t->name_off);
12616 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12617 tname, PTR_ERR(ret));
12621 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12622 aux->btf_var.mem_size = tsize;
12624 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12625 aux->btf_var.btf = btf;
12626 aux->btf_var.btf_id = type;
12629 /* check whether we recorded this BTF (and maybe module) already */
12630 for (i = 0; i < env->used_btf_cnt; i++) {
12631 if (env->used_btfs[i].btf == btf) {
12637 if (env->used_btf_cnt >= MAX_USED_BTFS) {
12642 btf_mod = &env->used_btfs[env->used_btf_cnt];
12643 btf_mod->btf = btf;
12644 btf_mod->module = NULL;
12646 /* if we reference variables from kernel module, bump its refcount */
12647 if (btf_is_module(btf)) {
12648 btf_mod->module = btf_try_get_module(btf);
12649 if (!btf_mod->module) {
12655 env->used_btf_cnt++;
12663 static bool is_tracing_prog_type(enum bpf_prog_type type)
12666 case BPF_PROG_TYPE_KPROBE:
12667 case BPF_PROG_TYPE_TRACEPOINT:
12668 case BPF_PROG_TYPE_PERF_EVENT:
12669 case BPF_PROG_TYPE_RAW_TRACEPOINT:
12670 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12677 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12678 struct bpf_map *map,
12679 struct bpf_prog *prog)
12682 enum bpf_prog_type prog_type = resolve_prog_type(prog);
12684 if (map_value_has_spin_lock(map)) {
12685 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12686 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12690 if (is_tracing_prog_type(prog_type)) {
12691 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12695 if (prog->aux->sleepable) {
12696 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12701 if (map_value_has_timer(map)) {
12702 if (is_tracing_prog_type(prog_type)) {
12703 verbose(env, "tracing progs cannot use bpf_timer yet\n");
12708 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12709 !bpf_offload_prog_map_match(prog, map)) {
12710 verbose(env, "offload device mismatch between prog and map\n");
12714 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12715 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12719 if (prog->aux->sleepable)
12720 switch (map->map_type) {
12721 case BPF_MAP_TYPE_HASH:
12722 case BPF_MAP_TYPE_LRU_HASH:
12723 case BPF_MAP_TYPE_ARRAY:
12724 case BPF_MAP_TYPE_PERCPU_HASH:
12725 case BPF_MAP_TYPE_PERCPU_ARRAY:
12726 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12727 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12728 case BPF_MAP_TYPE_HASH_OF_MAPS:
12729 case BPF_MAP_TYPE_RINGBUF:
12730 case BPF_MAP_TYPE_USER_RINGBUF:
12731 case BPF_MAP_TYPE_INODE_STORAGE:
12732 case BPF_MAP_TYPE_SK_STORAGE:
12733 case BPF_MAP_TYPE_TASK_STORAGE:
12737 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12744 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12746 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12747 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12750 /* find and rewrite pseudo imm in ld_imm64 instructions:
12752 * 1. if it accesses map FD, replace it with actual map pointer.
12753 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12755 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12757 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12759 struct bpf_insn *insn = env->prog->insnsi;
12760 int insn_cnt = env->prog->len;
12763 err = bpf_prog_calc_tag(env->prog);
12767 for (i = 0; i < insn_cnt; i++, insn++) {
12768 if (BPF_CLASS(insn->code) == BPF_LDX &&
12769 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12770 verbose(env, "BPF_LDX uses reserved fields\n");
12774 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12775 struct bpf_insn_aux_data *aux;
12776 struct bpf_map *map;
12781 if (i == insn_cnt - 1 || insn[1].code != 0 ||
12782 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12783 insn[1].off != 0) {
12784 verbose(env, "invalid bpf_ld_imm64 insn\n");
12788 if (insn[0].src_reg == 0)
12789 /* valid generic load 64-bit imm */
12792 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12793 aux = &env->insn_aux_data[i];
12794 err = check_pseudo_btf_id(env, insn, aux);
12800 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12801 aux = &env->insn_aux_data[i];
12802 aux->ptr_type = PTR_TO_FUNC;
12806 /* In final convert_pseudo_ld_imm64() step, this is
12807 * converted into regular 64-bit imm load insn.
12809 switch (insn[0].src_reg) {
12810 case BPF_PSEUDO_MAP_VALUE:
12811 case BPF_PSEUDO_MAP_IDX_VALUE:
12813 case BPF_PSEUDO_MAP_FD:
12814 case BPF_PSEUDO_MAP_IDX:
12815 if (insn[1].imm == 0)
12819 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12823 switch (insn[0].src_reg) {
12824 case BPF_PSEUDO_MAP_IDX_VALUE:
12825 case BPF_PSEUDO_MAP_IDX:
12826 if (bpfptr_is_null(env->fd_array)) {
12827 verbose(env, "fd_idx without fd_array is invalid\n");
12830 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12831 insn[0].imm * sizeof(fd),
12841 map = __bpf_map_get(f);
12843 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12845 return PTR_ERR(map);
12848 err = check_map_prog_compatibility(env, map, env->prog);
12854 aux = &env->insn_aux_data[i];
12855 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12856 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12857 addr = (unsigned long)map;
12859 u32 off = insn[1].imm;
12861 if (off >= BPF_MAX_VAR_OFF) {
12862 verbose(env, "direct value offset of %u is not allowed\n", off);
12867 if (!map->ops->map_direct_value_addr) {
12868 verbose(env, "no direct value access support for this map type\n");
12873 err = map->ops->map_direct_value_addr(map, &addr, off);
12875 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12876 map->value_size, off);
12881 aux->map_off = off;
12885 insn[0].imm = (u32)addr;
12886 insn[1].imm = addr >> 32;
12888 /* check whether we recorded this map already */
12889 for (j = 0; j < env->used_map_cnt; j++) {
12890 if (env->used_maps[j] == map) {
12891 aux->map_index = j;
12897 if (env->used_map_cnt >= MAX_USED_MAPS) {
12902 /* hold the map. If the program is rejected by verifier,
12903 * the map will be released by release_maps() or it
12904 * will be used by the valid program until it's unloaded
12905 * and all maps are released in free_used_maps()
12909 aux->map_index = env->used_map_cnt;
12910 env->used_maps[env->used_map_cnt++] = map;
12912 if (bpf_map_is_cgroup_storage(map) &&
12913 bpf_cgroup_storage_assign(env->prog->aux, map)) {
12914 verbose(env, "only one cgroup storage of each type is allowed\n");
12926 /* Basic sanity check before we invest more work here. */
12927 if (!bpf_opcode_in_insntable(insn->code)) {
12928 verbose(env, "unknown opcode %02x\n", insn->code);
12933 /* now all pseudo BPF_LD_IMM64 instructions load valid
12934 * 'struct bpf_map *' into a register instead of user map_fd.
12935 * These pointers will be used later by verifier to validate map access.
12940 /* drop refcnt of maps used by the rejected program */
12941 static void release_maps(struct bpf_verifier_env *env)
12943 __bpf_free_used_maps(env->prog->aux, env->used_maps,
12944 env->used_map_cnt);
12947 /* drop refcnt of maps used by the rejected program */
12948 static void release_btfs(struct bpf_verifier_env *env)
12950 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12951 env->used_btf_cnt);
12954 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12955 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12957 struct bpf_insn *insn = env->prog->insnsi;
12958 int insn_cnt = env->prog->len;
12961 for (i = 0; i < insn_cnt; i++, insn++) {
12962 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12964 if (insn->src_reg == BPF_PSEUDO_FUNC)
12970 /* single env->prog->insni[off] instruction was replaced with the range
12971 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
12972 * [0, off) and [off, end) to new locations, so the patched range stays zero
12974 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12975 struct bpf_insn_aux_data *new_data,
12976 struct bpf_prog *new_prog, u32 off, u32 cnt)
12978 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
12979 struct bpf_insn *insn = new_prog->insnsi;
12980 u32 old_seen = old_data[off].seen;
12984 /* aux info at OFF always needs adjustment, no matter fast path
12985 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12986 * original insn at old prog.
12988 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12992 prog_len = new_prog->len;
12994 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12995 memcpy(new_data + off + cnt - 1, old_data + off,
12996 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
12997 for (i = off; i < off + cnt - 1; i++) {
12998 /* Expand insni[off]'s seen count to the patched range. */
12999 new_data[i].seen = old_seen;
13000 new_data[i].zext_dst = insn_has_def32(env, insn + i);
13002 env->insn_aux_data = new_data;
13006 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13012 /* NOTE: fake 'exit' subprog should be updated as well. */
13013 for (i = 0; i <= env->subprog_cnt; i++) {
13014 if (env->subprog_info[i].start <= off)
13016 env->subprog_info[i].start += len - 1;
13020 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13022 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13023 int i, sz = prog->aux->size_poke_tab;
13024 struct bpf_jit_poke_descriptor *desc;
13026 for (i = 0; i < sz; i++) {
13028 if (desc->insn_idx <= off)
13030 desc->insn_idx += len - 1;
13034 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13035 const struct bpf_insn *patch, u32 len)
13037 struct bpf_prog *new_prog;
13038 struct bpf_insn_aux_data *new_data = NULL;
13041 new_data = vzalloc(array_size(env->prog->len + len - 1,
13042 sizeof(struct bpf_insn_aux_data)));
13047 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13048 if (IS_ERR(new_prog)) {
13049 if (PTR_ERR(new_prog) == -ERANGE)
13051 "insn %d cannot be patched due to 16-bit range\n",
13052 env->insn_aux_data[off].orig_idx);
13056 adjust_insn_aux_data(env, new_data, new_prog, off, len);
13057 adjust_subprog_starts(env, off, len);
13058 adjust_poke_descs(new_prog, off, len);
13062 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13067 /* find first prog starting at or after off (first to remove) */
13068 for (i = 0; i < env->subprog_cnt; i++)
13069 if (env->subprog_info[i].start >= off)
13071 /* find first prog starting at or after off + cnt (first to stay) */
13072 for (j = i; j < env->subprog_cnt; j++)
13073 if (env->subprog_info[j].start >= off + cnt)
13075 /* if j doesn't start exactly at off + cnt, we are just removing
13076 * the front of previous prog
13078 if (env->subprog_info[j].start != off + cnt)
13082 struct bpf_prog_aux *aux = env->prog->aux;
13085 /* move fake 'exit' subprog as well */
13086 move = env->subprog_cnt + 1 - j;
13088 memmove(env->subprog_info + i,
13089 env->subprog_info + j,
13090 sizeof(*env->subprog_info) * move);
13091 env->subprog_cnt -= j - i;
13093 /* remove func_info */
13094 if (aux->func_info) {
13095 move = aux->func_info_cnt - j;
13097 memmove(aux->func_info + i,
13098 aux->func_info + j,
13099 sizeof(*aux->func_info) * move);
13100 aux->func_info_cnt -= j - i;
13101 /* func_info->insn_off is set after all code rewrites,
13102 * in adjust_btf_func() - no need to adjust
13106 /* convert i from "first prog to remove" to "first to adjust" */
13107 if (env->subprog_info[i].start == off)
13111 /* update fake 'exit' subprog as well */
13112 for (; i <= env->subprog_cnt; i++)
13113 env->subprog_info[i].start -= cnt;
13118 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13121 struct bpf_prog *prog = env->prog;
13122 u32 i, l_off, l_cnt, nr_linfo;
13123 struct bpf_line_info *linfo;
13125 nr_linfo = prog->aux->nr_linfo;
13129 linfo = prog->aux->linfo;
13131 /* find first line info to remove, count lines to be removed */
13132 for (i = 0; i < nr_linfo; i++)
13133 if (linfo[i].insn_off >= off)
13138 for (; i < nr_linfo; i++)
13139 if (linfo[i].insn_off < off + cnt)
13144 /* First live insn doesn't match first live linfo, it needs to "inherit"
13145 * last removed linfo. prog is already modified, so prog->len == off
13146 * means no live instructions after (tail of the program was removed).
13148 if (prog->len != off && l_cnt &&
13149 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13151 linfo[--i].insn_off = off + cnt;
13154 /* remove the line info which refer to the removed instructions */
13156 memmove(linfo + l_off, linfo + i,
13157 sizeof(*linfo) * (nr_linfo - i));
13159 prog->aux->nr_linfo -= l_cnt;
13160 nr_linfo = prog->aux->nr_linfo;
13163 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13164 for (i = l_off; i < nr_linfo; i++)
13165 linfo[i].insn_off -= cnt;
13167 /* fix up all subprogs (incl. 'exit') which start >= off */
13168 for (i = 0; i <= env->subprog_cnt; i++)
13169 if (env->subprog_info[i].linfo_idx > l_off) {
13170 /* program may have started in the removed region but
13171 * may not be fully removed
13173 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13174 env->subprog_info[i].linfo_idx -= l_cnt;
13176 env->subprog_info[i].linfo_idx = l_off;
13182 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13184 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13185 unsigned int orig_prog_len = env->prog->len;
13188 if (bpf_prog_is_dev_bound(env->prog->aux))
13189 bpf_prog_offload_remove_insns(env, off, cnt);
13191 err = bpf_remove_insns(env->prog, off, cnt);
13195 err = adjust_subprog_starts_after_remove(env, off, cnt);
13199 err = bpf_adj_linfo_after_remove(env, off, cnt);
13203 memmove(aux_data + off, aux_data + off + cnt,
13204 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13209 /* The verifier does more data flow analysis than llvm and will not
13210 * explore branches that are dead at run time. Malicious programs can
13211 * have dead code too. Therefore replace all dead at-run-time code
13214 * Just nops are not optimal, e.g. if they would sit at the end of the
13215 * program and through another bug we would manage to jump there, then
13216 * we'd execute beyond program memory otherwise. Returning exception
13217 * code also wouldn't work since we can have subprogs where the dead
13218 * code could be located.
13220 static void sanitize_dead_code(struct bpf_verifier_env *env)
13222 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13223 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13224 struct bpf_insn *insn = env->prog->insnsi;
13225 const int insn_cnt = env->prog->len;
13228 for (i = 0; i < insn_cnt; i++) {
13229 if (aux_data[i].seen)
13231 memcpy(insn + i, &trap, sizeof(trap));
13232 aux_data[i].zext_dst = false;
13236 static bool insn_is_cond_jump(u8 code)
13240 if (BPF_CLASS(code) == BPF_JMP32)
13243 if (BPF_CLASS(code) != BPF_JMP)
13247 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13250 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13252 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13253 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13254 struct bpf_insn *insn = env->prog->insnsi;
13255 const int insn_cnt = env->prog->len;
13258 for (i = 0; i < insn_cnt; i++, insn++) {
13259 if (!insn_is_cond_jump(insn->code))
13262 if (!aux_data[i + 1].seen)
13263 ja.off = insn->off;
13264 else if (!aux_data[i + 1 + insn->off].seen)
13269 if (bpf_prog_is_dev_bound(env->prog->aux))
13270 bpf_prog_offload_replace_insn(env, i, &ja);
13272 memcpy(insn, &ja, sizeof(ja));
13276 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13278 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13279 int insn_cnt = env->prog->len;
13282 for (i = 0; i < insn_cnt; i++) {
13286 while (i + j < insn_cnt && !aux_data[i + j].seen)
13291 err = verifier_remove_insns(env, i, j);
13294 insn_cnt = env->prog->len;
13300 static int opt_remove_nops(struct bpf_verifier_env *env)
13302 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13303 struct bpf_insn *insn = env->prog->insnsi;
13304 int insn_cnt = env->prog->len;
13307 for (i = 0; i < insn_cnt; i++) {
13308 if (memcmp(&insn[i], &ja, sizeof(ja)))
13311 err = verifier_remove_insns(env, i, 1);
13321 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13322 const union bpf_attr *attr)
13324 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13325 struct bpf_insn_aux_data *aux = env->insn_aux_data;
13326 int i, patch_len, delta = 0, len = env->prog->len;
13327 struct bpf_insn *insns = env->prog->insnsi;
13328 struct bpf_prog *new_prog;
13331 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13332 zext_patch[1] = BPF_ZEXT_REG(0);
13333 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13334 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13335 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13336 for (i = 0; i < len; i++) {
13337 int adj_idx = i + delta;
13338 struct bpf_insn insn;
13341 insn = insns[adj_idx];
13342 load_reg = insn_def_regno(&insn);
13343 if (!aux[adj_idx].zext_dst) {
13351 class = BPF_CLASS(code);
13352 if (load_reg == -1)
13355 /* NOTE: arg "reg" (the fourth one) is only used for
13356 * BPF_STX + SRC_OP, so it is safe to pass NULL
13359 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13360 if (class == BPF_LD &&
13361 BPF_MODE(code) == BPF_IMM)
13366 /* ctx load could be transformed into wider load. */
13367 if (class == BPF_LDX &&
13368 aux[adj_idx].ptr_type == PTR_TO_CTX)
13371 imm_rnd = get_random_u32();
13372 rnd_hi32_patch[0] = insn;
13373 rnd_hi32_patch[1].imm = imm_rnd;
13374 rnd_hi32_patch[3].dst_reg = load_reg;
13375 patch = rnd_hi32_patch;
13377 goto apply_patch_buffer;
13380 /* Add in an zero-extend instruction if a) the JIT has requested
13381 * it or b) it's a CMPXCHG.
13383 * The latter is because: BPF_CMPXCHG always loads a value into
13384 * R0, therefore always zero-extends. However some archs'
13385 * equivalent instruction only does this load when the
13386 * comparison is successful. This detail of CMPXCHG is
13387 * orthogonal to the general zero-extension behaviour of the
13388 * CPU, so it's treated independently of bpf_jit_needs_zext.
13390 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13393 if (WARN_ON(load_reg == -1)) {
13394 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13398 zext_patch[0] = insn;
13399 zext_patch[1].dst_reg = load_reg;
13400 zext_patch[1].src_reg = load_reg;
13401 patch = zext_patch;
13403 apply_patch_buffer:
13404 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13407 env->prog = new_prog;
13408 insns = new_prog->insnsi;
13409 aux = env->insn_aux_data;
13410 delta += patch_len - 1;
13416 /* convert load instructions that access fields of a context type into a
13417 * sequence of instructions that access fields of the underlying structure:
13418 * struct __sk_buff -> struct sk_buff
13419 * struct bpf_sock_ops -> struct sock
13421 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13423 const struct bpf_verifier_ops *ops = env->ops;
13424 int i, cnt, size, ctx_field_size, delta = 0;
13425 const int insn_cnt = env->prog->len;
13426 struct bpf_insn insn_buf[16], *insn;
13427 u32 target_size, size_default, off;
13428 struct bpf_prog *new_prog;
13429 enum bpf_access_type type;
13430 bool is_narrower_load;
13432 if (ops->gen_prologue || env->seen_direct_write) {
13433 if (!ops->gen_prologue) {
13434 verbose(env, "bpf verifier is misconfigured\n");
13437 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13439 if (cnt >= ARRAY_SIZE(insn_buf)) {
13440 verbose(env, "bpf verifier is misconfigured\n");
13443 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13447 env->prog = new_prog;
13452 if (bpf_prog_is_dev_bound(env->prog->aux))
13455 insn = env->prog->insnsi + delta;
13457 for (i = 0; i < insn_cnt; i++, insn++) {
13458 bpf_convert_ctx_access_t convert_ctx_access;
13461 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13462 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13463 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13464 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13467 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13468 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13469 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13470 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13471 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13472 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13473 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13474 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13476 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13481 if (type == BPF_WRITE &&
13482 env->insn_aux_data[i + delta].sanitize_stack_spill) {
13483 struct bpf_insn patch[] = {
13488 cnt = ARRAY_SIZE(patch);
13489 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13494 env->prog = new_prog;
13495 insn = new_prog->insnsi + i + delta;
13502 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13504 if (!ops->convert_ctx_access)
13506 convert_ctx_access = ops->convert_ctx_access;
13508 case PTR_TO_SOCKET:
13509 case PTR_TO_SOCK_COMMON:
13510 convert_ctx_access = bpf_sock_convert_ctx_access;
13512 case PTR_TO_TCP_SOCK:
13513 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13515 case PTR_TO_XDP_SOCK:
13516 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13518 case PTR_TO_BTF_ID:
13519 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13520 if (type == BPF_READ) {
13521 insn->code = BPF_LDX | BPF_PROBE_MEM |
13522 BPF_SIZE((insn)->code);
13523 env->prog->aux->num_exentries++;
13530 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13531 size = BPF_LDST_BYTES(insn);
13533 /* If the read access is a narrower load of the field,
13534 * convert to a 4/8-byte load, to minimum program type specific
13535 * convert_ctx_access changes. If conversion is successful,
13536 * we will apply proper mask to the result.
13538 is_narrower_load = size < ctx_field_size;
13539 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13541 if (is_narrower_load) {
13544 if (type == BPF_WRITE) {
13545 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13550 if (ctx_field_size == 4)
13552 else if (ctx_field_size == 8)
13553 size_code = BPF_DW;
13555 insn->off = off & ~(size_default - 1);
13556 insn->code = BPF_LDX | BPF_MEM | size_code;
13560 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13562 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13563 (ctx_field_size && !target_size)) {
13564 verbose(env, "bpf verifier is misconfigured\n");
13568 if (is_narrower_load && size < target_size) {
13569 u8 shift = bpf_ctx_narrow_access_offset(
13570 off, size, size_default) * 8;
13571 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13572 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13575 if (ctx_field_size <= 4) {
13577 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13580 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13581 (1 << size * 8) - 1);
13584 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13587 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13588 (1ULL << size * 8) - 1);
13592 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13598 /* keep walking new program and skip insns we just inserted */
13599 env->prog = new_prog;
13600 insn = new_prog->insnsi + i + delta;
13606 static int jit_subprogs(struct bpf_verifier_env *env)
13608 struct bpf_prog *prog = env->prog, **func, *tmp;
13609 int i, j, subprog_start, subprog_end = 0, len, subprog;
13610 struct bpf_map *map_ptr;
13611 struct bpf_insn *insn;
13612 void *old_bpf_func;
13613 int err, num_exentries;
13615 if (env->subprog_cnt <= 1)
13618 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13619 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13622 /* Upon error here we cannot fall back to interpreter but
13623 * need a hard reject of the program. Thus -EFAULT is
13624 * propagated in any case.
13626 subprog = find_subprog(env, i + insn->imm + 1);
13628 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13629 i + insn->imm + 1);
13632 /* temporarily remember subprog id inside insn instead of
13633 * aux_data, since next loop will split up all insns into funcs
13635 insn->off = subprog;
13636 /* remember original imm in case JIT fails and fallback
13637 * to interpreter will be needed
13639 env->insn_aux_data[i].call_imm = insn->imm;
13640 /* point imm to __bpf_call_base+1 from JITs point of view */
13642 if (bpf_pseudo_func(insn))
13643 /* jit (e.g. x86_64) may emit fewer instructions
13644 * if it learns a u32 imm is the same as a u64 imm.
13645 * Force a non zero here.
13650 err = bpf_prog_alloc_jited_linfo(prog);
13652 goto out_undo_insn;
13655 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13657 goto out_undo_insn;
13659 for (i = 0; i < env->subprog_cnt; i++) {
13660 subprog_start = subprog_end;
13661 subprog_end = env->subprog_info[i + 1].start;
13663 len = subprog_end - subprog_start;
13664 /* bpf_prog_run() doesn't call subprogs directly,
13665 * hence main prog stats include the runtime of subprogs.
13666 * subprogs don't have IDs and not reachable via prog_get_next_id
13667 * func[i]->stats will never be accessed and stays NULL
13669 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13672 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13673 len * sizeof(struct bpf_insn));
13674 func[i]->type = prog->type;
13675 func[i]->len = len;
13676 if (bpf_prog_calc_tag(func[i]))
13678 func[i]->is_func = 1;
13679 func[i]->aux->func_idx = i;
13680 /* Below members will be freed only at prog->aux */
13681 func[i]->aux->btf = prog->aux->btf;
13682 func[i]->aux->func_info = prog->aux->func_info;
13683 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13684 func[i]->aux->poke_tab = prog->aux->poke_tab;
13685 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13687 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13688 struct bpf_jit_poke_descriptor *poke;
13690 poke = &prog->aux->poke_tab[j];
13691 if (poke->insn_idx < subprog_end &&
13692 poke->insn_idx >= subprog_start)
13693 poke->aux = func[i]->aux;
13696 func[i]->aux->name[0] = 'F';
13697 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13698 func[i]->jit_requested = 1;
13699 func[i]->blinding_requested = prog->blinding_requested;
13700 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13701 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13702 func[i]->aux->linfo = prog->aux->linfo;
13703 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13704 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13705 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13707 insn = func[i]->insnsi;
13708 for (j = 0; j < func[i]->len; j++, insn++) {
13709 if (BPF_CLASS(insn->code) == BPF_LDX &&
13710 BPF_MODE(insn->code) == BPF_PROBE_MEM)
13713 func[i]->aux->num_exentries = num_exentries;
13714 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13715 func[i] = bpf_int_jit_compile(func[i]);
13716 if (!func[i]->jited) {
13723 /* at this point all bpf functions were successfully JITed
13724 * now populate all bpf_calls with correct addresses and
13725 * run last pass of JIT
13727 for (i = 0; i < env->subprog_cnt; i++) {
13728 insn = func[i]->insnsi;
13729 for (j = 0; j < func[i]->len; j++, insn++) {
13730 if (bpf_pseudo_func(insn)) {
13731 subprog = insn->off;
13732 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13733 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13736 if (!bpf_pseudo_call(insn))
13738 subprog = insn->off;
13739 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13742 /* we use the aux data to keep a list of the start addresses
13743 * of the JITed images for each function in the program
13745 * for some architectures, such as powerpc64, the imm field
13746 * might not be large enough to hold the offset of the start
13747 * address of the callee's JITed image from __bpf_call_base
13749 * in such cases, we can lookup the start address of a callee
13750 * by using its subprog id, available from the off field of
13751 * the call instruction, as an index for this list
13753 func[i]->aux->func = func;
13754 func[i]->aux->func_cnt = env->subprog_cnt;
13756 for (i = 0; i < env->subprog_cnt; i++) {
13757 old_bpf_func = func[i]->bpf_func;
13758 tmp = bpf_int_jit_compile(func[i]);
13759 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13760 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13767 /* finally lock prog and jit images for all functions and
13768 * populate kallsysm
13770 for (i = 0; i < env->subprog_cnt; i++) {
13771 bpf_prog_lock_ro(func[i]);
13772 bpf_prog_kallsyms_add(func[i]);
13775 /* Last step: make now unused interpreter insns from main
13776 * prog consistent for later dump requests, so they can
13777 * later look the same as if they were interpreted only.
13779 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13780 if (bpf_pseudo_func(insn)) {
13781 insn[0].imm = env->insn_aux_data[i].call_imm;
13782 insn[1].imm = insn->off;
13786 if (!bpf_pseudo_call(insn))
13788 insn->off = env->insn_aux_data[i].call_imm;
13789 subprog = find_subprog(env, i + insn->off + 1);
13790 insn->imm = subprog;
13794 prog->bpf_func = func[0]->bpf_func;
13795 prog->jited_len = func[0]->jited_len;
13796 prog->aux->func = func;
13797 prog->aux->func_cnt = env->subprog_cnt;
13798 bpf_prog_jit_attempt_done(prog);
13801 /* We failed JIT'ing, so at this point we need to unregister poke
13802 * descriptors from subprogs, so that kernel is not attempting to
13803 * patch it anymore as we're freeing the subprog JIT memory.
13805 for (i = 0; i < prog->aux->size_poke_tab; i++) {
13806 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13807 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13809 /* At this point we're guaranteed that poke descriptors are not
13810 * live anymore. We can just unlink its descriptor table as it's
13811 * released with the main prog.
13813 for (i = 0; i < env->subprog_cnt; i++) {
13816 func[i]->aux->poke_tab = NULL;
13817 bpf_jit_free(func[i]);
13821 /* cleanup main prog to be interpreted */
13822 prog->jit_requested = 0;
13823 prog->blinding_requested = 0;
13824 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13825 if (!bpf_pseudo_call(insn))
13828 insn->imm = env->insn_aux_data[i].call_imm;
13830 bpf_prog_jit_attempt_done(prog);
13834 static int fixup_call_args(struct bpf_verifier_env *env)
13836 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13837 struct bpf_prog *prog = env->prog;
13838 struct bpf_insn *insn = prog->insnsi;
13839 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13844 if (env->prog->jit_requested &&
13845 !bpf_prog_is_dev_bound(env->prog->aux)) {
13846 err = jit_subprogs(env);
13849 if (err == -EFAULT)
13852 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13853 if (has_kfunc_call) {
13854 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13857 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13858 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13859 * have to be rejected, since interpreter doesn't support them yet.
13861 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13864 for (i = 0; i < prog->len; i++, insn++) {
13865 if (bpf_pseudo_func(insn)) {
13866 /* When JIT fails the progs with callback calls
13867 * have to be rejected, since interpreter doesn't support them yet.
13869 verbose(env, "callbacks are not allowed in non-JITed programs\n");
13873 if (!bpf_pseudo_call(insn))
13875 depth = get_callee_stack_depth(env, insn, i);
13878 bpf_patch_call_args(insn, depth);
13885 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13886 struct bpf_insn *insn)
13888 const struct bpf_kfunc_desc *desc;
13891 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13895 /* insn->imm has the btf func_id. Replace it with
13896 * an address (relative to __bpf_base_call).
13898 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13900 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13905 insn->imm = desc->imm;
13910 /* Do various post-verification rewrites in a single program pass.
13911 * These rewrites simplify JIT and interpreter implementations.
13913 static int do_misc_fixups(struct bpf_verifier_env *env)
13915 struct bpf_prog *prog = env->prog;
13916 enum bpf_attach_type eatype = prog->expected_attach_type;
13917 enum bpf_prog_type prog_type = resolve_prog_type(prog);
13918 struct bpf_insn *insn = prog->insnsi;
13919 const struct bpf_func_proto *fn;
13920 const int insn_cnt = prog->len;
13921 const struct bpf_map_ops *ops;
13922 struct bpf_insn_aux_data *aux;
13923 struct bpf_insn insn_buf[16];
13924 struct bpf_prog *new_prog;
13925 struct bpf_map *map_ptr;
13926 int i, ret, cnt, delta = 0;
13928 for (i = 0; i < insn_cnt; i++, insn++) {
13929 /* Make divide-by-zero exceptions impossible. */
13930 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13931 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13932 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13933 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13934 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13935 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13936 struct bpf_insn *patchlet;
13937 struct bpf_insn chk_and_div[] = {
13938 /* [R,W]x div 0 -> 0 */
13939 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13940 BPF_JNE | BPF_K, insn->src_reg,
13942 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13943 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13946 struct bpf_insn chk_and_mod[] = {
13947 /* [R,W]x mod 0 -> [R,W]x */
13948 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13949 BPF_JEQ | BPF_K, insn->src_reg,
13950 0, 1 + (is64 ? 0 : 1), 0),
13952 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13953 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13956 patchlet = isdiv ? chk_and_div : chk_and_mod;
13957 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13958 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
13960 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
13965 env->prog = prog = new_prog;
13966 insn = new_prog->insnsi + i + delta;
13970 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
13971 if (BPF_CLASS(insn->code) == BPF_LD &&
13972 (BPF_MODE(insn->code) == BPF_ABS ||
13973 BPF_MODE(insn->code) == BPF_IND)) {
13974 cnt = env->ops->gen_ld_abs(insn, insn_buf);
13975 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13976 verbose(env, "bpf verifier is misconfigured\n");
13980 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13985 env->prog = prog = new_prog;
13986 insn = new_prog->insnsi + i + delta;
13990 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
13991 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13992 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13993 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13994 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
13995 struct bpf_insn *patch = &insn_buf[0];
13996 bool issrc, isneg, isimm;
13999 aux = &env->insn_aux_data[i + delta];
14000 if (!aux->alu_state ||
14001 aux->alu_state == BPF_ALU_NON_POINTER)
14004 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14005 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14006 BPF_ALU_SANITIZE_SRC;
14007 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14009 off_reg = issrc ? insn->src_reg : insn->dst_reg;
14011 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14014 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14015 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14016 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14017 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14018 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14019 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14020 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14023 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14024 insn->src_reg = BPF_REG_AX;
14026 insn->code = insn->code == code_add ?
14027 code_sub : code_add;
14029 if (issrc && isneg && !isimm)
14030 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14031 cnt = patch - insn_buf;
14033 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14038 env->prog = prog = new_prog;
14039 insn = new_prog->insnsi + i + delta;
14043 if (insn->code != (BPF_JMP | BPF_CALL))
14045 if (insn->src_reg == BPF_PSEUDO_CALL)
14047 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14048 ret = fixup_kfunc_call(env, insn);
14054 if (insn->imm == BPF_FUNC_get_route_realm)
14055 prog->dst_needed = 1;
14056 if (insn->imm == BPF_FUNC_get_prandom_u32)
14057 bpf_user_rnd_init_once();
14058 if (insn->imm == BPF_FUNC_override_return)
14059 prog->kprobe_override = 1;
14060 if (insn->imm == BPF_FUNC_tail_call) {
14061 /* If we tail call into other programs, we
14062 * cannot make any assumptions since they can
14063 * be replaced dynamically during runtime in
14064 * the program array.
14066 prog->cb_access = 1;
14067 if (!allow_tail_call_in_subprogs(env))
14068 prog->aux->stack_depth = MAX_BPF_STACK;
14069 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14071 /* mark bpf_tail_call as different opcode to avoid
14072 * conditional branch in the interpreter for every normal
14073 * call and to prevent accidental JITing by JIT compiler
14074 * that doesn't support bpf_tail_call yet
14077 insn->code = BPF_JMP | BPF_TAIL_CALL;
14079 aux = &env->insn_aux_data[i + delta];
14080 if (env->bpf_capable && !prog->blinding_requested &&
14081 prog->jit_requested &&
14082 !bpf_map_key_poisoned(aux) &&
14083 !bpf_map_ptr_poisoned(aux) &&
14084 !bpf_map_ptr_unpriv(aux)) {
14085 struct bpf_jit_poke_descriptor desc = {
14086 .reason = BPF_POKE_REASON_TAIL_CALL,
14087 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14088 .tail_call.key = bpf_map_key_immediate(aux),
14089 .insn_idx = i + delta,
14092 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14094 verbose(env, "adding tail call poke descriptor failed\n");
14098 insn->imm = ret + 1;
14102 if (!bpf_map_ptr_unpriv(aux))
14105 /* instead of changing every JIT dealing with tail_call
14106 * emit two extra insns:
14107 * if (index >= max_entries) goto out;
14108 * index &= array->index_mask;
14109 * to avoid out-of-bounds cpu speculation
14111 if (bpf_map_ptr_poisoned(aux)) {
14112 verbose(env, "tail_call abusing map_ptr\n");
14116 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14117 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14118 map_ptr->max_entries, 2);
14119 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14120 container_of(map_ptr,
14123 insn_buf[2] = *insn;
14125 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14130 env->prog = prog = new_prog;
14131 insn = new_prog->insnsi + i + delta;
14135 if (insn->imm == BPF_FUNC_timer_set_callback) {
14136 /* The verifier will process callback_fn as many times as necessary
14137 * with different maps and the register states prepared by
14138 * set_timer_callback_state will be accurate.
14140 * The following use case is valid:
14141 * map1 is shared by prog1, prog2, prog3.
14142 * prog1 calls bpf_timer_init for some map1 elements
14143 * prog2 calls bpf_timer_set_callback for some map1 elements.
14144 * Those that were not bpf_timer_init-ed will return -EINVAL.
14145 * prog3 calls bpf_timer_start for some map1 elements.
14146 * Those that were not both bpf_timer_init-ed and
14147 * bpf_timer_set_callback-ed will return -EINVAL.
14149 struct bpf_insn ld_addrs[2] = {
14150 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14153 insn_buf[0] = ld_addrs[0];
14154 insn_buf[1] = ld_addrs[1];
14155 insn_buf[2] = *insn;
14158 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14163 env->prog = prog = new_prog;
14164 insn = new_prog->insnsi + i + delta;
14165 goto patch_call_imm;
14168 if (insn->imm == BPF_FUNC_task_storage_get ||
14169 insn->imm == BPF_FUNC_sk_storage_get ||
14170 insn->imm == BPF_FUNC_inode_storage_get) {
14171 if (env->prog->aux->sleepable)
14172 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14174 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14175 insn_buf[1] = *insn;
14178 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14183 env->prog = prog = new_prog;
14184 insn = new_prog->insnsi + i + delta;
14185 goto patch_call_imm;
14188 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14189 * and other inlining handlers are currently limited to 64 bit
14192 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14193 (insn->imm == BPF_FUNC_map_lookup_elem ||
14194 insn->imm == BPF_FUNC_map_update_elem ||
14195 insn->imm == BPF_FUNC_map_delete_elem ||
14196 insn->imm == BPF_FUNC_map_push_elem ||
14197 insn->imm == BPF_FUNC_map_pop_elem ||
14198 insn->imm == BPF_FUNC_map_peek_elem ||
14199 insn->imm == BPF_FUNC_redirect_map ||
14200 insn->imm == BPF_FUNC_for_each_map_elem ||
14201 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14202 aux = &env->insn_aux_data[i + delta];
14203 if (bpf_map_ptr_poisoned(aux))
14204 goto patch_call_imm;
14206 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14207 ops = map_ptr->ops;
14208 if (insn->imm == BPF_FUNC_map_lookup_elem &&
14209 ops->map_gen_lookup) {
14210 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14211 if (cnt == -EOPNOTSUPP)
14212 goto patch_map_ops_generic;
14213 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14214 verbose(env, "bpf verifier is misconfigured\n");
14218 new_prog = bpf_patch_insn_data(env, i + delta,
14224 env->prog = prog = new_prog;
14225 insn = new_prog->insnsi + i + delta;
14229 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14230 (void *(*)(struct bpf_map *map, void *key))NULL));
14231 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14232 (int (*)(struct bpf_map *map, void *key))NULL));
14233 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14234 (int (*)(struct bpf_map *map, void *key, void *value,
14236 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14237 (int (*)(struct bpf_map *map, void *value,
14239 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14240 (int (*)(struct bpf_map *map, void *value))NULL));
14241 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14242 (int (*)(struct bpf_map *map, void *value))NULL));
14243 BUILD_BUG_ON(!__same_type(ops->map_redirect,
14244 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14245 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14246 (int (*)(struct bpf_map *map,
14247 bpf_callback_t callback_fn,
14248 void *callback_ctx,
14250 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14251 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14253 patch_map_ops_generic:
14254 switch (insn->imm) {
14255 case BPF_FUNC_map_lookup_elem:
14256 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14258 case BPF_FUNC_map_update_elem:
14259 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14261 case BPF_FUNC_map_delete_elem:
14262 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14264 case BPF_FUNC_map_push_elem:
14265 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14267 case BPF_FUNC_map_pop_elem:
14268 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14270 case BPF_FUNC_map_peek_elem:
14271 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14273 case BPF_FUNC_redirect_map:
14274 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14276 case BPF_FUNC_for_each_map_elem:
14277 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14279 case BPF_FUNC_map_lookup_percpu_elem:
14280 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14284 goto patch_call_imm;
14287 /* Implement bpf_jiffies64 inline. */
14288 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14289 insn->imm == BPF_FUNC_jiffies64) {
14290 struct bpf_insn ld_jiffies_addr[2] = {
14291 BPF_LD_IMM64(BPF_REG_0,
14292 (unsigned long)&jiffies),
14295 insn_buf[0] = ld_jiffies_addr[0];
14296 insn_buf[1] = ld_jiffies_addr[1];
14297 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14301 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14307 env->prog = prog = new_prog;
14308 insn = new_prog->insnsi + i + delta;
14312 /* Implement bpf_get_func_arg inline. */
14313 if (prog_type == BPF_PROG_TYPE_TRACING &&
14314 insn->imm == BPF_FUNC_get_func_arg) {
14315 /* Load nr_args from ctx - 8 */
14316 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14317 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14318 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14319 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14320 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14321 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14322 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14323 insn_buf[7] = BPF_JMP_A(1);
14324 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14327 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14332 env->prog = prog = new_prog;
14333 insn = new_prog->insnsi + i + delta;
14337 /* Implement bpf_get_func_ret inline. */
14338 if (prog_type == BPF_PROG_TYPE_TRACING &&
14339 insn->imm == BPF_FUNC_get_func_ret) {
14340 if (eatype == BPF_TRACE_FEXIT ||
14341 eatype == BPF_MODIFY_RETURN) {
14342 /* Load nr_args from ctx - 8 */
14343 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14344 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14345 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14346 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14347 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14348 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14351 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14355 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14360 env->prog = prog = new_prog;
14361 insn = new_prog->insnsi + i + delta;
14365 /* Implement get_func_arg_cnt inline. */
14366 if (prog_type == BPF_PROG_TYPE_TRACING &&
14367 insn->imm == BPF_FUNC_get_func_arg_cnt) {
14368 /* Load nr_args from ctx - 8 */
14369 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14371 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14375 env->prog = prog = new_prog;
14376 insn = new_prog->insnsi + i + delta;
14380 /* Implement bpf_get_func_ip inline. */
14381 if (prog_type == BPF_PROG_TYPE_TRACING &&
14382 insn->imm == BPF_FUNC_get_func_ip) {
14383 /* Load IP address from ctx - 16 */
14384 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14386 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14390 env->prog = prog = new_prog;
14391 insn = new_prog->insnsi + i + delta;
14396 fn = env->ops->get_func_proto(insn->imm, env->prog);
14397 /* all functions that have prototype and verifier allowed
14398 * programs to call them, must be real in-kernel functions
14402 "kernel subsystem misconfigured func %s#%d\n",
14403 func_id_name(insn->imm), insn->imm);
14406 insn->imm = fn->func - __bpf_call_base;
14409 /* Since poke tab is now finalized, publish aux to tracker. */
14410 for (i = 0; i < prog->aux->size_poke_tab; i++) {
14411 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14412 if (!map_ptr->ops->map_poke_track ||
14413 !map_ptr->ops->map_poke_untrack ||
14414 !map_ptr->ops->map_poke_run) {
14415 verbose(env, "bpf verifier is misconfigured\n");
14419 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14421 verbose(env, "tracking tail call prog failed\n");
14426 sort_kfunc_descs_by_imm(env->prog);
14431 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14434 u32 callback_subprogno,
14437 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14438 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14439 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14440 int reg_loop_max = BPF_REG_6;
14441 int reg_loop_cnt = BPF_REG_7;
14442 int reg_loop_ctx = BPF_REG_8;
14444 struct bpf_prog *new_prog;
14445 u32 callback_start;
14446 u32 call_insn_offset;
14447 s32 callback_offset;
14449 /* This represents an inlined version of bpf_iter.c:bpf_loop,
14450 * be careful to modify this code in sync.
14452 struct bpf_insn insn_buf[] = {
14453 /* Return error and jump to the end of the patch if
14454 * expected number of iterations is too big.
14456 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14457 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14458 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14459 /* spill R6, R7, R8 to use these as loop vars */
14460 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14461 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14462 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14463 /* initialize loop vars */
14464 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14465 BPF_MOV32_IMM(reg_loop_cnt, 0),
14466 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14468 * if reg_loop_cnt >= reg_loop_max skip the loop body
14470 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14472 * correct callback offset would be set after patching
14474 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14475 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14477 /* increment loop counter */
14478 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14479 /* jump to loop header if callback returned 0 */
14480 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14481 /* return value of bpf_loop,
14482 * set R0 to the number of iterations
14484 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14485 /* restore original values of R6, R7, R8 */
14486 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14487 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14488 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14491 *cnt = ARRAY_SIZE(insn_buf);
14492 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14496 /* callback start is known only after patching */
14497 callback_start = env->subprog_info[callback_subprogno].start;
14498 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14499 call_insn_offset = position + 12;
14500 callback_offset = callback_start - call_insn_offset - 1;
14501 new_prog->insnsi[call_insn_offset].imm = callback_offset;
14506 static bool is_bpf_loop_call(struct bpf_insn *insn)
14508 return insn->code == (BPF_JMP | BPF_CALL) &&
14509 insn->src_reg == 0 &&
14510 insn->imm == BPF_FUNC_loop;
14513 /* For all sub-programs in the program (including main) check
14514 * insn_aux_data to see if there are bpf_loop calls that require
14515 * inlining. If such calls are found the calls are replaced with a
14516 * sequence of instructions produced by `inline_bpf_loop` function and
14517 * subprog stack_depth is increased by the size of 3 registers.
14518 * This stack space is used to spill values of the R6, R7, R8. These
14519 * registers are used to store the loop bound, counter and context
14522 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14524 struct bpf_subprog_info *subprogs = env->subprog_info;
14525 int i, cur_subprog = 0, cnt, delta = 0;
14526 struct bpf_insn *insn = env->prog->insnsi;
14527 int insn_cnt = env->prog->len;
14528 u16 stack_depth = subprogs[cur_subprog].stack_depth;
14529 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14530 u16 stack_depth_extra = 0;
14532 for (i = 0; i < insn_cnt; i++, insn++) {
14533 struct bpf_loop_inline_state *inline_state =
14534 &env->insn_aux_data[i + delta].loop_inline_state;
14536 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14537 struct bpf_prog *new_prog;
14539 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14540 new_prog = inline_bpf_loop(env,
14542 -(stack_depth + stack_depth_extra),
14543 inline_state->callback_subprogno,
14549 env->prog = new_prog;
14550 insn = new_prog->insnsi + i + delta;
14553 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14554 subprogs[cur_subprog].stack_depth += stack_depth_extra;
14556 stack_depth = subprogs[cur_subprog].stack_depth;
14557 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14558 stack_depth_extra = 0;
14562 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14567 static void free_states(struct bpf_verifier_env *env)
14569 struct bpf_verifier_state_list *sl, *sln;
14572 sl = env->free_list;
14575 free_verifier_state(&sl->state, false);
14579 env->free_list = NULL;
14581 if (!env->explored_states)
14584 for (i = 0; i < state_htab_size(env); i++) {
14585 sl = env->explored_states[i];
14589 free_verifier_state(&sl->state, false);
14593 env->explored_states[i] = NULL;
14597 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14599 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14600 struct bpf_verifier_state *state;
14601 struct bpf_reg_state *regs;
14604 env->prev_linfo = NULL;
14607 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14610 state->curframe = 0;
14611 state->speculative = false;
14612 state->branches = 1;
14613 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14614 if (!state->frame[0]) {
14618 env->cur_state = state;
14619 init_func_state(env, state->frame[0],
14620 BPF_MAIN_FUNC /* callsite */,
14624 regs = state->frame[state->curframe]->regs;
14625 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14626 ret = btf_prepare_func_args(env, subprog, regs);
14629 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14630 if (regs[i].type == PTR_TO_CTX)
14631 mark_reg_known_zero(env, regs, i);
14632 else if (regs[i].type == SCALAR_VALUE)
14633 mark_reg_unknown(env, regs, i);
14634 else if (base_type(regs[i].type) == PTR_TO_MEM) {
14635 const u32 mem_size = regs[i].mem_size;
14637 mark_reg_known_zero(env, regs, i);
14638 regs[i].mem_size = mem_size;
14639 regs[i].id = ++env->id_gen;
14643 /* 1st arg to a function */
14644 regs[BPF_REG_1].type = PTR_TO_CTX;
14645 mark_reg_known_zero(env, regs, BPF_REG_1);
14646 ret = btf_check_subprog_arg_match(env, subprog, regs);
14647 if (ret == -EFAULT)
14648 /* unlikely verifier bug. abort.
14649 * ret == 0 and ret < 0 are sadly acceptable for
14650 * main() function due to backward compatibility.
14651 * Like socket filter program may be written as:
14652 * int bpf_prog(struct pt_regs *ctx)
14653 * and never dereference that ctx in the program.
14654 * 'struct pt_regs' is a type mismatch for socket
14655 * filter that should be using 'struct __sk_buff'.
14660 ret = do_check(env);
14662 /* check for NULL is necessary, since cur_state can be freed inside
14663 * do_check() under memory pressure.
14665 if (env->cur_state) {
14666 free_verifier_state(env->cur_state, true);
14667 env->cur_state = NULL;
14669 while (!pop_stack(env, NULL, NULL, false));
14670 if (!ret && pop_log)
14671 bpf_vlog_reset(&env->log, 0);
14676 /* Verify all global functions in a BPF program one by one based on their BTF.
14677 * All global functions must pass verification. Otherwise the whole program is rejected.
14688 * foo() will be verified first for R1=any_scalar_value. During verification it
14689 * will be assumed that bar() already verified successfully and call to bar()
14690 * from foo() will be checked for type match only. Later bar() will be verified
14691 * independently to check that it's safe for R1=any_scalar_value.
14693 static int do_check_subprogs(struct bpf_verifier_env *env)
14695 struct bpf_prog_aux *aux = env->prog->aux;
14698 if (!aux->func_info)
14701 for (i = 1; i < env->subprog_cnt; i++) {
14702 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14704 env->insn_idx = env->subprog_info[i].start;
14705 WARN_ON_ONCE(env->insn_idx == 0);
14706 ret = do_check_common(env, i);
14709 } else if (env->log.level & BPF_LOG_LEVEL) {
14711 "Func#%d is safe for any args that match its prototype\n",
14718 static int do_check_main(struct bpf_verifier_env *env)
14723 ret = do_check_common(env, 0);
14725 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14730 static void print_verification_stats(struct bpf_verifier_env *env)
14734 if (env->log.level & BPF_LOG_STATS) {
14735 verbose(env, "verification time %lld usec\n",
14736 div_u64(env->verification_time, 1000));
14737 verbose(env, "stack depth ");
14738 for (i = 0; i < env->subprog_cnt; i++) {
14739 u32 depth = env->subprog_info[i].stack_depth;
14741 verbose(env, "%d", depth);
14742 if (i + 1 < env->subprog_cnt)
14745 verbose(env, "\n");
14747 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14748 "total_states %d peak_states %d mark_read %d\n",
14749 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14750 env->max_states_per_insn, env->total_states,
14751 env->peak_states, env->longest_mark_read_walk);
14754 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14756 const struct btf_type *t, *func_proto;
14757 const struct bpf_struct_ops *st_ops;
14758 const struct btf_member *member;
14759 struct bpf_prog *prog = env->prog;
14760 u32 btf_id, member_idx;
14763 if (!prog->gpl_compatible) {
14764 verbose(env, "struct ops programs must have a GPL compatible license\n");
14768 btf_id = prog->aux->attach_btf_id;
14769 st_ops = bpf_struct_ops_find(btf_id);
14771 verbose(env, "attach_btf_id %u is not a supported struct\n",
14777 member_idx = prog->expected_attach_type;
14778 if (member_idx >= btf_type_vlen(t)) {
14779 verbose(env, "attach to invalid member idx %u of struct %s\n",
14780 member_idx, st_ops->name);
14784 member = &btf_type_member(t)[member_idx];
14785 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14786 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14789 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14790 mname, member_idx, st_ops->name);
14794 if (st_ops->check_member) {
14795 int err = st_ops->check_member(t, member);
14798 verbose(env, "attach to unsupported member %s of struct %s\n",
14799 mname, st_ops->name);
14804 prog->aux->attach_func_proto = func_proto;
14805 prog->aux->attach_func_name = mname;
14806 env->ops = st_ops->verifier_ops;
14810 #define SECURITY_PREFIX "security_"
14812 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14814 if (within_error_injection_list(addr) ||
14815 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14821 /* list of non-sleepable functions that are otherwise on
14822 * ALLOW_ERROR_INJECTION list
14824 BTF_SET_START(btf_non_sleepable_error_inject)
14825 /* Three functions below can be called from sleepable and non-sleepable context.
14826 * Assume non-sleepable from bpf safety point of view.
14828 BTF_ID(func, __filemap_add_folio)
14829 BTF_ID(func, should_fail_alloc_page)
14830 BTF_ID(func, should_failslab)
14831 BTF_SET_END(btf_non_sleepable_error_inject)
14833 static int check_non_sleepable_error_inject(u32 btf_id)
14835 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14838 int bpf_check_attach_target(struct bpf_verifier_log *log,
14839 const struct bpf_prog *prog,
14840 const struct bpf_prog *tgt_prog,
14842 struct bpf_attach_target_info *tgt_info)
14844 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14845 const char prefix[] = "btf_trace_";
14846 int ret = 0, subprog = -1, i;
14847 const struct btf_type *t;
14848 bool conservative = true;
14854 bpf_log(log, "Tracing programs must provide btf_id\n");
14857 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14860 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14863 t = btf_type_by_id(btf, btf_id);
14865 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14868 tname = btf_name_by_offset(btf, t->name_off);
14870 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14874 struct bpf_prog_aux *aux = tgt_prog->aux;
14876 for (i = 0; i < aux->func_info_cnt; i++)
14877 if (aux->func_info[i].type_id == btf_id) {
14881 if (subprog == -1) {
14882 bpf_log(log, "Subprog %s doesn't exist\n", tname);
14885 conservative = aux->func_info_aux[subprog].unreliable;
14886 if (prog_extension) {
14887 if (conservative) {
14889 "Cannot replace static functions\n");
14892 if (!prog->jit_requested) {
14894 "Extension programs should be JITed\n");
14898 if (!tgt_prog->jited) {
14899 bpf_log(log, "Can attach to only JITed progs\n");
14902 if (tgt_prog->type == prog->type) {
14903 /* Cannot fentry/fexit another fentry/fexit program.
14904 * Cannot attach program extension to another extension.
14905 * It's ok to attach fentry/fexit to extension program.
14907 bpf_log(log, "Cannot recursively attach\n");
14910 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14912 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14913 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14914 /* Program extensions can extend all program types
14915 * except fentry/fexit. The reason is the following.
14916 * The fentry/fexit programs are used for performance
14917 * analysis, stats and can be attached to any program
14918 * type except themselves. When extension program is
14919 * replacing XDP function it is necessary to allow
14920 * performance analysis of all functions. Both original
14921 * XDP program and its program extension. Hence
14922 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14923 * allowed. If extending of fentry/fexit was allowed it
14924 * would be possible to create long call chain
14925 * fentry->extension->fentry->extension beyond
14926 * reasonable stack size. Hence extending fentry is not
14929 bpf_log(log, "Cannot extend fentry/fexit\n");
14933 if (prog_extension) {
14934 bpf_log(log, "Cannot replace kernel functions\n");
14939 switch (prog->expected_attach_type) {
14940 case BPF_TRACE_RAW_TP:
14943 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14946 if (!btf_type_is_typedef(t)) {
14947 bpf_log(log, "attach_btf_id %u is not a typedef\n",
14951 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
14952 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
14956 tname += sizeof(prefix) - 1;
14957 t = btf_type_by_id(btf, t->type);
14958 if (!btf_type_is_ptr(t))
14959 /* should never happen in valid vmlinux build */
14961 t = btf_type_by_id(btf, t->type);
14962 if (!btf_type_is_func_proto(t))
14963 /* should never happen in valid vmlinux build */
14967 case BPF_TRACE_ITER:
14968 if (!btf_type_is_func(t)) {
14969 bpf_log(log, "attach_btf_id %u is not a function\n",
14973 t = btf_type_by_id(btf, t->type);
14974 if (!btf_type_is_func_proto(t))
14976 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14981 if (!prog_extension)
14984 case BPF_MODIFY_RETURN:
14986 case BPF_LSM_CGROUP:
14987 case BPF_TRACE_FENTRY:
14988 case BPF_TRACE_FEXIT:
14989 if (!btf_type_is_func(t)) {
14990 bpf_log(log, "attach_btf_id %u is not a function\n",
14994 if (prog_extension &&
14995 btf_check_type_match(log, prog, btf, t))
14997 t = btf_type_by_id(btf, t->type);
14998 if (!btf_type_is_func_proto(t))
15001 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15002 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15003 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15006 if (tgt_prog && conservative)
15009 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15015 addr = (long) tgt_prog->bpf_func;
15017 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15019 addr = kallsyms_lookup_name(tname);
15022 "The address of function %s cannot be found\n",
15028 if (prog->aux->sleepable) {
15030 switch (prog->type) {
15031 case BPF_PROG_TYPE_TRACING:
15032 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
15033 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15035 if (!check_non_sleepable_error_inject(btf_id) &&
15036 within_error_injection_list(addr))
15039 case BPF_PROG_TYPE_LSM:
15040 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
15041 * Only some of them are sleepable.
15043 if (bpf_lsm_is_sleepable_hook(btf_id))
15050 bpf_log(log, "%s is not sleepable\n", tname);
15053 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15055 bpf_log(log, "can't modify return codes of BPF programs\n");
15058 ret = check_attach_modify_return(addr, tname);
15060 bpf_log(log, "%s() is not modifiable\n", tname);
15067 tgt_info->tgt_addr = addr;
15068 tgt_info->tgt_name = tname;
15069 tgt_info->tgt_type = t;
15073 BTF_SET_START(btf_id_deny)
15076 BTF_ID(func, migrate_disable)
15077 BTF_ID(func, migrate_enable)
15079 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15080 BTF_ID(func, rcu_read_unlock_strict)
15082 BTF_SET_END(btf_id_deny)
15084 static int check_attach_btf_id(struct bpf_verifier_env *env)
15086 struct bpf_prog *prog = env->prog;
15087 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15088 struct bpf_attach_target_info tgt_info = {};
15089 u32 btf_id = prog->aux->attach_btf_id;
15090 struct bpf_trampoline *tr;
15094 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15095 if (prog->aux->sleepable)
15096 /* attach_btf_id checked to be zero already */
15098 verbose(env, "Syscall programs can only be sleepable\n");
15102 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15103 prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15104 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15108 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15109 return check_struct_ops_btf_id(env);
15111 if (prog->type != BPF_PROG_TYPE_TRACING &&
15112 prog->type != BPF_PROG_TYPE_LSM &&
15113 prog->type != BPF_PROG_TYPE_EXT)
15116 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15120 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15121 /* to make freplace equivalent to their targets, they need to
15122 * inherit env->ops and expected_attach_type for the rest of the
15125 env->ops = bpf_verifier_ops[tgt_prog->type];
15126 prog->expected_attach_type = tgt_prog->expected_attach_type;
15129 /* store info about the attachment target that will be used later */
15130 prog->aux->attach_func_proto = tgt_info.tgt_type;
15131 prog->aux->attach_func_name = tgt_info.tgt_name;
15134 prog->aux->saved_dst_prog_type = tgt_prog->type;
15135 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15138 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15139 prog->aux->attach_btf_trace = true;
15141 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15142 if (!bpf_iter_prog_supported(prog))
15147 if (prog->type == BPF_PROG_TYPE_LSM) {
15148 ret = bpf_lsm_verify_prog(&env->log, prog);
15151 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15152 btf_id_set_contains(&btf_id_deny, btf_id)) {
15156 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15157 tr = bpf_trampoline_get(key, &tgt_info);
15161 prog->aux->dst_trampoline = tr;
15165 struct btf *bpf_get_btf_vmlinux(void)
15167 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15168 mutex_lock(&bpf_verifier_lock);
15170 btf_vmlinux = btf_parse_vmlinux();
15171 mutex_unlock(&bpf_verifier_lock);
15173 return btf_vmlinux;
15176 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15178 u64 start_time = ktime_get_ns();
15179 struct bpf_verifier_env *env;
15180 struct bpf_verifier_log *log;
15181 int i, len, ret = -EINVAL;
15184 /* no program is valid */
15185 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15188 /* 'struct bpf_verifier_env' can be global, but since it's not small,
15189 * allocate/free it every time bpf_check() is called
15191 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15196 len = (*prog)->len;
15197 env->insn_aux_data =
15198 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15200 if (!env->insn_aux_data)
15202 for (i = 0; i < len; i++)
15203 env->insn_aux_data[i].orig_idx = i;
15205 env->ops = bpf_verifier_ops[env->prog->type];
15206 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15207 is_priv = bpf_capable();
15209 bpf_get_btf_vmlinux();
15211 /* grab the mutex to protect few globals used by verifier */
15213 mutex_lock(&bpf_verifier_lock);
15215 if (attr->log_level || attr->log_buf || attr->log_size) {
15216 /* user requested verbose verifier output
15217 * and supplied buffer to store the verification trace
15219 log->level = attr->log_level;
15220 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15221 log->len_total = attr->log_size;
15223 /* log attributes have to be sane */
15224 if (!bpf_verifier_log_attr_valid(log)) {
15230 mark_verifier_state_clean(env);
15232 if (IS_ERR(btf_vmlinux)) {
15233 /* Either gcc or pahole or kernel are broken. */
15234 verbose(env, "in-kernel BTF is malformed\n");
15235 ret = PTR_ERR(btf_vmlinux);
15236 goto skip_full_check;
15239 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15240 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15241 env->strict_alignment = true;
15242 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15243 env->strict_alignment = false;
15245 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15246 env->allow_uninit_stack = bpf_allow_uninit_stack();
15247 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15248 env->bypass_spec_v1 = bpf_bypass_spec_v1();
15249 env->bypass_spec_v4 = bpf_bypass_spec_v4();
15250 env->bpf_capable = bpf_capable();
15253 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15255 env->explored_states = kvcalloc(state_htab_size(env),
15256 sizeof(struct bpf_verifier_state_list *),
15259 if (!env->explored_states)
15260 goto skip_full_check;
15262 ret = add_subprog_and_kfunc(env);
15264 goto skip_full_check;
15266 ret = check_subprogs(env);
15268 goto skip_full_check;
15270 ret = check_btf_info(env, attr, uattr);
15272 goto skip_full_check;
15274 ret = check_attach_btf_id(env);
15276 goto skip_full_check;
15278 ret = resolve_pseudo_ldimm64(env);
15280 goto skip_full_check;
15282 if (bpf_prog_is_dev_bound(env->prog->aux)) {
15283 ret = bpf_prog_offload_verifier_prep(env->prog);
15285 goto skip_full_check;
15288 ret = check_cfg(env);
15290 goto skip_full_check;
15292 ret = do_check_subprogs(env);
15293 ret = ret ?: do_check_main(env);
15295 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15296 ret = bpf_prog_offload_finalize(env);
15299 kvfree(env->explored_states);
15302 ret = check_max_stack_depth(env);
15304 /* instruction rewrites happen after this point */
15306 ret = optimize_bpf_loop(env);
15310 opt_hard_wire_dead_code_branches(env);
15312 ret = opt_remove_dead_code(env);
15314 ret = opt_remove_nops(env);
15317 sanitize_dead_code(env);
15321 /* program is valid, convert *(u32*)(ctx + off) accesses */
15322 ret = convert_ctx_accesses(env);
15325 ret = do_misc_fixups(env);
15327 /* do 32-bit optimization after insn patching has done so those patched
15328 * insns could be handled correctly.
15330 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15331 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15332 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15337 ret = fixup_call_args(env);
15339 env->verification_time = ktime_get_ns() - start_time;
15340 print_verification_stats(env);
15341 env->prog->aux->verified_insns = env->insn_processed;
15343 if (log->level && bpf_verifier_log_full(log))
15345 if (log->level && !log->ubuf) {
15347 goto err_release_maps;
15351 goto err_release_maps;
15353 if (env->used_map_cnt) {
15354 /* if program passed verifier, update used_maps in bpf_prog_info */
15355 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15356 sizeof(env->used_maps[0]),
15359 if (!env->prog->aux->used_maps) {
15361 goto err_release_maps;
15364 memcpy(env->prog->aux->used_maps, env->used_maps,
15365 sizeof(env->used_maps[0]) * env->used_map_cnt);
15366 env->prog->aux->used_map_cnt = env->used_map_cnt;
15368 if (env->used_btf_cnt) {
15369 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15370 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15371 sizeof(env->used_btfs[0]),
15373 if (!env->prog->aux->used_btfs) {
15375 goto err_release_maps;
15378 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15379 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15380 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15382 if (env->used_map_cnt || env->used_btf_cnt) {
15383 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15384 * bpf_ld_imm64 instructions
15386 convert_pseudo_ld_imm64(env);
15389 adjust_btf_func(env);
15392 if (!env->prog->aux->used_maps)
15393 /* if we didn't copy map pointers into bpf_prog_info, release
15394 * them now. Otherwise free_used_maps() will release them.
15397 if (!env->prog->aux->used_btfs)
15400 /* extension progs temporarily inherit the attach_type of their targets
15401 for verification purposes, so set it back to zero before returning
15403 if (env->prog->type == BPF_PROG_TYPE_EXT)
15404 env->prog->expected_attach_type = 0;
15409 mutex_unlock(&bpf_verifier_lock);
15410 vfree(env->insn_aux_data);