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 btf_field *kptr_field;
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 struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
456 struct btf_record *rec = NULL;
457 struct btf_struct_meta *meta;
459 if (reg->type == PTR_TO_MAP_VALUE) {
460 rec = reg->map_ptr->record;
461 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
462 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
469 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
471 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
474 static bool type_is_rdonly_mem(u32 type)
476 return type & MEM_RDONLY;
479 static bool type_may_be_null(u32 type)
481 return type & PTR_MAYBE_NULL;
484 static bool is_acquire_function(enum bpf_func_id func_id,
485 const struct bpf_map *map)
487 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
489 if (func_id == BPF_FUNC_sk_lookup_tcp ||
490 func_id == BPF_FUNC_sk_lookup_udp ||
491 func_id == BPF_FUNC_skc_lookup_tcp ||
492 func_id == BPF_FUNC_ringbuf_reserve ||
493 func_id == BPF_FUNC_kptr_xchg)
496 if (func_id == BPF_FUNC_map_lookup_elem &&
497 (map_type == BPF_MAP_TYPE_SOCKMAP ||
498 map_type == BPF_MAP_TYPE_SOCKHASH))
504 static bool is_ptr_cast_function(enum bpf_func_id func_id)
506 return func_id == BPF_FUNC_tcp_sock ||
507 func_id == BPF_FUNC_sk_fullsock ||
508 func_id == BPF_FUNC_skc_to_tcp_sock ||
509 func_id == BPF_FUNC_skc_to_tcp6_sock ||
510 func_id == BPF_FUNC_skc_to_udp6_sock ||
511 func_id == BPF_FUNC_skc_to_mptcp_sock ||
512 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
513 func_id == BPF_FUNC_skc_to_tcp_request_sock;
516 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
518 return func_id == BPF_FUNC_dynptr_data;
521 static bool is_callback_calling_function(enum bpf_func_id func_id)
523 return func_id == BPF_FUNC_for_each_map_elem ||
524 func_id == BPF_FUNC_timer_set_callback ||
525 func_id == BPF_FUNC_find_vma ||
526 func_id == BPF_FUNC_loop ||
527 func_id == BPF_FUNC_user_ringbuf_drain;
530 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
531 const struct bpf_map *map)
533 int ref_obj_uses = 0;
535 if (is_ptr_cast_function(func_id))
537 if (is_acquire_function(func_id, map))
539 if (is_dynptr_ref_function(func_id))
542 return ref_obj_uses > 1;
545 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
547 return BPF_CLASS(insn->code) == BPF_STX &&
548 BPF_MODE(insn->code) == BPF_ATOMIC &&
549 insn->imm == BPF_CMPXCHG;
552 /* string representation of 'enum bpf_reg_type'
554 * Note that reg_type_str() can not appear more than once in a single verbose()
557 static const char *reg_type_str(struct bpf_verifier_env *env,
558 enum bpf_reg_type type)
560 char postfix[16] = {0}, prefix[64] = {0};
561 static const char * const str[] = {
563 [SCALAR_VALUE] = "scalar",
564 [PTR_TO_CTX] = "ctx",
565 [CONST_PTR_TO_MAP] = "map_ptr",
566 [PTR_TO_MAP_VALUE] = "map_value",
567 [PTR_TO_STACK] = "fp",
568 [PTR_TO_PACKET] = "pkt",
569 [PTR_TO_PACKET_META] = "pkt_meta",
570 [PTR_TO_PACKET_END] = "pkt_end",
571 [PTR_TO_FLOW_KEYS] = "flow_keys",
572 [PTR_TO_SOCKET] = "sock",
573 [PTR_TO_SOCK_COMMON] = "sock_common",
574 [PTR_TO_TCP_SOCK] = "tcp_sock",
575 [PTR_TO_TP_BUFFER] = "tp_buffer",
576 [PTR_TO_XDP_SOCK] = "xdp_sock",
577 [PTR_TO_BTF_ID] = "ptr_",
578 [PTR_TO_MEM] = "mem",
579 [PTR_TO_BUF] = "buf",
580 [PTR_TO_FUNC] = "func",
581 [PTR_TO_MAP_KEY] = "map_key",
582 [PTR_TO_DYNPTR] = "dynptr_ptr",
585 if (type & PTR_MAYBE_NULL) {
586 if (base_type(type) == PTR_TO_BTF_ID)
587 strncpy(postfix, "or_null_", 16);
589 strncpy(postfix, "_or_null", 16);
592 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s",
593 type & MEM_RDONLY ? "rdonly_" : "",
594 type & MEM_RINGBUF ? "ringbuf_" : "",
595 type & MEM_USER ? "user_" : "",
596 type & MEM_PERCPU ? "percpu_" : "",
597 type & PTR_UNTRUSTED ? "untrusted_" : "",
598 type & PTR_TRUSTED ? "trusted_" : ""
601 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
602 prefix, str[base_type(type)], postfix);
603 return env->type_str_buf;
606 static char slot_type_char[] = {
607 [STACK_INVALID] = '?',
611 [STACK_DYNPTR] = 'd',
614 static void print_liveness(struct bpf_verifier_env *env,
615 enum bpf_reg_liveness live)
617 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
619 if (live & REG_LIVE_READ)
621 if (live & REG_LIVE_WRITTEN)
623 if (live & REG_LIVE_DONE)
627 static int get_spi(s32 off)
629 return (-off - 1) / BPF_REG_SIZE;
632 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
634 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
636 /* We need to check that slots between [spi - nr_slots + 1, spi] are
637 * within [0, allocated_stack).
639 * Please note that the spi grows downwards. For example, a dynptr
640 * takes the size of two stack slots; the first slot will be at
641 * spi and the second slot will be at spi - 1.
643 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
646 static struct bpf_func_state *func(struct bpf_verifier_env *env,
647 const struct bpf_reg_state *reg)
649 struct bpf_verifier_state *cur = env->cur_state;
651 return cur->frame[reg->frameno];
654 static const char *kernel_type_name(const struct btf* btf, u32 id)
656 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
659 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
661 env->scratched_regs |= 1U << regno;
664 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
666 env->scratched_stack_slots |= 1ULL << spi;
669 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
671 return (env->scratched_regs >> regno) & 1;
674 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
676 return (env->scratched_stack_slots >> regno) & 1;
679 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
681 return env->scratched_regs || env->scratched_stack_slots;
684 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
686 env->scratched_regs = 0U;
687 env->scratched_stack_slots = 0ULL;
690 /* Used for printing the entire verifier state. */
691 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
693 env->scratched_regs = ~0U;
694 env->scratched_stack_slots = ~0ULL;
697 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
699 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
700 case DYNPTR_TYPE_LOCAL:
701 return BPF_DYNPTR_TYPE_LOCAL;
702 case DYNPTR_TYPE_RINGBUF:
703 return BPF_DYNPTR_TYPE_RINGBUF;
705 return BPF_DYNPTR_TYPE_INVALID;
709 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
711 return type == BPF_DYNPTR_TYPE_RINGBUF;
714 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
715 enum bpf_arg_type arg_type, int insn_idx)
717 struct bpf_func_state *state = func(env, reg);
718 enum bpf_dynptr_type type;
721 spi = get_spi(reg->off);
723 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
726 for (i = 0; i < BPF_REG_SIZE; i++) {
727 state->stack[spi].slot_type[i] = STACK_DYNPTR;
728 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
731 type = arg_to_dynptr_type(arg_type);
732 if (type == BPF_DYNPTR_TYPE_INVALID)
735 state->stack[spi].spilled_ptr.dynptr.first_slot = true;
736 state->stack[spi].spilled_ptr.dynptr.type = type;
737 state->stack[spi - 1].spilled_ptr.dynptr.type = type;
739 if (dynptr_type_refcounted(type)) {
740 /* The id is used to track proper releasing */
741 id = acquire_reference_state(env, insn_idx);
745 state->stack[spi].spilled_ptr.id = id;
746 state->stack[spi - 1].spilled_ptr.id = id;
752 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
754 struct bpf_func_state *state = func(env, reg);
757 spi = get_spi(reg->off);
759 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
762 for (i = 0; i < BPF_REG_SIZE; i++) {
763 state->stack[spi].slot_type[i] = STACK_INVALID;
764 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
767 /* Invalidate any slices associated with this dynptr */
768 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
769 release_reference(env, state->stack[spi].spilled_ptr.id);
770 state->stack[spi].spilled_ptr.id = 0;
771 state->stack[spi - 1].spilled_ptr.id = 0;
774 state->stack[spi].spilled_ptr.dynptr.first_slot = false;
775 state->stack[spi].spilled_ptr.dynptr.type = 0;
776 state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
781 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
783 struct bpf_func_state *state = func(env, reg);
784 int spi = get_spi(reg->off);
787 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
790 for (i = 0; i < BPF_REG_SIZE; i++) {
791 if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
792 state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
799 bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
800 struct bpf_reg_state *reg)
802 struct bpf_func_state *state = func(env, reg);
803 int spi = get_spi(reg->off);
806 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
807 !state->stack[spi].spilled_ptr.dynptr.first_slot)
810 for (i = 0; i < BPF_REG_SIZE; i++) {
811 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
812 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
819 bool is_dynptr_type_expected(struct bpf_verifier_env *env,
820 struct bpf_reg_state *reg,
821 enum bpf_arg_type arg_type)
823 struct bpf_func_state *state = func(env, reg);
824 enum bpf_dynptr_type dynptr_type;
825 int spi = get_spi(reg->off);
827 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
828 if (arg_type == ARG_PTR_TO_DYNPTR)
831 dynptr_type = arg_to_dynptr_type(arg_type);
833 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
836 /* The reg state of a pointer or a bounded scalar was saved when
837 * it was spilled to the stack.
839 static bool is_spilled_reg(const struct bpf_stack_state *stack)
841 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
844 static void scrub_spilled_slot(u8 *stype)
846 if (*stype != STACK_INVALID)
850 static void print_verifier_state(struct bpf_verifier_env *env,
851 const struct bpf_func_state *state,
854 const struct bpf_reg_state *reg;
859 verbose(env, " frame%d:", state->frameno);
860 for (i = 0; i < MAX_BPF_REG; i++) {
861 reg = &state->regs[i];
865 if (!print_all && !reg_scratched(env, i))
867 verbose(env, " R%d", i);
868 print_liveness(env, reg->live);
870 if (t == SCALAR_VALUE && reg->precise)
872 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
873 tnum_is_const(reg->var_off)) {
874 /* reg->off should be 0 for SCALAR_VALUE */
875 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
876 verbose(env, "%lld", reg->var_off.value + reg->off);
878 const char *sep = "";
880 verbose(env, "%s", reg_type_str(env, t));
881 if (base_type(t) == PTR_TO_BTF_ID)
882 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
885 * _a stands for append, was shortened to avoid multiline statements below.
886 * This macro is used to output a comma separated list of attributes.
888 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
891 verbose_a("id=%d", reg->id);
893 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
894 if (t != SCALAR_VALUE)
895 verbose_a("off=%d", reg->off);
896 if (type_is_pkt_pointer(t))
897 verbose_a("r=%d", reg->range);
898 else if (base_type(t) == CONST_PTR_TO_MAP ||
899 base_type(t) == PTR_TO_MAP_KEY ||
900 base_type(t) == PTR_TO_MAP_VALUE)
901 verbose_a("ks=%d,vs=%d",
902 reg->map_ptr->key_size,
903 reg->map_ptr->value_size);
904 if (tnum_is_const(reg->var_off)) {
905 /* Typically an immediate SCALAR_VALUE, but
906 * could be a pointer whose offset is too big
909 verbose_a("imm=%llx", reg->var_off.value);
911 if (reg->smin_value != reg->umin_value &&
912 reg->smin_value != S64_MIN)
913 verbose_a("smin=%lld", (long long)reg->smin_value);
914 if (reg->smax_value != reg->umax_value &&
915 reg->smax_value != S64_MAX)
916 verbose_a("smax=%lld", (long long)reg->smax_value);
917 if (reg->umin_value != 0)
918 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
919 if (reg->umax_value != U64_MAX)
920 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
921 if (!tnum_is_unknown(reg->var_off)) {
924 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
925 verbose_a("var_off=%s", tn_buf);
927 if (reg->s32_min_value != reg->smin_value &&
928 reg->s32_min_value != S32_MIN)
929 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
930 if (reg->s32_max_value != reg->smax_value &&
931 reg->s32_max_value != S32_MAX)
932 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
933 if (reg->u32_min_value != reg->umin_value &&
934 reg->u32_min_value != U32_MIN)
935 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
936 if (reg->u32_max_value != reg->umax_value &&
937 reg->u32_max_value != U32_MAX)
938 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
945 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
946 char types_buf[BPF_REG_SIZE + 1];
950 for (j = 0; j < BPF_REG_SIZE; j++) {
951 if (state->stack[i].slot_type[j] != STACK_INVALID)
953 types_buf[j] = slot_type_char[
954 state->stack[i].slot_type[j]];
956 types_buf[BPF_REG_SIZE] = 0;
959 if (!print_all && !stack_slot_scratched(env, i))
961 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
962 print_liveness(env, state->stack[i].spilled_ptr.live);
963 if (is_spilled_reg(&state->stack[i])) {
964 reg = &state->stack[i].spilled_ptr;
966 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
967 if (t == SCALAR_VALUE && reg->precise)
969 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
970 verbose(env, "%lld", reg->var_off.value + reg->off);
972 verbose(env, "=%s", types_buf);
975 if (state->acquired_refs && state->refs[0].id) {
976 verbose(env, " refs=%d", state->refs[0].id);
977 for (i = 1; i < state->acquired_refs; i++)
978 if (state->refs[i].id)
979 verbose(env, ",%d", state->refs[i].id);
981 if (state->in_callback_fn)
983 if (state->in_async_callback_fn)
984 verbose(env, " async_cb");
986 mark_verifier_state_clean(env);
989 static inline u32 vlog_alignment(u32 pos)
991 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
992 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
995 static void print_insn_state(struct bpf_verifier_env *env,
996 const struct bpf_func_state *state)
998 if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
999 /* remove new line character */
1000 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1001 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1003 verbose(env, "%d:", env->insn_idx);
1005 print_verifier_state(env, state, false);
1008 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1009 * small to hold src. This is different from krealloc since we don't want to preserve
1010 * the contents of dst.
1012 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1015 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1019 if (ZERO_OR_NULL_PTR(src))
1022 if (unlikely(check_mul_overflow(n, size, &bytes)))
1025 if (ksize(dst) < ksize(src)) {
1027 dst = kmalloc_track_caller(kmalloc_size_roundup(bytes), flags);
1032 memcpy(dst, src, bytes);
1034 return dst ? dst : ZERO_SIZE_PTR;
1037 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1038 * small to hold new_n items. new items are zeroed out if the array grows.
1040 * Contrary to krealloc_array, does not free arr if new_n is zero.
1042 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1047 if (!new_n || old_n == new_n)
1050 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1051 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1059 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1062 return arr ? arr : ZERO_SIZE_PTR;
1065 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1067 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1068 sizeof(struct bpf_reference_state), GFP_KERNEL);
1072 dst->acquired_refs = src->acquired_refs;
1076 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1078 size_t n = src->allocated_stack / BPF_REG_SIZE;
1080 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1085 dst->allocated_stack = src->allocated_stack;
1089 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1091 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1092 sizeof(struct bpf_reference_state));
1096 state->acquired_refs = n;
1100 static int grow_stack_state(struct bpf_func_state *state, int size)
1102 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1107 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1111 state->allocated_stack = size;
1115 /* Acquire a pointer id from the env and update the state->refs to include
1116 * this new pointer reference.
1117 * On success, returns a valid pointer id to associate with the register
1118 * On failure, returns a negative errno.
1120 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1122 struct bpf_func_state *state = cur_func(env);
1123 int new_ofs = state->acquired_refs;
1126 err = resize_reference_state(state, state->acquired_refs + 1);
1130 state->refs[new_ofs].id = id;
1131 state->refs[new_ofs].insn_idx = insn_idx;
1132 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1137 /* release function corresponding to acquire_reference_state(). Idempotent. */
1138 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1142 last_idx = state->acquired_refs - 1;
1143 for (i = 0; i < state->acquired_refs; i++) {
1144 if (state->refs[i].id == ptr_id) {
1145 /* Cannot release caller references in callbacks */
1146 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1148 if (last_idx && i != last_idx)
1149 memcpy(&state->refs[i], &state->refs[last_idx],
1150 sizeof(*state->refs));
1151 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1152 state->acquired_refs--;
1159 static void free_func_state(struct bpf_func_state *state)
1164 kfree(state->stack);
1168 static void clear_jmp_history(struct bpf_verifier_state *state)
1170 kfree(state->jmp_history);
1171 state->jmp_history = NULL;
1172 state->jmp_history_cnt = 0;
1175 static void free_verifier_state(struct bpf_verifier_state *state,
1180 for (i = 0; i <= state->curframe; i++) {
1181 free_func_state(state->frame[i]);
1182 state->frame[i] = NULL;
1184 clear_jmp_history(state);
1189 /* copy verifier state from src to dst growing dst stack space
1190 * when necessary to accommodate larger src stack
1192 static int copy_func_state(struct bpf_func_state *dst,
1193 const struct bpf_func_state *src)
1197 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1198 err = copy_reference_state(dst, src);
1201 return copy_stack_state(dst, src);
1204 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1205 const struct bpf_verifier_state *src)
1207 struct bpf_func_state *dst;
1210 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1211 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1213 if (!dst_state->jmp_history)
1215 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1217 /* if dst has more stack frames then src frame, free them */
1218 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1219 free_func_state(dst_state->frame[i]);
1220 dst_state->frame[i] = NULL;
1222 dst_state->speculative = src->speculative;
1223 dst_state->curframe = src->curframe;
1224 dst_state->active_lock.ptr = src->active_lock.ptr;
1225 dst_state->active_lock.id = src->active_lock.id;
1226 dst_state->branches = src->branches;
1227 dst_state->parent = src->parent;
1228 dst_state->first_insn_idx = src->first_insn_idx;
1229 dst_state->last_insn_idx = src->last_insn_idx;
1230 for (i = 0; i <= src->curframe; i++) {
1231 dst = dst_state->frame[i];
1233 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1236 dst_state->frame[i] = dst;
1238 err = copy_func_state(dst, src->frame[i]);
1245 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1248 u32 br = --st->branches;
1250 /* WARN_ON(br > 1) technically makes sense here,
1251 * but see comment in push_stack(), hence:
1253 WARN_ONCE((int)br < 0,
1254 "BUG update_branch_counts:branches_to_explore=%d\n",
1262 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1263 int *insn_idx, bool pop_log)
1265 struct bpf_verifier_state *cur = env->cur_state;
1266 struct bpf_verifier_stack_elem *elem, *head = env->head;
1269 if (env->head == NULL)
1273 err = copy_verifier_state(cur, &head->st);
1278 bpf_vlog_reset(&env->log, head->log_pos);
1280 *insn_idx = head->insn_idx;
1282 *prev_insn_idx = head->prev_insn_idx;
1284 free_verifier_state(&head->st, false);
1291 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1292 int insn_idx, int prev_insn_idx,
1295 struct bpf_verifier_state *cur = env->cur_state;
1296 struct bpf_verifier_stack_elem *elem;
1299 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1303 elem->insn_idx = insn_idx;
1304 elem->prev_insn_idx = prev_insn_idx;
1305 elem->next = env->head;
1306 elem->log_pos = env->log.len_used;
1309 err = copy_verifier_state(&elem->st, cur);
1312 elem->st.speculative |= speculative;
1313 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1314 verbose(env, "The sequence of %d jumps is too complex.\n",
1318 if (elem->st.parent) {
1319 ++elem->st.parent->branches;
1320 /* WARN_ON(branches > 2) technically makes sense here,
1322 * 1. speculative states will bump 'branches' for non-branch
1324 * 2. is_state_visited() heuristics may decide not to create
1325 * a new state for a sequence of branches and all such current
1326 * and cloned states will be pointing to a single parent state
1327 * which might have large 'branches' count.
1332 free_verifier_state(env->cur_state, true);
1333 env->cur_state = NULL;
1334 /* pop all elements and return */
1335 while (!pop_stack(env, NULL, NULL, false));
1339 #define CALLER_SAVED_REGS 6
1340 static const int caller_saved[CALLER_SAVED_REGS] = {
1341 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1344 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1345 struct bpf_reg_state *reg);
1347 /* This helper doesn't clear reg->id */
1348 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1350 reg->var_off = tnum_const(imm);
1351 reg->smin_value = (s64)imm;
1352 reg->smax_value = (s64)imm;
1353 reg->umin_value = imm;
1354 reg->umax_value = imm;
1356 reg->s32_min_value = (s32)imm;
1357 reg->s32_max_value = (s32)imm;
1358 reg->u32_min_value = (u32)imm;
1359 reg->u32_max_value = (u32)imm;
1362 /* Mark the unknown part of a register (variable offset or scalar value) as
1363 * known to have the value @imm.
1365 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1367 /* Clear id, off, and union(map_ptr, range) */
1368 memset(((u8 *)reg) + sizeof(reg->type), 0,
1369 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1370 ___mark_reg_known(reg, imm);
1373 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1375 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1376 reg->s32_min_value = (s32)imm;
1377 reg->s32_max_value = (s32)imm;
1378 reg->u32_min_value = (u32)imm;
1379 reg->u32_max_value = (u32)imm;
1382 /* Mark the 'variable offset' part of a register as zero. This should be
1383 * used only on registers holding a pointer type.
1385 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1387 __mark_reg_known(reg, 0);
1390 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1392 __mark_reg_known(reg, 0);
1393 reg->type = SCALAR_VALUE;
1396 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1397 struct bpf_reg_state *regs, u32 regno)
1399 if (WARN_ON(regno >= MAX_BPF_REG)) {
1400 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1401 /* Something bad happened, let's kill all regs */
1402 for (regno = 0; regno < MAX_BPF_REG; regno++)
1403 __mark_reg_not_init(env, regs + regno);
1406 __mark_reg_known_zero(regs + regno);
1409 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1411 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1412 const struct bpf_map *map = reg->map_ptr;
1414 if (map->inner_map_meta) {
1415 reg->type = CONST_PTR_TO_MAP;
1416 reg->map_ptr = map->inner_map_meta;
1417 /* transfer reg's id which is unique for every map_lookup_elem
1418 * as UID of the inner map.
1420 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1421 reg->map_uid = reg->id;
1422 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1423 reg->type = PTR_TO_XDP_SOCK;
1424 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1425 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1426 reg->type = PTR_TO_SOCKET;
1428 reg->type = PTR_TO_MAP_VALUE;
1433 reg->type &= ~PTR_MAYBE_NULL;
1436 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1438 return type_is_pkt_pointer(reg->type);
1441 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1443 return reg_is_pkt_pointer(reg) ||
1444 reg->type == PTR_TO_PACKET_END;
1447 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1448 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1449 enum bpf_reg_type which)
1451 /* The register can already have a range from prior markings.
1452 * This is fine as long as it hasn't been advanced from its
1455 return reg->type == which &&
1458 tnum_equals_const(reg->var_off, 0);
1461 /* Reset the min/max bounds of a register */
1462 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1464 reg->smin_value = S64_MIN;
1465 reg->smax_value = S64_MAX;
1466 reg->umin_value = 0;
1467 reg->umax_value = U64_MAX;
1469 reg->s32_min_value = S32_MIN;
1470 reg->s32_max_value = S32_MAX;
1471 reg->u32_min_value = 0;
1472 reg->u32_max_value = U32_MAX;
1475 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1477 reg->smin_value = S64_MIN;
1478 reg->smax_value = S64_MAX;
1479 reg->umin_value = 0;
1480 reg->umax_value = U64_MAX;
1483 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1485 reg->s32_min_value = S32_MIN;
1486 reg->s32_max_value = S32_MAX;
1487 reg->u32_min_value = 0;
1488 reg->u32_max_value = U32_MAX;
1491 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1493 struct tnum var32_off = tnum_subreg(reg->var_off);
1495 /* min signed is max(sign bit) | min(other bits) */
1496 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1497 var32_off.value | (var32_off.mask & S32_MIN));
1498 /* max signed is min(sign bit) | max(other bits) */
1499 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1500 var32_off.value | (var32_off.mask & S32_MAX));
1501 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1502 reg->u32_max_value = min(reg->u32_max_value,
1503 (u32)(var32_off.value | var32_off.mask));
1506 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1508 /* min signed is max(sign bit) | min(other bits) */
1509 reg->smin_value = max_t(s64, reg->smin_value,
1510 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1511 /* max signed is min(sign bit) | max(other bits) */
1512 reg->smax_value = min_t(s64, reg->smax_value,
1513 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1514 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1515 reg->umax_value = min(reg->umax_value,
1516 reg->var_off.value | reg->var_off.mask);
1519 static void __update_reg_bounds(struct bpf_reg_state *reg)
1521 __update_reg32_bounds(reg);
1522 __update_reg64_bounds(reg);
1525 /* Uses signed min/max values to inform unsigned, and vice-versa */
1526 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1528 /* Learn sign from signed bounds.
1529 * If we cannot cross the sign boundary, then signed and unsigned bounds
1530 * are the same, so combine. This works even in the negative case, e.g.
1531 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1533 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1534 reg->s32_min_value = reg->u32_min_value =
1535 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1536 reg->s32_max_value = reg->u32_max_value =
1537 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1540 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1541 * boundary, so we must be careful.
1543 if ((s32)reg->u32_max_value >= 0) {
1544 /* Positive. We can't learn anything from the smin, but smax
1545 * is positive, hence safe.
1547 reg->s32_min_value = reg->u32_min_value;
1548 reg->s32_max_value = reg->u32_max_value =
1549 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1550 } else if ((s32)reg->u32_min_value < 0) {
1551 /* Negative. We can't learn anything from the smax, but smin
1552 * is negative, hence safe.
1554 reg->s32_min_value = reg->u32_min_value =
1555 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1556 reg->s32_max_value = reg->u32_max_value;
1560 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1562 /* Learn sign from signed bounds.
1563 * If we cannot cross the sign boundary, then signed and unsigned bounds
1564 * are the same, so combine. This works even in the negative case, e.g.
1565 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1567 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1568 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1570 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1574 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1575 * boundary, so we must be careful.
1577 if ((s64)reg->umax_value >= 0) {
1578 /* Positive. We can't learn anything from the smin, but smax
1579 * is positive, hence safe.
1581 reg->smin_value = reg->umin_value;
1582 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1584 } else if ((s64)reg->umin_value < 0) {
1585 /* Negative. We can't learn anything from the smax, but smin
1586 * is negative, hence safe.
1588 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1590 reg->smax_value = reg->umax_value;
1594 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1596 __reg32_deduce_bounds(reg);
1597 __reg64_deduce_bounds(reg);
1600 /* Attempts to improve var_off based on unsigned min/max information */
1601 static void __reg_bound_offset(struct bpf_reg_state *reg)
1603 struct tnum var64_off = tnum_intersect(reg->var_off,
1604 tnum_range(reg->umin_value,
1606 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1607 tnum_range(reg->u32_min_value,
1608 reg->u32_max_value));
1610 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1613 static void reg_bounds_sync(struct bpf_reg_state *reg)
1615 /* We might have learned new bounds from the var_off. */
1616 __update_reg_bounds(reg);
1617 /* We might have learned something about the sign bit. */
1618 __reg_deduce_bounds(reg);
1619 /* We might have learned some bits from the bounds. */
1620 __reg_bound_offset(reg);
1621 /* Intersecting with the old var_off might have improved our bounds
1622 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1623 * then new var_off is (0; 0x7f...fc) which improves our umax.
1625 __update_reg_bounds(reg);
1628 static bool __reg32_bound_s64(s32 a)
1630 return a >= 0 && a <= S32_MAX;
1633 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1635 reg->umin_value = reg->u32_min_value;
1636 reg->umax_value = reg->u32_max_value;
1638 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1639 * be positive otherwise set to worse case bounds and refine later
1642 if (__reg32_bound_s64(reg->s32_min_value) &&
1643 __reg32_bound_s64(reg->s32_max_value)) {
1644 reg->smin_value = reg->s32_min_value;
1645 reg->smax_value = reg->s32_max_value;
1647 reg->smin_value = 0;
1648 reg->smax_value = U32_MAX;
1652 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1654 /* special case when 64-bit register has upper 32-bit register
1655 * zeroed. Typically happens after zext or <<32, >>32 sequence
1656 * allowing us to use 32-bit bounds directly,
1658 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1659 __reg_assign_32_into_64(reg);
1661 /* Otherwise the best we can do is push lower 32bit known and
1662 * unknown bits into register (var_off set from jmp logic)
1663 * then learn as much as possible from the 64-bit tnum
1664 * known and unknown bits. The previous smin/smax bounds are
1665 * invalid here because of jmp32 compare so mark them unknown
1666 * so they do not impact tnum bounds calculation.
1668 __mark_reg64_unbounded(reg);
1670 reg_bounds_sync(reg);
1673 static bool __reg64_bound_s32(s64 a)
1675 return a >= S32_MIN && a <= S32_MAX;
1678 static bool __reg64_bound_u32(u64 a)
1680 return a >= U32_MIN && a <= U32_MAX;
1683 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1685 __mark_reg32_unbounded(reg);
1686 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1687 reg->s32_min_value = (s32)reg->smin_value;
1688 reg->s32_max_value = (s32)reg->smax_value;
1690 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1691 reg->u32_min_value = (u32)reg->umin_value;
1692 reg->u32_max_value = (u32)reg->umax_value;
1694 reg_bounds_sync(reg);
1697 /* Mark a register as having a completely unknown (scalar) value. */
1698 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1699 struct bpf_reg_state *reg)
1702 * Clear type, id, off, and union(map_ptr, range) and
1703 * padding between 'type' and union
1705 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1706 reg->type = SCALAR_VALUE;
1707 reg->var_off = tnum_unknown;
1709 reg->precise = !env->bpf_capable;
1710 __mark_reg_unbounded(reg);
1713 static void mark_reg_unknown(struct bpf_verifier_env *env,
1714 struct bpf_reg_state *regs, u32 regno)
1716 if (WARN_ON(regno >= MAX_BPF_REG)) {
1717 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1718 /* Something bad happened, let's kill all regs except FP */
1719 for (regno = 0; regno < BPF_REG_FP; regno++)
1720 __mark_reg_not_init(env, regs + regno);
1723 __mark_reg_unknown(env, regs + regno);
1726 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1727 struct bpf_reg_state *reg)
1729 __mark_reg_unknown(env, reg);
1730 reg->type = NOT_INIT;
1733 static void mark_reg_not_init(struct bpf_verifier_env *env,
1734 struct bpf_reg_state *regs, u32 regno)
1736 if (WARN_ON(regno >= MAX_BPF_REG)) {
1737 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1738 /* Something bad happened, let's kill all regs except FP */
1739 for (regno = 0; regno < BPF_REG_FP; regno++)
1740 __mark_reg_not_init(env, regs + regno);
1743 __mark_reg_not_init(env, regs + regno);
1746 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1747 struct bpf_reg_state *regs, u32 regno,
1748 enum bpf_reg_type reg_type,
1749 struct btf *btf, u32 btf_id,
1750 enum bpf_type_flag flag)
1752 if (reg_type == SCALAR_VALUE) {
1753 mark_reg_unknown(env, regs, regno);
1756 mark_reg_known_zero(env, regs, regno);
1757 regs[regno].type = PTR_TO_BTF_ID | flag;
1758 regs[regno].btf = btf;
1759 regs[regno].btf_id = btf_id;
1762 #define DEF_NOT_SUBREG (0)
1763 static void init_reg_state(struct bpf_verifier_env *env,
1764 struct bpf_func_state *state)
1766 struct bpf_reg_state *regs = state->regs;
1769 for (i = 0; i < MAX_BPF_REG; i++) {
1770 mark_reg_not_init(env, regs, i);
1771 regs[i].live = REG_LIVE_NONE;
1772 regs[i].parent = NULL;
1773 regs[i].subreg_def = DEF_NOT_SUBREG;
1777 regs[BPF_REG_FP].type = PTR_TO_STACK;
1778 mark_reg_known_zero(env, regs, BPF_REG_FP);
1779 regs[BPF_REG_FP].frameno = state->frameno;
1782 #define BPF_MAIN_FUNC (-1)
1783 static void init_func_state(struct bpf_verifier_env *env,
1784 struct bpf_func_state *state,
1785 int callsite, int frameno, int subprogno)
1787 state->callsite = callsite;
1788 state->frameno = frameno;
1789 state->subprogno = subprogno;
1790 state->callback_ret_range = tnum_range(0, 0);
1791 init_reg_state(env, state);
1792 mark_verifier_state_scratched(env);
1795 /* Similar to push_stack(), but for async callbacks */
1796 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1797 int insn_idx, int prev_insn_idx,
1800 struct bpf_verifier_stack_elem *elem;
1801 struct bpf_func_state *frame;
1803 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1807 elem->insn_idx = insn_idx;
1808 elem->prev_insn_idx = prev_insn_idx;
1809 elem->next = env->head;
1810 elem->log_pos = env->log.len_used;
1813 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1815 "The sequence of %d jumps is too complex for async cb.\n",
1819 /* Unlike push_stack() do not copy_verifier_state().
1820 * The caller state doesn't matter.
1821 * This is async callback. It starts in a fresh stack.
1822 * Initialize it similar to do_check_common().
1824 elem->st.branches = 1;
1825 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1828 init_func_state(env, frame,
1829 BPF_MAIN_FUNC /* callsite */,
1830 0 /* frameno within this callchain */,
1831 subprog /* subprog number within this prog */);
1832 elem->st.frame[0] = frame;
1835 free_verifier_state(env->cur_state, true);
1836 env->cur_state = NULL;
1837 /* pop all elements and return */
1838 while (!pop_stack(env, NULL, NULL, false));
1844 SRC_OP, /* register is used as source operand */
1845 DST_OP, /* register is used as destination operand */
1846 DST_OP_NO_MARK /* same as above, check only, don't mark */
1849 static int cmp_subprogs(const void *a, const void *b)
1851 return ((struct bpf_subprog_info *)a)->start -
1852 ((struct bpf_subprog_info *)b)->start;
1855 static int find_subprog(struct bpf_verifier_env *env, int off)
1857 struct bpf_subprog_info *p;
1859 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1860 sizeof(env->subprog_info[0]), cmp_subprogs);
1863 return p - env->subprog_info;
1867 static int add_subprog(struct bpf_verifier_env *env, int off)
1869 int insn_cnt = env->prog->len;
1872 if (off >= insn_cnt || off < 0) {
1873 verbose(env, "call to invalid destination\n");
1876 ret = find_subprog(env, off);
1879 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1880 verbose(env, "too many subprograms\n");
1883 /* determine subprog starts. The end is one before the next starts */
1884 env->subprog_info[env->subprog_cnt++].start = off;
1885 sort(env->subprog_info, env->subprog_cnt,
1886 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1887 return env->subprog_cnt - 1;
1890 #define MAX_KFUNC_DESCS 256
1891 #define MAX_KFUNC_BTFS 256
1893 struct bpf_kfunc_desc {
1894 struct btf_func_model func_model;
1900 struct bpf_kfunc_btf {
1902 struct module *module;
1906 struct bpf_kfunc_desc_tab {
1907 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1911 struct bpf_kfunc_btf_tab {
1912 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1916 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1918 const struct bpf_kfunc_desc *d0 = a;
1919 const struct bpf_kfunc_desc *d1 = b;
1921 /* func_id is not greater than BTF_MAX_TYPE */
1922 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1925 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1927 const struct bpf_kfunc_btf *d0 = a;
1928 const struct bpf_kfunc_btf *d1 = b;
1930 return d0->offset - d1->offset;
1933 static const struct bpf_kfunc_desc *
1934 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1936 struct bpf_kfunc_desc desc = {
1940 struct bpf_kfunc_desc_tab *tab;
1942 tab = prog->aux->kfunc_tab;
1943 return bsearch(&desc, tab->descs, tab->nr_descs,
1944 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1947 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1950 struct bpf_kfunc_btf kf_btf = { .offset = offset };
1951 struct bpf_kfunc_btf_tab *tab;
1952 struct bpf_kfunc_btf *b;
1957 tab = env->prog->aux->kfunc_btf_tab;
1958 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1959 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1961 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1962 verbose(env, "too many different module BTFs\n");
1963 return ERR_PTR(-E2BIG);
1966 if (bpfptr_is_null(env->fd_array)) {
1967 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1968 return ERR_PTR(-EPROTO);
1971 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1972 offset * sizeof(btf_fd),
1974 return ERR_PTR(-EFAULT);
1976 btf = btf_get_by_fd(btf_fd);
1978 verbose(env, "invalid module BTF fd specified\n");
1982 if (!btf_is_module(btf)) {
1983 verbose(env, "BTF fd for kfunc is not a module BTF\n");
1985 return ERR_PTR(-EINVAL);
1988 mod = btf_try_get_module(btf);
1991 return ERR_PTR(-ENXIO);
1994 b = &tab->descs[tab->nr_descs++];
1999 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2000 kfunc_btf_cmp_by_off, NULL);
2005 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2010 while (tab->nr_descs--) {
2011 module_put(tab->descs[tab->nr_descs].module);
2012 btf_put(tab->descs[tab->nr_descs].btf);
2017 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2021 /* In the future, this can be allowed to increase limit
2022 * of fd index into fd_array, interpreted as u16.
2024 verbose(env, "negative offset disallowed for kernel module function call\n");
2025 return ERR_PTR(-EINVAL);
2028 return __find_kfunc_desc_btf(env, offset);
2030 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2033 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2035 const struct btf_type *func, *func_proto;
2036 struct bpf_kfunc_btf_tab *btf_tab;
2037 struct bpf_kfunc_desc_tab *tab;
2038 struct bpf_prog_aux *prog_aux;
2039 struct bpf_kfunc_desc *desc;
2040 const char *func_name;
2041 struct btf *desc_btf;
2042 unsigned long call_imm;
2046 prog_aux = env->prog->aux;
2047 tab = prog_aux->kfunc_tab;
2048 btf_tab = prog_aux->kfunc_btf_tab;
2051 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2055 if (!env->prog->jit_requested) {
2056 verbose(env, "JIT is required for calling kernel function\n");
2060 if (!bpf_jit_supports_kfunc_call()) {
2061 verbose(env, "JIT does not support calling kernel function\n");
2065 if (!env->prog->gpl_compatible) {
2066 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2070 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2073 prog_aux->kfunc_tab = tab;
2076 /* func_id == 0 is always invalid, but instead of returning an error, be
2077 * conservative and wait until the code elimination pass before returning
2078 * error, so that invalid calls that get pruned out can be in BPF programs
2079 * loaded from userspace. It is also required that offset be untouched
2082 if (!func_id && !offset)
2085 if (!btf_tab && offset) {
2086 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2089 prog_aux->kfunc_btf_tab = btf_tab;
2092 desc_btf = find_kfunc_desc_btf(env, offset);
2093 if (IS_ERR(desc_btf)) {
2094 verbose(env, "failed to find BTF for kernel function\n");
2095 return PTR_ERR(desc_btf);
2098 if (find_kfunc_desc(env->prog, func_id, offset))
2101 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2102 verbose(env, "too many different kernel function calls\n");
2106 func = btf_type_by_id(desc_btf, func_id);
2107 if (!func || !btf_type_is_func(func)) {
2108 verbose(env, "kernel btf_id %u is not a function\n",
2112 func_proto = btf_type_by_id(desc_btf, func->type);
2113 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2114 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2119 func_name = btf_name_by_offset(desc_btf, func->name_off);
2120 addr = kallsyms_lookup_name(func_name);
2122 verbose(env, "cannot find address for kernel function %s\n",
2127 call_imm = BPF_CALL_IMM(addr);
2128 /* Check whether or not the relative offset overflows desc->imm */
2129 if ((unsigned long)(s32)call_imm != call_imm) {
2130 verbose(env, "address of kernel function %s is out of range\n",
2135 desc = &tab->descs[tab->nr_descs++];
2136 desc->func_id = func_id;
2137 desc->imm = call_imm;
2138 desc->offset = offset;
2139 err = btf_distill_func_proto(&env->log, desc_btf,
2140 func_proto, func_name,
2143 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2144 kfunc_desc_cmp_by_id_off, NULL);
2148 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2150 const struct bpf_kfunc_desc *d0 = a;
2151 const struct bpf_kfunc_desc *d1 = b;
2153 if (d0->imm > d1->imm)
2155 else if (d0->imm < d1->imm)
2160 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2162 struct bpf_kfunc_desc_tab *tab;
2164 tab = prog->aux->kfunc_tab;
2168 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2169 kfunc_desc_cmp_by_imm, NULL);
2172 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2174 return !!prog->aux->kfunc_tab;
2177 const struct btf_func_model *
2178 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2179 const struct bpf_insn *insn)
2181 const struct bpf_kfunc_desc desc = {
2184 const struct bpf_kfunc_desc *res;
2185 struct bpf_kfunc_desc_tab *tab;
2187 tab = prog->aux->kfunc_tab;
2188 res = bsearch(&desc, tab->descs, tab->nr_descs,
2189 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2191 return res ? &res->func_model : NULL;
2194 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2196 struct bpf_subprog_info *subprog = env->subprog_info;
2197 struct bpf_insn *insn = env->prog->insnsi;
2198 int i, ret, insn_cnt = env->prog->len;
2200 /* Add entry function. */
2201 ret = add_subprog(env, 0);
2205 for (i = 0; i < insn_cnt; i++, insn++) {
2206 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2207 !bpf_pseudo_kfunc_call(insn))
2210 if (!env->bpf_capable) {
2211 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2215 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2216 ret = add_subprog(env, i + insn->imm + 1);
2218 ret = add_kfunc_call(env, insn->imm, insn->off);
2224 /* Add a fake 'exit' subprog which could simplify subprog iteration
2225 * logic. 'subprog_cnt' should not be increased.
2227 subprog[env->subprog_cnt].start = insn_cnt;
2229 if (env->log.level & BPF_LOG_LEVEL2)
2230 for (i = 0; i < env->subprog_cnt; i++)
2231 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2236 static int check_subprogs(struct bpf_verifier_env *env)
2238 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2239 struct bpf_subprog_info *subprog = env->subprog_info;
2240 struct bpf_insn *insn = env->prog->insnsi;
2241 int insn_cnt = env->prog->len;
2243 /* now check that all jumps are within the same subprog */
2244 subprog_start = subprog[cur_subprog].start;
2245 subprog_end = subprog[cur_subprog + 1].start;
2246 for (i = 0; i < insn_cnt; i++) {
2247 u8 code = insn[i].code;
2249 if (code == (BPF_JMP | BPF_CALL) &&
2250 insn[i].imm == BPF_FUNC_tail_call &&
2251 insn[i].src_reg != BPF_PSEUDO_CALL)
2252 subprog[cur_subprog].has_tail_call = true;
2253 if (BPF_CLASS(code) == BPF_LD &&
2254 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2255 subprog[cur_subprog].has_ld_abs = true;
2256 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2258 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2260 off = i + insn[i].off + 1;
2261 if (off < subprog_start || off >= subprog_end) {
2262 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2266 if (i == subprog_end - 1) {
2267 /* to avoid fall-through from one subprog into another
2268 * the last insn of the subprog should be either exit
2269 * or unconditional jump back
2271 if (code != (BPF_JMP | BPF_EXIT) &&
2272 code != (BPF_JMP | BPF_JA)) {
2273 verbose(env, "last insn is not an exit or jmp\n");
2276 subprog_start = subprog_end;
2278 if (cur_subprog < env->subprog_cnt)
2279 subprog_end = subprog[cur_subprog + 1].start;
2285 /* Parentage chain of this register (or stack slot) should take care of all
2286 * issues like callee-saved registers, stack slot allocation time, etc.
2288 static int mark_reg_read(struct bpf_verifier_env *env,
2289 const struct bpf_reg_state *state,
2290 struct bpf_reg_state *parent, u8 flag)
2292 bool writes = parent == state->parent; /* Observe write marks */
2296 /* if read wasn't screened by an earlier write ... */
2297 if (writes && state->live & REG_LIVE_WRITTEN)
2299 if (parent->live & REG_LIVE_DONE) {
2300 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2301 reg_type_str(env, parent->type),
2302 parent->var_off.value, parent->off);
2305 /* The first condition is more likely to be true than the
2306 * second, checked it first.
2308 if ((parent->live & REG_LIVE_READ) == flag ||
2309 parent->live & REG_LIVE_READ64)
2310 /* The parentage chain never changes and
2311 * this parent was already marked as LIVE_READ.
2312 * There is no need to keep walking the chain again and
2313 * keep re-marking all parents as LIVE_READ.
2314 * This case happens when the same register is read
2315 * multiple times without writes into it in-between.
2316 * Also, if parent has the stronger REG_LIVE_READ64 set,
2317 * then no need to set the weak REG_LIVE_READ32.
2320 /* ... then we depend on parent's value */
2321 parent->live |= flag;
2322 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2323 if (flag == REG_LIVE_READ64)
2324 parent->live &= ~REG_LIVE_READ32;
2326 parent = state->parent;
2331 if (env->longest_mark_read_walk < cnt)
2332 env->longest_mark_read_walk = cnt;
2336 /* This function is supposed to be used by the following 32-bit optimization
2337 * code only. It returns TRUE if the source or destination register operates
2338 * on 64-bit, otherwise return FALSE.
2340 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2341 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2346 class = BPF_CLASS(code);
2348 if (class == BPF_JMP) {
2349 /* BPF_EXIT for "main" will reach here. Return TRUE
2354 if (op == BPF_CALL) {
2355 /* BPF to BPF call will reach here because of marking
2356 * caller saved clobber with DST_OP_NO_MARK for which we
2357 * don't care the register def because they are anyway
2358 * marked as NOT_INIT already.
2360 if (insn->src_reg == BPF_PSEUDO_CALL)
2362 /* Helper call will reach here because of arg type
2363 * check, conservatively return TRUE.
2372 if (class == BPF_ALU64 || class == BPF_JMP ||
2373 /* BPF_END always use BPF_ALU class. */
2374 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2377 if (class == BPF_ALU || class == BPF_JMP32)
2380 if (class == BPF_LDX) {
2382 return BPF_SIZE(code) == BPF_DW;
2383 /* LDX source must be ptr. */
2387 if (class == BPF_STX) {
2388 /* BPF_STX (including atomic variants) has multiple source
2389 * operands, one of which is a ptr. Check whether the caller is
2392 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2394 return BPF_SIZE(code) == BPF_DW;
2397 if (class == BPF_LD) {
2398 u8 mode = BPF_MODE(code);
2401 if (mode == BPF_IMM)
2404 /* Both LD_IND and LD_ABS return 32-bit data. */
2408 /* Implicit ctx ptr. */
2409 if (regno == BPF_REG_6)
2412 /* Explicit source could be any width. */
2416 if (class == BPF_ST)
2417 /* The only source register for BPF_ST is a ptr. */
2420 /* Conservatively return true at default. */
2424 /* Return the regno defined by the insn, or -1. */
2425 static int insn_def_regno(const struct bpf_insn *insn)
2427 switch (BPF_CLASS(insn->code)) {
2433 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2434 (insn->imm & BPF_FETCH)) {
2435 if (insn->imm == BPF_CMPXCHG)
2438 return insn->src_reg;
2443 return insn->dst_reg;
2447 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2448 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2450 int dst_reg = insn_def_regno(insn);
2455 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2458 static void mark_insn_zext(struct bpf_verifier_env *env,
2459 struct bpf_reg_state *reg)
2461 s32 def_idx = reg->subreg_def;
2463 if (def_idx == DEF_NOT_SUBREG)
2466 env->insn_aux_data[def_idx - 1].zext_dst = true;
2467 /* The dst will be zero extended, so won't be sub-register anymore. */
2468 reg->subreg_def = DEF_NOT_SUBREG;
2471 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2472 enum reg_arg_type t)
2474 struct bpf_verifier_state *vstate = env->cur_state;
2475 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2476 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2477 struct bpf_reg_state *reg, *regs = state->regs;
2480 if (regno >= MAX_BPF_REG) {
2481 verbose(env, "R%d is invalid\n", regno);
2485 mark_reg_scratched(env, regno);
2488 rw64 = is_reg64(env, insn, regno, reg, t);
2490 /* check whether register used as source operand can be read */
2491 if (reg->type == NOT_INIT) {
2492 verbose(env, "R%d !read_ok\n", regno);
2495 /* We don't need to worry about FP liveness because it's read-only */
2496 if (regno == BPF_REG_FP)
2500 mark_insn_zext(env, reg);
2502 return mark_reg_read(env, reg, reg->parent,
2503 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2505 /* check whether register used as dest operand can be written to */
2506 if (regno == BPF_REG_FP) {
2507 verbose(env, "frame pointer is read only\n");
2510 reg->live |= REG_LIVE_WRITTEN;
2511 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2513 mark_reg_unknown(env, regs, regno);
2518 /* for any branch, call, exit record the history of jmps in the given state */
2519 static int push_jmp_history(struct bpf_verifier_env *env,
2520 struct bpf_verifier_state *cur)
2522 u32 cnt = cur->jmp_history_cnt;
2523 struct bpf_idx_pair *p;
2527 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2528 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2531 p[cnt - 1].idx = env->insn_idx;
2532 p[cnt - 1].prev_idx = env->prev_insn_idx;
2533 cur->jmp_history = p;
2534 cur->jmp_history_cnt = cnt;
2538 /* Backtrack one insn at a time. If idx is not at the top of recorded
2539 * history then previous instruction came from straight line execution.
2541 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2546 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2547 i = st->jmp_history[cnt - 1].prev_idx;
2555 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2557 const struct btf_type *func;
2558 struct btf *desc_btf;
2560 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2563 desc_btf = find_kfunc_desc_btf(data, insn->off);
2564 if (IS_ERR(desc_btf))
2567 func = btf_type_by_id(desc_btf, insn->imm);
2568 return btf_name_by_offset(desc_btf, func->name_off);
2571 /* For given verifier state backtrack_insn() is called from the last insn to
2572 * the first insn. Its purpose is to compute a bitmask of registers and
2573 * stack slots that needs precision in the parent verifier state.
2575 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2576 u32 *reg_mask, u64 *stack_mask)
2578 const struct bpf_insn_cbs cbs = {
2579 .cb_call = disasm_kfunc_name,
2580 .cb_print = verbose,
2581 .private_data = env,
2583 struct bpf_insn *insn = env->prog->insnsi + idx;
2584 u8 class = BPF_CLASS(insn->code);
2585 u8 opcode = BPF_OP(insn->code);
2586 u8 mode = BPF_MODE(insn->code);
2587 u32 dreg = 1u << insn->dst_reg;
2588 u32 sreg = 1u << insn->src_reg;
2591 if (insn->code == 0)
2593 if (env->log.level & BPF_LOG_LEVEL2) {
2594 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2595 verbose(env, "%d: ", idx);
2596 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2599 if (class == BPF_ALU || class == BPF_ALU64) {
2600 if (!(*reg_mask & dreg))
2602 if (opcode == BPF_MOV) {
2603 if (BPF_SRC(insn->code) == BPF_X) {
2605 * dreg needs precision after this insn
2606 * sreg needs precision before this insn
2612 * dreg needs precision after this insn.
2613 * Corresponding register is already marked
2614 * as precise=true in this verifier state.
2615 * No further markings in parent are necessary
2620 if (BPF_SRC(insn->code) == BPF_X) {
2622 * both dreg and sreg need precision
2627 * dreg still needs precision before this insn
2630 } else if (class == BPF_LDX) {
2631 if (!(*reg_mask & dreg))
2635 /* scalars can only be spilled into stack w/o losing precision.
2636 * Load from any other memory can be zero extended.
2637 * The desire to keep that precision is already indicated
2638 * by 'precise' mark in corresponding register of this state.
2639 * No further tracking necessary.
2641 if (insn->src_reg != BPF_REG_FP)
2644 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2645 * that [fp - off] slot contains scalar that needs to be
2646 * tracked with precision
2648 spi = (-insn->off - 1) / BPF_REG_SIZE;
2650 verbose(env, "BUG spi %d\n", spi);
2651 WARN_ONCE(1, "verifier backtracking bug");
2654 *stack_mask |= 1ull << spi;
2655 } else if (class == BPF_STX || class == BPF_ST) {
2656 if (*reg_mask & dreg)
2657 /* stx & st shouldn't be using _scalar_ dst_reg
2658 * to access memory. It means backtracking
2659 * encountered a case of pointer subtraction.
2662 /* scalars can only be spilled into stack */
2663 if (insn->dst_reg != BPF_REG_FP)
2665 spi = (-insn->off - 1) / BPF_REG_SIZE;
2667 verbose(env, "BUG spi %d\n", spi);
2668 WARN_ONCE(1, "verifier backtracking bug");
2671 if (!(*stack_mask & (1ull << spi)))
2673 *stack_mask &= ~(1ull << spi);
2674 if (class == BPF_STX)
2676 } else if (class == BPF_JMP || class == BPF_JMP32) {
2677 if (opcode == BPF_CALL) {
2678 if (insn->src_reg == BPF_PSEUDO_CALL)
2680 /* BPF helpers that invoke callback subprogs are
2681 * equivalent to BPF_PSEUDO_CALL above
2683 if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2685 /* regular helper call sets R0 */
2687 if (*reg_mask & 0x3f) {
2688 /* if backtracing was looking for registers R1-R5
2689 * they should have been found already.
2691 verbose(env, "BUG regs %x\n", *reg_mask);
2692 WARN_ONCE(1, "verifier backtracking bug");
2695 } else if (opcode == BPF_EXIT) {
2698 } else if (class == BPF_LD) {
2699 if (!(*reg_mask & dreg))
2702 /* It's ld_imm64 or ld_abs or ld_ind.
2703 * For ld_imm64 no further tracking of precision
2704 * into parent is necessary
2706 if (mode == BPF_IND || mode == BPF_ABS)
2707 /* to be analyzed */
2713 /* the scalar precision tracking algorithm:
2714 * . at the start all registers have precise=false.
2715 * . scalar ranges are tracked as normal through alu and jmp insns.
2716 * . once precise value of the scalar register is used in:
2717 * . ptr + scalar alu
2718 * . if (scalar cond K|scalar)
2719 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2720 * backtrack through the verifier states and mark all registers and
2721 * stack slots with spilled constants that these scalar regisers
2722 * should be precise.
2723 * . during state pruning two registers (or spilled stack slots)
2724 * are equivalent if both are not precise.
2726 * Note the verifier cannot simply walk register parentage chain,
2727 * since many different registers and stack slots could have been
2728 * used to compute single precise scalar.
2730 * The approach of starting with precise=true for all registers and then
2731 * backtrack to mark a register as not precise when the verifier detects
2732 * that program doesn't care about specific value (e.g., when helper
2733 * takes register as ARG_ANYTHING parameter) is not safe.
2735 * It's ok to walk single parentage chain of the verifier states.
2736 * It's possible that this backtracking will go all the way till 1st insn.
2737 * All other branches will be explored for needing precision later.
2739 * The backtracking needs to deal with cases like:
2740 * 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)
2743 * if r5 > 0x79f goto pc+7
2744 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2747 * call bpf_perf_event_output#25
2748 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2752 * call foo // uses callee's r6 inside to compute r0
2756 * to track above reg_mask/stack_mask needs to be independent for each frame.
2758 * Also if parent's curframe > frame where backtracking started,
2759 * the verifier need to mark registers in both frames, otherwise callees
2760 * may incorrectly prune callers. This is similar to
2761 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2763 * For now backtracking falls back into conservative marking.
2765 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2766 struct bpf_verifier_state *st)
2768 struct bpf_func_state *func;
2769 struct bpf_reg_state *reg;
2772 /* big hammer: mark all scalars precise in this path.
2773 * pop_stack may still get !precise scalars.
2774 * We also skip current state and go straight to first parent state,
2775 * because precision markings in current non-checkpointed state are
2776 * not needed. See why in the comment in __mark_chain_precision below.
2778 for (st = st->parent; st; st = st->parent) {
2779 for (i = 0; i <= st->curframe; i++) {
2780 func = st->frame[i];
2781 for (j = 0; j < BPF_REG_FP; j++) {
2782 reg = &func->regs[j];
2783 if (reg->type != SCALAR_VALUE)
2785 reg->precise = true;
2787 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2788 if (!is_spilled_reg(&func->stack[j]))
2790 reg = &func->stack[j].spilled_ptr;
2791 if (reg->type != SCALAR_VALUE)
2793 reg->precise = true;
2799 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2801 struct bpf_func_state *func;
2802 struct bpf_reg_state *reg;
2805 for (i = 0; i <= st->curframe; i++) {
2806 func = st->frame[i];
2807 for (j = 0; j < BPF_REG_FP; j++) {
2808 reg = &func->regs[j];
2809 if (reg->type != SCALAR_VALUE)
2811 reg->precise = false;
2813 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2814 if (!is_spilled_reg(&func->stack[j]))
2816 reg = &func->stack[j].spilled_ptr;
2817 if (reg->type != SCALAR_VALUE)
2819 reg->precise = false;
2825 * __mark_chain_precision() backtracks BPF program instruction sequence and
2826 * chain of verifier states making sure that register *regno* (if regno >= 0)
2827 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2828 * SCALARS, as well as any other registers and slots that contribute to
2829 * a tracked state of given registers/stack slots, depending on specific BPF
2830 * assembly instructions (see backtrack_insns() for exact instruction handling
2831 * logic). This backtracking relies on recorded jmp_history and is able to
2832 * traverse entire chain of parent states. This process ends only when all the
2833 * necessary registers/slots and their transitive dependencies are marked as
2836 * One important and subtle aspect is that precise marks *do not matter* in
2837 * the currently verified state (current state). It is important to understand
2838 * why this is the case.
2840 * First, note that current state is the state that is not yet "checkpointed",
2841 * i.e., it is not yet put into env->explored_states, and it has no children
2842 * states as well. It's ephemeral, and can end up either a) being discarded if
2843 * compatible explored state is found at some point or BPF_EXIT instruction is
2844 * reached or b) checkpointed and put into env->explored_states, branching out
2845 * into one or more children states.
2847 * In the former case, precise markings in current state are completely
2848 * ignored by state comparison code (see regsafe() for details). Only
2849 * checkpointed ("old") state precise markings are important, and if old
2850 * state's register/slot is precise, regsafe() assumes current state's
2851 * register/slot as precise and checks value ranges exactly and precisely. If
2852 * states turn out to be compatible, current state's necessary precise
2853 * markings and any required parent states' precise markings are enforced
2854 * after the fact with propagate_precision() logic, after the fact. But it's
2855 * important to realize that in this case, even after marking current state
2856 * registers/slots as precise, we immediately discard current state. So what
2857 * actually matters is any of the precise markings propagated into current
2858 * state's parent states, which are always checkpointed (due to b) case above).
2859 * As such, for scenario a) it doesn't matter if current state has precise
2860 * markings set or not.
2862 * Now, for the scenario b), checkpointing and forking into child(ren)
2863 * state(s). Note that before current state gets to checkpointing step, any
2864 * processed instruction always assumes precise SCALAR register/slot
2865 * knowledge: if precise value or range is useful to prune jump branch, BPF
2866 * verifier takes this opportunity enthusiastically. Similarly, when
2867 * register's value is used to calculate offset or memory address, exact
2868 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2869 * what we mentioned above about state comparison ignoring precise markings
2870 * during state comparison, BPF verifier ignores and also assumes precise
2871 * markings *at will* during instruction verification process. But as verifier
2872 * assumes precision, it also propagates any precision dependencies across
2873 * parent states, which are not yet finalized, so can be further restricted
2874 * based on new knowledge gained from restrictions enforced by their children
2875 * states. This is so that once those parent states are finalized, i.e., when
2876 * they have no more active children state, state comparison logic in
2877 * is_state_visited() would enforce strict and precise SCALAR ranges, if
2878 * required for correctness.
2880 * To build a bit more intuition, note also that once a state is checkpointed,
2881 * the path we took to get to that state is not important. This is crucial
2882 * property for state pruning. When state is checkpointed and finalized at
2883 * some instruction index, it can be correctly and safely used to "short
2884 * circuit" any *compatible* state that reaches exactly the same instruction
2885 * index. I.e., if we jumped to that instruction from a completely different
2886 * code path than original finalized state was derived from, it doesn't
2887 * matter, current state can be discarded because from that instruction
2888 * forward having a compatible state will ensure we will safely reach the
2889 * exit. States describe preconditions for further exploration, but completely
2890 * forget the history of how we got here.
2892 * This also means that even if we needed precise SCALAR range to get to
2893 * finalized state, but from that point forward *that same* SCALAR register is
2894 * never used in a precise context (i.e., it's precise value is not needed for
2895 * correctness), it's correct and safe to mark such register as "imprecise"
2896 * (i.e., precise marking set to false). This is what we rely on when we do
2897 * not set precise marking in current state. If no child state requires
2898 * precision for any given SCALAR register, it's safe to dictate that it can
2899 * be imprecise. If any child state does require this register to be precise,
2900 * we'll mark it precise later retroactively during precise markings
2901 * propagation from child state to parent states.
2903 * Skipping precise marking setting in current state is a mild version of
2904 * relying on the above observation. But we can utilize this property even
2905 * more aggressively by proactively forgetting any precise marking in the
2906 * current state (which we inherited from the parent state), right before we
2907 * checkpoint it and branch off into new child state. This is done by
2908 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2909 * finalized states which help in short circuiting more future states.
2911 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2914 struct bpf_verifier_state *st = env->cur_state;
2915 int first_idx = st->first_insn_idx;
2916 int last_idx = env->insn_idx;
2917 struct bpf_func_state *func;
2918 struct bpf_reg_state *reg;
2919 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2920 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2921 bool skip_first = true;
2922 bool new_marks = false;
2925 if (!env->bpf_capable)
2928 /* Do sanity checks against current state of register and/or stack
2929 * slot, but don't set precise flag in current state, as precision
2930 * tracking in the current state is unnecessary.
2932 func = st->frame[frame];
2934 reg = &func->regs[regno];
2935 if (reg->type != SCALAR_VALUE) {
2936 WARN_ONCE(1, "backtracing misuse");
2943 if (!is_spilled_reg(&func->stack[spi])) {
2947 reg = &func->stack[spi].spilled_ptr;
2948 if (reg->type != SCALAR_VALUE) {
2958 if (!reg_mask && !stack_mask)
2962 DECLARE_BITMAP(mask, 64);
2963 u32 history = st->jmp_history_cnt;
2965 if (env->log.level & BPF_LOG_LEVEL2)
2966 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2969 /* we are at the entry into subprog, which
2970 * is expected for global funcs, but only if
2971 * requested precise registers are R1-R5
2972 * (which are global func's input arguments)
2974 if (st->curframe == 0 &&
2975 st->frame[0]->subprogno > 0 &&
2976 st->frame[0]->callsite == BPF_MAIN_FUNC &&
2977 stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
2978 bitmap_from_u64(mask, reg_mask);
2979 for_each_set_bit(i, mask, 32) {
2980 reg = &st->frame[0]->regs[i];
2981 if (reg->type != SCALAR_VALUE) {
2982 reg_mask &= ~(1u << i);
2985 reg->precise = true;
2990 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
2991 st->frame[0]->subprogno, reg_mask, stack_mask);
2992 WARN_ONCE(1, "verifier backtracking bug");
2996 for (i = last_idx;;) {
3001 err = backtrack_insn(env, i, ®_mask, &stack_mask);
3003 if (err == -ENOTSUPP) {
3004 mark_all_scalars_precise(env, st);
3009 if (!reg_mask && !stack_mask)
3010 /* Found assignment(s) into tracked register in this state.
3011 * Since this state is already marked, just return.
3012 * Nothing to be tracked further in the parent state.
3017 i = get_prev_insn_idx(st, i, &history);
3018 if (i >= env->prog->len) {
3019 /* This can happen if backtracking reached insn 0
3020 * and there are still reg_mask or stack_mask
3022 * It means the backtracking missed the spot where
3023 * particular register was initialized with a constant.
3025 verbose(env, "BUG backtracking idx %d\n", i);
3026 WARN_ONCE(1, "verifier backtracking bug");
3035 func = st->frame[frame];
3036 bitmap_from_u64(mask, reg_mask);
3037 for_each_set_bit(i, mask, 32) {
3038 reg = &func->regs[i];
3039 if (reg->type != SCALAR_VALUE) {
3040 reg_mask &= ~(1u << i);
3045 reg->precise = true;
3048 bitmap_from_u64(mask, stack_mask);
3049 for_each_set_bit(i, mask, 64) {
3050 if (i >= func->allocated_stack / BPF_REG_SIZE) {
3051 /* the sequence of instructions:
3053 * 3: (7b) *(u64 *)(r3 -8) = r0
3054 * 4: (79) r4 = *(u64 *)(r10 -8)
3055 * doesn't contain jmps. It's backtracked
3056 * as a single block.
3057 * During backtracking insn 3 is not recognized as
3058 * stack access, so at the end of backtracking
3059 * stack slot fp-8 is still marked in stack_mask.
3060 * However the parent state may not have accessed
3061 * fp-8 and it's "unallocated" stack space.
3062 * In such case fallback to conservative.
3064 mark_all_scalars_precise(env, st);
3068 if (!is_spilled_reg(&func->stack[i])) {
3069 stack_mask &= ~(1ull << i);
3072 reg = &func->stack[i].spilled_ptr;
3073 if (reg->type != SCALAR_VALUE) {
3074 stack_mask &= ~(1ull << i);
3079 reg->precise = true;
3081 if (env->log.level & BPF_LOG_LEVEL2) {
3082 verbose(env, "parent %s regs=%x stack=%llx marks:",
3083 new_marks ? "didn't have" : "already had",
3084 reg_mask, stack_mask);
3085 print_verifier_state(env, func, true);
3088 if (!reg_mask && !stack_mask)
3093 last_idx = st->last_insn_idx;
3094 first_idx = st->first_insn_idx;
3099 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3101 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3104 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3106 return __mark_chain_precision(env, frame, regno, -1);
3109 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3111 return __mark_chain_precision(env, frame, -1, spi);
3114 static bool is_spillable_regtype(enum bpf_reg_type type)
3116 switch (base_type(type)) {
3117 case PTR_TO_MAP_VALUE:
3121 case PTR_TO_PACKET_META:
3122 case PTR_TO_PACKET_END:
3123 case PTR_TO_FLOW_KEYS:
3124 case CONST_PTR_TO_MAP:
3126 case PTR_TO_SOCK_COMMON:
3127 case PTR_TO_TCP_SOCK:
3128 case PTR_TO_XDP_SOCK:
3133 case PTR_TO_MAP_KEY:
3140 /* Does this register contain a constant zero? */
3141 static bool register_is_null(struct bpf_reg_state *reg)
3143 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3146 static bool register_is_const(struct bpf_reg_state *reg)
3148 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3151 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3153 return tnum_is_unknown(reg->var_off) &&
3154 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3155 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3156 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3157 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3160 static bool register_is_bounded(struct bpf_reg_state *reg)
3162 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3165 static bool __is_pointer_value(bool allow_ptr_leaks,
3166 const struct bpf_reg_state *reg)
3168 if (allow_ptr_leaks)
3171 return reg->type != SCALAR_VALUE;
3174 static void save_register_state(struct bpf_func_state *state,
3175 int spi, struct bpf_reg_state *reg,
3180 state->stack[spi].spilled_ptr = *reg;
3181 if (size == BPF_REG_SIZE)
3182 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3184 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3185 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3187 /* size < 8 bytes spill */
3189 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3192 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3193 * stack boundary and alignment are checked in check_mem_access()
3195 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3196 /* stack frame we're writing to */
3197 struct bpf_func_state *state,
3198 int off, int size, int value_regno,
3201 struct bpf_func_state *cur; /* state of the current function */
3202 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3203 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3204 struct bpf_reg_state *reg = NULL;
3206 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3209 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3210 * so it's aligned access and [off, off + size) are within stack limits
3212 if (!env->allow_ptr_leaks &&
3213 state->stack[spi].slot_type[0] == STACK_SPILL &&
3214 size != BPF_REG_SIZE) {
3215 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3219 cur = env->cur_state->frame[env->cur_state->curframe];
3220 if (value_regno >= 0)
3221 reg = &cur->regs[value_regno];
3222 if (!env->bypass_spec_v4) {
3223 bool sanitize = reg && is_spillable_regtype(reg->type);
3225 for (i = 0; i < size; i++) {
3226 if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3233 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3236 mark_stack_slot_scratched(env, spi);
3237 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3238 !register_is_null(reg) && env->bpf_capable) {
3239 if (dst_reg != BPF_REG_FP) {
3240 /* The backtracking logic can only recognize explicit
3241 * stack slot address like [fp - 8]. Other spill of
3242 * scalar via different register has to be conservative.
3243 * Backtrack from here and mark all registers as precise
3244 * that contributed into 'reg' being a constant.
3246 err = mark_chain_precision(env, value_regno);
3250 save_register_state(state, spi, reg, size);
3251 } else if (reg && is_spillable_regtype(reg->type)) {
3252 /* register containing pointer is being spilled into stack */
3253 if (size != BPF_REG_SIZE) {
3254 verbose_linfo(env, insn_idx, "; ");
3255 verbose(env, "invalid size of register spill\n");
3258 if (state != cur && reg->type == PTR_TO_STACK) {
3259 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3262 save_register_state(state, spi, reg, size);
3264 u8 type = STACK_MISC;
3266 /* regular write of data into stack destroys any spilled ptr */
3267 state->stack[spi].spilled_ptr.type = NOT_INIT;
3268 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3269 if (is_spilled_reg(&state->stack[spi]))
3270 for (i = 0; i < BPF_REG_SIZE; i++)
3271 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3273 /* only mark the slot as written if all 8 bytes were written
3274 * otherwise read propagation may incorrectly stop too soon
3275 * when stack slots are partially written.
3276 * This heuristic means that read propagation will be
3277 * conservative, since it will add reg_live_read marks
3278 * to stack slots all the way to first state when programs
3279 * writes+reads less than 8 bytes
3281 if (size == BPF_REG_SIZE)
3282 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3284 /* when we zero initialize stack slots mark them as such */
3285 if (reg && register_is_null(reg)) {
3286 /* backtracking doesn't work for STACK_ZERO yet. */
3287 err = mark_chain_precision(env, value_regno);
3293 /* Mark slots affected by this stack write. */
3294 for (i = 0; i < size; i++)
3295 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3301 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3302 * known to contain a variable offset.
3303 * This function checks whether the write is permitted and conservatively
3304 * tracks the effects of the write, considering that each stack slot in the
3305 * dynamic range is potentially written to.
3307 * 'off' includes 'regno->off'.
3308 * 'value_regno' can be -1, meaning that an unknown value is being written to
3311 * Spilled pointers in range are not marked as written because we don't know
3312 * what's going to be actually written. This means that read propagation for
3313 * future reads cannot be terminated by this write.
3315 * For privileged programs, uninitialized stack slots are considered
3316 * initialized by this write (even though we don't know exactly what offsets
3317 * are going to be written to). The idea is that we don't want the verifier to
3318 * reject future reads that access slots written to through variable offsets.
3320 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3321 /* func where register points to */
3322 struct bpf_func_state *state,
3323 int ptr_regno, int off, int size,
3324 int value_regno, int insn_idx)
3326 struct bpf_func_state *cur; /* state of the current function */
3327 int min_off, max_off;
3329 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3330 bool writing_zero = false;
3331 /* set if the fact that we're writing a zero is used to let any
3332 * stack slots remain STACK_ZERO
3334 bool zero_used = false;
3336 cur = env->cur_state->frame[env->cur_state->curframe];
3337 ptr_reg = &cur->regs[ptr_regno];
3338 min_off = ptr_reg->smin_value + off;
3339 max_off = ptr_reg->smax_value + off + size;
3340 if (value_regno >= 0)
3341 value_reg = &cur->regs[value_regno];
3342 if (value_reg && register_is_null(value_reg))
3343 writing_zero = true;
3345 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3350 /* Variable offset writes destroy any spilled pointers in range. */
3351 for (i = min_off; i < max_off; i++) {
3352 u8 new_type, *stype;
3356 spi = slot / BPF_REG_SIZE;
3357 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3358 mark_stack_slot_scratched(env, spi);
3360 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3361 /* Reject the write if range we may write to has not
3362 * been initialized beforehand. If we didn't reject
3363 * here, the ptr status would be erased below (even
3364 * though not all slots are actually overwritten),
3365 * possibly opening the door to leaks.
3367 * We do however catch STACK_INVALID case below, and
3368 * only allow reading possibly uninitialized memory
3369 * later for CAP_PERFMON, as the write may not happen to
3372 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3377 /* Erase all spilled pointers. */
3378 state->stack[spi].spilled_ptr.type = NOT_INIT;
3380 /* Update the slot type. */
3381 new_type = STACK_MISC;
3382 if (writing_zero && *stype == STACK_ZERO) {
3383 new_type = STACK_ZERO;
3386 /* If the slot is STACK_INVALID, we check whether it's OK to
3387 * pretend that it will be initialized by this write. The slot
3388 * might not actually be written to, and so if we mark it as
3389 * initialized future reads might leak uninitialized memory.
3390 * For privileged programs, we will accept such reads to slots
3391 * that may or may not be written because, if we're reject
3392 * them, the error would be too confusing.
3394 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3395 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3402 /* backtracking doesn't work for STACK_ZERO yet. */
3403 err = mark_chain_precision(env, value_regno);
3410 /* When register 'dst_regno' is assigned some values from stack[min_off,
3411 * max_off), we set the register's type according to the types of the
3412 * respective stack slots. If all the stack values are known to be zeros, then
3413 * so is the destination reg. Otherwise, the register is considered to be
3414 * SCALAR. This function does not deal with register filling; the caller must
3415 * ensure that all spilled registers in the stack range have been marked as
3418 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3419 /* func where src register points to */
3420 struct bpf_func_state *ptr_state,
3421 int min_off, int max_off, int dst_regno)
3423 struct bpf_verifier_state *vstate = env->cur_state;
3424 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3429 for (i = min_off; i < max_off; i++) {
3431 spi = slot / BPF_REG_SIZE;
3432 stype = ptr_state->stack[spi].slot_type;
3433 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3437 if (zeros == max_off - min_off) {
3438 /* any access_size read into register is zero extended,
3439 * so the whole register == const_zero
3441 __mark_reg_const_zero(&state->regs[dst_regno]);
3442 /* backtracking doesn't support STACK_ZERO yet,
3443 * so mark it precise here, so that later
3444 * backtracking can stop here.
3445 * Backtracking may not need this if this register
3446 * doesn't participate in pointer adjustment.
3447 * Forward propagation of precise flag is not
3448 * necessary either. This mark is only to stop
3449 * backtracking. Any register that contributed
3450 * to const 0 was marked precise before spill.
3452 state->regs[dst_regno].precise = true;
3454 /* have read misc data from the stack */
3455 mark_reg_unknown(env, state->regs, dst_regno);
3457 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3460 /* Read the stack at 'off' and put the results into the register indicated by
3461 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3464 * 'dst_regno' can be -1, meaning that the read value is not going to a
3467 * The access is assumed to be within the current stack bounds.
3469 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3470 /* func where src register points to */
3471 struct bpf_func_state *reg_state,
3472 int off, int size, int dst_regno)
3474 struct bpf_verifier_state *vstate = env->cur_state;
3475 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3476 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3477 struct bpf_reg_state *reg;
3480 stype = reg_state->stack[spi].slot_type;
3481 reg = ®_state->stack[spi].spilled_ptr;
3483 if (is_spilled_reg(®_state->stack[spi])) {
3486 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3489 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3490 if (reg->type != SCALAR_VALUE) {
3491 verbose_linfo(env, env->insn_idx, "; ");
3492 verbose(env, "invalid size of register fill\n");
3496 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3500 if (!(off % BPF_REG_SIZE) && size == spill_size) {
3501 /* The earlier check_reg_arg() has decided the
3502 * subreg_def for this insn. Save it first.
3504 s32 subreg_def = state->regs[dst_regno].subreg_def;
3506 state->regs[dst_regno] = *reg;
3507 state->regs[dst_regno].subreg_def = subreg_def;
3509 for (i = 0; i < size; i++) {
3510 type = stype[(slot - i) % BPF_REG_SIZE];
3511 if (type == STACK_SPILL)
3513 if (type == STACK_MISC)
3515 verbose(env, "invalid read from stack off %d+%d size %d\n",
3519 mark_reg_unknown(env, state->regs, dst_regno);
3521 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3525 if (dst_regno >= 0) {
3526 /* restore register state from stack */
3527 state->regs[dst_regno] = *reg;
3528 /* mark reg as written since spilled pointer state likely
3529 * has its liveness marks cleared by is_state_visited()
3530 * which resets stack/reg liveness for state transitions
3532 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3533 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3534 /* If dst_regno==-1, the caller is asking us whether
3535 * it is acceptable to use this value as a SCALAR_VALUE
3537 * We must not allow unprivileged callers to do that
3538 * with spilled pointers.
3540 verbose(env, "leaking pointer from stack off %d\n",
3544 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3546 for (i = 0; i < size; i++) {
3547 type = stype[(slot - i) % BPF_REG_SIZE];
3548 if (type == STACK_MISC)
3550 if (type == STACK_ZERO)
3552 verbose(env, "invalid read from stack off %d+%d size %d\n",
3556 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3558 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3563 enum bpf_access_src {
3564 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
3565 ACCESS_HELPER = 2, /* the access is performed by a helper */
3568 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3569 int regno, int off, int access_size,
3570 bool zero_size_allowed,
3571 enum bpf_access_src type,
3572 struct bpf_call_arg_meta *meta);
3574 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3576 return cur_regs(env) + regno;
3579 /* Read the stack at 'ptr_regno + off' and put the result into the register
3581 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3582 * but not its variable offset.
3583 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3585 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3586 * filling registers (i.e. reads of spilled register cannot be detected when
3587 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3588 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3589 * offset; for a fixed offset check_stack_read_fixed_off should be used
3592 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3593 int ptr_regno, int off, int size, int dst_regno)
3595 /* The state of the source register. */
3596 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3597 struct bpf_func_state *ptr_state = func(env, reg);
3599 int min_off, max_off;
3601 /* Note that we pass a NULL meta, so raw access will not be permitted.
3603 err = check_stack_range_initialized(env, ptr_regno, off, size,
3604 false, ACCESS_DIRECT, NULL);
3608 min_off = reg->smin_value + off;
3609 max_off = reg->smax_value + off;
3610 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3614 /* check_stack_read dispatches to check_stack_read_fixed_off or
3615 * check_stack_read_var_off.
3617 * The caller must ensure that the offset falls within the allocated stack
3620 * 'dst_regno' is a register which will receive the value from the stack. It
3621 * can be -1, meaning that the read value is not going to a register.
3623 static int check_stack_read(struct bpf_verifier_env *env,
3624 int ptr_regno, int off, int size,
3627 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3628 struct bpf_func_state *state = func(env, reg);
3630 /* Some accesses are only permitted with a static offset. */
3631 bool var_off = !tnum_is_const(reg->var_off);
3633 /* The offset is required to be static when reads don't go to a
3634 * register, in order to not leak pointers (see
3635 * check_stack_read_fixed_off).
3637 if (dst_regno < 0 && var_off) {
3640 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3641 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3645 /* Variable offset is prohibited for unprivileged mode for simplicity
3646 * since it requires corresponding support in Spectre masking for stack
3647 * ALU. See also retrieve_ptr_limit().
3649 if (!env->bypass_spec_v1 && var_off) {
3652 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3653 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3659 off += reg->var_off.value;
3660 err = check_stack_read_fixed_off(env, state, off, size,
3663 /* Variable offset stack reads need more conservative handling
3664 * than fixed offset ones. Note that dst_regno >= 0 on this
3667 err = check_stack_read_var_off(env, ptr_regno, off, size,
3674 /* check_stack_write dispatches to check_stack_write_fixed_off or
3675 * check_stack_write_var_off.
3677 * 'ptr_regno' is the register used as a pointer into the stack.
3678 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3679 * 'value_regno' is the register whose value we're writing to the stack. It can
3680 * be -1, meaning that we're not writing from a register.
3682 * The caller must ensure that the offset falls within the maximum stack size.
3684 static int check_stack_write(struct bpf_verifier_env *env,
3685 int ptr_regno, int off, int size,
3686 int value_regno, int insn_idx)
3688 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3689 struct bpf_func_state *state = func(env, reg);
3692 if (tnum_is_const(reg->var_off)) {
3693 off += reg->var_off.value;
3694 err = check_stack_write_fixed_off(env, state, off, size,
3695 value_regno, insn_idx);
3697 /* Variable offset stack reads need more conservative handling
3698 * than fixed offset ones.
3700 err = check_stack_write_var_off(env, state,
3701 ptr_regno, off, size,
3702 value_regno, insn_idx);
3707 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3708 int off, int size, enum bpf_access_type type)
3710 struct bpf_reg_state *regs = cur_regs(env);
3711 struct bpf_map *map = regs[regno].map_ptr;
3712 u32 cap = bpf_map_flags_to_cap(map);
3714 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3715 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3716 map->value_size, off, size);
3720 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3721 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3722 map->value_size, off, size);
3729 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3730 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3731 int off, int size, u32 mem_size,
3732 bool zero_size_allowed)
3734 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3735 struct bpf_reg_state *reg;
3737 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3740 reg = &cur_regs(env)[regno];
3741 switch (reg->type) {
3742 case PTR_TO_MAP_KEY:
3743 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3744 mem_size, off, size);
3746 case PTR_TO_MAP_VALUE:
3747 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3748 mem_size, off, size);
3751 case PTR_TO_PACKET_META:
3752 case PTR_TO_PACKET_END:
3753 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3754 off, size, regno, reg->id, off, mem_size);
3758 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3759 mem_size, off, size);
3765 /* check read/write into a memory region with possible variable offset */
3766 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3767 int off, int size, u32 mem_size,
3768 bool zero_size_allowed)
3770 struct bpf_verifier_state *vstate = env->cur_state;
3771 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3772 struct bpf_reg_state *reg = &state->regs[regno];
3775 /* We may have adjusted the register pointing to memory region, so we
3776 * need to try adding each of min_value and max_value to off
3777 * to make sure our theoretical access will be safe.
3779 * The minimum value is only important with signed
3780 * comparisons where we can't assume the floor of a
3781 * value is 0. If we are using signed variables for our
3782 * index'es we need to make sure that whatever we use
3783 * will have a set floor within our range.
3785 if (reg->smin_value < 0 &&
3786 (reg->smin_value == S64_MIN ||
3787 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3788 reg->smin_value + off < 0)) {
3789 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3793 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3794 mem_size, zero_size_allowed);
3796 verbose(env, "R%d min value is outside of the allowed memory range\n",
3801 /* If we haven't set a max value then we need to bail since we can't be
3802 * sure we won't do bad things.
3803 * If reg->umax_value + off could overflow, treat that as unbounded too.
3805 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3806 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3810 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3811 mem_size, zero_size_allowed);
3813 verbose(env, "R%d max value is outside of the allowed memory range\n",
3821 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3822 const struct bpf_reg_state *reg, int regno,
3825 /* Access to this pointer-typed register or passing it to a helper
3826 * is only allowed in its original, unmodified form.
3830 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3831 reg_type_str(env, reg->type), regno, reg->off);
3835 if (!fixed_off_ok && reg->off) {
3836 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3837 reg_type_str(env, reg->type), regno, reg->off);
3841 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3844 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3845 verbose(env, "variable %s access var_off=%s disallowed\n",
3846 reg_type_str(env, reg->type), tn_buf);
3853 int check_ptr_off_reg(struct bpf_verifier_env *env,
3854 const struct bpf_reg_state *reg, int regno)
3856 return __check_ptr_off_reg(env, reg, regno, false);
3859 static int map_kptr_match_type(struct bpf_verifier_env *env,
3860 struct btf_field *kptr_field,
3861 struct bpf_reg_state *reg, u32 regno)
3863 const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
3864 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED;
3865 const char *reg_name = "";
3867 /* Only unreferenced case accepts untrusted pointers */
3868 if (kptr_field->type == BPF_KPTR_UNREF)
3869 perm_flags |= PTR_UNTRUSTED;
3871 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3874 if (!btf_is_kernel(reg->btf)) {
3875 verbose(env, "R%d must point to kernel BTF\n", regno);
3878 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3879 reg_name = kernel_type_name(reg->btf, reg->btf_id);
3881 /* For ref_ptr case, release function check should ensure we get one
3882 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3883 * normal store of unreferenced kptr, we must ensure var_off is zero.
3884 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3885 * reg->off and reg->ref_obj_id are not needed here.
3887 if (__check_ptr_off_reg(env, reg, regno, true))
3890 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3891 * we also need to take into account the reg->off.
3893 * We want to support cases like:
3901 * v = func(); // PTR_TO_BTF_ID
3902 * val->foo = v; // reg->off is zero, btf and btf_id match type
3903 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3904 * // first member type of struct after comparison fails
3905 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3908 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3909 * is zero. We must also ensure that btf_struct_ids_match does not walk
3910 * the struct to match type against first member of struct, i.e. reject
3911 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3912 * strict mode to true for type match.
3914 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3915 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
3916 kptr_field->type == BPF_KPTR_REF))
3920 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3921 reg_type_str(env, reg->type), reg_name);
3922 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3923 if (kptr_field->type == BPF_KPTR_UNREF)
3924 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3931 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3932 int value_regno, int insn_idx,
3933 struct btf_field *kptr_field)
3935 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3936 int class = BPF_CLASS(insn->code);
3937 struct bpf_reg_state *val_reg;
3939 /* Things we already checked for in check_map_access and caller:
3940 * - Reject cases where variable offset may touch kptr
3941 * - size of access (must be BPF_DW)
3942 * - tnum_is_const(reg->var_off)
3943 * - kptr_field->offset == off + reg->var_off.value
3945 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3946 if (BPF_MODE(insn->code) != BPF_MEM) {
3947 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3951 /* We only allow loading referenced kptr, since it will be marked as
3952 * untrusted, similar to unreferenced kptr.
3954 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
3955 verbose(env, "store to referenced kptr disallowed\n");
3959 if (class == BPF_LDX) {
3960 val_reg = reg_state(env, value_regno);
3961 /* We can simply mark the value_regno receiving the pointer
3962 * value from map as PTR_TO_BTF_ID, with the correct type.
3964 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
3965 kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3966 /* For mark_ptr_or_null_reg */
3967 val_reg->id = ++env->id_gen;
3968 } else if (class == BPF_STX) {
3969 val_reg = reg_state(env, value_regno);
3970 if (!register_is_null(val_reg) &&
3971 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
3973 } else if (class == BPF_ST) {
3975 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3976 kptr_field->offset);
3980 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3986 /* check read/write into a map element with possible variable offset */
3987 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3988 int off, int size, bool zero_size_allowed,
3989 enum bpf_access_src src)
3991 struct bpf_verifier_state *vstate = env->cur_state;
3992 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3993 struct bpf_reg_state *reg = &state->regs[regno];
3994 struct bpf_map *map = reg->map_ptr;
3995 struct btf_record *rec;
3998 err = check_mem_region_access(env, regno, off, size, map->value_size,
4003 if (IS_ERR_OR_NULL(map->record))
4006 for (i = 0; i < rec->cnt; i++) {
4007 struct btf_field *field = &rec->fields[i];
4008 u32 p = field->offset;
4010 /* If any part of a field can be touched by load/store, reject
4011 * this program. To check that [x1, x2) overlaps with [y1, y2),
4012 * it is sufficient to check x1 < y2 && y1 < x2.
4014 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4015 p < reg->umax_value + off + size) {
4016 switch (field->type) {
4017 case BPF_KPTR_UNREF:
4019 if (src != ACCESS_DIRECT) {
4020 verbose(env, "kptr cannot be accessed indirectly by helper\n");
4023 if (!tnum_is_const(reg->var_off)) {
4024 verbose(env, "kptr access cannot have variable offset\n");
4027 if (p != off + reg->var_off.value) {
4028 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4029 p, off + reg->var_off.value);
4032 if (size != bpf_size_to_bytes(BPF_DW)) {
4033 verbose(env, "kptr access size must be BPF_DW\n");
4038 verbose(env, "%s cannot be accessed directly by load/store\n",
4039 btf_field_type_name(field->type));
4047 #define MAX_PACKET_OFF 0xffff
4049 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4050 const struct bpf_call_arg_meta *meta,
4051 enum bpf_access_type t)
4053 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4055 switch (prog_type) {
4056 /* Program types only with direct read access go here! */
4057 case BPF_PROG_TYPE_LWT_IN:
4058 case BPF_PROG_TYPE_LWT_OUT:
4059 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4060 case BPF_PROG_TYPE_SK_REUSEPORT:
4061 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4062 case BPF_PROG_TYPE_CGROUP_SKB:
4067 /* Program types with direct read + write access go here! */
4068 case BPF_PROG_TYPE_SCHED_CLS:
4069 case BPF_PROG_TYPE_SCHED_ACT:
4070 case BPF_PROG_TYPE_XDP:
4071 case BPF_PROG_TYPE_LWT_XMIT:
4072 case BPF_PROG_TYPE_SK_SKB:
4073 case BPF_PROG_TYPE_SK_MSG:
4075 return meta->pkt_access;
4077 env->seen_direct_write = true;
4080 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4082 env->seen_direct_write = true;
4091 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4092 int size, bool zero_size_allowed)
4094 struct bpf_reg_state *regs = cur_regs(env);
4095 struct bpf_reg_state *reg = ®s[regno];
4098 /* We may have added a variable offset to the packet pointer; but any
4099 * reg->range we have comes after that. We are only checking the fixed
4103 /* We don't allow negative numbers, because we aren't tracking enough
4104 * detail to prove they're safe.
4106 if (reg->smin_value < 0) {
4107 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4112 err = reg->range < 0 ? -EINVAL :
4113 __check_mem_access(env, regno, off, size, reg->range,
4116 verbose(env, "R%d offset is outside of the packet\n", regno);
4120 /* __check_mem_access has made sure "off + size - 1" is within u16.
4121 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4122 * otherwise find_good_pkt_pointers would have refused to set range info
4123 * that __check_mem_access would have rejected this pkt access.
4124 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4126 env->prog->aux->max_pkt_offset =
4127 max_t(u32, env->prog->aux->max_pkt_offset,
4128 off + reg->umax_value + size - 1);
4133 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
4134 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4135 enum bpf_access_type t, enum bpf_reg_type *reg_type,
4136 struct btf **btf, u32 *btf_id)
4138 struct bpf_insn_access_aux info = {
4139 .reg_type = *reg_type,
4143 if (env->ops->is_valid_access &&
4144 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4145 /* A non zero info.ctx_field_size indicates that this field is a
4146 * candidate for later verifier transformation to load the whole
4147 * field and then apply a mask when accessed with a narrower
4148 * access than actual ctx access size. A zero info.ctx_field_size
4149 * will only allow for whole field access and rejects any other
4150 * type of narrower access.
4152 *reg_type = info.reg_type;
4154 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4156 *btf_id = info.btf_id;
4158 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4160 /* remember the offset of last byte accessed in ctx */
4161 if (env->prog->aux->max_ctx_offset < off + size)
4162 env->prog->aux->max_ctx_offset = off + size;
4166 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4170 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4173 if (size < 0 || off < 0 ||
4174 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4175 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4182 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4183 u32 regno, int off, int size,
4184 enum bpf_access_type t)
4186 struct bpf_reg_state *regs = cur_regs(env);
4187 struct bpf_reg_state *reg = ®s[regno];
4188 struct bpf_insn_access_aux info = {};
4191 if (reg->smin_value < 0) {
4192 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4197 switch (reg->type) {
4198 case PTR_TO_SOCK_COMMON:
4199 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4202 valid = bpf_sock_is_valid_access(off, size, t, &info);
4204 case PTR_TO_TCP_SOCK:
4205 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4207 case PTR_TO_XDP_SOCK:
4208 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4216 env->insn_aux_data[insn_idx].ctx_field_size =
4217 info.ctx_field_size;
4221 verbose(env, "R%d invalid %s access off=%d size=%d\n",
4222 regno, reg_type_str(env, reg->type), off, size);
4227 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4229 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4232 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4234 const struct bpf_reg_state *reg = reg_state(env, regno);
4236 return reg->type == PTR_TO_CTX;
4239 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4241 const struct bpf_reg_state *reg = reg_state(env, regno);
4243 return type_is_sk_pointer(reg->type);
4246 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4248 const struct bpf_reg_state *reg = reg_state(env, regno);
4250 return type_is_pkt_pointer(reg->type);
4253 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4255 const struct bpf_reg_state *reg = reg_state(env, regno);
4257 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4258 return reg->type == PTR_TO_FLOW_KEYS;
4261 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4262 const struct bpf_reg_state *reg,
4263 int off, int size, bool strict)
4265 struct tnum reg_off;
4268 /* Byte size accesses are always allowed. */
4269 if (!strict || size == 1)
4272 /* For platforms that do not have a Kconfig enabling
4273 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4274 * NET_IP_ALIGN is universally set to '2'. And on platforms
4275 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4276 * to this code only in strict mode where we want to emulate
4277 * the NET_IP_ALIGN==2 checking. Therefore use an
4278 * unconditional IP align value of '2'.
4282 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4283 if (!tnum_is_aligned(reg_off, size)) {
4286 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4288 "misaligned packet access off %d+%s+%d+%d size %d\n",
4289 ip_align, tn_buf, reg->off, off, size);
4296 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4297 const struct bpf_reg_state *reg,
4298 const char *pointer_desc,
4299 int off, int size, bool strict)
4301 struct tnum reg_off;
4303 /* Byte size accesses are always allowed. */
4304 if (!strict || size == 1)
4307 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4308 if (!tnum_is_aligned(reg_off, size)) {
4311 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4312 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4313 pointer_desc, tn_buf, reg->off, off, size);
4320 static int check_ptr_alignment(struct bpf_verifier_env *env,
4321 const struct bpf_reg_state *reg, int off,
4322 int size, bool strict_alignment_once)
4324 bool strict = env->strict_alignment || strict_alignment_once;
4325 const char *pointer_desc = "";
4327 switch (reg->type) {
4329 case PTR_TO_PACKET_META:
4330 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4331 * right in front, treat it the very same way.
4333 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4334 case PTR_TO_FLOW_KEYS:
4335 pointer_desc = "flow keys ";
4337 case PTR_TO_MAP_KEY:
4338 pointer_desc = "key ";
4340 case PTR_TO_MAP_VALUE:
4341 pointer_desc = "value ";
4344 pointer_desc = "context ";
4347 pointer_desc = "stack ";
4348 /* The stack spill tracking logic in check_stack_write_fixed_off()
4349 * and check_stack_read_fixed_off() relies on stack accesses being
4355 pointer_desc = "sock ";
4357 case PTR_TO_SOCK_COMMON:
4358 pointer_desc = "sock_common ";
4360 case PTR_TO_TCP_SOCK:
4361 pointer_desc = "tcp_sock ";
4363 case PTR_TO_XDP_SOCK:
4364 pointer_desc = "xdp_sock ";
4369 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4373 static int update_stack_depth(struct bpf_verifier_env *env,
4374 const struct bpf_func_state *func,
4377 u16 stack = env->subprog_info[func->subprogno].stack_depth;
4382 /* update known max for given subprogram */
4383 env->subprog_info[func->subprogno].stack_depth = -off;
4387 /* starting from main bpf function walk all instructions of the function
4388 * and recursively walk all callees that given function can call.
4389 * Ignore jump and exit insns.
4390 * Since recursion is prevented by check_cfg() this algorithm
4391 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4393 static int check_max_stack_depth(struct bpf_verifier_env *env)
4395 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4396 struct bpf_subprog_info *subprog = env->subprog_info;
4397 struct bpf_insn *insn = env->prog->insnsi;
4398 bool tail_call_reachable = false;
4399 int ret_insn[MAX_CALL_FRAMES];
4400 int ret_prog[MAX_CALL_FRAMES];
4404 /* protect against potential stack overflow that might happen when
4405 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4406 * depth for such case down to 256 so that the worst case scenario
4407 * would result in 8k stack size (32 which is tailcall limit * 256 =
4410 * To get the idea what might happen, see an example:
4411 * func1 -> sub rsp, 128
4412 * subfunc1 -> sub rsp, 256
4413 * tailcall1 -> add rsp, 256
4414 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4415 * subfunc2 -> sub rsp, 64
4416 * subfunc22 -> sub rsp, 128
4417 * tailcall2 -> add rsp, 128
4418 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4420 * tailcall will unwind the current stack frame but it will not get rid
4421 * of caller's stack as shown on the example above.
4423 if (idx && subprog[idx].has_tail_call && depth >= 256) {
4425 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4429 /* round up to 32-bytes, since this is granularity
4430 * of interpreter stack size
4432 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4433 if (depth > MAX_BPF_STACK) {
4434 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4439 subprog_end = subprog[idx + 1].start;
4440 for (; i < subprog_end; i++) {
4443 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4445 /* remember insn and function to return to */
4446 ret_insn[frame] = i + 1;
4447 ret_prog[frame] = idx;
4449 /* find the callee */
4450 next_insn = i + insn[i].imm + 1;
4451 idx = find_subprog(env, next_insn);
4453 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4457 if (subprog[idx].is_async_cb) {
4458 if (subprog[idx].has_tail_call) {
4459 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4462 /* async callbacks don't increase bpf prog stack size */
4467 if (subprog[idx].has_tail_call)
4468 tail_call_reachable = true;
4471 if (frame >= MAX_CALL_FRAMES) {
4472 verbose(env, "the call stack of %d frames is too deep !\n",
4478 /* if tail call got detected across bpf2bpf calls then mark each of the
4479 * currently present subprog frames as tail call reachable subprogs;
4480 * this info will be utilized by JIT so that we will be preserving the
4481 * tail call counter throughout bpf2bpf calls combined with tailcalls
4483 if (tail_call_reachable)
4484 for (j = 0; j < frame; j++)
4485 subprog[ret_prog[j]].tail_call_reachable = true;
4486 if (subprog[0].tail_call_reachable)
4487 env->prog->aux->tail_call_reachable = true;
4489 /* end of for() loop means the last insn of the 'subprog'
4490 * was reached. Doesn't matter whether it was JA or EXIT
4494 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4496 i = ret_insn[frame];
4497 idx = ret_prog[frame];
4501 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4502 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4503 const struct bpf_insn *insn, int idx)
4505 int start = idx + insn->imm + 1, subprog;
4507 subprog = find_subprog(env, start);
4509 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4513 return env->subprog_info[subprog].stack_depth;
4517 static int __check_buffer_access(struct bpf_verifier_env *env,
4518 const char *buf_info,
4519 const struct bpf_reg_state *reg,
4520 int regno, int off, int size)
4524 "R%d invalid %s buffer access: off=%d, size=%d\n",
4525 regno, buf_info, off, size);
4528 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4531 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4533 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4534 regno, off, tn_buf);
4541 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4542 const struct bpf_reg_state *reg,
4543 int regno, int off, int size)
4547 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4551 if (off + size > env->prog->aux->max_tp_access)
4552 env->prog->aux->max_tp_access = off + size;
4557 static int check_buffer_access(struct bpf_verifier_env *env,
4558 const struct bpf_reg_state *reg,
4559 int regno, int off, int size,
4560 bool zero_size_allowed,
4563 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4566 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4570 if (off + size > *max_access)
4571 *max_access = off + size;
4576 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4577 static void zext_32_to_64(struct bpf_reg_state *reg)
4579 reg->var_off = tnum_subreg(reg->var_off);
4580 __reg_assign_32_into_64(reg);
4583 /* truncate register to smaller size (in bytes)
4584 * must be called with size < BPF_REG_SIZE
4586 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4590 /* clear high bits in bit representation */
4591 reg->var_off = tnum_cast(reg->var_off, size);
4593 /* fix arithmetic bounds */
4594 mask = ((u64)1 << (size * 8)) - 1;
4595 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4596 reg->umin_value &= mask;
4597 reg->umax_value &= mask;
4599 reg->umin_value = 0;
4600 reg->umax_value = mask;
4602 reg->smin_value = reg->umin_value;
4603 reg->smax_value = reg->umax_value;
4605 /* If size is smaller than 32bit register the 32bit register
4606 * values are also truncated so we push 64-bit bounds into
4607 * 32-bit bounds. Above were truncated < 32-bits already.
4611 __reg_combine_64_into_32(reg);
4614 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4616 /* A map is considered read-only if the following condition are true:
4618 * 1) BPF program side cannot change any of the map content. The
4619 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4620 * and was set at map creation time.
4621 * 2) The map value(s) have been initialized from user space by a
4622 * loader and then "frozen", such that no new map update/delete
4623 * operations from syscall side are possible for the rest of
4624 * the map's lifetime from that point onwards.
4625 * 3) Any parallel/pending map update/delete operations from syscall
4626 * side have been completed. Only after that point, it's safe to
4627 * assume that map value(s) are immutable.
4629 return (map->map_flags & BPF_F_RDONLY_PROG) &&
4630 READ_ONCE(map->frozen) &&
4631 !bpf_map_write_active(map);
4634 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4640 err = map->ops->map_direct_value_addr(map, &addr, off);
4643 ptr = (void *)(long)addr + off;
4647 *val = (u64)*(u8 *)ptr;
4650 *val = (u64)*(u16 *)ptr;
4653 *val = (u64)*(u32 *)ptr;
4664 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4665 struct bpf_reg_state *regs,
4666 int regno, int off, int size,
4667 enum bpf_access_type atype,
4670 struct bpf_reg_state *reg = regs + regno;
4671 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4672 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4673 enum bpf_type_flag flag = 0;
4679 "R%d is ptr_%s invalid negative access: off=%d\n",
4683 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4686 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4688 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4689 regno, tname, off, tn_buf);
4693 if (reg->type & MEM_USER) {
4695 "R%d is ptr_%s access user memory: off=%d\n",
4700 if (reg->type & MEM_PERCPU) {
4702 "R%d is ptr_%s access percpu memory: off=%d\n",
4707 if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
4708 if (!btf_is_kernel(reg->btf)) {
4709 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
4712 ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4714 /* Writes are permitted with default btf_struct_access for
4715 * program allocated objects (which always have ref_obj_id > 0),
4716 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
4718 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
4719 verbose(env, "only read is supported\n");
4723 if (type_is_alloc(reg->type) && !reg->ref_obj_id) {
4724 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
4728 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4734 /* If this is an untrusted pointer, all pointers formed by walking it
4735 * also inherit the untrusted flag.
4737 if (type_flag(reg->type) & PTR_UNTRUSTED)
4738 flag |= PTR_UNTRUSTED;
4740 /* Any pointer obtained from walking a trusted pointer is no longer trusted. */
4741 flag &= ~PTR_TRUSTED;
4743 if (atype == BPF_READ && value_regno >= 0)
4744 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4749 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4750 struct bpf_reg_state *regs,
4751 int regno, int off, int size,
4752 enum bpf_access_type atype,
4755 struct bpf_reg_state *reg = regs + regno;
4756 struct bpf_map *map = reg->map_ptr;
4757 struct bpf_reg_state map_reg;
4758 enum bpf_type_flag flag = 0;
4759 const struct btf_type *t;
4765 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4769 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4770 verbose(env, "map_ptr access not supported for map type %d\n",
4775 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4776 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4778 if (!env->allow_ptr_to_map_access) {
4780 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4786 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4791 if (atype != BPF_READ) {
4792 verbose(env, "only read from %s is supported\n", tname);
4796 /* Simulate access to a PTR_TO_BTF_ID */
4797 memset(&map_reg, 0, sizeof(map_reg));
4798 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
4799 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
4803 if (value_regno >= 0)
4804 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4809 /* Check that the stack access at the given offset is within bounds. The
4810 * maximum valid offset is -1.
4812 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4813 * -state->allocated_stack for reads.
4815 static int check_stack_slot_within_bounds(int off,
4816 struct bpf_func_state *state,
4817 enum bpf_access_type t)
4822 min_valid_off = -MAX_BPF_STACK;
4824 min_valid_off = -state->allocated_stack;
4826 if (off < min_valid_off || off > -1)
4831 /* Check that the stack access at 'regno + off' falls within the maximum stack
4834 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4836 static int check_stack_access_within_bounds(
4837 struct bpf_verifier_env *env,
4838 int regno, int off, int access_size,
4839 enum bpf_access_src src, enum bpf_access_type type)
4841 struct bpf_reg_state *regs = cur_regs(env);
4842 struct bpf_reg_state *reg = regs + regno;
4843 struct bpf_func_state *state = func(env, reg);
4844 int min_off, max_off;
4848 if (src == ACCESS_HELPER)
4849 /* We don't know if helpers are reading or writing (or both). */
4850 err_extra = " indirect access to";
4851 else if (type == BPF_READ)
4852 err_extra = " read from";
4854 err_extra = " write to";
4856 if (tnum_is_const(reg->var_off)) {
4857 min_off = reg->var_off.value + off;
4858 if (access_size > 0)
4859 max_off = min_off + access_size - 1;
4863 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4864 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4865 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4869 min_off = reg->smin_value + off;
4870 if (access_size > 0)
4871 max_off = reg->smax_value + off + access_size - 1;
4876 err = check_stack_slot_within_bounds(min_off, state, type);
4878 err = check_stack_slot_within_bounds(max_off, state, type);
4881 if (tnum_is_const(reg->var_off)) {
4882 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4883 err_extra, regno, off, access_size);
4887 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4888 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4889 err_extra, regno, tn_buf, access_size);
4895 /* check whether memory at (regno + off) is accessible for t = (read | write)
4896 * if t==write, value_regno is a register which value is stored into memory
4897 * if t==read, value_regno is a register which will receive the value from memory
4898 * if t==write && value_regno==-1, some unknown value is stored into memory
4899 * if t==read && value_regno==-1, don't care what we read from memory
4901 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4902 int off, int bpf_size, enum bpf_access_type t,
4903 int value_regno, bool strict_alignment_once)
4905 struct bpf_reg_state *regs = cur_regs(env);
4906 struct bpf_reg_state *reg = regs + regno;
4907 struct bpf_func_state *state;
4910 size = bpf_size_to_bytes(bpf_size);
4914 /* alignment checks will add in reg->off themselves */
4915 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4919 /* for access checks, reg->off is just part of off */
4922 if (reg->type == PTR_TO_MAP_KEY) {
4923 if (t == BPF_WRITE) {
4924 verbose(env, "write to change key R%d not allowed\n", regno);
4928 err = check_mem_region_access(env, regno, off, size,
4929 reg->map_ptr->key_size, false);
4932 if (value_regno >= 0)
4933 mark_reg_unknown(env, regs, value_regno);
4934 } else if (reg->type == PTR_TO_MAP_VALUE) {
4935 struct btf_field *kptr_field = NULL;
4937 if (t == BPF_WRITE && value_regno >= 0 &&
4938 is_pointer_value(env, value_regno)) {
4939 verbose(env, "R%d leaks addr into map\n", value_regno);
4942 err = check_map_access_type(env, regno, off, size, t);
4945 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4948 if (tnum_is_const(reg->var_off))
4949 kptr_field = btf_record_find(reg->map_ptr->record,
4950 off + reg->var_off.value, BPF_KPTR);
4952 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
4953 } else if (t == BPF_READ && value_regno >= 0) {
4954 struct bpf_map *map = reg->map_ptr;
4956 /* if map is read-only, track its contents as scalars */
4957 if (tnum_is_const(reg->var_off) &&
4958 bpf_map_is_rdonly(map) &&
4959 map->ops->map_direct_value_addr) {
4960 int map_off = off + reg->var_off.value;
4963 err = bpf_map_direct_read(map, map_off, size,
4968 regs[value_regno].type = SCALAR_VALUE;
4969 __mark_reg_known(®s[value_regno], val);
4971 mark_reg_unknown(env, regs, value_regno);
4974 } else if (base_type(reg->type) == PTR_TO_MEM) {
4975 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4977 if (type_may_be_null(reg->type)) {
4978 verbose(env, "R%d invalid mem access '%s'\n", regno,
4979 reg_type_str(env, reg->type));
4983 if (t == BPF_WRITE && rdonly_mem) {
4984 verbose(env, "R%d cannot write into %s\n",
4985 regno, reg_type_str(env, reg->type));
4989 if (t == BPF_WRITE && value_regno >= 0 &&
4990 is_pointer_value(env, value_regno)) {
4991 verbose(env, "R%d leaks addr into mem\n", value_regno);
4995 err = check_mem_region_access(env, regno, off, size,
4996 reg->mem_size, false);
4997 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4998 mark_reg_unknown(env, regs, value_regno);
4999 } else if (reg->type == PTR_TO_CTX) {
5000 enum bpf_reg_type reg_type = SCALAR_VALUE;
5001 struct btf *btf = NULL;
5004 if (t == BPF_WRITE && value_regno >= 0 &&
5005 is_pointer_value(env, value_regno)) {
5006 verbose(env, "R%d leaks addr into ctx\n", value_regno);
5010 err = check_ptr_off_reg(env, reg, regno);
5014 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
5017 verbose_linfo(env, insn_idx, "; ");
5018 if (!err && t == BPF_READ && value_regno >= 0) {
5019 /* ctx access returns either a scalar, or a
5020 * PTR_TO_PACKET[_META,_END]. In the latter
5021 * case, we know the offset is zero.
5023 if (reg_type == SCALAR_VALUE) {
5024 mark_reg_unknown(env, regs, value_regno);
5026 mark_reg_known_zero(env, regs,
5028 if (type_may_be_null(reg_type))
5029 regs[value_regno].id = ++env->id_gen;
5030 /* A load of ctx field could have different
5031 * actual load size with the one encoded in the
5032 * insn. When the dst is PTR, it is for sure not
5035 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5036 if (base_type(reg_type) == PTR_TO_BTF_ID) {
5037 regs[value_regno].btf = btf;
5038 regs[value_regno].btf_id = btf_id;
5041 regs[value_regno].type = reg_type;
5044 } else if (reg->type == PTR_TO_STACK) {
5045 /* Basic bounds checks. */
5046 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5050 state = func(env, reg);
5051 err = update_stack_depth(env, state, off);
5056 err = check_stack_read(env, regno, off, size,
5059 err = check_stack_write(env, regno, off, size,
5060 value_regno, insn_idx);
5061 } else if (reg_is_pkt_pointer(reg)) {
5062 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5063 verbose(env, "cannot write into packet\n");
5066 if (t == BPF_WRITE && value_regno >= 0 &&
5067 is_pointer_value(env, value_regno)) {
5068 verbose(env, "R%d leaks addr into packet\n",
5072 err = check_packet_access(env, regno, off, size, false);
5073 if (!err && t == BPF_READ && value_regno >= 0)
5074 mark_reg_unknown(env, regs, value_regno);
5075 } else if (reg->type == PTR_TO_FLOW_KEYS) {
5076 if (t == BPF_WRITE && value_regno >= 0 &&
5077 is_pointer_value(env, value_regno)) {
5078 verbose(env, "R%d leaks addr into flow keys\n",
5083 err = check_flow_keys_access(env, off, size);
5084 if (!err && t == BPF_READ && value_regno >= 0)
5085 mark_reg_unknown(env, regs, value_regno);
5086 } else if (type_is_sk_pointer(reg->type)) {
5087 if (t == BPF_WRITE) {
5088 verbose(env, "R%d cannot write into %s\n",
5089 regno, reg_type_str(env, reg->type));
5092 err = check_sock_access(env, insn_idx, regno, off, size, t);
5093 if (!err && value_regno >= 0)
5094 mark_reg_unknown(env, regs, value_regno);
5095 } else if (reg->type == PTR_TO_TP_BUFFER) {
5096 err = check_tp_buffer_access(env, reg, regno, off, size);
5097 if (!err && t == BPF_READ && value_regno >= 0)
5098 mark_reg_unknown(env, regs, value_regno);
5099 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5100 !type_may_be_null(reg->type)) {
5101 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5103 } else if (reg->type == CONST_PTR_TO_MAP) {
5104 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5106 } else if (base_type(reg->type) == PTR_TO_BUF) {
5107 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5111 if (t == BPF_WRITE) {
5112 verbose(env, "R%d cannot write into %s\n",
5113 regno, reg_type_str(env, reg->type));
5116 max_access = &env->prog->aux->max_rdonly_access;
5118 max_access = &env->prog->aux->max_rdwr_access;
5121 err = check_buffer_access(env, reg, regno, off, size, false,
5124 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5125 mark_reg_unknown(env, regs, value_regno);
5127 verbose(env, "R%d invalid mem access '%s'\n", regno,
5128 reg_type_str(env, reg->type));
5132 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5133 regs[value_regno].type == SCALAR_VALUE) {
5134 /* b/h/w load zero-extends, mark upper bits as known 0 */
5135 coerce_reg_to_size(®s[value_regno], size);
5140 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5145 switch (insn->imm) {
5147 case BPF_ADD | BPF_FETCH:
5149 case BPF_AND | BPF_FETCH:
5151 case BPF_OR | BPF_FETCH:
5153 case BPF_XOR | BPF_FETCH:
5158 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5162 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5163 verbose(env, "invalid atomic operand size\n");
5167 /* check src1 operand */
5168 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5172 /* check src2 operand */
5173 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5177 if (insn->imm == BPF_CMPXCHG) {
5178 /* Check comparison of R0 with memory location */
5179 const u32 aux_reg = BPF_REG_0;
5181 err = check_reg_arg(env, aux_reg, SRC_OP);
5185 if (is_pointer_value(env, aux_reg)) {
5186 verbose(env, "R%d leaks addr into mem\n", aux_reg);
5191 if (is_pointer_value(env, insn->src_reg)) {
5192 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5196 if (is_ctx_reg(env, insn->dst_reg) ||
5197 is_pkt_reg(env, insn->dst_reg) ||
5198 is_flow_key_reg(env, insn->dst_reg) ||
5199 is_sk_reg(env, insn->dst_reg)) {
5200 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5202 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5206 if (insn->imm & BPF_FETCH) {
5207 if (insn->imm == BPF_CMPXCHG)
5208 load_reg = BPF_REG_0;
5210 load_reg = insn->src_reg;
5212 /* check and record load of old value */
5213 err = check_reg_arg(env, load_reg, DST_OP);
5217 /* This instruction accesses a memory location but doesn't
5218 * actually load it into a register.
5223 /* Check whether we can read the memory, with second call for fetch
5224 * case to simulate the register fill.
5226 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5227 BPF_SIZE(insn->code), BPF_READ, -1, true);
5228 if (!err && load_reg >= 0)
5229 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5230 BPF_SIZE(insn->code), BPF_READ, load_reg,
5235 /* Check whether we can write into the same memory. */
5236 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5237 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5244 /* When register 'regno' is used to read the stack (either directly or through
5245 * a helper function) make sure that it's within stack boundary and, depending
5246 * on the access type, that all elements of the stack are initialized.
5248 * 'off' includes 'regno->off', but not its dynamic part (if any).
5250 * All registers that have been spilled on the stack in the slots within the
5251 * read offsets are marked as read.
5253 static int check_stack_range_initialized(
5254 struct bpf_verifier_env *env, int regno, int off,
5255 int access_size, bool zero_size_allowed,
5256 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5258 struct bpf_reg_state *reg = reg_state(env, regno);
5259 struct bpf_func_state *state = func(env, reg);
5260 int err, min_off, max_off, i, j, slot, spi;
5261 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5262 enum bpf_access_type bounds_check_type;
5263 /* Some accesses can write anything into the stack, others are
5266 bool clobber = false;
5268 if (access_size == 0 && !zero_size_allowed) {
5269 verbose(env, "invalid zero-sized read\n");
5273 if (type == ACCESS_HELPER) {
5274 /* The bounds checks for writes are more permissive than for
5275 * reads. However, if raw_mode is not set, we'll do extra
5278 bounds_check_type = BPF_WRITE;
5281 bounds_check_type = BPF_READ;
5283 err = check_stack_access_within_bounds(env, regno, off, access_size,
5284 type, bounds_check_type);
5289 if (tnum_is_const(reg->var_off)) {
5290 min_off = max_off = reg->var_off.value + off;
5292 /* Variable offset is prohibited for unprivileged mode for
5293 * simplicity since it requires corresponding support in
5294 * Spectre masking for stack ALU.
5295 * See also retrieve_ptr_limit().
5297 if (!env->bypass_spec_v1) {
5300 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5301 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5302 regno, err_extra, tn_buf);
5305 /* Only initialized buffer on stack is allowed to be accessed
5306 * with variable offset. With uninitialized buffer it's hard to
5307 * guarantee that whole memory is marked as initialized on
5308 * helper return since specific bounds are unknown what may
5309 * cause uninitialized stack leaking.
5311 if (meta && meta->raw_mode)
5314 min_off = reg->smin_value + off;
5315 max_off = reg->smax_value + off;
5318 if (meta && meta->raw_mode) {
5319 meta->access_size = access_size;
5320 meta->regno = regno;
5324 for (i = min_off; i < max_off + access_size; i++) {
5328 spi = slot / BPF_REG_SIZE;
5329 if (state->allocated_stack <= slot)
5331 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5332 if (*stype == STACK_MISC)
5334 if (*stype == STACK_ZERO) {
5336 /* helper can write anything into the stack */
5337 *stype = STACK_MISC;
5342 if (is_spilled_reg(&state->stack[spi]) &&
5343 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5344 env->allow_ptr_leaks)) {
5346 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5347 for (j = 0; j < BPF_REG_SIZE; j++)
5348 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5354 if (tnum_is_const(reg->var_off)) {
5355 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5356 err_extra, regno, min_off, i - min_off, access_size);
5360 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5361 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5362 err_extra, regno, tn_buf, i - min_off, access_size);
5366 /* reading any byte out of 8-byte 'spill_slot' will cause
5367 * the whole slot to be marked as 'read'
5369 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5370 state->stack[spi].spilled_ptr.parent,
5372 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5373 * be sure that whether stack slot is written to or not. Hence,
5374 * we must still conservatively propagate reads upwards even if
5375 * helper may write to the entire memory range.
5378 return update_stack_depth(env, state, min_off);
5381 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5382 int access_size, bool zero_size_allowed,
5383 struct bpf_call_arg_meta *meta)
5385 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5388 switch (base_type(reg->type)) {
5390 case PTR_TO_PACKET_META:
5391 return check_packet_access(env, regno, reg->off, access_size,
5393 case PTR_TO_MAP_KEY:
5394 if (meta && meta->raw_mode) {
5395 verbose(env, "R%d cannot write into %s\n", regno,
5396 reg_type_str(env, reg->type));
5399 return check_mem_region_access(env, regno, reg->off, access_size,
5400 reg->map_ptr->key_size, false);
5401 case PTR_TO_MAP_VALUE:
5402 if (check_map_access_type(env, regno, reg->off, access_size,
5403 meta && meta->raw_mode ? BPF_WRITE :
5406 return check_map_access(env, regno, reg->off, access_size,
5407 zero_size_allowed, ACCESS_HELPER);
5409 if (type_is_rdonly_mem(reg->type)) {
5410 if (meta && meta->raw_mode) {
5411 verbose(env, "R%d cannot write into %s\n", regno,
5412 reg_type_str(env, reg->type));
5416 return check_mem_region_access(env, regno, reg->off,
5417 access_size, reg->mem_size,
5420 if (type_is_rdonly_mem(reg->type)) {
5421 if (meta && meta->raw_mode) {
5422 verbose(env, "R%d cannot write into %s\n", regno,
5423 reg_type_str(env, reg->type));
5427 max_access = &env->prog->aux->max_rdonly_access;
5429 max_access = &env->prog->aux->max_rdwr_access;
5431 return check_buffer_access(env, reg, regno, reg->off,
5432 access_size, zero_size_allowed,
5435 return check_stack_range_initialized(
5437 regno, reg->off, access_size,
5438 zero_size_allowed, ACCESS_HELPER, meta);
5440 /* in case the function doesn't know how to access the context,
5441 * (because we are in a program of type SYSCALL for example), we
5442 * can not statically check its size.
5443 * Dynamically check it now.
5445 if (!env->ops->convert_ctx_access) {
5446 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5447 int offset = access_size - 1;
5449 /* Allow zero-byte read from PTR_TO_CTX */
5450 if (access_size == 0)
5451 return zero_size_allowed ? 0 : -EACCES;
5453 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5458 default: /* scalar_value or invalid ptr */
5459 /* Allow zero-byte read from NULL, regardless of pointer type */
5460 if (zero_size_allowed && access_size == 0 &&
5461 register_is_null(reg))
5464 verbose(env, "R%d type=%s ", regno,
5465 reg_type_str(env, reg->type));
5466 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5471 static int check_mem_size_reg(struct bpf_verifier_env *env,
5472 struct bpf_reg_state *reg, u32 regno,
5473 bool zero_size_allowed,
5474 struct bpf_call_arg_meta *meta)
5478 /* This is used to refine r0 return value bounds for helpers
5479 * that enforce this value as an upper bound on return values.
5480 * See do_refine_retval_range() for helpers that can refine
5481 * the return value. C type of helper is u32 so we pull register
5482 * bound from umax_value however, if negative verifier errors
5483 * out. Only upper bounds can be learned because retval is an
5484 * int type and negative retvals are allowed.
5486 meta->msize_max_value = reg->umax_value;
5488 /* The register is SCALAR_VALUE; the access check
5489 * happens using its boundaries.
5491 if (!tnum_is_const(reg->var_off))
5492 /* For unprivileged variable accesses, disable raw
5493 * mode so that the program is required to
5494 * initialize all the memory that the helper could
5495 * just partially fill up.
5499 if (reg->smin_value < 0) {
5500 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5505 if (reg->umin_value == 0) {
5506 err = check_helper_mem_access(env, regno - 1, 0,
5513 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5514 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5518 err = check_helper_mem_access(env, regno - 1,
5520 zero_size_allowed, meta);
5522 err = mark_chain_precision(env, regno);
5526 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5527 u32 regno, u32 mem_size)
5529 bool may_be_null = type_may_be_null(reg->type);
5530 struct bpf_reg_state saved_reg;
5531 struct bpf_call_arg_meta meta;
5534 if (register_is_null(reg))
5537 memset(&meta, 0, sizeof(meta));
5538 /* Assuming that the register contains a value check if the memory
5539 * access is safe. Temporarily save and restore the register's state as
5540 * the conversion shouldn't be visible to a caller.
5544 mark_ptr_not_null_reg(reg);
5547 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5548 /* Check access for BPF_WRITE */
5549 meta.raw_mode = true;
5550 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5558 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5561 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5562 bool may_be_null = type_may_be_null(mem_reg->type);
5563 struct bpf_reg_state saved_reg;
5564 struct bpf_call_arg_meta meta;
5567 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5569 memset(&meta, 0, sizeof(meta));
5572 saved_reg = *mem_reg;
5573 mark_ptr_not_null_reg(mem_reg);
5576 err = check_mem_size_reg(env, reg, regno, true, &meta);
5577 /* Check access for BPF_WRITE */
5578 meta.raw_mode = true;
5579 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5582 *mem_reg = saved_reg;
5586 /* Implementation details:
5587 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
5588 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
5589 * Two bpf_map_lookups (even with the same key) will have different reg->id.
5590 * Two separate bpf_obj_new will also have different reg->id.
5591 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
5592 * clears reg->id after value_or_null->value transition, since the verifier only
5593 * cares about the range of access to valid map value pointer and doesn't care
5594 * about actual address of the map element.
5595 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5596 * reg->id > 0 after value_or_null->value transition. By doing so
5597 * two bpf_map_lookups will be considered two different pointers that
5598 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
5599 * returned from bpf_obj_new.
5600 * The verifier allows taking only one bpf_spin_lock at a time to avoid
5602 * Since only one bpf_spin_lock is allowed the checks are simpler than
5603 * reg_is_refcounted() logic. The verifier needs to remember only
5604 * one spin_lock instead of array of acquired_refs.
5605 * cur_state->active_lock remembers which map value element or allocated
5606 * object got locked and clears it after bpf_spin_unlock.
5608 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5611 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5612 struct bpf_verifier_state *cur = env->cur_state;
5613 bool is_const = tnum_is_const(reg->var_off);
5614 u64 val = reg->var_off.value;
5615 struct bpf_map *map = NULL;
5616 struct btf *btf = NULL;
5617 struct btf_record *rec;
5621 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5625 if (reg->type == PTR_TO_MAP_VALUE) {
5629 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5637 rec = reg_btf_record(reg);
5638 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
5639 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
5640 map ? map->name : "kptr");
5643 if (rec->spin_lock_off != val + reg->off) {
5644 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
5645 val + reg->off, rec->spin_lock_off);
5649 if (cur->active_lock.ptr) {
5651 "Locking two bpf_spin_locks are not allowed\n");
5655 cur->active_lock.ptr = map;
5657 cur->active_lock.ptr = btf;
5658 cur->active_lock.id = reg->id;
5660 struct bpf_func_state *fstate = cur_func(env);
5669 if (!cur->active_lock.ptr) {
5670 verbose(env, "bpf_spin_unlock without taking a lock\n");
5673 if (cur->active_lock.ptr != ptr ||
5674 cur->active_lock.id != reg->id) {
5675 verbose(env, "bpf_spin_unlock of different lock\n");
5678 cur->active_lock.ptr = NULL;
5679 cur->active_lock.id = 0;
5681 for (i = 0; i < fstate->acquired_refs; i++) {
5684 /* Complain on error because this reference state cannot
5685 * be freed before this point, as bpf_spin_lock critical
5686 * section does not allow functions that release the
5687 * allocated object immediately.
5689 if (!fstate->refs[i].release_on_unlock)
5691 err = release_reference(env, fstate->refs[i].id);
5693 verbose(env, "failed to release release_on_unlock reference");
5701 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5702 struct bpf_call_arg_meta *meta)
5704 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5705 bool is_const = tnum_is_const(reg->var_off);
5706 struct bpf_map *map = reg->map_ptr;
5707 u64 val = reg->var_off.value;
5711 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5716 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5720 if (!btf_record_has_field(map->record, BPF_TIMER)) {
5721 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
5724 if (map->record->timer_off != val + reg->off) {
5725 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5726 val + reg->off, map->record->timer_off);
5729 if (meta->map_ptr) {
5730 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5733 meta->map_uid = reg->map_uid;
5734 meta->map_ptr = map;
5738 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5739 struct bpf_call_arg_meta *meta)
5741 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5742 struct bpf_map *map_ptr = reg->map_ptr;
5743 struct btf_field *kptr_field;
5746 if (!tnum_is_const(reg->var_off)) {
5748 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5752 if (!map_ptr->btf) {
5753 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5757 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
5758 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5762 meta->map_ptr = map_ptr;
5763 kptr_off = reg->off + reg->var_off.value;
5764 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
5766 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5769 if (kptr_field->type != BPF_KPTR_REF) {
5770 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5773 meta->kptr_field = kptr_field;
5777 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5779 return type == ARG_CONST_SIZE ||
5780 type == ARG_CONST_SIZE_OR_ZERO;
5783 static bool arg_type_is_release(enum bpf_arg_type type)
5785 return type & OBJ_RELEASE;
5788 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5790 return base_type(type) == ARG_PTR_TO_DYNPTR;
5793 static int int_ptr_type_to_size(enum bpf_arg_type type)
5795 if (type == ARG_PTR_TO_INT)
5797 else if (type == ARG_PTR_TO_LONG)
5803 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5804 const struct bpf_call_arg_meta *meta,
5805 enum bpf_arg_type *arg_type)
5807 if (!meta->map_ptr) {
5808 /* kernel subsystem misconfigured verifier */
5809 verbose(env, "invalid map_ptr to access map->type\n");
5813 switch (meta->map_ptr->map_type) {
5814 case BPF_MAP_TYPE_SOCKMAP:
5815 case BPF_MAP_TYPE_SOCKHASH:
5816 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5817 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5819 verbose(env, "invalid arg_type for sockmap/sockhash\n");
5823 case BPF_MAP_TYPE_BLOOM_FILTER:
5824 if (meta->func_id == BPF_FUNC_map_peek_elem)
5825 *arg_type = ARG_PTR_TO_MAP_VALUE;
5833 struct bpf_reg_types {
5834 const enum bpf_reg_type types[10];
5838 static const struct bpf_reg_types sock_types = {
5848 static const struct bpf_reg_types btf_id_sock_common_types = {
5855 PTR_TO_BTF_ID | PTR_TRUSTED,
5857 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5861 static const struct bpf_reg_types mem_types = {
5869 PTR_TO_MEM | MEM_RINGBUF,
5874 static const struct bpf_reg_types int_ptr_types = {
5884 static const struct bpf_reg_types spin_lock_types = {
5887 PTR_TO_BTF_ID | MEM_ALLOC,
5891 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5892 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5893 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5894 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
5895 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5896 static const struct bpf_reg_types btf_ptr_types = {
5899 PTR_TO_BTF_ID | PTR_TRUSTED,
5902 static const struct bpf_reg_types percpu_btf_ptr_types = {
5904 PTR_TO_BTF_ID | MEM_PERCPU,
5905 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
5908 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5909 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5910 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5911 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5912 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5913 static const struct bpf_reg_types dynptr_types = {
5916 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5920 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5921 [ARG_PTR_TO_MAP_KEY] = &mem_types,
5922 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
5923 [ARG_CONST_SIZE] = &scalar_types,
5924 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
5925 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
5926 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
5927 [ARG_PTR_TO_CTX] = &context_types,
5928 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
5930 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5932 [ARG_PTR_TO_SOCKET] = &fullsock_types,
5933 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
5934 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
5935 [ARG_PTR_TO_MEM] = &mem_types,
5936 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
5937 [ARG_PTR_TO_INT] = &int_ptr_types,
5938 [ARG_PTR_TO_LONG] = &int_ptr_types,
5939 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
5940 [ARG_PTR_TO_FUNC] = &func_ptr_types,
5941 [ARG_PTR_TO_STACK] = &stack_ptr_types,
5942 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
5943 [ARG_PTR_TO_TIMER] = &timer_types,
5944 [ARG_PTR_TO_KPTR] = &kptr_types,
5945 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
5948 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5949 enum bpf_arg_type arg_type,
5950 const u32 *arg_btf_id,
5951 struct bpf_call_arg_meta *meta)
5953 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5954 enum bpf_reg_type expected, type = reg->type;
5955 const struct bpf_reg_types *compatible;
5958 compatible = compatible_reg_types[base_type(arg_type)];
5960 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5964 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5965 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5967 * Same for MAYBE_NULL:
5969 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5970 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5972 * Therefore we fold these flags depending on the arg_type before comparison.
5974 if (arg_type & MEM_RDONLY)
5975 type &= ~MEM_RDONLY;
5976 if (arg_type & PTR_MAYBE_NULL)
5977 type &= ~PTR_MAYBE_NULL;
5979 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5980 expected = compatible->types[i];
5981 if (expected == NOT_INIT)
5984 if (type == expected)
5988 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5989 for (j = 0; j + 1 < i; j++)
5990 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5991 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5995 if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) {
5996 /* For bpf_sk_release, it needs to match against first member
5997 * 'struct sock_common', hence make an exception for it. This
5998 * allows bpf_sk_release to work for multiple socket types.
6000 bool strict_type_match = arg_type_is_release(arg_type) &&
6001 meta->func_id != BPF_FUNC_sk_release;
6004 if (!compatible->btf_id) {
6005 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6008 arg_btf_id = compatible->btf_id;
6011 if (meta->func_id == BPF_FUNC_kptr_xchg) {
6012 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6015 if (arg_btf_id == BPF_PTR_POISON) {
6016 verbose(env, "verifier internal error:");
6017 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6022 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6023 btf_vmlinux, *arg_btf_id,
6024 strict_type_match)) {
6025 verbose(env, "R%d is of type %s but %s is expected\n",
6026 regno, kernel_type_name(reg->btf, reg->btf_id),
6027 kernel_type_name(btf_vmlinux, *arg_btf_id));
6031 } else if (type_is_alloc(reg->type)) {
6032 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6033 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6041 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6042 const struct bpf_reg_state *reg, int regno,
6043 enum bpf_arg_type arg_type)
6045 enum bpf_reg_type type = reg->type;
6046 bool fixed_off_ok = false;
6048 switch ((u32)type) {
6049 /* Pointer types where reg offset is explicitly allowed: */
6051 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
6052 verbose(env, "cannot pass in dynptr at an offset\n");
6057 case PTR_TO_PACKET_META:
6058 case PTR_TO_MAP_KEY:
6059 case PTR_TO_MAP_VALUE:
6061 case PTR_TO_MEM | MEM_RDONLY:
6062 case PTR_TO_MEM | MEM_RINGBUF:
6064 case PTR_TO_BUF | MEM_RDONLY:
6066 /* Some of the argument types nevertheless require a
6067 * zero register offset.
6069 if (base_type(arg_type) != ARG_PTR_TO_RINGBUF_MEM)
6072 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6076 case PTR_TO_BTF_ID | MEM_ALLOC:
6077 case PTR_TO_BTF_ID | PTR_TRUSTED:
6078 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
6079 /* When referenced PTR_TO_BTF_ID is passed to release function,
6080 * it's fixed offset must be 0. In the other cases, fixed offset
6083 if (arg_type_is_release(arg_type) && reg->off) {
6084 verbose(env, "R%d must have zero offset when passed to release func\n",
6088 /* For arg is release pointer, fixed_off_ok must be false, but
6089 * we already checked and rejected reg->off != 0 above, so set
6090 * to true to allow fixed offset for all other cases.
6092 fixed_off_ok = true;
6097 return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
6100 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6102 struct bpf_func_state *state = func(env, reg);
6103 int spi = get_spi(reg->off);
6105 return state->stack[spi].spilled_ptr.id;
6108 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6109 struct bpf_call_arg_meta *meta,
6110 const struct bpf_func_proto *fn)
6112 u32 regno = BPF_REG_1 + arg;
6113 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6114 enum bpf_arg_type arg_type = fn->arg_type[arg];
6115 enum bpf_reg_type type = reg->type;
6116 u32 *arg_btf_id = NULL;
6119 if (arg_type == ARG_DONTCARE)
6122 err = check_reg_arg(env, regno, SRC_OP);
6126 if (arg_type == ARG_ANYTHING) {
6127 if (is_pointer_value(env, regno)) {
6128 verbose(env, "R%d leaks addr into helper function\n",
6135 if (type_is_pkt_pointer(type) &&
6136 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6137 verbose(env, "helper access to the packet is not allowed\n");
6141 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6142 err = resolve_map_arg_type(env, meta, &arg_type);
6147 if (register_is_null(reg) && type_may_be_null(arg_type))
6148 /* A NULL register has a SCALAR_VALUE type, so skip
6151 goto skip_type_check;
6153 /* arg_btf_id and arg_size are in a union. */
6154 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6155 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6156 arg_btf_id = fn->arg_btf_id[arg];
6158 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6162 err = check_func_arg_reg_off(env, reg, regno, arg_type);
6167 if (arg_type_is_release(arg_type)) {
6168 if (arg_type_is_dynptr(arg_type)) {
6169 struct bpf_func_state *state = func(env, reg);
6170 int spi = get_spi(reg->off);
6172 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6173 !state->stack[spi].spilled_ptr.id) {
6174 verbose(env, "arg %d is an unacquired reference\n", regno);
6177 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
6178 verbose(env, "R%d must be referenced when passed to release function\n",
6182 if (meta->release_regno) {
6183 verbose(env, "verifier internal error: more than one release argument\n");
6186 meta->release_regno = regno;
6189 if (reg->ref_obj_id) {
6190 if (meta->ref_obj_id) {
6191 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6192 regno, reg->ref_obj_id,
6196 meta->ref_obj_id = reg->ref_obj_id;
6199 switch (base_type(arg_type)) {
6200 case ARG_CONST_MAP_PTR:
6201 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6202 if (meta->map_ptr) {
6203 /* Use map_uid (which is unique id of inner map) to reject:
6204 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6205 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6206 * if (inner_map1 && inner_map2) {
6207 * timer = bpf_map_lookup_elem(inner_map1);
6209 * // mismatch would have been allowed
6210 * bpf_timer_init(timer, inner_map2);
6213 * Comparing map_ptr is enough to distinguish normal and outer maps.
6215 if (meta->map_ptr != reg->map_ptr ||
6216 meta->map_uid != reg->map_uid) {
6218 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6219 meta->map_uid, reg->map_uid);
6223 meta->map_ptr = reg->map_ptr;
6224 meta->map_uid = reg->map_uid;
6226 case ARG_PTR_TO_MAP_KEY:
6227 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6228 * check that [key, key + map->key_size) are within
6229 * stack limits and initialized
6231 if (!meta->map_ptr) {
6232 /* in function declaration map_ptr must come before
6233 * map_key, so that it's verified and known before
6234 * we have to check map_key here. Otherwise it means
6235 * that kernel subsystem misconfigured verifier
6237 verbose(env, "invalid map_ptr to access map->key\n");
6240 err = check_helper_mem_access(env, regno,
6241 meta->map_ptr->key_size, false,
6244 case ARG_PTR_TO_MAP_VALUE:
6245 if (type_may_be_null(arg_type) && register_is_null(reg))
6248 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6249 * check [value, value + map->value_size) validity
6251 if (!meta->map_ptr) {
6252 /* kernel subsystem misconfigured verifier */
6253 verbose(env, "invalid map_ptr to access map->value\n");
6256 meta->raw_mode = arg_type & MEM_UNINIT;
6257 err = check_helper_mem_access(env, regno,
6258 meta->map_ptr->value_size, false,
6261 case ARG_PTR_TO_PERCPU_BTF_ID:
6263 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6266 meta->ret_btf = reg->btf;
6267 meta->ret_btf_id = reg->btf_id;
6269 case ARG_PTR_TO_SPIN_LOCK:
6270 if (meta->func_id == BPF_FUNC_spin_lock) {
6271 if (process_spin_lock(env, regno, true))
6273 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6274 if (process_spin_lock(env, regno, false))
6277 verbose(env, "verifier internal error\n");
6281 case ARG_PTR_TO_TIMER:
6282 if (process_timer_func(env, regno, meta))
6285 case ARG_PTR_TO_FUNC:
6286 meta->subprogno = reg->subprogno;
6288 case ARG_PTR_TO_MEM:
6289 /* The access to this pointer is only checked when we hit the
6290 * next is_mem_size argument below.
6292 meta->raw_mode = arg_type & MEM_UNINIT;
6293 if (arg_type & MEM_FIXED_SIZE) {
6294 err = check_helper_mem_access(env, regno,
6295 fn->arg_size[arg], false,
6299 case ARG_CONST_SIZE:
6300 err = check_mem_size_reg(env, reg, regno, false, meta);
6302 case ARG_CONST_SIZE_OR_ZERO:
6303 err = check_mem_size_reg(env, reg, regno, true, meta);
6305 case ARG_PTR_TO_DYNPTR:
6306 /* We only need to check for initialized / uninitialized helper
6307 * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6308 * assumption is that if it is, that a helper function
6309 * initialized the dynptr on behalf of the BPF program.
6311 if (base_type(reg->type) == PTR_TO_DYNPTR)
6313 if (arg_type & MEM_UNINIT) {
6314 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6315 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6319 /* We only support one dynptr being uninitialized at the moment,
6320 * which is sufficient for the helper functions we have right now.
6322 if (meta->uninit_dynptr_regno) {
6323 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6327 meta->uninit_dynptr_regno = regno;
6328 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6330 "Expected an initialized dynptr as arg #%d\n",
6333 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6334 const char *err_extra = "";
6336 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6337 case DYNPTR_TYPE_LOCAL:
6338 err_extra = "local";
6340 case DYNPTR_TYPE_RINGBUF:
6341 err_extra = "ringbuf";
6344 err_extra = "<unknown>";
6348 "Expected a dynptr of type %s as arg #%d\n",
6349 err_extra, arg + 1);
6353 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6354 if (!tnum_is_const(reg->var_off)) {
6355 verbose(env, "R%d is not a known constant'\n",
6359 meta->mem_size = reg->var_off.value;
6360 err = mark_chain_precision(env, regno);
6364 case ARG_PTR_TO_INT:
6365 case ARG_PTR_TO_LONG:
6367 int size = int_ptr_type_to_size(arg_type);
6369 err = check_helper_mem_access(env, regno, size, false, meta);
6372 err = check_ptr_alignment(env, reg, 0, size, true);
6375 case ARG_PTR_TO_CONST_STR:
6377 struct bpf_map *map = reg->map_ptr;
6382 if (!bpf_map_is_rdonly(map)) {
6383 verbose(env, "R%d does not point to a readonly map'\n", regno);
6387 if (!tnum_is_const(reg->var_off)) {
6388 verbose(env, "R%d is not a constant address'\n", regno);
6392 if (!map->ops->map_direct_value_addr) {
6393 verbose(env, "no direct value access support for this map type\n");
6397 err = check_map_access(env, regno, reg->off,
6398 map->value_size - reg->off, false,
6403 map_off = reg->off + reg->var_off.value;
6404 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6406 verbose(env, "direct value access on string failed\n");
6410 str_ptr = (char *)(long)(map_addr);
6411 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6412 verbose(env, "string is not zero-terminated\n");
6417 case ARG_PTR_TO_KPTR:
6418 if (process_kptr_func(env, regno, meta))
6426 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6428 enum bpf_attach_type eatype = env->prog->expected_attach_type;
6429 enum bpf_prog_type type = resolve_prog_type(env->prog);
6431 if (func_id != BPF_FUNC_map_update_elem)
6434 /* It's not possible to get access to a locked struct sock in these
6435 * contexts, so updating is safe.
6438 case BPF_PROG_TYPE_TRACING:
6439 if (eatype == BPF_TRACE_ITER)
6442 case BPF_PROG_TYPE_SOCKET_FILTER:
6443 case BPF_PROG_TYPE_SCHED_CLS:
6444 case BPF_PROG_TYPE_SCHED_ACT:
6445 case BPF_PROG_TYPE_XDP:
6446 case BPF_PROG_TYPE_SK_REUSEPORT:
6447 case BPF_PROG_TYPE_FLOW_DISSECTOR:
6448 case BPF_PROG_TYPE_SK_LOOKUP:
6454 verbose(env, "cannot update sockmap in this context\n");
6458 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6460 return env->prog->jit_requested &&
6461 bpf_jit_supports_subprog_tailcalls();
6464 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6465 struct bpf_map *map, int func_id)
6470 /* We need a two way check, first is from map perspective ... */
6471 switch (map->map_type) {
6472 case BPF_MAP_TYPE_PROG_ARRAY:
6473 if (func_id != BPF_FUNC_tail_call)
6476 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6477 if (func_id != BPF_FUNC_perf_event_read &&
6478 func_id != BPF_FUNC_perf_event_output &&
6479 func_id != BPF_FUNC_skb_output &&
6480 func_id != BPF_FUNC_perf_event_read_value &&
6481 func_id != BPF_FUNC_xdp_output)
6484 case BPF_MAP_TYPE_RINGBUF:
6485 if (func_id != BPF_FUNC_ringbuf_output &&
6486 func_id != BPF_FUNC_ringbuf_reserve &&
6487 func_id != BPF_FUNC_ringbuf_query &&
6488 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6489 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6490 func_id != BPF_FUNC_ringbuf_discard_dynptr)
6493 case BPF_MAP_TYPE_USER_RINGBUF:
6494 if (func_id != BPF_FUNC_user_ringbuf_drain)
6497 case BPF_MAP_TYPE_STACK_TRACE:
6498 if (func_id != BPF_FUNC_get_stackid)
6501 case BPF_MAP_TYPE_CGROUP_ARRAY:
6502 if (func_id != BPF_FUNC_skb_under_cgroup &&
6503 func_id != BPF_FUNC_current_task_under_cgroup)
6506 case BPF_MAP_TYPE_CGROUP_STORAGE:
6507 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6508 if (func_id != BPF_FUNC_get_local_storage)
6511 case BPF_MAP_TYPE_DEVMAP:
6512 case BPF_MAP_TYPE_DEVMAP_HASH:
6513 if (func_id != BPF_FUNC_redirect_map &&
6514 func_id != BPF_FUNC_map_lookup_elem)
6517 /* Restrict bpf side of cpumap and xskmap, open when use-cases
6520 case BPF_MAP_TYPE_CPUMAP:
6521 if (func_id != BPF_FUNC_redirect_map)
6524 case BPF_MAP_TYPE_XSKMAP:
6525 if (func_id != BPF_FUNC_redirect_map &&
6526 func_id != BPF_FUNC_map_lookup_elem)
6529 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6530 case BPF_MAP_TYPE_HASH_OF_MAPS:
6531 if (func_id != BPF_FUNC_map_lookup_elem)
6534 case BPF_MAP_TYPE_SOCKMAP:
6535 if (func_id != BPF_FUNC_sk_redirect_map &&
6536 func_id != BPF_FUNC_sock_map_update &&
6537 func_id != BPF_FUNC_map_delete_elem &&
6538 func_id != BPF_FUNC_msg_redirect_map &&
6539 func_id != BPF_FUNC_sk_select_reuseport &&
6540 func_id != BPF_FUNC_map_lookup_elem &&
6541 !may_update_sockmap(env, func_id))
6544 case BPF_MAP_TYPE_SOCKHASH:
6545 if (func_id != BPF_FUNC_sk_redirect_hash &&
6546 func_id != BPF_FUNC_sock_hash_update &&
6547 func_id != BPF_FUNC_map_delete_elem &&
6548 func_id != BPF_FUNC_msg_redirect_hash &&
6549 func_id != BPF_FUNC_sk_select_reuseport &&
6550 func_id != BPF_FUNC_map_lookup_elem &&
6551 !may_update_sockmap(env, func_id))
6554 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6555 if (func_id != BPF_FUNC_sk_select_reuseport)
6558 case BPF_MAP_TYPE_QUEUE:
6559 case BPF_MAP_TYPE_STACK:
6560 if (func_id != BPF_FUNC_map_peek_elem &&
6561 func_id != BPF_FUNC_map_pop_elem &&
6562 func_id != BPF_FUNC_map_push_elem)
6565 case BPF_MAP_TYPE_SK_STORAGE:
6566 if (func_id != BPF_FUNC_sk_storage_get &&
6567 func_id != BPF_FUNC_sk_storage_delete)
6570 case BPF_MAP_TYPE_INODE_STORAGE:
6571 if (func_id != BPF_FUNC_inode_storage_get &&
6572 func_id != BPF_FUNC_inode_storage_delete)
6575 case BPF_MAP_TYPE_TASK_STORAGE:
6576 if (func_id != BPF_FUNC_task_storage_get &&
6577 func_id != BPF_FUNC_task_storage_delete)
6580 case BPF_MAP_TYPE_CGRP_STORAGE:
6581 if (func_id != BPF_FUNC_cgrp_storage_get &&
6582 func_id != BPF_FUNC_cgrp_storage_delete)
6585 case BPF_MAP_TYPE_BLOOM_FILTER:
6586 if (func_id != BPF_FUNC_map_peek_elem &&
6587 func_id != BPF_FUNC_map_push_elem)
6594 /* ... and second from the function itself. */
6596 case BPF_FUNC_tail_call:
6597 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6599 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6600 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6604 case BPF_FUNC_perf_event_read:
6605 case BPF_FUNC_perf_event_output:
6606 case BPF_FUNC_perf_event_read_value:
6607 case BPF_FUNC_skb_output:
6608 case BPF_FUNC_xdp_output:
6609 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6612 case BPF_FUNC_ringbuf_output:
6613 case BPF_FUNC_ringbuf_reserve:
6614 case BPF_FUNC_ringbuf_query:
6615 case BPF_FUNC_ringbuf_reserve_dynptr:
6616 case BPF_FUNC_ringbuf_submit_dynptr:
6617 case BPF_FUNC_ringbuf_discard_dynptr:
6618 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6621 case BPF_FUNC_user_ringbuf_drain:
6622 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6625 case BPF_FUNC_get_stackid:
6626 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6629 case BPF_FUNC_current_task_under_cgroup:
6630 case BPF_FUNC_skb_under_cgroup:
6631 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6634 case BPF_FUNC_redirect_map:
6635 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6636 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6637 map->map_type != BPF_MAP_TYPE_CPUMAP &&
6638 map->map_type != BPF_MAP_TYPE_XSKMAP)
6641 case BPF_FUNC_sk_redirect_map:
6642 case BPF_FUNC_msg_redirect_map:
6643 case BPF_FUNC_sock_map_update:
6644 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6647 case BPF_FUNC_sk_redirect_hash:
6648 case BPF_FUNC_msg_redirect_hash:
6649 case BPF_FUNC_sock_hash_update:
6650 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6653 case BPF_FUNC_get_local_storage:
6654 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6655 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6658 case BPF_FUNC_sk_select_reuseport:
6659 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6660 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6661 map->map_type != BPF_MAP_TYPE_SOCKHASH)
6664 case BPF_FUNC_map_pop_elem:
6665 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6666 map->map_type != BPF_MAP_TYPE_STACK)
6669 case BPF_FUNC_map_peek_elem:
6670 case BPF_FUNC_map_push_elem:
6671 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6672 map->map_type != BPF_MAP_TYPE_STACK &&
6673 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6676 case BPF_FUNC_map_lookup_percpu_elem:
6677 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6678 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6679 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6682 case BPF_FUNC_sk_storage_get:
6683 case BPF_FUNC_sk_storage_delete:
6684 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6687 case BPF_FUNC_inode_storage_get:
6688 case BPF_FUNC_inode_storage_delete:
6689 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6692 case BPF_FUNC_task_storage_get:
6693 case BPF_FUNC_task_storage_delete:
6694 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6697 case BPF_FUNC_cgrp_storage_get:
6698 case BPF_FUNC_cgrp_storage_delete:
6699 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
6708 verbose(env, "cannot pass map_type %d into func %s#%d\n",
6709 map->map_type, func_id_name(func_id), func_id);
6713 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6717 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6719 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6721 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6723 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6725 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6728 /* We only support one arg being in raw mode at the moment,
6729 * which is sufficient for the helper functions we have
6735 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6737 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6738 bool has_size = fn->arg_size[arg] != 0;
6739 bool is_next_size = false;
6741 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6742 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6744 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6745 return is_next_size;
6747 return has_size == is_next_size || is_next_size == is_fixed;
6750 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6752 /* bpf_xxx(..., buf, len) call will access 'len'
6753 * bytes from memory 'buf'. Both arg types need
6754 * to be paired, so make sure there's no buggy
6755 * helper function specification.
6757 if (arg_type_is_mem_size(fn->arg1_type) ||
6758 check_args_pair_invalid(fn, 0) ||
6759 check_args_pair_invalid(fn, 1) ||
6760 check_args_pair_invalid(fn, 2) ||
6761 check_args_pair_invalid(fn, 3) ||
6762 check_args_pair_invalid(fn, 4))
6768 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6772 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6773 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
6774 return !!fn->arg_btf_id[i];
6775 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
6776 return fn->arg_btf_id[i] == BPF_PTR_POISON;
6777 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6778 /* arg_btf_id and arg_size are in a union. */
6779 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6780 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6787 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6789 return check_raw_mode_ok(fn) &&
6790 check_arg_pair_ok(fn) &&
6791 check_btf_id_ok(fn) ? 0 : -EINVAL;
6794 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6795 * are now invalid, so turn them into unknown SCALAR_VALUE.
6797 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6799 struct bpf_func_state *state;
6800 struct bpf_reg_state *reg;
6802 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6803 if (reg_is_pkt_pointer_any(reg))
6804 __mark_reg_unknown(env, reg);
6810 BEYOND_PKT_END = -2,
6813 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6815 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6816 struct bpf_reg_state *reg = &state->regs[regn];
6818 if (reg->type != PTR_TO_PACKET)
6819 /* PTR_TO_PACKET_META is not supported yet */
6822 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6823 * How far beyond pkt_end it goes is unknown.
6824 * if (!range_open) it's the case of pkt >= pkt_end
6825 * if (range_open) it's the case of pkt > pkt_end
6826 * hence this pointer is at least 1 byte bigger than pkt_end
6829 reg->range = BEYOND_PKT_END;
6831 reg->range = AT_PKT_END;
6834 /* The pointer with the specified id has released its reference to kernel
6835 * resources. Identify all copies of the same pointer and clear the reference.
6837 static int release_reference(struct bpf_verifier_env *env,
6840 struct bpf_func_state *state;
6841 struct bpf_reg_state *reg;
6844 err = release_reference_state(cur_func(env), ref_obj_id);
6848 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6849 if (reg->ref_obj_id == ref_obj_id) {
6850 if (!env->allow_ptr_leaks)
6851 __mark_reg_not_init(env, reg);
6853 __mark_reg_unknown(env, reg);
6860 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6861 struct bpf_reg_state *regs)
6865 /* after the call registers r0 - r5 were scratched */
6866 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6867 mark_reg_not_init(env, regs, caller_saved[i]);
6868 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6872 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6873 struct bpf_func_state *caller,
6874 struct bpf_func_state *callee,
6877 static int set_callee_state(struct bpf_verifier_env *env,
6878 struct bpf_func_state *caller,
6879 struct bpf_func_state *callee, int insn_idx);
6881 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6882 int *insn_idx, int subprog,
6883 set_callee_state_fn set_callee_state_cb)
6885 struct bpf_verifier_state *state = env->cur_state;
6886 struct bpf_func_info_aux *func_info_aux;
6887 struct bpf_func_state *caller, *callee;
6889 bool is_global = false;
6891 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6892 verbose(env, "the call stack of %d frames is too deep\n",
6893 state->curframe + 2);
6897 caller = state->frame[state->curframe];
6898 if (state->frame[state->curframe + 1]) {
6899 verbose(env, "verifier bug. Frame %d already allocated\n",
6900 state->curframe + 1);
6904 func_info_aux = env->prog->aux->func_info_aux;
6906 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6907 err = btf_check_subprog_call(env, subprog, caller->regs);
6912 verbose(env, "Caller passes invalid args into func#%d\n",
6916 if (env->log.level & BPF_LOG_LEVEL)
6918 "Func#%d is global and valid. Skipping.\n",
6920 clear_caller_saved_regs(env, caller->regs);
6922 /* All global functions return a 64-bit SCALAR_VALUE */
6923 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6924 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6926 /* continue with next insn after call */
6931 /* set_callee_state is used for direct subprog calls, but we are
6932 * interested in validating only BPF helpers that can call subprogs as
6935 if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
6936 verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
6937 func_id_name(insn->imm), insn->imm);
6941 if (insn->code == (BPF_JMP | BPF_CALL) &&
6942 insn->src_reg == 0 &&
6943 insn->imm == BPF_FUNC_timer_set_callback) {
6944 struct bpf_verifier_state *async_cb;
6946 /* there is no real recursion here. timer callbacks are async */
6947 env->subprog_info[subprog].is_async_cb = true;
6948 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6949 *insn_idx, subprog);
6952 callee = async_cb->frame[0];
6953 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6955 /* Convert bpf_timer_set_callback() args into timer callback args */
6956 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6960 clear_caller_saved_regs(env, caller->regs);
6961 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6962 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6963 /* continue with next insn after call */
6967 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6970 state->frame[state->curframe + 1] = callee;
6972 /* callee cannot access r0, r6 - r9 for reading and has to write
6973 * into its own stack before reading from it.
6974 * callee can read/write into caller's stack
6976 init_func_state(env, callee,
6977 /* remember the callsite, it will be used by bpf_exit */
6978 *insn_idx /* callsite */,
6979 state->curframe + 1 /* frameno within this callchain */,
6980 subprog /* subprog number within this prog */);
6982 /* Transfer references to the callee */
6983 err = copy_reference_state(callee, caller);
6987 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6991 clear_caller_saved_regs(env, caller->regs);
6993 /* only increment it after check_reg_arg() finished */
6996 /* and go analyze first insn of the callee */
6997 *insn_idx = env->subprog_info[subprog].start - 1;
6999 if (env->log.level & BPF_LOG_LEVEL) {
7000 verbose(env, "caller:\n");
7001 print_verifier_state(env, caller, true);
7002 verbose(env, "callee:\n");
7003 print_verifier_state(env, callee, true);
7008 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7009 struct bpf_func_state *caller,
7010 struct bpf_func_state *callee)
7012 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7013 * void *callback_ctx, u64 flags);
7014 * callback_fn(struct bpf_map *map, void *key, void *value,
7015 * void *callback_ctx);
7017 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7019 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7020 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7021 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7023 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7024 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7025 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7027 /* pointer to stack or null */
7028 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7031 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7035 static int set_callee_state(struct bpf_verifier_env *env,
7036 struct bpf_func_state *caller,
7037 struct bpf_func_state *callee, int insn_idx)
7041 /* copy r1 - r5 args that callee can access. The copy includes parent
7042 * pointers, which connects us up to the liveness chain
7044 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7045 callee->regs[i] = caller->regs[i];
7049 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7052 int subprog, target_insn;
7054 target_insn = *insn_idx + insn->imm + 1;
7055 subprog = find_subprog(env, target_insn);
7057 verbose(env, "verifier bug. No program starts at insn %d\n",
7062 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7065 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7066 struct bpf_func_state *caller,
7067 struct bpf_func_state *callee,
7070 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7071 struct bpf_map *map;
7074 if (bpf_map_ptr_poisoned(insn_aux)) {
7075 verbose(env, "tail_call abusing map_ptr\n");
7079 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7080 if (!map->ops->map_set_for_each_callback_args ||
7081 !map->ops->map_for_each_callback) {
7082 verbose(env, "callback function not allowed for map\n");
7086 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7090 callee->in_callback_fn = true;
7091 callee->callback_ret_range = tnum_range(0, 1);
7095 static int set_loop_callback_state(struct bpf_verifier_env *env,
7096 struct bpf_func_state *caller,
7097 struct bpf_func_state *callee,
7100 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7102 * callback_fn(u32 index, void *callback_ctx);
7104 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7105 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7108 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7109 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7110 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7112 callee->in_callback_fn = true;
7113 callee->callback_ret_range = tnum_range(0, 1);
7117 static int set_timer_callback_state(struct bpf_verifier_env *env,
7118 struct bpf_func_state *caller,
7119 struct bpf_func_state *callee,
7122 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7124 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7125 * callback_fn(struct bpf_map *map, void *key, void *value);
7127 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7128 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7129 callee->regs[BPF_REG_1].map_ptr = map_ptr;
7131 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7132 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7133 callee->regs[BPF_REG_2].map_ptr = map_ptr;
7135 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7136 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7137 callee->regs[BPF_REG_3].map_ptr = map_ptr;
7140 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7141 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7142 callee->in_async_callback_fn = true;
7143 callee->callback_ret_range = tnum_range(0, 1);
7147 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7148 struct bpf_func_state *caller,
7149 struct bpf_func_state *callee,
7152 /* bpf_find_vma(struct task_struct *task, u64 addr,
7153 * void *callback_fn, void *callback_ctx, u64 flags)
7154 * (callback_fn)(struct task_struct *task,
7155 * struct vm_area_struct *vma, void *callback_ctx);
7157 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7159 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7160 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7161 callee->regs[BPF_REG_2].btf = btf_vmlinux;
7162 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7164 /* pointer to stack or null */
7165 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7168 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7169 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7170 callee->in_callback_fn = true;
7171 callee->callback_ret_range = tnum_range(0, 1);
7175 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7176 struct bpf_func_state *caller,
7177 struct bpf_func_state *callee,
7180 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7181 * callback_ctx, u64 flags);
7182 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
7184 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7185 callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
7186 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7187 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7190 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7191 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7192 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7194 callee->in_callback_fn = true;
7195 callee->callback_ret_range = tnum_range(0, 1);
7199 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7201 struct bpf_verifier_state *state = env->cur_state;
7202 struct bpf_func_state *caller, *callee;
7203 struct bpf_reg_state *r0;
7206 callee = state->frame[state->curframe];
7207 r0 = &callee->regs[BPF_REG_0];
7208 if (r0->type == PTR_TO_STACK) {
7209 /* technically it's ok to return caller's stack pointer
7210 * (or caller's caller's pointer) back to the caller,
7211 * since these pointers are valid. Only current stack
7212 * pointer will be invalid as soon as function exits,
7213 * but let's be conservative
7215 verbose(env, "cannot return stack pointer to the caller\n");
7220 caller = state->frame[state->curframe];
7221 if (callee->in_callback_fn) {
7222 /* enforce R0 return value range [0, 1]. */
7223 struct tnum range = callee->callback_ret_range;
7225 if (r0->type != SCALAR_VALUE) {
7226 verbose(env, "R0 not a scalar value\n");
7229 if (!tnum_in(range, r0->var_off)) {
7230 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7234 /* return to the caller whatever r0 had in the callee */
7235 caller->regs[BPF_REG_0] = *r0;
7238 /* callback_fn frame should have released its own additions to parent's
7239 * reference state at this point, or check_reference_leak would
7240 * complain, hence it must be the same as the caller. There is no need
7243 if (!callee->in_callback_fn) {
7244 /* Transfer references to the caller */
7245 err = copy_reference_state(caller, callee);
7250 *insn_idx = callee->callsite + 1;
7251 if (env->log.level & BPF_LOG_LEVEL) {
7252 verbose(env, "returning from callee:\n");
7253 print_verifier_state(env, callee, true);
7254 verbose(env, "to caller at %d:\n", *insn_idx);
7255 print_verifier_state(env, caller, true);
7257 /* clear everything in the callee */
7258 free_func_state(callee);
7259 state->frame[state->curframe + 1] = NULL;
7263 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7265 struct bpf_call_arg_meta *meta)
7267 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
7269 if (ret_type != RET_INTEGER ||
7270 (func_id != BPF_FUNC_get_stack &&
7271 func_id != BPF_FUNC_get_task_stack &&
7272 func_id != BPF_FUNC_probe_read_str &&
7273 func_id != BPF_FUNC_probe_read_kernel_str &&
7274 func_id != BPF_FUNC_probe_read_user_str))
7277 ret_reg->smax_value = meta->msize_max_value;
7278 ret_reg->s32_max_value = meta->msize_max_value;
7279 ret_reg->smin_value = -MAX_ERRNO;
7280 ret_reg->s32_min_value = -MAX_ERRNO;
7281 reg_bounds_sync(ret_reg);
7285 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7286 int func_id, int insn_idx)
7288 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7289 struct bpf_map *map = meta->map_ptr;
7291 if (func_id != BPF_FUNC_tail_call &&
7292 func_id != BPF_FUNC_map_lookup_elem &&
7293 func_id != BPF_FUNC_map_update_elem &&
7294 func_id != BPF_FUNC_map_delete_elem &&
7295 func_id != BPF_FUNC_map_push_elem &&
7296 func_id != BPF_FUNC_map_pop_elem &&
7297 func_id != BPF_FUNC_map_peek_elem &&
7298 func_id != BPF_FUNC_for_each_map_elem &&
7299 func_id != BPF_FUNC_redirect_map &&
7300 func_id != BPF_FUNC_map_lookup_percpu_elem)
7304 verbose(env, "kernel subsystem misconfigured verifier\n");
7308 /* In case of read-only, some additional restrictions
7309 * need to be applied in order to prevent altering the
7310 * state of the map from program side.
7312 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7313 (func_id == BPF_FUNC_map_delete_elem ||
7314 func_id == BPF_FUNC_map_update_elem ||
7315 func_id == BPF_FUNC_map_push_elem ||
7316 func_id == BPF_FUNC_map_pop_elem)) {
7317 verbose(env, "write into map forbidden\n");
7321 if (!BPF_MAP_PTR(aux->map_ptr_state))
7322 bpf_map_ptr_store(aux, meta->map_ptr,
7323 !meta->map_ptr->bypass_spec_v1);
7324 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7325 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7326 !meta->map_ptr->bypass_spec_v1);
7331 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7332 int func_id, int insn_idx)
7334 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7335 struct bpf_reg_state *regs = cur_regs(env), *reg;
7336 struct bpf_map *map = meta->map_ptr;
7340 if (func_id != BPF_FUNC_tail_call)
7342 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7343 verbose(env, "kernel subsystem misconfigured verifier\n");
7347 reg = ®s[BPF_REG_3];
7348 val = reg->var_off.value;
7349 max = map->max_entries;
7351 if (!(register_is_const(reg) && val < max)) {
7352 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7356 err = mark_chain_precision(env, BPF_REG_3);
7359 if (bpf_map_key_unseen(aux))
7360 bpf_map_key_store(aux, val);
7361 else if (!bpf_map_key_poisoned(aux) &&
7362 bpf_map_key_immediate(aux) != val)
7363 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7367 static int check_reference_leak(struct bpf_verifier_env *env)
7369 struct bpf_func_state *state = cur_func(env);
7370 bool refs_lingering = false;
7373 if (state->frameno && !state->in_callback_fn)
7376 for (i = 0; i < state->acquired_refs; i++) {
7377 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7379 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7380 state->refs[i].id, state->refs[i].insn_idx);
7381 refs_lingering = true;
7383 return refs_lingering ? -EINVAL : 0;
7386 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7387 struct bpf_reg_state *regs)
7389 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
7390 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
7391 struct bpf_map *fmt_map = fmt_reg->map_ptr;
7392 int err, fmt_map_off, num_args;
7396 /* data must be an array of u64 */
7397 if (data_len_reg->var_off.value % 8)
7399 num_args = data_len_reg->var_off.value / 8;
7401 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7402 * and map_direct_value_addr is set.
7404 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7405 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7408 verbose(env, "verifier bug\n");
7411 fmt = (char *)(long)fmt_addr + fmt_map_off;
7413 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7414 * can focus on validating the format specifiers.
7416 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7418 verbose(env, "Invalid format string\n");
7423 static int check_get_func_ip(struct bpf_verifier_env *env)
7425 enum bpf_prog_type type = resolve_prog_type(env->prog);
7426 int func_id = BPF_FUNC_get_func_ip;
7428 if (type == BPF_PROG_TYPE_TRACING) {
7429 if (!bpf_prog_has_trampoline(env->prog)) {
7430 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7431 func_id_name(func_id), func_id);
7435 } else if (type == BPF_PROG_TYPE_KPROBE) {
7439 verbose(env, "func %s#%d not supported for program type %d\n",
7440 func_id_name(func_id), func_id, type);
7444 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7446 return &env->insn_aux_data[env->insn_idx];
7449 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7451 struct bpf_reg_state *regs = cur_regs(env);
7452 struct bpf_reg_state *reg = ®s[BPF_REG_4];
7453 bool reg_is_null = register_is_null(reg);
7456 mark_chain_precision(env, BPF_REG_4);
7461 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7463 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7465 if (!state->initialized) {
7466 state->initialized = 1;
7467 state->fit_for_inline = loop_flag_is_zero(env);
7468 state->callback_subprogno = subprogno;
7472 if (!state->fit_for_inline)
7475 state->fit_for_inline = (loop_flag_is_zero(env) &&
7476 state->callback_subprogno == subprogno);
7479 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7482 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7483 const struct bpf_func_proto *fn = NULL;
7484 enum bpf_return_type ret_type;
7485 enum bpf_type_flag ret_flag;
7486 struct bpf_reg_state *regs;
7487 struct bpf_call_arg_meta meta;
7488 int insn_idx = *insn_idx_p;
7490 int i, err, func_id;
7492 /* find function prototype */
7493 func_id = insn->imm;
7494 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7495 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7500 if (env->ops->get_func_proto)
7501 fn = env->ops->get_func_proto(func_id, env->prog);
7503 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7508 /* eBPF programs must be GPL compatible to use GPL-ed functions */
7509 if (!env->prog->gpl_compatible && fn->gpl_only) {
7510 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7514 if (fn->allowed && !fn->allowed(env->prog)) {
7515 verbose(env, "helper call is not allowed in probe\n");
7519 if (!env->prog->aux->sleepable && fn->might_sleep) {
7520 verbose(env, "helper call might sleep in a non-sleepable prog\n");
7524 /* With LD_ABS/IND some JITs save/restore skb from r1. */
7525 changes_data = bpf_helper_changes_pkt_data(fn->func);
7526 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7527 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7528 func_id_name(func_id), func_id);
7532 memset(&meta, 0, sizeof(meta));
7533 meta.pkt_access = fn->pkt_access;
7535 err = check_func_proto(fn, func_id);
7537 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7538 func_id_name(func_id), func_id);
7542 meta.func_id = func_id;
7544 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7545 err = check_func_arg(env, i, &meta, fn);
7550 err = record_func_map(env, &meta, func_id, insn_idx);
7554 err = record_func_key(env, &meta, func_id, insn_idx);
7558 /* Mark slots with STACK_MISC in case of raw mode, stack offset
7559 * is inferred from register state.
7561 for (i = 0; i < meta.access_size; i++) {
7562 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7563 BPF_WRITE, -1, false);
7568 regs = cur_regs(env);
7570 if (meta.uninit_dynptr_regno) {
7571 /* we write BPF_DW bits (8 bytes) at a time */
7572 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7573 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7574 i, BPF_DW, BPF_WRITE, -1, false);
7579 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno],
7580 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7586 if (meta.release_regno) {
7588 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7589 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
7590 else if (meta.ref_obj_id)
7591 err = release_reference(env, meta.ref_obj_id);
7592 /* meta.ref_obj_id can only be 0 if register that is meant to be
7593 * released is NULL, which must be > R0.
7595 else if (register_is_null(®s[meta.release_regno]))
7598 verbose(env, "func %s#%d reference has not been acquired before\n",
7599 func_id_name(func_id), func_id);
7605 case BPF_FUNC_tail_call:
7606 err = check_reference_leak(env);
7608 verbose(env, "tail_call would lead to reference leak\n");
7612 case BPF_FUNC_get_local_storage:
7613 /* check that flags argument in get_local_storage(map, flags) is 0,
7614 * this is required because get_local_storage() can't return an error.
7616 if (!register_is_null(®s[BPF_REG_2])) {
7617 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7621 case BPF_FUNC_for_each_map_elem:
7622 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7623 set_map_elem_callback_state);
7625 case BPF_FUNC_timer_set_callback:
7626 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7627 set_timer_callback_state);
7629 case BPF_FUNC_find_vma:
7630 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7631 set_find_vma_callback_state);
7633 case BPF_FUNC_snprintf:
7634 err = check_bpf_snprintf_call(env, regs);
7637 update_loop_inline_state(env, meta.subprogno);
7638 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7639 set_loop_callback_state);
7641 case BPF_FUNC_dynptr_from_mem:
7642 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7643 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7644 reg_type_str(env, regs[BPF_REG_1].type));
7648 case BPF_FUNC_set_retval:
7649 if (prog_type == BPF_PROG_TYPE_LSM &&
7650 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7651 if (!env->prog->aux->attach_func_proto->type) {
7652 /* Make sure programs that attach to void
7653 * hooks don't try to modify return value.
7655 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7660 case BPF_FUNC_dynptr_data:
7661 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7662 if (arg_type_is_dynptr(fn->arg_type[i])) {
7663 struct bpf_reg_state *reg = ®s[BPF_REG_1 + i];
7665 if (meta.ref_obj_id) {
7666 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7670 if (base_type(reg->type) != PTR_TO_DYNPTR)
7671 /* Find the id of the dynptr we're
7672 * tracking the reference of
7674 meta.ref_obj_id = stack_slot_get_id(env, reg);
7678 if (i == MAX_BPF_FUNC_REG_ARGS) {
7679 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7683 case BPF_FUNC_user_ringbuf_drain:
7684 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7685 set_user_ringbuf_callback_state);
7692 /* reset caller saved regs */
7693 for (i = 0; i < CALLER_SAVED_REGS; i++) {
7694 mark_reg_not_init(env, regs, caller_saved[i]);
7695 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7698 /* helper call returns 64-bit value. */
7699 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7701 /* update return register (already marked as written above) */
7702 ret_type = fn->ret_type;
7703 ret_flag = type_flag(ret_type);
7705 switch (base_type(ret_type)) {
7707 /* sets type to SCALAR_VALUE */
7708 mark_reg_unknown(env, regs, BPF_REG_0);
7711 regs[BPF_REG_0].type = NOT_INIT;
7713 case RET_PTR_TO_MAP_VALUE:
7714 /* There is no offset yet applied, variable or fixed */
7715 mark_reg_known_zero(env, regs, BPF_REG_0);
7716 /* remember map_ptr, so that check_map_access()
7717 * can check 'value_size' boundary of memory access
7718 * to map element returned from bpf_map_lookup_elem()
7720 if (meta.map_ptr == NULL) {
7722 "kernel subsystem misconfigured verifier\n");
7725 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7726 regs[BPF_REG_0].map_uid = meta.map_uid;
7727 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7728 if (!type_may_be_null(ret_type) &&
7729 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
7730 regs[BPF_REG_0].id = ++env->id_gen;
7733 case RET_PTR_TO_SOCKET:
7734 mark_reg_known_zero(env, regs, BPF_REG_0);
7735 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7737 case RET_PTR_TO_SOCK_COMMON:
7738 mark_reg_known_zero(env, regs, BPF_REG_0);
7739 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7741 case RET_PTR_TO_TCP_SOCK:
7742 mark_reg_known_zero(env, regs, BPF_REG_0);
7743 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7745 case RET_PTR_TO_MEM:
7746 mark_reg_known_zero(env, regs, BPF_REG_0);
7747 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7748 regs[BPF_REG_0].mem_size = meta.mem_size;
7750 case RET_PTR_TO_MEM_OR_BTF_ID:
7752 const struct btf_type *t;
7754 mark_reg_known_zero(env, regs, BPF_REG_0);
7755 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7756 if (!btf_type_is_struct(t)) {
7758 const struct btf_type *ret;
7761 /* resolve the type size of ksym. */
7762 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7764 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7765 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7766 tname, PTR_ERR(ret));
7769 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7770 regs[BPF_REG_0].mem_size = tsize;
7772 /* MEM_RDONLY may be carried from ret_flag, but it
7773 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7774 * it will confuse the check of PTR_TO_BTF_ID in
7775 * check_mem_access().
7777 ret_flag &= ~MEM_RDONLY;
7779 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7780 regs[BPF_REG_0].btf = meta.ret_btf;
7781 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7785 case RET_PTR_TO_BTF_ID:
7787 struct btf *ret_btf;
7790 mark_reg_known_zero(env, regs, BPF_REG_0);
7791 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7792 if (func_id == BPF_FUNC_kptr_xchg) {
7793 ret_btf = meta.kptr_field->kptr.btf;
7794 ret_btf_id = meta.kptr_field->kptr.btf_id;
7796 if (fn->ret_btf_id == BPF_PTR_POISON) {
7797 verbose(env, "verifier internal error:");
7798 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7799 func_id_name(func_id));
7802 ret_btf = btf_vmlinux;
7803 ret_btf_id = *fn->ret_btf_id;
7805 if (ret_btf_id == 0) {
7806 verbose(env, "invalid return type %u of func %s#%d\n",
7807 base_type(ret_type), func_id_name(func_id),
7811 regs[BPF_REG_0].btf = ret_btf;
7812 regs[BPF_REG_0].btf_id = ret_btf_id;
7816 verbose(env, "unknown return type %u of func %s#%d\n",
7817 base_type(ret_type), func_id_name(func_id), func_id);
7821 if (type_may_be_null(regs[BPF_REG_0].type))
7822 regs[BPF_REG_0].id = ++env->id_gen;
7824 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7825 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7826 func_id_name(func_id), func_id);
7830 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7831 /* For release_reference() */
7832 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7833 } else if (is_acquire_function(func_id, meta.map_ptr)) {
7834 int id = acquire_reference_state(env, insn_idx);
7838 /* For mark_ptr_or_null_reg() */
7839 regs[BPF_REG_0].id = id;
7840 /* For release_reference() */
7841 regs[BPF_REG_0].ref_obj_id = id;
7844 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7846 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7850 if ((func_id == BPF_FUNC_get_stack ||
7851 func_id == BPF_FUNC_get_task_stack) &&
7852 !env->prog->has_callchain_buf) {
7853 const char *err_str;
7855 #ifdef CONFIG_PERF_EVENTS
7856 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7857 err_str = "cannot get callchain buffer for func %s#%d\n";
7860 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7863 verbose(env, err_str, func_id_name(func_id), func_id);
7867 env->prog->has_callchain_buf = true;
7870 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7871 env->prog->call_get_stack = true;
7873 if (func_id == BPF_FUNC_get_func_ip) {
7874 if (check_get_func_ip(env))
7876 env->prog->call_get_func_ip = true;
7880 clear_all_pkt_pointers(env);
7884 /* mark_btf_func_reg_size() is used when the reg size is determined by
7885 * the BTF func_proto's return value size and argument.
7887 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7890 struct bpf_reg_state *reg = &cur_regs(env)[regno];
7892 if (regno == BPF_REG_0) {
7893 /* Function return value */
7894 reg->live |= REG_LIVE_WRITTEN;
7895 reg->subreg_def = reg_size == sizeof(u64) ?
7896 DEF_NOT_SUBREG : env->insn_idx + 1;
7898 /* Function argument */
7899 if (reg_size == sizeof(u64)) {
7900 mark_insn_zext(env, reg);
7901 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7903 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7908 struct bpf_kfunc_call_arg_meta {
7913 const struct btf_type *func_proto;
7914 const char *func_name;
7915 /* Out parameters */
7930 struct btf_field *field;
7934 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
7936 return meta->kfunc_flags & KF_ACQUIRE;
7939 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
7941 return meta->kfunc_flags & KF_RET_NULL;
7944 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
7946 return meta->kfunc_flags & KF_RELEASE;
7949 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
7951 return meta->kfunc_flags & KF_TRUSTED_ARGS;
7954 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
7956 return meta->kfunc_flags & KF_SLEEPABLE;
7959 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
7961 return meta->kfunc_flags & KF_DESTRUCTIVE;
7964 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
7966 return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
7969 static bool is_trusted_reg(const struct bpf_reg_state *reg)
7971 /* A referenced register is always trusted. */
7972 if (reg->ref_obj_id)
7975 /* If a register is not referenced, it is trusted if it has either the
7976 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
7977 * other type modifiers may be safe, but we elect to take an opt-in
7978 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
7981 * Eventually, we should make PTR_TRUSTED the single source of truth
7982 * for whether a register is trusted.
7984 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
7985 !bpf_type_has_unsafe_modifiers(reg->type);
7988 static bool __kfunc_param_match_suffix(const struct btf *btf,
7989 const struct btf_param *arg,
7992 int suffix_len = strlen(suffix), len;
7993 const char *param_name;
7995 /* In the future, this can be ported to use BTF tagging */
7996 param_name = btf_name_by_offset(btf, arg->name_off);
7997 if (str_is_empty(param_name))
7999 len = strlen(param_name);
8000 if (len < suffix_len)
8002 param_name += len - suffix_len;
8003 return !strncmp(param_name, suffix, suffix_len);
8006 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8007 const struct btf_param *arg,
8008 const struct bpf_reg_state *reg)
8010 const struct btf_type *t;
8012 t = btf_type_skip_modifiers(btf, arg->type, NULL);
8013 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8016 return __kfunc_param_match_suffix(btf, arg, "__sz");
8019 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8021 return __kfunc_param_match_suffix(btf, arg, "__k");
8024 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8026 return __kfunc_param_match_suffix(btf, arg, "__ign");
8029 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8031 return __kfunc_param_match_suffix(btf, arg, "__alloc");
8034 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8035 const struct btf_param *arg,
8038 int len, target_len = strlen(name);
8039 const char *param_name;
8041 param_name = btf_name_by_offset(btf, arg->name_off);
8042 if (str_is_empty(param_name))
8044 len = strlen(param_name);
8045 if (len != target_len)
8047 if (strcmp(param_name, name))
8055 KF_ARG_LIST_HEAD_ID,
8056 KF_ARG_LIST_NODE_ID,
8059 BTF_ID_LIST(kf_arg_btf_ids)
8060 BTF_ID(struct, bpf_dynptr_kern)
8061 BTF_ID(struct, bpf_list_head)
8062 BTF_ID(struct, bpf_list_node)
8064 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8065 const struct btf_param *arg, int type)
8067 const struct btf_type *t;
8070 t = btf_type_skip_modifiers(btf, arg->type, NULL);
8073 if (!btf_type_is_ptr(t))
8075 t = btf_type_skip_modifiers(btf, t->type, &res_id);
8078 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
8081 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
8083 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
8086 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
8088 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
8091 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
8093 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
8096 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
8097 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
8098 const struct btf *btf,
8099 const struct btf_type *t, int rec)
8101 const struct btf_type *member_type;
8102 const struct btf_member *member;
8105 if (!btf_type_is_struct(t))
8108 for_each_member(i, t, member) {
8109 const struct btf_array *array;
8111 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
8112 if (btf_type_is_struct(member_type)) {
8114 verbose(env, "max struct nesting depth exceeded\n");
8117 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
8121 if (btf_type_is_array(member_type)) {
8122 array = btf_array(member_type);
8125 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
8126 if (!btf_type_is_scalar(member_type))
8130 if (!btf_type_is_scalar(member_type))
8137 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
8139 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
8140 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8141 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
8145 enum kfunc_ptr_arg_type {
8147 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
8148 KF_ARG_PTR_TO_KPTR, /* PTR_TO_KPTR but type specific */
8149 KF_ARG_PTR_TO_DYNPTR,
8150 KF_ARG_PTR_TO_LIST_HEAD,
8151 KF_ARG_PTR_TO_LIST_NODE,
8152 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
8154 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
8157 enum special_kfunc_type {
8158 KF_bpf_obj_new_impl,
8159 KF_bpf_obj_drop_impl,
8160 KF_bpf_list_push_front,
8161 KF_bpf_list_push_back,
8162 KF_bpf_list_pop_front,
8163 KF_bpf_list_pop_back,
8164 KF_bpf_cast_to_kern_ctx,
8168 BTF_SET_START(special_kfunc_set)
8169 BTF_ID(func, bpf_obj_new_impl)
8170 BTF_ID(func, bpf_obj_drop_impl)
8171 BTF_ID(func, bpf_list_push_front)
8172 BTF_ID(func, bpf_list_push_back)
8173 BTF_ID(func, bpf_list_pop_front)
8174 BTF_ID(func, bpf_list_pop_back)
8175 BTF_ID(func, bpf_cast_to_kern_ctx)
8176 BTF_ID(func, bpf_rdonly_cast)
8177 BTF_SET_END(special_kfunc_set)
8179 BTF_ID_LIST(special_kfunc_list)
8180 BTF_ID(func, bpf_obj_new_impl)
8181 BTF_ID(func, bpf_obj_drop_impl)
8182 BTF_ID(func, bpf_list_push_front)
8183 BTF_ID(func, bpf_list_push_back)
8184 BTF_ID(func, bpf_list_pop_front)
8185 BTF_ID(func, bpf_list_pop_back)
8186 BTF_ID(func, bpf_cast_to_kern_ctx)
8187 BTF_ID(func, bpf_rdonly_cast)
8189 static enum kfunc_ptr_arg_type
8190 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
8191 struct bpf_kfunc_call_arg_meta *meta,
8192 const struct btf_type *t, const struct btf_type *ref_t,
8193 const char *ref_tname, const struct btf_param *args,
8194 int argno, int nargs)
8196 u32 regno = argno + 1;
8197 struct bpf_reg_state *regs = cur_regs(env);
8198 struct bpf_reg_state *reg = ®s[regno];
8199 bool arg_mem_size = false;
8201 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
8202 return KF_ARG_PTR_TO_CTX;
8204 /* In this function, we verify the kfunc's BTF as per the argument type,
8205 * leaving the rest of the verification with respect to the register
8206 * type to our caller. When a set of conditions hold in the BTF type of
8207 * arguments, we resolve it to a known kfunc_ptr_arg_type.
8209 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
8210 return KF_ARG_PTR_TO_CTX;
8212 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
8213 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
8215 if (is_kfunc_arg_kptr_get(meta, argno)) {
8216 if (!btf_type_is_ptr(ref_t)) {
8217 verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
8220 ref_t = btf_type_by_id(meta->btf, ref_t->type);
8221 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
8222 if (!btf_type_is_struct(ref_t)) {
8223 verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
8224 meta->func_name, btf_type_str(ref_t), ref_tname);
8227 return KF_ARG_PTR_TO_KPTR;
8230 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
8231 return KF_ARG_PTR_TO_DYNPTR;
8233 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
8234 return KF_ARG_PTR_TO_LIST_HEAD;
8236 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
8237 return KF_ARG_PTR_TO_LIST_NODE;
8239 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
8240 if (!btf_type_is_struct(ref_t)) {
8241 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
8242 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8245 return KF_ARG_PTR_TO_BTF_ID;
8248 if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))
8249 arg_mem_size = true;
8251 /* This is the catch all argument type of register types supported by
8252 * check_helper_mem_access. However, we only allow when argument type is
8253 * pointer to scalar, or struct composed (recursively) of scalars. When
8254 * arg_mem_size is true, the pointer can be void *.
8256 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
8257 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
8258 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
8259 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
8262 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
8265 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
8266 struct bpf_reg_state *reg,
8267 const struct btf_type *ref_t,
8268 const char *ref_tname, u32 ref_id,
8269 struct bpf_kfunc_call_arg_meta *meta,
8272 const struct btf_type *reg_ref_t;
8273 bool strict_type_match = false;
8274 const struct btf *reg_btf;
8275 const char *reg_ref_tname;
8278 if (base_type(reg->type) == PTR_TO_BTF_ID) {
8280 reg_ref_id = reg->btf_id;
8282 reg_btf = btf_vmlinux;
8283 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
8286 if (is_kfunc_trusted_args(meta) || (is_kfunc_release(meta) && reg->ref_obj_id))
8287 strict_type_match = true;
8289 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
8290 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
8291 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
8292 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
8293 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
8294 btf_type_str(reg_ref_t), reg_ref_tname);
8300 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
8301 struct bpf_reg_state *reg,
8302 const struct btf_type *ref_t,
8303 const char *ref_tname,
8304 struct bpf_kfunc_call_arg_meta *meta,
8307 struct btf_field *kptr_field;
8309 /* check_func_arg_reg_off allows var_off for
8310 * PTR_TO_MAP_VALUE, but we need fixed offset to find
8313 if (!tnum_is_const(reg->var_off)) {
8314 verbose(env, "arg#0 must have constant offset\n");
8318 kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
8319 if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
8320 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
8321 reg->off + reg->var_off.value);
8325 if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
8326 kptr_field->kptr.btf_id, true)) {
8327 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
8328 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8334 static int ref_set_release_on_unlock(struct bpf_verifier_env *env, u32 ref_obj_id)
8336 struct bpf_func_state *state = cur_func(env);
8337 struct bpf_reg_state *reg;
8340 /* bpf_spin_lock only allows calling list_push and list_pop, no BPF
8341 * subprogs, no global functions. This means that the references would
8342 * not be released inside the critical section but they may be added to
8343 * the reference state, and the acquired_refs are never copied out for a
8344 * different frame as BPF to BPF calls don't work in bpf_spin_lock
8345 * critical sections.
8348 verbose(env, "verifier internal error: ref_obj_id is zero for release_on_unlock\n");
8351 for (i = 0; i < state->acquired_refs; i++) {
8352 if (state->refs[i].id == ref_obj_id) {
8353 if (state->refs[i].release_on_unlock) {
8354 verbose(env, "verifier internal error: expected false release_on_unlock");
8357 state->refs[i].release_on_unlock = true;
8358 /* Now mark everyone sharing same ref_obj_id as untrusted */
8359 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8360 if (reg->ref_obj_id == ref_obj_id)
8361 reg->type |= PTR_UNTRUSTED;
8366 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
8370 /* Implementation details:
8372 * Each register points to some region of memory, which we define as an
8373 * allocation. Each allocation may embed a bpf_spin_lock which protects any
8374 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
8375 * allocation. The lock and the data it protects are colocated in the same
8378 * Hence, everytime a register holds a pointer value pointing to such
8379 * allocation, the verifier preserves a unique reg->id for it.
8381 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
8382 * bpf_spin_lock is called.
8384 * To enable this, lock state in the verifier captures two values:
8385 * active_lock.ptr = Register's type specific pointer
8386 * active_lock.id = A unique ID for each register pointer value
8388 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
8389 * supported register types.
8391 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
8392 * allocated objects is the reg->btf pointer.
8394 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
8395 * can establish the provenance of the map value statically for each distinct
8396 * lookup into such maps. They always contain a single map value hence unique
8397 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
8399 * So, in case of global variables, they use array maps with max_entries = 1,
8400 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
8401 * into the same map value as max_entries is 1, as described above).
8403 * In case of inner map lookups, the inner map pointer has same map_ptr as the
8404 * outer map pointer (in verifier context), but each lookup into an inner map
8405 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
8406 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
8407 * will get different reg->id assigned to each lookup, hence different
8410 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
8411 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
8412 * returned from bpf_obj_new. Each allocation receives a new reg->id.
8414 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8419 switch ((int)reg->type) {
8420 case PTR_TO_MAP_VALUE:
8423 case PTR_TO_BTF_ID | MEM_ALLOC:
8424 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
8428 verbose(env, "verifier internal error: unknown reg type for lock check\n");
8433 if (!env->cur_state->active_lock.ptr)
8435 if (env->cur_state->active_lock.ptr != ptr ||
8436 env->cur_state->active_lock.id != id) {
8437 verbose(env, "held lock and object are not in the same allocation\n");
8443 static bool is_bpf_list_api_kfunc(u32 btf_id)
8445 return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
8446 btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
8447 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
8448 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
8451 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
8452 struct bpf_reg_state *reg, u32 regno,
8453 struct bpf_kfunc_call_arg_meta *meta)
8455 struct btf_field *field;
8456 struct btf_record *rec;
8459 if (meta->btf != btf_vmlinux || !is_bpf_list_api_kfunc(meta->func_id)) {
8460 verbose(env, "verifier internal error: bpf_list_head argument for unknown kfunc\n");
8464 if (!tnum_is_const(reg->var_off)) {
8466 "R%d doesn't have constant offset. bpf_list_head has to be at the constant offset\n",
8471 rec = reg_btf_record(reg);
8472 list_head_off = reg->off + reg->var_off.value;
8473 field = btf_record_find(rec, list_head_off, BPF_LIST_HEAD);
8475 verbose(env, "bpf_list_head not found at offset=%u\n", list_head_off);
8479 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
8480 if (check_reg_allocation_locked(env, reg)) {
8481 verbose(env, "bpf_spin_lock at off=%d must be held for bpf_list_head\n",
8482 rec->spin_lock_off);
8486 if (meta->arg_list_head.field) {
8487 verbose(env, "verifier internal error: repeating bpf_list_head arg\n");
8490 meta->arg_list_head.field = field;
8494 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
8495 struct bpf_reg_state *reg, u32 regno,
8496 struct bpf_kfunc_call_arg_meta *meta)
8498 const struct btf_type *et, *t;
8499 struct btf_field *field;
8500 struct btf_record *rec;
8503 if (meta->btf != btf_vmlinux ||
8504 (meta->func_id != special_kfunc_list[KF_bpf_list_push_front] &&
8505 meta->func_id != special_kfunc_list[KF_bpf_list_push_back])) {
8506 verbose(env, "verifier internal error: bpf_list_node argument for unknown kfunc\n");
8510 if (!tnum_is_const(reg->var_off)) {
8512 "R%d doesn't have constant offset. bpf_list_node has to be at the constant offset\n",
8517 rec = reg_btf_record(reg);
8518 list_node_off = reg->off + reg->var_off.value;
8519 field = btf_record_find(rec, list_node_off, BPF_LIST_NODE);
8520 if (!field || field->offset != list_node_off) {
8521 verbose(env, "bpf_list_node not found at offset=%u\n", list_node_off);
8525 field = meta->arg_list_head.field;
8527 et = btf_type_by_id(field->list_head.btf, field->list_head.value_btf_id);
8528 t = btf_type_by_id(reg->btf, reg->btf_id);
8529 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->list_head.btf,
8530 field->list_head.value_btf_id, true)) {
8531 verbose(env, "operation on bpf_list_head expects arg#1 bpf_list_node at offset=%d "
8532 "in struct %s, but arg is at offset=%d in struct %s\n",
8533 field->list_head.node_offset, btf_name_by_offset(field->list_head.btf, et->name_off),
8534 list_node_off, btf_name_by_offset(reg->btf, t->name_off));
8538 if (list_node_off != field->list_head.node_offset) {
8539 verbose(env, "arg#1 offset=%d, but expected bpf_list_node at offset=%d in struct %s\n",
8540 list_node_off, field->list_head.node_offset,
8541 btf_name_by_offset(field->list_head.btf, et->name_off));
8544 /* Set arg#1 for expiration after unlock */
8545 return ref_set_release_on_unlock(env, reg->ref_obj_id);
8548 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
8550 const char *func_name = meta->func_name, *ref_tname;
8551 const struct btf *btf = meta->btf;
8552 const struct btf_param *args;
8556 args = (const struct btf_param *)(meta->func_proto + 1);
8557 nargs = btf_type_vlen(meta->func_proto);
8558 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
8559 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
8560 MAX_BPF_FUNC_REG_ARGS);
8564 /* Check that BTF function arguments match actual types that the
8567 for (i = 0; i < nargs; i++) {
8568 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
8569 const struct btf_type *t, *ref_t, *resolve_ret;
8570 enum bpf_arg_type arg_type = ARG_DONTCARE;
8571 u32 regno = i + 1, ref_id, type_size;
8572 bool is_ret_buf_sz = false;
8575 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
8577 if (is_kfunc_arg_ignore(btf, &args[i]))
8580 if (btf_type_is_scalar(t)) {
8581 if (reg->type != SCALAR_VALUE) {
8582 verbose(env, "R%d is not a scalar\n", regno);
8586 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
8587 if (meta->arg_constant.found) {
8588 verbose(env, "verifier internal error: only one constant argument permitted\n");
8591 if (!tnum_is_const(reg->var_off)) {
8592 verbose(env, "R%d must be a known constant\n", regno);
8595 ret = mark_chain_precision(env, regno);
8598 meta->arg_constant.found = true;
8599 meta->arg_constant.value = reg->var_off.value;
8600 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
8601 meta->r0_rdonly = true;
8602 is_ret_buf_sz = true;
8603 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
8604 is_ret_buf_sz = true;
8607 if (is_ret_buf_sz) {
8608 if (meta->r0_size) {
8609 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
8613 if (!tnum_is_const(reg->var_off)) {
8614 verbose(env, "R%d is not a const\n", regno);
8618 meta->r0_size = reg->var_off.value;
8619 ret = mark_chain_precision(env, regno);
8626 if (!btf_type_is_ptr(t)) {
8627 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
8631 if (reg->ref_obj_id) {
8632 if (is_kfunc_release(meta) && meta->ref_obj_id) {
8633 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8634 regno, reg->ref_obj_id,
8638 meta->ref_obj_id = reg->ref_obj_id;
8639 if (is_kfunc_release(meta))
8640 meta->release_regno = regno;
8643 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
8644 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
8646 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
8647 if (kf_arg_type < 0)
8650 switch (kf_arg_type) {
8651 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8652 case KF_ARG_PTR_TO_BTF_ID:
8653 if (!is_kfunc_trusted_args(meta))
8656 if (!is_trusted_reg(reg)) {
8657 verbose(env, "R%d must be referenced or trusted\n", regno);
8661 case KF_ARG_PTR_TO_CTX:
8662 /* Trusted arguments have the same offset checks as release arguments */
8663 arg_type |= OBJ_RELEASE;
8665 case KF_ARG_PTR_TO_KPTR:
8666 case KF_ARG_PTR_TO_DYNPTR:
8667 case KF_ARG_PTR_TO_LIST_HEAD:
8668 case KF_ARG_PTR_TO_LIST_NODE:
8669 case KF_ARG_PTR_TO_MEM:
8670 case KF_ARG_PTR_TO_MEM_SIZE:
8671 /* Trusted by default */
8678 if (is_kfunc_release(meta) && reg->ref_obj_id)
8679 arg_type |= OBJ_RELEASE;
8680 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
8684 switch (kf_arg_type) {
8685 case KF_ARG_PTR_TO_CTX:
8686 if (reg->type != PTR_TO_CTX) {
8687 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
8691 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
8692 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
8695 meta->ret_btf_id = ret;
8698 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8699 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8700 verbose(env, "arg#%d expected pointer to allocated object\n", i);
8703 if (!reg->ref_obj_id) {
8704 verbose(env, "allocated object must be referenced\n");
8707 if (meta->btf == btf_vmlinux &&
8708 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
8709 meta->arg_obj_drop.btf = reg->btf;
8710 meta->arg_obj_drop.btf_id = reg->btf_id;
8713 case KF_ARG_PTR_TO_KPTR:
8714 if (reg->type != PTR_TO_MAP_VALUE) {
8715 verbose(env, "arg#0 expected pointer to map value\n");
8718 ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
8722 case KF_ARG_PTR_TO_DYNPTR:
8723 if (reg->type != PTR_TO_STACK) {
8724 verbose(env, "arg#%d expected pointer to stack\n", i);
8728 if (!is_dynptr_reg_valid_init(env, reg)) {
8729 verbose(env, "arg#%d pointer type %s %s must be valid and initialized\n",
8730 i, btf_type_str(ref_t), ref_tname);
8734 if (!is_dynptr_type_expected(env, reg, ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL)) {
8735 verbose(env, "arg#%d pointer type %s %s points to unsupported dynamic pointer type\n",
8736 i, btf_type_str(ref_t), ref_tname);
8740 case KF_ARG_PTR_TO_LIST_HEAD:
8741 if (reg->type != PTR_TO_MAP_VALUE &&
8742 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8743 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
8746 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
8747 verbose(env, "allocated object must be referenced\n");
8750 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
8754 case KF_ARG_PTR_TO_LIST_NODE:
8755 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8756 verbose(env, "arg#%d expected pointer to allocated object\n", i);
8759 if (!reg->ref_obj_id) {
8760 verbose(env, "allocated object must be referenced\n");
8763 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
8767 case KF_ARG_PTR_TO_BTF_ID:
8768 /* Only base_type is checked, further checks are done here */
8769 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
8770 bpf_type_has_unsafe_modifiers(reg->type)) &&
8771 !reg2btf_ids[base_type(reg->type)]) {
8772 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
8773 verbose(env, "expected %s or socket\n",
8774 reg_type_str(env, base_type(reg->type) |
8775 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
8778 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
8782 case KF_ARG_PTR_TO_MEM:
8783 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
8784 if (IS_ERR(resolve_ret)) {
8785 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
8786 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
8789 ret = check_mem_reg(env, reg, regno, type_size);
8793 case KF_ARG_PTR_TO_MEM_SIZE:
8794 ret = check_kfunc_mem_size_reg(env, ®s[regno + 1], regno + 1);
8796 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
8799 /* Skip next '__sz' argument */
8805 if (is_kfunc_release(meta) && !meta->release_regno) {
8806 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
8814 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8817 const struct btf_type *t, *func, *func_proto, *ptr_type;
8818 struct bpf_reg_state *regs = cur_regs(env);
8819 const char *func_name, *ptr_type_name;
8820 struct bpf_kfunc_call_arg_meta meta;
8821 u32 i, nargs, func_id, ptr_type_id;
8822 int err, insn_idx = *insn_idx_p;
8823 const struct btf_param *args;
8824 const struct btf_type *ret_t;
8825 struct btf *desc_btf;
8828 /* skip for now, but return error when we find this in fixup_kfunc_call */
8832 desc_btf = find_kfunc_desc_btf(env, insn->off);
8833 if (IS_ERR(desc_btf))
8834 return PTR_ERR(desc_btf);
8836 func_id = insn->imm;
8837 func = btf_type_by_id(desc_btf, func_id);
8838 func_name = btf_name_by_offset(desc_btf, func->name_off);
8839 func_proto = btf_type_by_id(desc_btf, func->type);
8841 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
8843 verbose(env, "calling kernel function %s is not allowed\n",
8848 /* Prepare kfunc call metadata */
8849 memset(&meta, 0, sizeof(meta));
8850 meta.btf = desc_btf;
8851 meta.func_id = func_id;
8852 meta.kfunc_flags = *kfunc_flags;
8853 meta.func_proto = func_proto;
8854 meta.func_name = func_name;
8856 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
8857 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
8861 if (is_kfunc_sleepable(&meta) && !env->prog->aux->sleepable) {
8862 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
8866 /* Check the arguments */
8867 err = check_kfunc_args(env, &meta);
8870 /* In case of release function, we get register number of refcounted
8871 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
8873 if (meta.release_regno) {
8874 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
8876 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
8877 func_name, func_id);
8882 for (i = 0; i < CALLER_SAVED_REGS; i++)
8883 mark_reg_not_init(env, regs, caller_saved[i]);
8885 /* Check return type */
8886 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
8888 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
8889 /* Only exception is bpf_obj_new_impl */
8890 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
8891 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
8896 if (btf_type_is_scalar(t)) {
8897 mark_reg_unknown(env, regs, BPF_REG_0);
8898 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
8899 } else if (btf_type_is_ptr(t)) {
8900 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
8902 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
8903 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
8904 struct btf *ret_btf;
8907 if (unlikely(!bpf_global_ma_set))
8910 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
8911 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
8915 ret_btf = env->prog->aux->btf;
8916 ret_btf_id = meta.arg_constant.value;
8918 /* This may be NULL due to user not supplying a BTF */
8920 verbose(env, "bpf_obj_new requires prog BTF\n");
8924 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
8925 if (!ret_t || !__btf_type_is_struct(ret_t)) {
8926 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
8930 mark_reg_known_zero(env, regs, BPF_REG_0);
8931 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
8932 regs[BPF_REG_0].btf = ret_btf;
8933 regs[BPF_REG_0].btf_id = ret_btf_id;
8935 env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
8936 env->insn_aux_data[insn_idx].kptr_struct_meta =
8937 btf_find_struct_meta(ret_btf, ret_btf_id);
8938 } else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
8939 env->insn_aux_data[insn_idx].kptr_struct_meta =
8940 btf_find_struct_meta(meta.arg_obj_drop.btf,
8941 meta.arg_obj_drop.btf_id);
8942 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
8943 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
8944 struct btf_field *field = meta.arg_list_head.field;
8946 mark_reg_known_zero(env, regs, BPF_REG_0);
8947 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
8948 regs[BPF_REG_0].btf = field->list_head.btf;
8949 regs[BPF_REG_0].btf_id = field->list_head.value_btf_id;
8950 regs[BPF_REG_0].off = field->list_head.node_offset;
8951 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
8952 mark_reg_known_zero(env, regs, BPF_REG_0);
8953 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
8954 regs[BPF_REG_0].btf = desc_btf;
8955 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8956 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
8957 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
8958 if (!ret_t || !btf_type_is_struct(ret_t)) {
8960 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
8964 mark_reg_known_zero(env, regs, BPF_REG_0);
8965 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
8966 regs[BPF_REG_0].btf = desc_btf;
8967 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
8969 verbose(env, "kernel function %s unhandled dynamic return type\n",
8973 } else if (!__btf_type_is_struct(ptr_type)) {
8974 if (!meta.r0_size) {
8975 ptr_type_name = btf_name_by_offset(desc_btf,
8976 ptr_type->name_off);
8978 "kernel function %s returns pointer type %s %s is not supported\n",
8980 btf_type_str(ptr_type),
8985 mark_reg_known_zero(env, regs, BPF_REG_0);
8986 regs[BPF_REG_0].type = PTR_TO_MEM;
8987 regs[BPF_REG_0].mem_size = meta.r0_size;
8990 regs[BPF_REG_0].type |= MEM_RDONLY;
8992 /* Ensures we don't access the memory after a release_reference() */
8993 if (meta.ref_obj_id)
8994 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8996 mark_reg_known_zero(env, regs, BPF_REG_0);
8997 regs[BPF_REG_0].btf = desc_btf;
8998 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
8999 regs[BPF_REG_0].btf_id = ptr_type_id;
9002 if (is_kfunc_ret_null(&meta)) {
9003 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
9004 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
9005 regs[BPF_REG_0].id = ++env->id_gen;
9007 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
9008 if (is_kfunc_acquire(&meta)) {
9009 int id = acquire_reference_state(env, insn_idx);
9013 if (is_kfunc_ret_null(&meta))
9014 regs[BPF_REG_0].id = id;
9015 regs[BPF_REG_0].ref_obj_id = id;
9017 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
9018 regs[BPF_REG_0].id = ++env->id_gen;
9019 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
9021 nargs = btf_type_vlen(func_proto);
9022 args = (const struct btf_param *)(func_proto + 1);
9023 for (i = 0; i < nargs; i++) {
9026 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
9027 if (btf_type_is_ptr(t))
9028 mark_btf_func_reg_size(env, regno, sizeof(void *));
9030 /* scalar. ensured by btf_check_kfunc_arg_match() */
9031 mark_btf_func_reg_size(env, regno, t->size);
9037 static bool signed_add_overflows(s64 a, s64 b)
9039 /* Do the add in u64, where overflow is well-defined */
9040 s64 res = (s64)((u64)a + (u64)b);
9047 static bool signed_add32_overflows(s32 a, s32 b)
9049 /* Do the add in u32, where overflow is well-defined */
9050 s32 res = (s32)((u32)a + (u32)b);
9057 static bool signed_sub_overflows(s64 a, s64 b)
9059 /* Do the sub in u64, where overflow is well-defined */
9060 s64 res = (s64)((u64)a - (u64)b);
9067 static bool signed_sub32_overflows(s32 a, s32 b)
9069 /* Do the sub in u32, where overflow is well-defined */
9070 s32 res = (s32)((u32)a - (u32)b);
9077 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
9078 const struct bpf_reg_state *reg,
9079 enum bpf_reg_type type)
9081 bool known = tnum_is_const(reg->var_off);
9082 s64 val = reg->var_off.value;
9083 s64 smin = reg->smin_value;
9085 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
9086 verbose(env, "math between %s pointer and %lld is not allowed\n",
9087 reg_type_str(env, type), val);
9091 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
9092 verbose(env, "%s pointer offset %d is not allowed\n",
9093 reg_type_str(env, type), reg->off);
9097 if (smin == S64_MIN) {
9098 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
9099 reg_type_str(env, type));
9103 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
9104 verbose(env, "value %lld makes %s pointer be out of bounds\n",
9105 smin, reg_type_str(env, type));
9120 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
9121 u32 *alu_limit, bool mask_to_left)
9123 u32 max = 0, ptr_limit = 0;
9125 switch (ptr_reg->type) {
9127 /* Offset 0 is out-of-bounds, but acceptable start for the
9128 * left direction, see BPF_REG_FP. Also, unknown scalar
9129 * offset where we would need to deal with min/max bounds is
9130 * currently prohibited for unprivileged.
9132 max = MAX_BPF_STACK + mask_to_left;
9133 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
9135 case PTR_TO_MAP_VALUE:
9136 max = ptr_reg->map_ptr->value_size;
9137 ptr_limit = (mask_to_left ?
9138 ptr_reg->smin_value :
9139 ptr_reg->umax_value) + ptr_reg->off;
9145 if (ptr_limit >= max)
9146 return REASON_LIMIT;
9147 *alu_limit = ptr_limit;
9151 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
9152 const struct bpf_insn *insn)
9154 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
9157 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
9158 u32 alu_state, u32 alu_limit)
9160 /* If we arrived here from different branches with different
9161 * state or limits to sanitize, then this won't work.
9163 if (aux->alu_state &&
9164 (aux->alu_state != alu_state ||
9165 aux->alu_limit != alu_limit))
9166 return REASON_PATHS;
9168 /* Corresponding fixup done in do_misc_fixups(). */
9169 aux->alu_state = alu_state;
9170 aux->alu_limit = alu_limit;
9174 static int sanitize_val_alu(struct bpf_verifier_env *env,
9175 struct bpf_insn *insn)
9177 struct bpf_insn_aux_data *aux = cur_aux(env);
9179 if (can_skip_alu_sanitation(env, insn))
9182 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
9185 static bool sanitize_needed(u8 opcode)
9187 return opcode == BPF_ADD || opcode == BPF_SUB;
9190 struct bpf_sanitize_info {
9191 struct bpf_insn_aux_data aux;
9195 static struct bpf_verifier_state *
9196 sanitize_speculative_path(struct bpf_verifier_env *env,
9197 const struct bpf_insn *insn,
9198 u32 next_idx, u32 curr_idx)
9200 struct bpf_verifier_state *branch;
9201 struct bpf_reg_state *regs;
9203 branch = push_stack(env, next_idx, curr_idx, true);
9204 if (branch && insn) {
9205 regs = branch->frame[branch->curframe]->regs;
9206 if (BPF_SRC(insn->code) == BPF_K) {
9207 mark_reg_unknown(env, regs, insn->dst_reg);
9208 } else if (BPF_SRC(insn->code) == BPF_X) {
9209 mark_reg_unknown(env, regs, insn->dst_reg);
9210 mark_reg_unknown(env, regs, insn->src_reg);
9216 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
9217 struct bpf_insn *insn,
9218 const struct bpf_reg_state *ptr_reg,
9219 const struct bpf_reg_state *off_reg,
9220 struct bpf_reg_state *dst_reg,
9221 struct bpf_sanitize_info *info,
9222 const bool commit_window)
9224 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
9225 struct bpf_verifier_state *vstate = env->cur_state;
9226 bool off_is_imm = tnum_is_const(off_reg->var_off);
9227 bool off_is_neg = off_reg->smin_value < 0;
9228 bool ptr_is_dst_reg = ptr_reg == dst_reg;
9229 u8 opcode = BPF_OP(insn->code);
9230 u32 alu_state, alu_limit;
9231 struct bpf_reg_state tmp;
9235 if (can_skip_alu_sanitation(env, insn))
9238 /* We already marked aux for masking from non-speculative
9239 * paths, thus we got here in the first place. We only care
9240 * to explore bad access from here.
9242 if (vstate->speculative)
9245 if (!commit_window) {
9246 if (!tnum_is_const(off_reg->var_off) &&
9247 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
9248 return REASON_BOUNDS;
9250 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
9251 (opcode == BPF_SUB && !off_is_neg);
9254 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
9258 if (commit_window) {
9259 /* In commit phase we narrow the masking window based on
9260 * the observed pointer move after the simulated operation.
9262 alu_state = info->aux.alu_state;
9263 alu_limit = abs(info->aux.alu_limit - alu_limit);
9265 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
9266 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
9267 alu_state |= ptr_is_dst_reg ?
9268 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
9270 /* Limit pruning on unknown scalars to enable deep search for
9271 * potential masking differences from other program paths.
9274 env->explore_alu_limits = true;
9277 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
9281 /* If we're in commit phase, we're done here given we already
9282 * pushed the truncated dst_reg into the speculative verification
9285 * Also, when register is a known constant, we rewrite register-based
9286 * operation to immediate-based, and thus do not need masking (and as
9287 * a consequence, do not need to simulate the zero-truncation either).
9289 if (commit_window || off_is_imm)
9292 /* Simulate and find potential out-of-bounds access under
9293 * speculative execution from truncation as a result of
9294 * masking when off was not within expected range. If off
9295 * sits in dst, then we temporarily need to move ptr there
9296 * to simulate dst (== 0) +/-= ptr. Needed, for example,
9297 * for cases where we use K-based arithmetic in one direction
9298 * and truncated reg-based in the other in order to explore
9301 if (!ptr_is_dst_reg) {
9303 *dst_reg = *ptr_reg;
9305 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
9307 if (!ptr_is_dst_reg && ret)
9309 return !ret ? REASON_STACK : 0;
9312 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
9314 struct bpf_verifier_state *vstate = env->cur_state;
9316 /* If we simulate paths under speculation, we don't update the
9317 * insn as 'seen' such that when we verify unreachable paths in
9318 * the non-speculative domain, sanitize_dead_code() can still
9319 * rewrite/sanitize them.
9321 if (!vstate->speculative)
9322 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9325 static int sanitize_err(struct bpf_verifier_env *env,
9326 const struct bpf_insn *insn, int reason,
9327 const struct bpf_reg_state *off_reg,
9328 const struct bpf_reg_state *dst_reg)
9330 static const char *err = "pointer arithmetic with it prohibited for !root";
9331 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
9332 u32 dst = insn->dst_reg, src = insn->src_reg;
9336 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
9337 off_reg == dst_reg ? dst : src, err);
9340 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
9341 off_reg == dst_reg ? src : dst, err);
9344 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
9348 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
9352 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
9356 verbose(env, "verifier internal error: unknown reason (%d)\n",
9364 /* check that stack access falls within stack limits and that 'reg' doesn't
9365 * have a variable offset.
9367 * Variable offset is prohibited for unprivileged mode for simplicity since it
9368 * requires corresponding support in Spectre masking for stack ALU. See also
9369 * retrieve_ptr_limit().
9372 * 'off' includes 'reg->off'.
9374 static int check_stack_access_for_ptr_arithmetic(
9375 struct bpf_verifier_env *env,
9377 const struct bpf_reg_state *reg,
9380 if (!tnum_is_const(reg->var_off)) {
9383 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
9384 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
9385 regno, tn_buf, off);
9389 if (off >= 0 || off < -MAX_BPF_STACK) {
9390 verbose(env, "R%d stack pointer arithmetic goes out of range, "
9391 "prohibited for !root; off=%d\n", regno, off);
9398 static int sanitize_check_bounds(struct bpf_verifier_env *env,
9399 const struct bpf_insn *insn,
9400 const struct bpf_reg_state *dst_reg)
9402 u32 dst = insn->dst_reg;
9404 /* For unprivileged we require that resulting offset must be in bounds
9405 * in order to be able to sanitize access later on.
9407 if (env->bypass_spec_v1)
9410 switch (dst_reg->type) {
9412 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
9413 dst_reg->off + dst_reg->var_off.value))
9416 case PTR_TO_MAP_VALUE:
9417 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
9418 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
9419 "prohibited for !root\n", dst);
9430 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
9431 * Caller should also handle BPF_MOV case separately.
9432 * If we return -EACCES, caller may want to try again treating pointer as a
9433 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
9435 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
9436 struct bpf_insn *insn,
9437 const struct bpf_reg_state *ptr_reg,
9438 const struct bpf_reg_state *off_reg)
9440 struct bpf_verifier_state *vstate = env->cur_state;
9441 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9442 struct bpf_reg_state *regs = state->regs, *dst_reg;
9443 bool known = tnum_is_const(off_reg->var_off);
9444 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
9445 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
9446 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
9447 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9448 struct bpf_sanitize_info info = {};
9449 u8 opcode = BPF_OP(insn->code);
9450 u32 dst = insn->dst_reg;
9453 dst_reg = ®s[dst];
9455 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
9456 smin_val > smax_val || umin_val > umax_val) {
9457 /* Taint dst register if offset had invalid bounds derived from
9458 * e.g. dead branches.
9460 __mark_reg_unknown(env, dst_reg);
9464 if (BPF_CLASS(insn->code) != BPF_ALU64) {
9465 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
9466 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9467 __mark_reg_unknown(env, dst_reg);
9472 "R%d 32-bit pointer arithmetic prohibited\n",
9477 if (ptr_reg->type & PTR_MAYBE_NULL) {
9478 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
9479 dst, reg_type_str(env, ptr_reg->type));
9483 switch (base_type(ptr_reg->type)) {
9484 case CONST_PTR_TO_MAP:
9485 /* smin_val represents the known value */
9486 if (known && smin_val == 0 && opcode == BPF_ADD)
9489 case PTR_TO_PACKET_END:
9491 case PTR_TO_SOCK_COMMON:
9492 case PTR_TO_TCP_SOCK:
9493 case PTR_TO_XDP_SOCK:
9494 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
9495 dst, reg_type_str(env, ptr_reg->type));
9501 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
9502 * The id may be overwritten later if we create a new variable offset.
9504 dst_reg->type = ptr_reg->type;
9505 dst_reg->id = ptr_reg->id;
9507 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
9508 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
9511 /* pointer types do not carry 32-bit bounds at the moment. */
9512 __mark_reg32_unbounded(dst_reg);
9514 if (sanitize_needed(opcode)) {
9515 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
9518 return sanitize_err(env, insn, ret, off_reg, dst_reg);
9523 /* We can take a fixed offset as long as it doesn't overflow
9524 * the s32 'off' field
9526 if (known && (ptr_reg->off + smin_val ==
9527 (s64)(s32)(ptr_reg->off + smin_val))) {
9528 /* pointer += K. Accumulate it into fixed offset */
9529 dst_reg->smin_value = smin_ptr;
9530 dst_reg->smax_value = smax_ptr;
9531 dst_reg->umin_value = umin_ptr;
9532 dst_reg->umax_value = umax_ptr;
9533 dst_reg->var_off = ptr_reg->var_off;
9534 dst_reg->off = ptr_reg->off + smin_val;
9535 dst_reg->raw = ptr_reg->raw;
9538 /* A new variable offset is created. Note that off_reg->off
9539 * == 0, since it's a scalar.
9540 * dst_reg gets the pointer type and since some positive
9541 * integer value was added to the pointer, give it a new 'id'
9542 * if it's a PTR_TO_PACKET.
9543 * this creates a new 'base' pointer, off_reg (variable) gets
9544 * added into the variable offset, and we copy the fixed offset
9547 if (signed_add_overflows(smin_ptr, smin_val) ||
9548 signed_add_overflows(smax_ptr, smax_val)) {
9549 dst_reg->smin_value = S64_MIN;
9550 dst_reg->smax_value = S64_MAX;
9552 dst_reg->smin_value = smin_ptr + smin_val;
9553 dst_reg->smax_value = smax_ptr + smax_val;
9555 if (umin_ptr + umin_val < umin_ptr ||
9556 umax_ptr + umax_val < umax_ptr) {
9557 dst_reg->umin_value = 0;
9558 dst_reg->umax_value = U64_MAX;
9560 dst_reg->umin_value = umin_ptr + umin_val;
9561 dst_reg->umax_value = umax_ptr + umax_val;
9563 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
9564 dst_reg->off = ptr_reg->off;
9565 dst_reg->raw = ptr_reg->raw;
9566 if (reg_is_pkt_pointer(ptr_reg)) {
9567 dst_reg->id = ++env->id_gen;
9568 /* something was added to pkt_ptr, set range to zero */
9569 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9573 if (dst_reg == off_reg) {
9574 /* scalar -= pointer. Creates an unknown scalar */
9575 verbose(env, "R%d tried to subtract pointer from scalar\n",
9579 /* We don't allow subtraction from FP, because (according to
9580 * test_verifier.c test "invalid fp arithmetic", JITs might not
9581 * be able to deal with it.
9583 if (ptr_reg->type == PTR_TO_STACK) {
9584 verbose(env, "R%d subtraction from stack pointer prohibited\n",
9588 if (known && (ptr_reg->off - smin_val ==
9589 (s64)(s32)(ptr_reg->off - smin_val))) {
9590 /* pointer -= K. Subtract it from fixed offset */
9591 dst_reg->smin_value = smin_ptr;
9592 dst_reg->smax_value = smax_ptr;
9593 dst_reg->umin_value = umin_ptr;
9594 dst_reg->umax_value = umax_ptr;
9595 dst_reg->var_off = ptr_reg->var_off;
9596 dst_reg->id = ptr_reg->id;
9597 dst_reg->off = ptr_reg->off - smin_val;
9598 dst_reg->raw = ptr_reg->raw;
9601 /* A new variable offset is created. If the subtrahend is known
9602 * nonnegative, then any reg->range we had before is still good.
9604 if (signed_sub_overflows(smin_ptr, smax_val) ||
9605 signed_sub_overflows(smax_ptr, smin_val)) {
9606 /* Overflow possible, we know nothing */
9607 dst_reg->smin_value = S64_MIN;
9608 dst_reg->smax_value = S64_MAX;
9610 dst_reg->smin_value = smin_ptr - smax_val;
9611 dst_reg->smax_value = smax_ptr - smin_val;
9613 if (umin_ptr < umax_val) {
9614 /* Overflow possible, we know nothing */
9615 dst_reg->umin_value = 0;
9616 dst_reg->umax_value = U64_MAX;
9618 /* Cannot overflow (as long as bounds are consistent) */
9619 dst_reg->umin_value = umin_ptr - umax_val;
9620 dst_reg->umax_value = umax_ptr - umin_val;
9622 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
9623 dst_reg->off = ptr_reg->off;
9624 dst_reg->raw = ptr_reg->raw;
9625 if (reg_is_pkt_pointer(ptr_reg)) {
9626 dst_reg->id = ++env->id_gen;
9627 /* something was added to pkt_ptr, set range to zero */
9629 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9635 /* bitwise ops on pointers are troublesome, prohibit. */
9636 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
9637 dst, bpf_alu_string[opcode >> 4]);
9640 /* other operators (e.g. MUL,LSH) produce non-pointer results */
9641 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
9642 dst, bpf_alu_string[opcode >> 4]);
9646 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
9648 reg_bounds_sync(dst_reg);
9649 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
9651 if (sanitize_needed(opcode)) {
9652 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
9655 return sanitize_err(env, insn, ret, off_reg, dst_reg);
9661 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
9662 struct bpf_reg_state *src_reg)
9664 s32 smin_val = src_reg->s32_min_value;
9665 s32 smax_val = src_reg->s32_max_value;
9666 u32 umin_val = src_reg->u32_min_value;
9667 u32 umax_val = src_reg->u32_max_value;
9669 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
9670 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
9671 dst_reg->s32_min_value = S32_MIN;
9672 dst_reg->s32_max_value = S32_MAX;
9674 dst_reg->s32_min_value += smin_val;
9675 dst_reg->s32_max_value += smax_val;
9677 if (dst_reg->u32_min_value + umin_val < umin_val ||
9678 dst_reg->u32_max_value + umax_val < umax_val) {
9679 dst_reg->u32_min_value = 0;
9680 dst_reg->u32_max_value = U32_MAX;
9682 dst_reg->u32_min_value += umin_val;
9683 dst_reg->u32_max_value += umax_val;
9687 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
9688 struct bpf_reg_state *src_reg)
9690 s64 smin_val = src_reg->smin_value;
9691 s64 smax_val = src_reg->smax_value;
9692 u64 umin_val = src_reg->umin_value;
9693 u64 umax_val = src_reg->umax_value;
9695 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
9696 signed_add_overflows(dst_reg->smax_value, smax_val)) {
9697 dst_reg->smin_value = S64_MIN;
9698 dst_reg->smax_value = S64_MAX;
9700 dst_reg->smin_value += smin_val;
9701 dst_reg->smax_value += smax_val;
9703 if (dst_reg->umin_value + umin_val < umin_val ||
9704 dst_reg->umax_value + umax_val < umax_val) {
9705 dst_reg->umin_value = 0;
9706 dst_reg->umax_value = U64_MAX;
9708 dst_reg->umin_value += umin_val;
9709 dst_reg->umax_value += umax_val;
9713 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
9714 struct bpf_reg_state *src_reg)
9716 s32 smin_val = src_reg->s32_min_value;
9717 s32 smax_val = src_reg->s32_max_value;
9718 u32 umin_val = src_reg->u32_min_value;
9719 u32 umax_val = src_reg->u32_max_value;
9721 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
9722 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
9723 /* Overflow possible, we know nothing */
9724 dst_reg->s32_min_value = S32_MIN;
9725 dst_reg->s32_max_value = S32_MAX;
9727 dst_reg->s32_min_value -= smax_val;
9728 dst_reg->s32_max_value -= smin_val;
9730 if (dst_reg->u32_min_value < umax_val) {
9731 /* Overflow possible, we know nothing */
9732 dst_reg->u32_min_value = 0;
9733 dst_reg->u32_max_value = U32_MAX;
9735 /* Cannot overflow (as long as bounds are consistent) */
9736 dst_reg->u32_min_value -= umax_val;
9737 dst_reg->u32_max_value -= umin_val;
9741 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
9742 struct bpf_reg_state *src_reg)
9744 s64 smin_val = src_reg->smin_value;
9745 s64 smax_val = src_reg->smax_value;
9746 u64 umin_val = src_reg->umin_value;
9747 u64 umax_val = src_reg->umax_value;
9749 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
9750 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
9751 /* Overflow possible, we know nothing */
9752 dst_reg->smin_value = S64_MIN;
9753 dst_reg->smax_value = S64_MAX;
9755 dst_reg->smin_value -= smax_val;
9756 dst_reg->smax_value -= smin_val;
9758 if (dst_reg->umin_value < umax_val) {
9759 /* Overflow possible, we know nothing */
9760 dst_reg->umin_value = 0;
9761 dst_reg->umax_value = U64_MAX;
9763 /* Cannot overflow (as long as bounds are consistent) */
9764 dst_reg->umin_value -= umax_val;
9765 dst_reg->umax_value -= umin_val;
9769 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
9770 struct bpf_reg_state *src_reg)
9772 s32 smin_val = src_reg->s32_min_value;
9773 u32 umin_val = src_reg->u32_min_value;
9774 u32 umax_val = src_reg->u32_max_value;
9776 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
9777 /* Ain't nobody got time to multiply that sign */
9778 __mark_reg32_unbounded(dst_reg);
9781 /* Both values are positive, so we can work with unsigned and
9782 * copy the result to signed (unless it exceeds S32_MAX).
9784 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
9785 /* Potential overflow, we know nothing */
9786 __mark_reg32_unbounded(dst_reg);
9789 dst_reg->u32_min_value *= umin_val;
9790 dst_reg->u32_max_value *= umax_val;
9791 if (dst_reg->u32_max_value > S32_MAX) {
9792 /* Overflow possible, we know nothing */
9793 dst_reg->s32_min_value = S32_MIN;
9794 dst_reg->s32_max_value = S32_MAX;
9796 dst_reg->s32_min_value = dst_reg->u32_min_value;
9797 dst_reg->s32_max_value = dst_reg->u32_max_value;
9801 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
9802 struct bpf_reg_state *src_reg)
9804 s64 smin_val = src_reg->smin_value;
9805 u64 umin_val = src_reg->umin_value;
9806 u64 umax_val = src_reg->umax_value;
9808 if (smin_val < 0 || dst_reg->smin_value < 0) {
9809 /* Ain't nobody got time to multiply that sign */
9810 __mark_reg64_unbounded(dst_reg);
9813 /* Both values are positive, so we can work with unsigned and
9814 * copy the result to signed (unless it exceeds S64_MAX).
9816 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
9817 /* Potential overflow, we know nothing */
9818 __mark_reg64_unbounded(dst_reg);
9821 dst_reg->umin_value *= umin_val;
9822 dst_reg->umax_value *= umax_val;
9823 if (dst_reg->umax_value > S64_MAX) {
9824 /* Overflow possible, we know nothing */
9825 dst_reg->smin_value = S64_MIN;
9826 dst_reg->smax_value = S64_MAX;
9828 dst_reg->smin_value = dst_reg->umin_value;
9829 dst_reg->smax_value = dst_reg->umax_value;
9833 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
9834 struct bpf_reg_state *src_reg)
9836 bool src_known = tnum_subreg_is_const(src_reg->var_off);
9837 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9838 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
9839 s32 smin_val = src_reg->s32_min_value;
9840 u32 umax_val = src_reg->u32_max_value;
9842 if (src_known && dst_known) {
9843 __mark_reg32_known(dst_reg, var32_off.value);
9847 /* We get our minimum from the var_off, since that's inherently
9848 * bitwise. Our maximum is the minimum of the operands' maxima.
9850 dst_reg->u32_min_value = var32_off.value;
9851 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
9852 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
9853 /* Lose signed bounds when ANDing negative numbers,
9854 * ain't nobody got time for that.
9856 dst_reg->s32_min_value = S32_MIN;
9857 dst_reg->s32_max_value = S32_MAX;
9859 /* ANDing two positives gives a positive, so safe to
9860 * cast result into s64.
9862 dst_reg->s32_min_value = dst_reg->u32_min_value;
9863 dst_reg->s32_max_value = dst_reg->u32_max_value;
9867 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
9868 struct bpf_reg_state *src_reg)
9870 bool src_known = tnum_is_const(src_reg->var_off);
9871 bool dst_known = tnum_is_const(dst_reg->var_off);
9872 s64 smin_val = src_reg->smin_value;
9873 u64 umax_val = src_reg->umax_value;
9875 if (src_known && dst_known) {
9876 __mark_reg_known(dst_reg, dst_reg->var_off.value);
9880 /* We get our minimum from the var_off, since that's inherently
9881 * bitwise. Our maximum is the minimum of the operands' maxima.
9883 dst_reg->umin_value = dst_reg->var_off.value;
9884 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
9885 if (dst_reg->smin_value < 0 || smin_val < 0) {
9886 /* Lose signed bounds when ANDing negative numbers,
9887 * ain't nobody got time for that.
9889 dst_reg->smin_value = S64_MIN;
9890 dst_reg->smax_value = S64_MAX;
9892 /* ANDing two positives gives a positive, so safe to
9893 * cast result into s64.
9895 dst_reg->smin_value = dst_reg->umin_value;
9896 dst_reg->smax_value = dst_reg->umax_value;
9898 /* We may learn something more from the var_off */
9899 __update_reg_bounds(dst_reg);
9902 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
9903 struct bpf_reg_state *src_reg)
9905 bool src_known = tnum_subreg_is_const(src_reg->var_off);
9906 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9907 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
9908 s32 smin_val = src_reg->s32_min_value;
9909 u32 umin_val = src_reg->u32_min_value;
9911 if (src_known && dst_known) {
9912 __mark_reg32_known(dst_reg, var32_off.value);
9916 /* We get our maximum from the var_off, and our minimum is the
9917 * maximum of the operands' minima
9919 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
9920 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
9921 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
9922 /* Lose signed bounds when ORing negative numbers,
9923 * ain't nobody got time for that.
9925 dst_reg->s32_min_value = S32_MIN;
9926 dst_reg->s32_max_value = S32_MAX;
9928 /* ORing two positives gives a positive, so safe to
9929 * cast result into s64.
9931 dst_reg->s32_min_value = dst_reg->u32_min_value;
9932 dst_reg->s32_max_value = dst_reg->u32_max_value;
9936 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
9937 struct bpf_reg_state *src_reg)
9939 bool src_known = tnum_is_const(src_reg->var_off);
9940 bool dst_known = tnum_is_const(dst_reg->var_off);
9941 s64 smin_val = src_reg->smin_value;
9942 u64 umin_val = src_reg->umin_value;
9944 if (src_known && dst_known) {
9945 __mark_reg_known(dst_reg, dst_reg->var_off.value);
9949 /* We get our maximum from the var_off, and our minimum is the
9950 * maximum of the operands' minima
9952 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
9953 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
9954 if (dst_reg->smin_value < 0 || smin_val < 0) {
9955 /* Lose signed bounds when ORing negative numbers,
9956 * ain't nobody got time for that.
9958 dst_reg->smin_value = S64_MIN;
9959 dst_reg->smax_value = S64_MAX;
9961 /* ORing two positives gives a positive, so safe to
9962 * cast result into s64.
9964 dst_reg->smin_value = dst_reg->umin_value;
9965 dst_reg->smax_value = dst_reg->umax_value;
9967 /* We may learn something more from the var_off */
9968 __update_reg_bounds(dst_reg);
9971 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
9972 struct bpf_reg_state *src_reg)
9974 bool src_known = tnum_subreg_is_const(src_reg->var_off);
9975 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9976 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
9977 s32 smin_val = src_reg->s32_min_value;
9979 if (src_known && dst_known) {
9980 __mark_reg32_known(dst_reg, var32_off.value);
9984 /* We get both minimum and maximum from the var32_off. */
9985 dst_reg->u32_min_value = var32_off.value;
9986 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
9988 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
9989 /* XORing two positive sign numbers gives a positive,
9990 * so safe to cast u32 result into s32.
9992 dst_reg->s32_min_value = dst_reg->u32_min_value;
9993 dst_reg->s32_max_value = dst_reg->u32_max_value;
9995 dst_reg->s32_min_value = S32_MIN;
9996 dst_reg->s32_max_value = S32_MAX;
10000 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
10001 struct bpf_reg_state *src_reg)
10003 bool src_known = tnum_is_const(src_reg->var_off);
10004 bool dst_known = tnum_is_const(dst_reg->var_off);
10005 s64 smin_val = src_reg->smin_value;
10007 if (src_known && dst_known) {
10008 /* dst_reg->var_off.value has been updated earlier */
10009 __mark_reg_known(dst_reg, dst_reg->var_off.value);
10013 /* We get both minimum and maximum from the var_off. */
10014 dst_reg->umin_value = dst_reg->var_off.value;
10015 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10017 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
10018 /* XORing two positive sign numbers gives a positive,
10019 * so safe to cast u64 result into s64.
10021 dst_reg->smin_value = dst_reg->umin_value;
10022 dst_reg->smax_value = dst_reg->umax_value;
10024 dst_reg->smin_value = S64_MIN;
10025 dst_reg->smax_value = S64_MAX;
10028 __update_reg_bounds(dst_reg);
10031 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10032 u64 umin_val, u64 umax_val)
10034 /* We lose all sign bit information (except what we can pick
10037 dst_reg->s32_min_value = S32_MIN;
10038 dst_reg->s32_max_value = S32_MAX;
10039 /* If we might shift our top bit out, then we know nothing */
10040 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
10041 dst_reg->u32_min_value = 0;
10042 dst_reg->u32_max_value = U32_MAX;
10044 dst_reg->u32_min_value <<= umin_val;
10045 dst_reg->u32_max_value <<= umax_val;
10049 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10050 struct bpf_reg_state *src_reg)
10052 u32 umax_val = src_reg->u32_max_value;
10053 u32 umin_val = src_reg->u32_min_value;
10054 /* u32 alu operation will zext upper bits */
10055 struct tnum subreg = tnum_subreg(dst_reg->var_off);
10057 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10058 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
10059 /* Not required but being careful mark reg64 bounds as unknown so
10060 * that we are forced to pick them up from tnum and zext later and
10061 * if some path skips this step we are still safe.
10063 __mark_reg64_unbounded(dst_reg);
10064 __update_reg32_bounds(dst_reg);
10067 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
10068 u64 umin_val, u64 umax_val)
10070 /* Special case <<32 because it is a common compiler pattern to sign
10071 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
10072 * positive we know this shift will also be positive so we can track
10073 * bounds correctly. Otherwise we lose all sign bit information except
10074 * what we can pick up from var_off. Perhaps we can generalize this
10075 * later to shifts of any length.
10077 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
10078 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
10080 dst_reg->smax_value = S64_MAX;
10082 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
10083 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
10085 dst_reg->smin_value = S64_MIN;
10087 /* If we might shift our top bit out, then we know nothing */
10088 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
10089 dst_reg->umin_value = 0;
10090 dst_reg->umax_value = U64_MAX;
10092 dst_reg->umin_value <<= umin_val;
10093 dst_reg->umax_value <<= umax_val;
10097 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
10098 struct bpf_reg_state *src_reg)
10100 u64 umax_val = src_reg->umax_value;
10101 u64 umin_val = src_reg->umin_value;
10103 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
10104 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
10105 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10107 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
10108 /* We may learn something more from the var_off */
10109 __update_reg_bounds(dst_reg);
10112 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
10113 struct bpf_reg_state *src_reg)
10115 struct tnum subreg = tnum_subreg(dst_reg->var_off);
10116 u32 umax_val = src_reg->u32_max_value;
10117 u32 umin_val = src_reg->u32_min_value;
10119 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
10120 * be negative, then either:
10121 * 1) src_reg might be zero, so the sign bit of the result is
10122 * unknown, so we lose our signed bounds
10123 * 2) it's known negative, thus the unsigned bounds capture the
10125 * 3) the signed bounds cross zero, so they tell us nothing
10127 * If the value in dst_reg is known nonnegative, then again the
10128 * unsigned bounds capture the signed bounds.
10129 * Thus, in all cases it suffices to blow away our signed bounds
10130 * and rely on inferring new ones from the unsigned bounds and
10131 * var_off of the result.
10133 dst_reg->s32_min_value = S32_MIN;
10134 dst_reg->s32_max_value = S32_MAX;
10136 dst_reg->var_off = tnum_rshift(subreg, umin_val);
10137 dst_reg->u32_min_value >>= umax_val;
10138 dst_reg->u32_max_value >>= umin_val;
10140 __mark_reg64_unbounded(dst_reg);
10141 __update_reg32_bounds(dst_reg);
10144 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
10145 struct bpf_reg_state *src_reg)
10147 u64 umax_val = src_reg->umax_value;
10148 u64 umin_val = src_reg->umin_value;
10150 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
10151 * be negative, then either:
10152 * 1) src_reg might be zero, so the sign bit of the result is
10153 * unknown, so we lose our signed bounds
10154 * 2) it's known negative, thus the unsigned bounds capture the
10156 * 3) the signed bounds cross zero, so they tell us nothing
10158 * If the value in dst_reg is known nonnegative, then again the
10159 * unsigned bounds capture the signed bounds.
10160 * Thus, in all cases it suffices to blow away our signed bounds
10161 * and rely on inferring new ones from the unsigned bounds and
10162 * var_off of the result.
10164 dst_reg->smin_value = S64_MIN;
10165 dst_reg->smax_value = S64_MAX;
10166 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
10167 dst_reg->umin_value >>= umax_val;
10168 dst_reg->umax_value >>= umin_val;
10170 /* Its not easy to operate on alu32 bounds here because it depends
10171 * on bits being shifted in. Take easy way out and mark unbounded
10172 * so we can recalculate later from tnum.
10174 __mark_reg32_unbounded(dst_reg);
10175 __update_reg_bounds(dst_reg);
10178 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
10179 struct bpf_reg_state *src_reg)
10181 u64 umin_val = src_reg->u32_min_value;
10183 /* Upon reaching here, src_known is true and
10184 * umax_val is equal to umin_val.
10186 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
10187 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
10189 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
10191 /* blow away the dst_reg umin_value/umax_value and rely on
10192 * dst_reg var_off to refine the result.
10194 dst_reg->u32_min_value = 0;
10195 dst_reg->u32_max_value = U32_MAX;
10197 __mark_reg64_unbounded(dst_reg);
10198 __update_reg32_bounds(dst_reg);
10201 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
10202 struct bpf_reg_state *src_reg)
10204 u64 umin_val = src_reg->umin_value;
10206 /* Upon reaching here, src_known is true and umax_val is equal
10209 dst_reg->smin_value >>= umin_val;
10210 dst_reg->smax_value >>= umin_val;
10212 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
10214 /* blow away the dst_reg umin_value/umax_value and rely on
10215 * dst_reg var_off to refine the result.
10217 dst_reg->umin_value = 0;
10218 dst_reg->umax_value = U64_MAX;
10220 /* Its not easy to operate on alu32 bounds here because it depends
10221 * on bits being shifted in from upper 32-bits. Take easy way out
10222 * and mark unbounded so we can recalculate later from tnum.
10224 __mark_reg32_unbounded(dst_reg);
10225 __update_reg_bounds(dst_reg);
10228 /* WARNING: This function does calculations on 64-bit values, but the actual
10229 * execution may occur on 32-bit values. Therefore, things like bitshifts
10230 * need extra checks in the 32-bit case.
10232 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
10233 struct bpf_insn *insn,
10234 struct bpf_reg_state *dst_reg,
10235 struct bpf_reg_state src_reg)
10237 struct bpf_reg_state *regs = cur_regs(env);
10238 u8 opcode = BPF_OP(insn->code);
10240 s64 smin_val, smax_val;
10241 u64 umin_val, umax_val;
10242 s32 s32_min_val, s32_max_val;
10243 u32 u32_min_val, u32_max_val;
10244 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
10245 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
10248 smin_val = src_reg.smin_value;
10249 smax_val = src_reg.smax_value;
10250 umin_val = src_reg.umin_value;
10251 umax_val = src_reg.umax_value;
10253 s32_min_val = src_reg.s32_min_value;
10254 s32_max_val = src_reg.s32_max_value;
10255 u32_min_val = src_reg.u32_min_value;
10256 u32_max_val = src_reg.u32_max_value;
10259 src_known = tnum_subreg_is_const(src_reg.var_off);
10261 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
10262 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
10263 /* Taint dst register if offset had invalid bounds
10264 * derived from e.g. dead branches.
10266 __mark_reg_unknown(env, dst_reg);
10270 src_known = tnum_is_const(src_reg.var_off);
10272 (smin_val != smax_val || umin_val != umax_val)) ||
10273 smin_val > smax_val || umin_val > umax_val) {
10274 /* Taint dst register if offset had invalid bounds
10275 * derived from e.g. dead branches.
10277 __mark_reg_unknown(env, dst_reg);
10283 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
10284 __mark_reg_unknown(env, dst_reg);
10288 if (sanitize_needed(opcode)) {
10289 ret = sanitize_val_alu(env, insn);
10291 return sanitize_err(env, insn, ret, NULL, NULL);
10294 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
10295 * There are two classes of instructions: The first class we track both
10296 * alu32 and alu64 sign/unsigned bounds independently this provides the
10297 * greatest amount of precision when alu operations are mixed with jmp32
10298 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
10299 * and BPF_OR. This is possible because these ops have fairly easy to
10300 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
10301 * See alu32 verifier tests for examples. The second class of
10302 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
10303 * with regards to tracking sign/unsigned bounds because the bits may
10304 * cross subreg boundaries in the alu64 case. When this happens we mark
10305 * the reg unbounded in the subreg bound space and use the resulting
10306 * tnum to calculate an approximation of the sign/unsigned bounds.
10310 scalar32_min_max_add(dst_reg, &src_reg);
10311 scalar_min_max_add(dst_reg, &src_reg);
10312 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
10315 scalar32_min_max_sub(dst_reg, &src_reg);
10316 scalar_min_max_sub(dst_reg, &src_reg);
10317 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
10320 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
10321 scalar32_min_max_mul(dst_reg, &src_reg);
10322 scalar_min_max_mul(dst_reg, &src_reg);
10325 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
10326 scalar32_min_max_and(dst_reg, &src_reg);
10327 scalar_min_max_and(dst_reg, &src_reg);
10330 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
10331 scalar32_min_max_or(dst_reg, &src_reg);
10332 scalar_min_max_or(dst_reg, &src_reg);
10335 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
10336 scalar32_min_max_xor(dst_reg, &src_reg);
10337 scalar_min_max_xor(dst_reg, &src_reg);
10340 if (umax_val >= insn_bitness) {
10341 /* Shifts greater than 31 or 63 are undefined.
10342 * This includes shifts by a negative number.
10344 mark_reg_unknown(env, regs, insn->dst_reg);
10348 scalar32_min_max_lsh(dst_reg, &src_reg);
10350 scalar_min_max_lsh(dst_reg, &src_reg);
10353 if (umax_val >= insn_bitness) {
10354 /* Shifts greater than 31 or 63 are undefined.
10355 * This includes shifts by a negative number.
10357 mark_reg_unknown(env, regs, insn->dst_reg);
10361 scalar32_min_max_rsh(dst_reg, &src_reg);
10363 scalar_min_max_rsh(dst_reg, &src_reg);
10366 if (umax_val >= insn_bitness) {
10367 /* Shifts greater than 31 or 63 are undefined.
10368 * This includes shifts by a negative number.
10370 mark_reg_unknown(env, regs, insn->dst_reg);
10374 scalar32_min_max_arsh(dst_reg, &src_reg);
10376 scalar_min_max_arsh(dst_reg, &src_reg);
10379 mark_reg_unknown(env, regs, insn->dst_reg);
10383 /* ALU32 ops are zero extended into 64bit register */
10385 zext_32_to_64(dst_reg);
10386 reg_bounds_sync(dst_reg);
10390 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
10393 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
10394 struct bpf_insn *insn)
10396 struct bpf_verifier_state *vstate = env->cur_state;
10397 struct bpf_func_state *state = vstate->frame[vstate->curframe];
10398 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
10399 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
10400 u8 opcode = BPF_OP(insn->code);
10403 dst_reg = ®s[insn->dst_reg];
10405 if (dst_reg->type != SCALAR_VALUE)
10408 /* Make sure ID is cleared otherwise dst_reg min/max could be
10409 * incorrectly propagated into other registers by find_equal_scalars()
10412 if (BPF_SRC(insn->code) == BPF_X) {
10413 src_reg = ®s[insn->src_reg];
10414 if (src_reg->type != SCALAR_VALUE) {
10415 if (dst_reg->type != SCALAR_VALUE) {
10416 /* Combining two pointers by any ALU op yields
10417 * an arbitrary scalar. Disallow all math except
10418 * pointer subtraction
10420 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10421 mark_reg_unknown(env, regs, insn->dst_reg);
10424 verbose(env, "R%d pointer %s pointer prohibited\n",
10426 bpf_alu_string[opcode >> 4]);
10429 /* scalar += pointer
10430 * This is legal, but we have to reverse our
10431 * src/dest handling in computing the range
10433 err = mark_chain_precision(env, insn->dst_reg);
10436 return adjust_ptr_min_max_vals(env, insn,
10439 } else if (ptr_reg) {
10440 /* pointer += scalar */
10441 err = mark_chain_precision(env, insn->src_reg);
10444 return adjust_ptr_min_max_vals(env, insn,
10446 } else if (dst_reg->precise) {
10447 /* if dst_reg is precise, src_reg should be precise as well */
10448 err = mark_chain_precision(env, insn->src_reg);
10453 /* Pretend the src is a reg with a known value, since we only
10454 * need to be able to read from this state.
10456 off_reg.type = SCALAR_VALUE;
10457 __mark_reg_known(&off_reg, insn->imm);
10458 src_reg = &off_reg;
10459 if (ptr_reg) /* pointer += K */
10460 return adjust_ptr_min_max_vals(env, insn,
10464 /* Got here implies adding two SCALAR_VALUEs */
10465 if (WARN_ON_ONCE(ptr_reg)) {
10466 print_verifier_state(env, state, true);
10467 verbose(env, "verifier internal error: unexpected ptr_reg\n");
10470 if (WARN_ON(!src_reg)) {
10471 print_verifier_state(env, state, true);
10472 verbose(env, "verifier internal error: no src_reg\n");
10475 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
10478 /* check validity of 32-bit and 64-bit arithmetic operations */
10479 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
10481 struct bpf_reg_state *regs = cur_regs(env);
10482 u8 opcode = BPF_OP(insn->code);
10485 if (opcode == BPF_END || opcode == BPF_NEG) {
10486 if (opcode == BPF_NEG) {
10487 if (BPF_SRC(insn->code) != BPF_K ||
10488 insn->src_reg != BPF_REG_0 ||
10489 insn->off != 0 || insn->imm != 0) {
10490 verbose(env, "BPF_NEG uses reserved fields\n");
10494 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
10495 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
10496 BPF_CLASS(insn->code) == BPF_ALU64) {
10497 verbose(env, "BPF_END uses reserved fields\n");
10502 /* check src operand */
10503 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10507 if (is_pointer_value(env, insn->dst_reg)) {
10508 verbose(env, "R%d pointer arithmetic prohibited\n",
10513 /* check dest operand */
10514 err = check_reg_arg(env, insn->dst_reg, DST_OP);
10518 } else if (opcode == BPF_MOV) {
10520 if (BPF_SRC(insn->code) == BPF_X) {
10521 if (insn->imm != 0 || insn->off != 0) {
10522 verbose(env, "BPF_MOV uses reserved fields\n");
10526 /* check src operand */
10527 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10531 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10532 verbose(env, "BPF_MOV uses reserved fields\n");
10537 /* check dest operand, mark as required later */
10538 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10542 if (BPF_SRC(insn->code) == BPF_X) {
10543 struct bpf_reg_state *src_reg = regs + insn->src_reg;
10544 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
10546 if (BPF_CLASS(insn->code) == BPF_ALU64) {
10548 * copy register state to dest reg
10550 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
10551 /* Assign src and dst registers the same ID
10552 * that will be used by find_equal_scalars()
10553 * to propagate min/max range.
10555 src_reg->id = ++env->id_gen;
10556 *dst_reg = *src_reg;
10557 dst_reg->live |= REG_LIVE_WRITTEN;
10558 dst_reg->subreg_def = DEF_NOT_SUBREG;
10560 /* R1 = (u32) R2 */
10561 if (is_pointer_value(env, insn->src_reg)) {
10563 "R%d partial copy of pointer\n",
10566 } else if (src_reg->type == SCALAR_VALUE) {
10567 *dst_reg = *src_reg;
10568 /* Make sure ID is cleared otherwise
10569 * dst_reg min/max could be incorrectly
10570 * propagated into src_reg by find_equal_scalars()
10573 dst_reg->live |= REG_LIVE_WRITTEN;
10574 dst_reg->subreg_def = env->insn_idx + 1;
10576 mark_reg_unknown(env, regs,
10579 zext_32_to_64(dst_reg);
10580 reg_bounds_sync(dst_reg);
10584 * remember the value we stored into this reg
10586 /* clear any state __mark_reg_known doesn't set */
10587 mark_reg_unknown(env, regs, insn->dst_reg);
10588 regs[insn->dst_reg].type = SCALAR_VALUE;
10589 if (BPF_CLASS(insn->code) == BPF_ALU64) {
10590 __mark_reg_known(regs + insn->dst_reg,
10593 __mark_reg_known(regs + insn->dst_reg,
10598 } else if (opcode > BPF_END) {
10599 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
10602 } else { /* all other ALU ops: and, sub, xor, add, ... */
10604 if (BPF_SRC(insn->code) == BPF_X) {
10605 if (insn->imm != 0 || insn->off != 0) {
10606 verbose(env, "BPF_ALU uses reserved fields\n");
10609 /* check src1 operand */
10610 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10614 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10615 verbose(env, "BPF_ALU uses reserved fields\n");
10620 /* check src2 operand */
10621 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10625 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
10626 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
10627 verbose(env, "div by zero\n");
10631 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
10632 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
10633 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
10635 if (insn->imm < 0 || insn->imm >= size) {
10636 verbose(env, "invalid shift %d\n", insn->imm);
10641 /* check dest operand */
10642 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10646 return adjust_reg_min_max_vals(env, insn);
10652 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
10653 struct bpf_reg_state *dst_reg,
10654 enum bpf_reg_type type,
10655 bool range_right_open)
10657 struct bpf_func_state *state;
10658 struct bpf_reg_state *reg;
10661 if (dst_reg->off < 0 ||
10662 (dst_reg->off == 0 && range_right_open))
10663 /* This doesn't give us any range */
10666 if (dst_reg->umax_value > MAX_PACKET_OFF ||
10667 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
10668 /* Risk of overflow. For instance, ptr + (1<<63) may be less
10669 * than pkt_end, but that's because it's also less than pkt.
10673 new_range = dst_reg->off;
10674 if (range_right_open)
10677 /* Examples for register markings:
10679 * pkt_data in dst register:
10683 * if (r2 > pkt_end) goto <handle exception>
10688 * if (r2 < pkt_end) goto <access okay>
10689 * <handle exception>
10692 * r2 == dst_reg, pkt_end == src_reg
10693 * r2=pkt(id=n,off=8,r=0)
10694 * r3=pkt(id=n,off=0,r=0)
10696 * pkt_data in src register:
10700 * if (pkt_end >= r2) goto <access okay>
10701 * <handle exception>
10705 * if (pkt_end <= r2) goto <handle exception>
10709 * pkt_end == dst_reg, r2 == src_reg
10710 * r2=pkt(id=n,off=8,r=0)
10711 * r3=pkt(id=n,off=0,r=0)
10713 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
10714 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
10715 * and [r3, r3 + 8-1) respectively is safe to access depending on
10719 /* If our ids match, then we must have the same max_value. And we
10720 * don't care about the other reg's fixed offset, since if it's too big
10721 * the range won't allow anything.
10722 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
10724 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10725 if (reg->type == type && reg->id == dst_reg->id)
10726 /* keep the maximum range already checked */
10727 reg->range = max(reg->range, new_range);
10731 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
10733 struct tnum subreg = tnum_subreg(reg->var_off);
10734 s32 sval = (s32)val;
10738 if (tnum_is_const(subreg))
10739 return !!tnum_equals_const(subreg, val);
10742 if (tnum_is_const(subreg))
10743 return !tnum_equals_const(subreg, val);
10746 if ((~subreg.mask & subreg.value) & val)
10748 if (!((subreg.mask | subreg.value) & val))
10752 if (reg->u32_min_value > val)
10754 else if (reg->u32_max_value <= val)
10758 if (reg->s32_min_value > sval)
10760 else if (reg->s32_max_value <= sval)
10764 if (reg->u32_max_value < val)
10766 else if (reg->u32_min_value >= val)
10770 if (reg->s32_max_value < sval)
10772 else if (reg->s32_min_value >= sval)
10776 if (reg->u32_min_value >= val)
10778 else if (reg->u32_max_value < val)
10782 if (reg->s32_min_value >= sval)
10784 else if (reg->s32_max_value < sval)
10788 if (reg->u32_max_value <= val)
10790 else if (reg->u32_min_value > val)
10794 if (reg->s32_max_value <= sval)
10796 else if (reg->s32_min_value > sval)
10805 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
10807 s64 sval = (s64)val;
10811 if (tnum_is_const(reg->var_off))
10812 return !!tnum_equals_const(reg->var_off, val);
10815 if (tnum_is_const(reg->var_off))
10816 return !tnum_equals_const(reg->var_off, val);
10819 if ((~reg->var_off.mask & reg->var_off.value) & val)
10821 if (!((reg->var_off.mask | reg->var_off.value) & val))
10825 if (reg->umin_value > val)
10827 else if (reg->umax_value <= val)
10831 if (reg->smin_value > sval)
10833 else if (reg->smax_value <= sval)
10837 if (reg->umax_value < val)
10839 else if (reg->umin_value >= val)
10843 if (reg->smax_value < sval)
10845 else if (reg->smin_value >= sval)
10849 if (reg->umin_value >= val)
10851 else if (reg->umax_value < val)
10855 if (reg->smin_value >= sval)
10857 else if (reg->smax_value < sval)
10861 if (reg->umax_value <= val)
10863 else if (reg->umin_value > val)
10867 if (reg->smax_value <= sval)
10869 else if (reg->smin_value > sval)
10877 /* compute branch direction of the expression "if (reg opcode val) goto target;"
10879 * 1 - branch will be taken and "goto target" will be executed
10880 * 0 - branch will not be taken and fall-through to next insn
10881 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
10884 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
10887 if (__is_pointer_value(false, reg)) {
10888 if (!reg_type_not_null(reg->type))
10891 /* If pointer is valid tests against zero will fail so we can
10892 * use this to direct branch taken.
10908 return is_branch32_taken(reg, val, opcode);
10909 return is_branch64_taken(reg, val, opcode);
10912 static int flip_opcode(u32 opcode)
10914 /* How can we transform "a <op> b" into "b <op> a"? */
10915 static const u8 opcode_flip[16] = {
10916 /* these stay the same */
10917 [BPF_JEQ >> 4] = BPF_JEQ,
10918 [BPF_JNE >> 4] = BPF_JNE,
10919 [BPF_JSET >> 4] = BPF_JSET,
10920 /* these swap "lesser" and "greater" (L and G in the opcodes) */
10921 [BPF_JGE >> 4] = BPF_JLE,
10922 [BPF_JGT >> 4] = BPF_JLT,
10923 [BPF_JLE >> 4] = BPF_JGE,
10924 [BPF_JLT >> 4] = BPF_JGT,
10925 [BPF_JSGE >> 4] = BPF_JSLE,
10926 [BPF_JSGT >> 4] = BPF_JSLT,
10927 [BPF_JSLE >> 4] = BPF_JSGE,
10928 [BPF_JSLT >> 4] = BPF_JSGT
10930 return opcode_flip[opcode >> 4];
10933 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
10934 struct bpf_reg_state *src_reg,
10937 struct bpf_reg_state *pkt;
10939 if (src_reg->type == PTR_TO_PACKET_END) {
10941 } else if (dst_reg->type == PTR_TO_PACKET_END) {
10943 opcode = flip_opcode(opcode);
10948 if (pkt->range >= 0)
10953 /* pkt <= pkt_end */
10956 /* pkt > pkt_end */
10957 if (pkt->range == BEYOND_PKT_END)
10958 /* pkt has at last one extra byte beyond pkt_end */
10959 return opcode == BPF_JGT;
10962 /* pkt < pkt_end */
10965 /* pkt >= pkt_end */
10966 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
10967 return opcode == BPF_JGE;
10973 /* Adjusts the register min/max values in the case that the dst_reg is the
10974 * variable register that we are working on, and src_reg is a constant or we're
10975 * simply doing a BPF_K check.
10976 * In JEQ/JNE cases we also adjust the var_off values.
10978 static void reg_set_min_max(struct bpf_reg_state *true_reg,
10979 struct bpf_reg_state *false_reg,
10980 u64 val, u32 val32,
10981 u8 opcode, bool is_jmp32)
10983 struct tnum false_32off = tnum_subreg(false_reg->var_off);
10984 struct tnum false_64off = false_reg->var_off;
10985 struct tnum true_32off = tnum_subreg(true_reg->var_off);
10986 struct tnum true_64off = true_reg->var_off;
10987 s64 sval = (s64)val;
10988 s32 sval32 = (s32)val32;
10990 /* If the dst_reg is a pointer, we can't learn anything about its
10991 * variable offset from the compare (unless src_reg were a pointer into
10992 * the same object, but we don't bother with that.
10993 * Since false_reg and true_reg have the same type by construction, we
10994 * only need to check one of them for pointerness.
10996 if (__is_pointer_value(false, false_reg))
11000 /* JEQ/JNE comparison doesn't change the register equivalence.
11003 * if (r1 == 42) goto label;
11005 * label: // here both r1 and r2 are known to be 42.
11007 * Hence when marking register as known preserve it's ID.
11011 __mark_reg32_known(true_reg, val32);
11012 true_32off = tnum_subreg(true_reg->var_off);
11014 ___mark_reg_known(true_reg, val);
11015 true_64off = true_reg->var_off;
11020 __mark_reg32_known(false_reg, val32);
11021 false_32off = tnum_subreg(false_reg->var_off);
11023 ___mark_reg_known(false_reg, val);
11024 false_64off = false_reg->var_off;
11029 false_32off = tnum_and(false_32off, tnum_const(~val32));
11030 if (is_power_of_2(val32))
11031 true_32off = tnum_or(true_32off,
11032 tnum_const(val32));
11034 false_64off = tnum_and(false_64off, tnum_const(~val));
11035 if (is_power_of_2(val))
11036 true_64off = tnum_or(true_64off,
11044 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
11045 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
11047 false_reg->u32_max_value = min(false_reg->u32_max_value,
11049 true_reg->u32_min_value = max(true_reg->u32_min_value,
11052 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
11053 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
11055 false_reg->umax_value = min(false_reg->umax_value, false_umax);
11056 true_reg->umin_value = max(true_reg->umin_value, true_umin);
11064 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
11065 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
11067 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
11068 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
11070 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
11071 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
11073 false_reg->smax_value = min(false_reg->smax_value, false_smax);
11074 true_reg->smin_value = max(true_reg->smin_value, true_smin);
11082 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
11083 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
11085 false_reg->u32_min_value = max(false_reg->u32_min_value,
11087 true_reg->u32_max_value = min(true_reg->u32_max_value,
11090 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
11091 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
11093 false_reg->umin_value = max(false_reg->umin_value, false_umin);
11094 true_reg->umax_value = min(true_reg->umax_value, true_umax);
11102 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
11103 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
11105 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
11106 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
11108 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
11109 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
11111 false_reg->smin_value = max(false_reg->smin_value, false_smin);
11112 true_reg->smax_value = min(true_reg->smax_value, true_smax);
11121 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
11122 tnum_subreg(false_32off));
11123 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
11124 tnum_subreg(true_32off));
11125 __reg_combine_32_into_64(false_reg);
11126 __reg_combine_32_into_64(true_reg);
11128 false_reg->var_off = false_64off;
11129 true_reg->var_off = true_64off;
11130 __reg_combine_64_into_32(false_reg);
11131 __reg_combine_64_into_32(true_reg);
11135 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
11136 * the variable reg.
11138 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
11139 struct bpf_reg_state *false_reg,
11140 u64 val, u32 val32,
11141 u8 opcode, bool is_jmp32)
11143 opcode = flip_opcode(opcode);
11144 /* This uses zero as "not present in table"; luckily the zero opcode,
11145 * BPF_JA, can't get here.
11148 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
11151 /* Regs are known to be equal, so intersect their min/max/var_off */
11152 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
11153 struct bpf_reg_state *dst_reg)
11155 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
11156 dst_reg->umin_value);
11157 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
11158 dst_reg->umax_value);
11159 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
11160 dst_reg->smin_value);
11161 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
11162 dst_reg->smax_value);
11163 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
11165 reg_bounds_sync(src_reg);
11166 reg_bounds_sync(dst_reg);
11169 static void reg_combine_min_max(struct bpf_reg_state *true_src,
11170 struct bpf_reg_state *true_dst,
11171 struct bpf_reg_state *false_src,
11172 struct bpf_reg_state *false_dst,
11177 __reg_combine_min_max(true_src, true_dst);
11180 __reg_combine_min_max(false_src, false_dst);
11185 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
11186 struct bpf_reg_state *reg, u32 id,
11189 if (type_may_be_null(reg->type) && reg->id == id &&
11190 !WARN_ON_ONCE(!reg->id)) {
11191 /* Old offset (both fixed and variable parts) should have been
11192 * known-zero, because we don't allow pointer arithmetic on
11193 * pointers that might be NULL. If we see this happening, don't
11194 * convert the register.
11196 * But in some cases, some helpers that return local kptrs
11197 * advance offset for the returned pointer. In those cases, it
11198 * is fine to expect to see reg->off.
11200 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
11202 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL) && WARN_ON_ONCE(reg->off))
11205 reg->type = SCALAR_VALUE;
11206 /* We don't need id and ref_obj_id from this point
11207 * onwards anymore, thus we should better reset it,
11208 * so that state pruning has chances to take effect.
11211 reg->ref_obj_id = 0;
11216 mark_ptr_not_null_reg(reg);
11218 if (!reg_may_point_to_spin_lock(reg)) {
11219 /* For not-NULL ptr, reg->ref_obj_id will be reset
11220 * in release_reference().
11222 * reg->id is still used by spin_lock ptr. Other
11223 * than spin_lock ptr type, reg->id can be reset.
11230 /* The logic is similar to find_good_pkt_pointers(), both could eventually
11231 * be folded together at some point.
11233 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
11236 struct bpf_func_state *state = vstate->frame[vstate->curframe];
11237 struct bpf_reg_state *regs = state->regs, *reg;
11238 u32 ref_obj_id = regs[regno].ref_obj_id;
11239 u32 id = regs[regno].id;
11241 if (ref_obj_id && ref_obj_id == id && is_null)
11242 /* regs[regno] is in the " == NULL" branch.
11243 * No one could have freed the reference state before
11244 * doing the NULL check.
11246 WARN_ON_ONCE(release_reference_state(state, id));
11248 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11249 mark_ptr_or_null_reg(state, reg, id, is_null);
11253 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
11254 struct bpf_reg_state *dst_reg,
11255 struct bpf_reg_state *src_reg,
11256 struct bpf_verifier_state *this_branch,
11257 struct bpf_verifier_state *other_branch)
11259 if (BPF_SRC(insn->code) != BPF_X)
11262 /* Pointers are always 64-bit. */
11263 if (BPF_CLASS(insn->code) == BPF_JMP32)
11266 switch (BPF_OP(insn->code)) {
11268 if ((dst_reg->type == PTR_TO_PACKET &&
11269 src_reg->type == PTR_TO_PACKET_END) ||
11270 (dst_reg->type == PTR_TO_PACKET_META &&
11271 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11272 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
11273 find_good_pkt_pointers(this_branch, dst_reg,
11274 dst_reg->type, false);
11275 mark_pkt_end(other_branch, insn->dst_reg, true);
11276 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11277 src_reg->type == PTR_TO_PACKET) ||
11278 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11279 src_reg->type == PTR_TO_PACKET_META)) {
11280 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
11281 find_good_pkt_pointers(other_branch, src_reg,
11282 src_reg->type, true);
11283 mark_pkt_end(this_branch, insn->src_reg, false);
11289 if ((dst_reg->type == PTR_TO_PACKET &&
11290 src_reg->type == PTR_TO_PACKET_END) ||
11291 (dst_reg->type == PTR_TO_PACKET_META &&
11292 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11293 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
11294 find_good_pkt_pointers(other_branch, dst_reg,
11295 dst_reg->type, true);
11296 mark_pkt_end(this_branch, insn->dst_reg, false);
11297 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11298 src_reg->type == PTR_TO_PACKET) ||
11299 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11300 src_reg->type == PTR_TO_PACKET_META)) {
11301 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
11302 find_good_pkt_pointers(this_branch, src_reg,
11303 src_reg->type, false);
11304 mark_pkt_end(other_branch, insn->src_reg, true);
11310 if ((dst_reg->type == PTR_TO_PACKET &&
11311 src_reg->type == PTR_TO_PACKET_END) ||
11312 (dst_reg->type == PTR_TO_PACKET_META &&
11313 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11314 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
11315 find_good_pkt_pointers(this_branch, dst_reg,
11316 dst_reg->type, true);
11317 mark_pkt_end(other_branch, insn->dst_reg, false);
11318 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11319 src_reg->type == PTR_TO_PACKET) ||
11320 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11321 src_reg->type == PTR_TO_PACKET_META)) {
11322 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
11323 find_good_pkt_pointers(other_branch, src_reg,
11324 src_reg->type, false);
11325 mark_pkt_end(this_branch, insn->src_reg, true);
11331 if ((dst_reg->type == PTR_TO_PACKET &&
11332 src_reg->type == PTR_TO_PACKET_END) ||
11333 (dst_reg->type == PTR_TO_PACKET_META &&
11334 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11335 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
11336 find_good_pkt_pointers(other_branch, dst_reg,
11337 dst_reg->type, false);
11338 mark_pkt_end(this_branch, insn->dst_reg, true);
11339 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11340 src_reg->type == PTR_TO_PACKET) ||
11341 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11342 src_reg->type == PTR_TO_PACKET_META)) {
11343 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
11344 find_good_pkt_pointers(this_branch, src_reg,
11345 src_reg->type, true);
11346 mark_pkt_end(other_branch, insn->src_reg, false);
11358 static void find_equal_scalars(struct bpf_verifier_state *vstate,
11359 struct bpf_reg_state *known_reg)
11361 struct bpf_func_state *state;
11362 struct bpf_reg_state *reg;
11364 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11365 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
11370 static int check_cond_jmp_op(struct bpf_verifier_env *env,
11371 struct bpf_insn *insn, int *insn_idx)
11373 struct bpf_verifier_state *this_branch = env->cur_state;
11374 struct bpf_verifier_state *other_branch;
11375 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
11376 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
11377 struct bpf_reg_state *eq_branch_regs;
11378 u8 opcode = BPF_OP(insn->code);
11383 /* Only conditional jumps are expected to reach here. */
11384 if (opcode == BPF_JA || opcode > BPF_JSLE) {
11385 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
11389 if (BPF_SRC(insn->code) == BPF_X) {
11390 if (insn->imm != 0) {
11391 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11395 /* check src1 operand */
11396 err = check_reg_arg(env, insn->src_reg, SRC_OP);
11400 if (is_pointer_value(env, insn->src_reg)) {
11401 verbose(env, "R%d pointer comparison prohibited\n",
11405 src_reg = ®s[insn->src_reg];
11407 if (insn->src_reg != BPF_REG_0) {
11408 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11413 /* check src2 operand */
11414 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11418 dst_reg = ®s[insn->dst_reg];
11419 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
11421 if (BPF_SRC(insn->code) == BPF_K) {
11422 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
11423 } else if (src_reg->type == SCALAR_VALUE &&
11424 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
11425 pred = is_branch_taken(dst_reg,
11426 tnum_subreg(src_reg->var_off).value,
11429 } else if (src_reg->type == SCALAR_VALUE &&
11430 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
11431 pred = is_branch_taken(dst_reg,
11432 src_reg->var_off.value,
11435 } else if (reg_is_pkt_pointer_any(dst_reg) &&
11436 reg_is_pkt_pointer_any(src_reg) &&
11438 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
11442 /* If we get here with a dst_reg pointer type it is because
11443 * above is_branch_taken() special cased the 0 comparison.
11445 if (!__is_pointer_value(false, dst_reg))
11446 err = mark_chain_precision(env, insn->dst_reg);
11447 if (BPF_SRC(insn->code) == BPF_X && !err &&
11448 !__is_pointer_value(false, src_reg))
11449 err = mark_chain_precision(env, insn->src_reg);
11455 /* Only follow the goto, ignore fall-through. If needed, push
11456 * the fall-through branch for simulation under speculative
11459 if (!env->bypass_spec_v1 &&
11460 !sanitize_speculative_path(env, insn, *insn_idx + 1,
11463 *insn_idx += insn->off;
11465 } else if (pred == 0) {
11466 /* Only follow the fall-through branch, since that's where the
11467 * program will go. If needed, push the goto branch for
11468 * simulation under speculative execution.
11470 if (!env->bypass_spec_v1 &&
11471 !sanitize_speculative_path(env, insn,
11472 *insn_idx + insn->off + 1,
11478 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
11482 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
11484 /* detect if we are comparing against a constant value so we can adjust
11485 * our min/max values for our dst register.
11486 * this is only legit if both are scalars (or pointers to the same
11487 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
11488 * because otherwise the different base pointers mean the offsets aren't
11491 if (BPF_SRC(insn->code) == BPF_X) {
11492 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
11494 if (dst_reg->type == SCALAR_VALUE &&
11495 src_reg->type == SCALAR_VALUE) {
11496 if (tnum_is_const(src_reg->var_off) ||
11498 tnum_is_const(tnum_subreg(src_reg->var_off))))
11499 reg_set_min_max(&other_branch_regs[insn->dst_reg],
11501 src_reg->var_off.value,
11502 tnum_subreg(src_reg->var_off).value,
11504 else if (tnum_is_const(dst_reg->var_off) ||
11506 tnum_is_const(tnum_subreg(dst_reg->var_off))))
11507 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
11509 dst_reg->var_off.value,
11510 tnum_subreg(dst_reg->var_off).value,
11512 else if (!is_jmp32 &&
11513 (opcode == BPF_JEQ || opcode == BPF_JNE))
11514 /* Comparing for equality, we can combine knowledge */
11515 reg_combine_min_max(&other_branch_regs[insn->src_reg],
11516 &other_branch_regs[insn->dst_reg],
11517 src_reg, dst_reg, opcode);
11519 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
11520 find_equal_scalars(this_branch, src_reg);
11521 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
11525 } else if (dst_reg->type == SCALAR_VALUE) {
11526 reg_set_min_max(&other_branch_regs[insn->dst_reg],
11527 dst_reg, insn->imm, (u32)insn->imm,
11531 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
11532 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
11533 find_equal_scalars(this_branch, dst_reg);
11534 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
11537 /* if one pointer register is compared to another pointer
11538 * register check if PTR_MAYBE_NULL could be lifted.
11539 * E.g. register A - maybe null
11540 * register B - not null
11541 * for JNE A, B, ... - A is not null in the false branch;
11542 * for JEQ A, B, ... - A is not null in the true branch.
11544 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
11545 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
11546 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type)) {
11547 eq_branch_regs = NULL;
11550 eq_branch_regs = other_branch_regs;
11553 eq_branch_regs = regs;
11559 if (eq_branch_regs) {
11560 if (type_may_be_null(src_reg->type))
11561 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
11563 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
11567 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
11568 * NOTE: these optimizations below are related with pointer comparison
11569 * which will never be JMP32.
11571 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
11572 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
11573 type_may_be_null(dst_reg->type)) {
11574 /* Mark all identical registers in each branch as either
11575 * safe or unknown depending R == 0 or R != 0 conditional.
11577 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
11578 opcode == BPF_JNE);
11579 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
11580 opcode == BPF_JEQ);
11581 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
11582 this_branch, other_branch) &&
11583 is_pointer_value(env, insn->dst_reg)) {
11584 verbose(env, "R%d pointer comparison prohibited\n",
11588 if (env->log.level & BPF_LOG_LEVEL)
11589 print_insn_state(env, this_branch->frame[this_branch->curframe]);
11593 /* verify BPF_LD_IMM64 instruction */
11594 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
11596 struct bpf_insn_aux_data *aux = cur_aux(env);
11597 struct bpf_reg_state *regs = cur_regs(env);
11598 struct bpf_reg_state *dst_reg;
11599 struct bpf_map *map;
11602 if (BPF_SIZE(insn->code) != BPF_DW) {
11603 verbose(env, "invalid BPF_LD_IMM insn\n");
11606 if (insn->off != 0) {
11607 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
11611 err = check_reg_arg(env, insn->dst_reg, DST_OP);
11615 dst_reg = ®s[insn->dst_reg];
11616 if (insn->src_reg == 0) {
11617 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
11619 dst_reg->type = SCALAR_VALUE;
11620 __mark_reg_known(®s[insn->dst_reg], imm);
11624 /* All special src_reg cases are listed below. From this point onwards
11625 * we either succeed and assign a corresponding dst_reg->type after
11626 * zeroing the offset, or fail and reject the program.
11628 mark_reg_known_zero(env, regs, insn->dst_reg);
11630 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
11631 dst_reg->type = aux->btf_var.reg_type;
11632 switch (base_type(dst_reg->type)) {
11634 dst_reg->mem_size = aux->btf_var.mem_size;
11636 case PTR_TO_BTF_ID:
11637 dst_reg->btf = aux->btf_var.btf;
11638 dst_reg->btf_id = aux->btf_var.btf_id;
11641 verbose(env, "bpf verifier is misconfigured\n");
11647 if (insn->src_reg == BPF_PSEUDO_FUNC) {
11648 struct bpf_prog_aux *aux = env->prog->aux;
11649 u32 subprogno = find_subprog(env,
11650 env->insn_idx + insn->imm + 1);
11652 if (!aux->func_info) {
11653 verbose(env, "missing btf func_info\n");
11656 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
11657 verbose(env, "callback function not static\n");
11661 dst_reg->type = PTR_TO_FUNC;
11662 dst_reg->subprogno = subprogno;
11666 map = env->used_maps[aux->map_index];
11667 dst_reg->map_ptr = map;
11669 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
11670 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
11671 dst_reg->type = PTR_TO_MAP_VALUE;
11672 dst_reg->off = aux->map_off;
11673 WARN_ON_ONCE(map->max_entries != 1);
11674 /* We want reg->id to be same (0) as map_value is not distinct */
11675 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
11676 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
11677 dst_reg->type = CONST_PTR_TO_MAP;
11679 verbose(env, "bpf verifier is misconfigured\n");
11686 static bool may_access_skb(enum bpf_prog_type type)
11689 case BPF_PROG_TYPE_SOCKET_FILTER:
11690 case BPF_PROG_TYPE_SCHED_CLS:
11691 case BPF_PROG_TYPE_SCHED_ACT:
11698 /* verify safety of LD_ABS|LD_IND instructions:
11699 * - they can only appear in the programs where ctx == skb
11700 * - since they are wrappers of function calls, they scratch R1-R5 registers,
11701 * preserve R6-R9, and store return value into R0
11704 * ctx == skb == R6 == CTX
11707 * SRC == any register
11708 * IMM == 32-bit immediate
11711 * R0 - 8/16/32-bit skb data converted to cpu endianness
11713 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
11715 struct bpf_reg_state *regs = cur_regs(env);
11716 static const int ctx_reg = BPF_REG_6;
11717 u8 mode = BPF_MODE(insn->code);
11720 if (!may_access_skb(resolve_prog_type(env->prog))) {
11721 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
11725 if (!env->ops->gen_ld_abs) {
11726 verbose(env, "bpf verifier is misconfigured\n");
11730 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
11731 BPF_SIZE(insn->code) == BPF_DW ||
11732 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
11733 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
11737 /* check whether implicit source operand (register R6) is readable */
11738 err = check_reg_arg(env, ctx_reg, SRC_OP);
11742 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
11743 * gen_ld_abs() may terminate the program at runtime, leading to
11746 err = check_reference_leak(env);
11748 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
11752 if (env->cur_state->active_lock.ptr) {
11753 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
11757 if (regs[ctx_reg].type != PTR_TO_CTX) {
11759 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
11763 if (mode == BPF_IND) {
11764 /* check explicit source operand */
11765 err = check_reg_arg(env, insn->src_reg, SRC_OP);
11770 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
11774 /* reset caller saved regs to unreadable */
11775 for (i = 0; i < CALLER_SAVED_REGS; i++) {
11776 mark_reg_not_init(env, regs, caller_saved[i]);
11777 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11780 /* mark destination R0 register as readable, since it contains
11781 * the value fetched from the packet.
11782 * Already marked as written above.
11784 mark_reg_unknown(env, regs, BPF_REG_0);
11785 /* ld_abs load up to 32-bit skb data. */
11786 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
11790 static int check_return_code(struct bpf_verifier_env *env)
11792 struct tnum enforce_attach_type_range = tnum_unknown;
11793 const struct bpf_prog *prog = env->prog;
11794 struct bpf_reg_state *reg;
11795 struct tnum range = tnum_range(0, 1);
11796 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11798 struct bpf_func_state *frame = env->cur_state->frame[0];
11799 const bool is_subprog = frame->subprogno;
11801 /* LSM and struct_ops func-ptr's return type could be "void" */
11803 switch (prog_type) {
11804 case BPF_PROG_TYPE_LSM:
11805 if (prog->expected_attach_type == BPF_LSM_CGROUP)
11806 /* See below, can be 0 or 0-1 depending on hook. */
11809 case BPF_PROG_TYPE_STRUCT_OPS:
11810 if (!prog->aux->attach_func_proto->type)
11818 /* eBPF calling convention is such that R0 is used
11819 * to return the value from eBPF program.
11820 * Make sure that it's readable at this time
11821 * of bpf_exit, which means that program wrote
11822 * something into it earlier
11824 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
11828 if (is_pointer_value(env, BPF_REG_0)) {
11829 verbose(env, "R0 leaks addr as return value\n");
11833 reg = cur_regs(env) + BPF_REG_0;
11835 if (frame->in_async_callback_fn) {
11836 /* enforce return zero from async callbacks like timer */
11837 if (reg->type != SCALAR_VALUE) {
11838 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
11839 reg_type_str(env, reg->type));
11843 if (!tnum_in(tnum_const(0), reg->var_off)) {
11844 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
11851 if (reg->type != SCALAR_VALUE) {
11852 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
11853 reg_type_str(env, reg->type));
11859 switch (prog_type) {
11860 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
11861 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
11862 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
11863 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
11864 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
11865 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
11866 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
11867 range = tnum_range(1, 1);
11868 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
11869 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
11870 range = tnum_range(0, 3);
11872 case BPF_PROG_TYPE_CGROUP_SKB:
11873 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
11874 range = tnum_range(0, 3);
11875 enforce_attach_type_range = tnum_range(2, 3);
11878 case BPF_PROG_TYPE_CGROUP_SOCK:
11879 case BPF_PROG_TYPE_SOCK_OPS:
11880 case BPF_PROG_TYPE_CGROUP_DEVICE:
11881 case BPF_PROG_TYPE_CGROUP_SYSCTL:
11882 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
11884 case BPF_PROG_TYPE_RAW_TRACEPOINT:
11885 if (!env->prog->aux->attach_btf_id)
11887 range = tnum_const(0);
11889 case BPF_PROG_TYPE_TRACING:
11890 switch (env->prog->expected_attach_type) {
11891 case BPF_TRACE_FENTRY:
11892 case BPF_TRACE_FEXIT:
11893 range = tnum_const(0);
11895 case BPF_TRACE_RAW_TP:
11896 case BPF_MODIFY_RETURN:
11898 case BPF_TRACE_ITER:
11904 case BPF_PROG_TYPE_SK_LOOKUP:
11905 range = tnum_range(SK_DROP, SK_PASS);
11908 case BPF_PROG_TYPE_LSM:
11909 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
11910 /* Regular BPF_PROG_TYPE_LSM programs can return
11915 if (!env->prog->aux->attach_func_proto->type) {
11916 /* Make sure programs that attach to void
11917 * hooks don't try to modify return value.
11919 range = tnum_range(1, 1);
11923 case BPF_PROG_TYPE_EXT:
11924 /* freplace program can return anything as its return value
11925 * depends on the to-be-replaced kernel func or bpf program.
11931 if (reg->type != SCALAR_VALUE) {
11932 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
11933 reg_type_str(env, reg->type));
11937 if (!tnum_in(range, reg->var_off)) {
11938 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
11939 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
11940 prog_type == BPF_PROG_TYPE_LSM &&
11941 !prog->aux->attach_func_proto->type)
11942 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11946 if (!tnum_is_unknown(enforce_attach_type_range) &&
11947 tnum_in(enforce_attach_type_range, reg->var_off))
11948 env->prog->enforce_expected_attach_type = 1;
11952 /* non-recursive DFS pseudo code
11953 * 1 procedure DFS-iterative(G,v):
11954 * 2 label v as discovered
11955 * 3 let S be a stack
11957 * 5 while S is not empty
11959 * 7 if t is what we're looking for:
11961 * 9 for all edges e in G.adjacentEdges(t) do
11962 * 10 if edge e is already labelled
11963 * 11 continue with the next edge
11964 * 12 w <- G.adjacentVertex(t,e)
11965 * 13 if vertex w is not discovered and not explored
11966 * 14 label e as tree-edge
11967 * 15 label w as discovered
11970 * 18 else if vertex w is discovered
11971 * 19 label e as back-edge
11973 * 21 // vertex w is explored
11974 * 22 label e as forward- or cross-edge
11975 * 23 label t as explored
11979 * 0x10 - discovered
11980 * 0x11 - discovered and fall-through edge labelled
11981 * 0x12 - discovered and fall-through and branch edges labelled
11992 static u32 state_htab_size(struct bpf_verifier_env *env)
11994 return env->prog->len;
11997 static struct bpf_verifier_state_list **explored_state(
11998 struct bpf_verifier_env *env,
12001 struct bpf_verifier_state *cur = env->cur_state;
12002 struct bpf_func_state *state = cur->frame[cur->curframe];
12004 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
12007 static void init_explored_state(struct bpf_verifier_env *env, int idx)
12009 env->insn_aux_data[idx].prune_point = true;
12013 DONE_EXPLORING = 0,
12014 KEEP_EXPLORING = 1,
12017 /* t, w, e - match pseudo-code above:
12018 * t - index of current instruction
12019 * w - next instruction
12022 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
12025 int *insn_stack = env->cfg.insn_stack;
12026 int *insn_state = env->cfg.insn_state;
12028 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
12029 return DONE_EXPLORING;
12031 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
12032 return DONE_EXPLORING;
12034 if (w < 0 || w >= env->prog->len) {
12035 verbose_linfo(env, t, "%d: ", t);
12036 verbose(env, "jump out of range from insn %d to %d\n", t, w);
12041 /* mark branch target for state pruning */
12042 init_explored_state(env, w);
12044 if (insn_state[w] == 0) {
12046 insn_state[t] = DISCOVERED | e;
12047 insn_state[w] = DISCOVERED;
12048 if (env->cfg.cur_stack >= env->prog->len)
12050 insn_stack[env->cfg.cur_stack++] = w;
12051 return KEEP_EXPLORING;
12052 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
12053 if (loop_ok && env->bpf_capable)
12054 return DONE_EXPLORING;
12055 verbose_linfo(env, t, "%d: ", t);
12056 verbose_linfo(env, w, "%d: ", w);
12057 verbose(env, "back-edge from insn %d to %d\n", t, w);
12059 } else if (insn_state[w] == EXPLORED) {
12060 /* forward- or cross-edge */
12061 insn_state[t] = DISCOVERED | e;
12063 verbose(env, "insn state internal bug\n");
12066 return DONE_EXPLORING;
12069 static int visit_func_call_insn(int t, int insn_cnt,
12070 struct bpf_insn *insns,
12071 struct bpf_verifier_env *env,
12076 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
12080 if (t + 1 < insn_cnt)
12081 init_explored_state(env, t + 1);
12082 if (visit_callee) {
12083 init_explored_state(env, t);
12084 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
12085 /* It's ok to allow recursion from CFG point of
12086 * view. __check_func_call() will do the actual
12089 bpf_pseudo_func(insns + t));
12094 /* Visits the instruction at index t and returns one of the following:
12095 * < 0 - an error occurred
12096 * DONE_EXPLORING - the instruction was fully explored
12097 * KEEP_EXPLORING - there is still work to be done before it is fully explored
12099 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
12101 struct bpf_insn *insns = env->prog->insnsi;
12104 if (bpf_pseudo_func(insns + t))
12105 return visit_func_call_insn(t, insn_cnt, insns, env, true);
12107 /* All non-branch instructions have a single fall-through edge. */
12108 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
12109 BPF_CLASS(insns[t].code) != BPF_JMP32)
12110 return push_insn(t, t + 1, FALLTHROUGH, env, false);
12112 switch (BPF_OP(insns[t].code)) {
12114 return DONE_EXPLORING;
12117 if (insns[t].imm == BPF_FUNC_timer_set_callback)
12118 /* Mark this call insn to trigger is_state_visited() check
12119 * before call itself is processed by __check_func_call().
12120 * Otherwise new async state will be pushed for further
12123 init_explored_state(env, t);
12124 return visit_func_call_insn(t, insn_cnt, insns, env,
12125 insns[t].src_reg == BPF_PSEUDO_CALL);
12128 if (BPF_SRC(insns[t].code) != BPF_K)
12131 /* unconditional jump with single edge */
12132 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
12137 /* unconditional jmp is not a good pruning point,
12138 * but it's marked, since backtracking needs
12139 * to record jmp history in is_state_visited().
12141 init_explored_state(env, t + insns[t].off + 1);
12142 /* tell verifier to check for equivalent states
12143 * after every call and jump
12145 if (t + 1 < insn_cnt)
12146 init_explored_state(env, t + 1);
12151 /* conditional jump with two edges */
12152 init_explored_state(env, t);
12153 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
12157 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
12161 /* non-recursive depth-first-search to detect loops in BPF program
12162 * loop == back-edge in directed graph
12164 static int check_cfg(struct bpf_verifier_env *env)
12166 int insn_cnt = env->prog->len;
12167 int *insn_stack, *insn_state;
12171 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12175 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12177 kvfree(insn_state);
12181 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
12182 insn_stack[0] = 0; /* 0 is the first instruction */
12183 env->cfg.cur_stack = 1;
12185 while (env->cfg.cur_stack > 0) {
12186 int t = insn_stack[env->cfg.cur_stack - 1];
12188 ret = visit_insn(t, insn_cnt, env);
12190 case DONE_EXPLORING:
12191 insn_state[t] = EXPLORED;
12192 env->cfg.cur_stack--;
12194 case KEEP_EXPLORING:
12198 verbose(env, "visit_insn internal bug\n");
12205 if (env->cfg.cur_stack < 0) {
12206 verbose(env, "pop stack internal bug\n");
12211 for (i = 0; i < insn_cnt; i++) {
12212 if (insn_state[i] != EXPLORED) {
12213 verbose(env, "unreachable insn %d\n", i);
12218 ret = 0; /* cfg looks good */
12221 kvfree(insn_state);
12222 kvfree(insn_stack);
12223 env->cfg.insn_state = env->cfg.insn_stack = NULL;
12227 static int check_abnormal_return(struct bpf_verifier_env *env)
12231 for (i = 1; i < env->subprog_cnt; i++) {
12232 if (env->subprog_info[i].has_ld_abs) {
12233 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
12236 if (env->subprog_info[i].has_tail_call) {
12237 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
12244 /* The minimum supported BTF func info size */
12245 #define MIN_BPF_FUNCINFO_SIZE 8
12246 #define MAX_FUNCINFO_REC_SIZE 252
12248 static int check_btf_func(struct bpf_verifier_env *env,
12249 const union bpf_attr *attr,
12252 const struct btf_type *type, *func_proto, *ret_type;
12253 u32 i, nfuncs, urec_size, min_size;
12254 u32 krec_size = sizeof(struct bpf_func_info);
12255 struct bpf_func_info *krecord;
12256 struct bpf_func_info_aux *info_aux = NULL;
12257 struct bpf_prog *prog;
12258 const struct btf *btf;
12260 u32 prev_offset = 0;
12261 bool scalar_return;
12264 nfuncs = attr->func_info_cnt;
12266 if (check_abnormal_return(env))
12271 if (nfuncs != env->subprog_cnt) {
12272 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
12276 urec_size = attr->func_info_rec_size;
12277 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
12278 urec_size > MAX_FUNCINFO_REC_SIZE ||
12279 urec_size % sizeof(u32)) {
12280 verbose(env, "invalid func info rec size %u\n", urec_size);
12285 btf = prog->aux->btf;
12287 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
12288 min_size = min_t(u32, krec_size, urec_size);
12290 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
12293 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
12297 for (i = 0; i < nfuncs; i++) {
12298 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
12300 if (ret == -E2BIG) {
12301 verbose(env, "nonzero tailing record in func info");
12302 /* set the size kernel expects so loader can zero
12303 * out the rest of the record.
12305 if (copy_to_bpfptr_offset(uattr,
12306 offsetof(union bpf_attr, func_info_rec_size),
12307 &min_size, sizeof(min_size)))
12313 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
12318 /* check insn_off */
12321 if (krecord[i].insn_off) {
12323 "nonzero insn_off %u for the first func info record",
12324 krecord[i].insn_off);
12327 } else if (krecord[i].insn_off <= prev_offset) {
12329 "same or smaller insn offset (%u) than previous func info record (%u)",
12330 krecord[i].insn_off, prev_offset);
12334 if (env->subprog_info[i].start != krecord[i].insn_off) {
12335 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
12339 /* check type_id */
12340 type = btf_type_by_id(btf, krecord[i].type_id);
12341 if (!type || !btf_type_is_func(type)) {
12342 verbose(env, "invalid type id %d in func info",
12343 krecord[i].type_id);
12346 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
12348 func_proto = btf_type_by_id(btf, type->type);
12349 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
12350 /* btf_func_check() already verified it during BTF load */
12352 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
12354 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
12355 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
12356 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
12359 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
12360 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
12364 prev_offset = krecord[i].insn_off;
12365 bpfptr_add(&urecord, urec_size);
12368 prog->aux->func_info = krecord;
12369 prog->aux->func_info_cnt = nfuncs;
12370 prog->aux->func_info_aux = info_aux;
12379 static void adjust_btf_func(struct bpf_verifier_env *env)
12381 struct bpf_prog_aux *aux = env->prog->aux;
12384 if (!aux->func_info)
12387 for (i = 0; i < env->subprog_cnt; i++)
12388 aux->func_info[i].insn_off = env->subprog_info[i].start;
12391 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
12392 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
12394 static int check_btf_line(struct bpf_verifier_env *env,
12395 const union bpf_attr *attr,
12398 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
12399 struct bpf_subprog_info *sub;
12400 struct bpf_line_info *linfo;
12401 struct bpf_prog *prog;
12402 const struct btf *btf;
12406 nr_linfo = attr->line_info_cnt;
12409 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
12412 rec_size = attr->line_info_rec_size;
12413 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
12414 rec_size > MAX_LINEINFO_REC_SIZE ||
12415 rec_size & (sizeof(u32) - 1))
12418 /* Need to zero it in case the userspace may
12419 * pass in a smaller bpf_line_info object.
12421 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
12422 GFP_KERNEL | __GFP_NOWARN);
12427 btf = prog->aux->btf;
12430 sub = env->subprog_info;
12431 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
12432 expected_size = sizeof(struct bpf_line_info);
12433 ncopy = min_t(u32, expected_size, rec_size);
12434 for (i = 0; i < nr_linfo; i++) {
12435 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
12437 if (err == -E2BIG) {
12438 verbose(env, "nonzero tailing record in line_info");
12439 if (copy_to_bpfptr_offset(uattr,
12440 offsetof(union bpf_attr, line_info_rec_size),
12441 &expected_size, sizeof(expected_size)))
12447 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
12453 * Check insn_off to ensure
12454 * 1) strictly increasing AND
12455 * 2) bounded by prog->len
12457 * The linfo[0].insn_off == 0 check logically falls into
12458 * the later "missing bpf_line_info for func..." case
12459 * because the first linfo[0].insn_off must be the
12460 * first sub also and the first sub must have
12461 * subprog_info[0].start == 0.
12463 if ((i && linfo[i].insn_off <= prev_offset) ||
12464 linfo[i].insn_off >= prog->len) {
12465 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
12466 i, linfo[i].insn_off, prev_offset,
12472 if (!prog->insnsi[linfo[i].insn_off].code) {
12474 "Invalid insn code at line_info[%u].insn_off\n",
12480 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
12481 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
12482 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
12487 if (s != env->subprog_cnt) {
12488 if (linfo[i].insn_off == sub[s].start) {
12489 sub[s].linfo_idx = i;
12491 } else if (sub[s].start < linfo[i].insn_off) {
12492 verbose(env, "missing bpf_line_info for func#%u\n", s);
12498 prev_offset = linfo[i].insn_off;
12499 bpfptr_add(&ulinfo, rec_size);
12502 if (s != env->subprog_cnt) {
12503 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
12504 env->subprog_cnt - s, s);
12509 prog->aux->linfo = linfo;
12510 prog->aux->nr_linfo = nr_linfo;
12519 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
12520 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
12522 static int check_core_relo(struct bpf_verifier_env *env,
12523 const union bpf_attr *attr,
12526 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
12527 struct bpf_core_relo core_relo = {};
12528 struct bpf_prog *prog = env->prog;
12529 const struct btf *btf = prog->aux->btf;
12530 struct bpf_core_ctx ctx = {
12534 bpfptr_t u_core_relo;
12537 nr_core_relo = attr->core_relo_cnt;
12540 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
12543 rec_size = attr->core_relo_rec_size;
12544 if (rec_size < MIN_CORE_RELO_SIZE ||
12545 rec_size > MAX_CORE_RELO_SIZE ||
12546 rec_size % sizeof(u32))
12549 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
12550 expected_size = sizeof(struct bpf_core_relo);
12551 ncopy = min_t(u32, expected_size, rec_size);
12553 /* Unlike func_info and line_info, copy and apply each CO-RE
12554 * relocation record one at a time.
12556 for (i = 0; i < nr_core_relo; i++) {
12557 /* future proofing when sizeof(bpf_core_relo) changes */
12558 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
12560 if (err == -E2BIG) {
12561 verbose(env, "nonzero tailing record in core_relo");
12562 if (copy_to_bpfptr_offset(uattr,
12563 offsetof(union bpf_attr, core_relo_rec_size),
12564 &expected_size, sizeof(expected_size)))
12570 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
12575 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
12576 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
12577 i, core_relo.insn_off, prog->len);
12582 err = bpf_core_apply(&ctx, &core_relo, i,
12583 &prog->insnsi[core_relo.insn_off / 8]);
12586 bpfptr_add(&u_core_relo, rec_size);
12591 static int check_btf_info(struct bpf_verifier_env *env,
12592 const union bpf_attr *attr,
12598 if (!attr->func_info_cnt && !attr->line_info_cnt) {
12599 if (check_abnormal_return(env))
12604 btf = btf_get_by_fd(attr->prog_btf_fd);
12606 return PTR_ERR(btf);
12607 if (btf_is_kernel(btf)) {
12611 env->prog->aux->btf = btf;
12613 err = check_btf_func(env, attr, uattr);
12617 err = check_btf_line(env, attr, uattr);
12621 err = check_core_relo(env, attr, uattr);
12628 /* check %cur's range satisfies %old's */
12629 static bool range_within(struct bpf_reg_state *old,
12630 struct bpf_reg_state *cur)
12632 return old->umin_value <= cur->umin_value &&
12633 old->umax_value >= cur->umax_value &&
12634 old->smin_value <= cur->smin_value &&
12635 old->smax_value >= cur->smax_value &&
12636 old->u32_min_value <= cur->u32_min_value &&
12637 old->u32_max_value >= cur->u32_max_value &&
12638 old->s32_min_value <= cur->s32_min_value &&
12639 old->s32_max_value >= cur->s32_max_value;
12642 /* If in the old state two registers had the same id, then they need to have
12643 * the same id in the new state as well. But that id could be different from
12644 * the old state, so we need to track the mapping from old to new ids.
12645 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
12646 * regs with old id 5 must also have new id 9 for the new state to be safe. But
12647 * regs with a different old id could still have new id 9, we don't care about
12649 * So we look through our idmap to see if this old id has been seen before. If
12650 * so, we require the new id to match; otherwise, we add the id pair to the map.
12652 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
12656 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
12657 if (!idmap[i].old) {
12658 /* Reached an empty slot; haven't seen this id before */
12659 idmap[i].old = old_id;
12660 idmap[i].cur = cur_id;
12663 if (idmap[i].old == old_id)
12664 return idmap[i].cur == cur_id;
12666 /* We ran out of idmap slots, which should be impossible */
12671 static void clean_func_state(struct bpf_verifier_env *env,
12672 struct bpf_func_state *st)
12674 enum bpf_reg_liveness live;
12677 for (i = 0; i < BPF_REG_FP; i++) {
12678 live = st->regs[i].live;
12679 /* liveness must not touch this register anymore */
12680 st->regs[i].live |= REG_LIVE_DONE;
12681 if (!(live & REG_LIVE_READ))
12682 /* since the register is unused, clear its state
12683 * to make further comparison simpler
12685 __mark_reg_not_init(env, &st->regs[i]);
12688 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
12689 live = st->stack[i].spilled_ptr.live;
12690 /* liveness must not touch this stack slot anymore */
12691 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
12692 if (!(live & REG_LIVE_READ)) {
12693 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
12694 for (j = 0; j < BPF_REG_SIZE; j++)
12695 st->stack[i].slot_type[j] = STACK_INVALID;
12700 static void clean_verifier_state(struct bpf_verifier_env *env,
12701 struct bpf_verifier_state *st)
12705 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
12706 /* all regs in this state in all frames were already marked */
12709 for (i = 0; i <= st->curframe; i++)
12710 clean_func_state(env, st->frame[i]);
12713 /* the parentage chains form a tree.
12714 * the verifier states are added to state lists at given insn and
12715 * pushed into state stack for future exploration.
12716 * when the verifier reaches bpf_exit insn some of the verifer states
12717 * stored in the state lists have their final liveness state already,
12718 * but a lot of states will get revised from liveness point of view when
12719 * the verifier explores other branches.
12722 * 2: if r1 == 100 goto pc+1
12725 * when the verifier reaches exit insn the register r0 in the state list of
12726 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
12727 * of insn 2 and goes exploring further. At the insn 4 it will walk the
12728 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
12730 * Since the verifier pushes the branch states as it sees them while exploring
12731 * the program the condition of walking the branch instruction for the second
12732 * time means that all states below this branch were already explored and
12733 * their final liveness marks are already propagated.
12734 * Hence when the verifier completes the search of state list in is_state_visited()
12735 * we can call this clean_live_states() function to mark all liveness states
12736 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
12737 * will not be used.
12738 * This function also clears the registers and stack for states that !READ
12739 * to simplify state merging.
12741 * Important note here that walking the same branch instruction in the callee
12742 * doesn't meant that the states are DONE. The verifier has to compare
12745 static void clean_live_states(struct bpf_verifier_env *env, int insn,
12746 struct bpf_verifier_state *cur)
12748 struct bpf_verifier_state_list *sl;
12751 sl = *explored_state(env, insn);
12753 if (sl->state.branches)
12755 if (sl->state.insn_idx != insn ||
12756 sl->state.curframe != cur->curframe)
12758 for (i = 0; i <= cur->curframe; i++)
12759 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
12761 clean_verifier_state(env, &sl->state);
12767 /* Returns true if (rold safe implies rcur safe) */
12768 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
12769 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
12773 if (!(rold->live & REG_LIVE_READ))
12774 /* explored state didn't use this */
12777 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
12779 if (rold->type == PTR_TO_STACK)
12780 /* two stack pointers are equal only if they're pointing to
12781 * the same stack frame, since fp-8 in foo != fp-8 in bar
12783 return equal && rold->frameno == rcur->frameno;
12788 if (rold->type == NOT_INIT)
12789 /* explored state can't have used this */
12791 if (rcur->type == NOT_INIT)
12793 switch (base_type(rold->type)) {
12795 if (env->explore_alu_limits)
12797 if (rcur->type == SCALAR_VALUE) {
12798 if (!rold->precise)
12800 /* new val must satisfy old val knowledge */
12801 return range_within(rold, rcur) &&
12802 tnum_in(rold->var_off, rcur->var_off);
12804 /* We're trying to use a pointer in place of a scalar.
12805 * Even if the scalar was unbounded, this could lead to
12806 * pointer leaks because scalars are allowed to leak
12807 * while pointers are not. We could make this safe in
12808 * special cases if root is calling us, but it's
12809 * probably not worth the hassle.
12813 case PTR_TO_MAP_KEY:
12814 case PTR_TO_MAP_VALUE:
12815 /* a PTR_TO_MAP_VALUE could be safe to use as a
12816 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
12817 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
12818 * checked, doing so could have affected others with the same
12819 * id, and we can't check for that because we lost the id when
12820 * we converted to a PTR_TO_MAP_VALUE.
12822 if (type_may_be_null(rold->type)) {
12823 if (!type_may_be_null(rcur->type))
12825 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
12827 /* Check our ids match any regs they're supposed to */
12828 return check_ids(rold->id, rcur->id, idmap);
12831 /* If the new min/max/var_off satisfy the old ones and
12832 * everything else matches, we are OK.
12833 * 'id' is not compared, since it's only used for maps with
12834 * bpf_spin_lock inside map element and in such cases if
12835 * the rest of the prog is valid for one map element then
12836 * it's valid for all map elements regardless of the key
12837 * used in bpf_map_lookup()
12839 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
12840 range_within(rold, rcur) &&
12841 tnum_in(rold->var_off, rcur->var_off);
12842 case PTR_TO_PACKET_META:
12843 case PTR_TO_PACKET:
12844 if (rcur->type != rold->type)
12846 /* We must have at least as much range as the old ptr
12847 * did, so that any accesses which were safe before are
12848 * still safe. This is true even if old range < old off,
12849 * since someone could have accessed through (ptr - k), or
12850 * even done ptr -= k in a register, to get a safe access.
12852 if (rold->range > rcur->range)
12854 /* If the offsets don't match, we can't trust our alignment;
12855 * nor can we be sure that we won't fall out of range.
12857 if (rold->off != rcur->off)
12859 /* id relations must be preserved */
12860 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
12862 /* new val must satisfy old val knowledge */
12863 return range_within(rold, rcur) &&
12864 tnum_in(rold->var_off, rcur->var_off);
12866 case CONST_PTR_TO_MAP:
12867 case PTR_TO_PACKET_END:
12868 case PTR_TO_FLOW_KEYS:
12869 case PTR_TO_SOCKET:
12870 case PTR_TO_SOCK_COMMON:
12871 case PTR_TO_TCP_SOCK:
12872 case PTR_TO_XDP_SOCK:
12873 /* Only valid matches are exact, which memcmp() above
12874 * would have accepted
12877 /* Don't know what's going on, just say it's not safe */
12881 /* Shouldn't get here; if we do, say it's not safe */
12886 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
12887 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
12891 /* walk slots of the explored stack and ignore any additional
12892 * slots in the current stack, since explored(safe) state
12895 for (i = 0; i < old->allocated_stack; i++) {
12896 spi = i / BPF_REG_SIZE;
12898 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
12899 i += BPF_REG_SIZE - 1;
12900 /* explored state didn't use this */
12904 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
12907 /* explored stack has more populated slots than current stack
12908 * and these slots were used
12910 if (i >= cur->allocated_stack)
12913 /* if old state was safe with misc data in the stack
12914 * it will be safe with zero-initialized stack.
12915 * The opposite is not true
12917 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
12918 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
12920 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
12921 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
12922 /* Ex: old explored (safe) state has STACK_SPILL in
12923 * this stack slot, but current has STACK_MISC ->
12924 * this verifier states are not equivalent,
12925 * return false to continue verification of this path
12928 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
12930 if (!is_spilled_reg(&old->stack[spi]))
12932 if (!regsafe(env, &old->stack[spi].spilled_ptr,
12933 &cur->stack[spi].spilled_ptr, idmap))
12934 /* when explored and current stack slot are both storing
12935 * spilled registers, check that stored pointers types
12936 * are the same as well.
12937 * Ex: explored safe path could have stored
12938 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
12939 * but current path has stored:
12940 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
12941 * such verifier states are not equivalent.
12942 * return false to continue verification of this path
12949 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
12951 if (old->acquired_refs != cur->acquired_refs)
12953 return !memcmp(old->refs, cur->refs,
12954 sizeof(*old->refs) * old->acquired_refs);
12957 /* compare two verifier states
12959 * all states stored in state_list are known to be valid, since
12960 * verifier reached 'bpf_exit' instruction through them
12962 * this function is called when verifier exploring different branches of
12963 * execution popped from the state stack. If it sees an old state that has
12964 * more strict register state and more strict stack state then this execution
12965 * branch doesn't need to be explored further, since verifier already
12966 * concluded that more strict state leads to valid finish.
12968 * Therefore two states are equivalent if register state is more conservative
12969 * and explored stack state is more conservative than the current one.
12972 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
12973 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
12975 * In other words if current stack state (one being explored) has more
12976 * valid slots than old one that already passed validation, it means
12977 * the verifier can stop exploring and conclude that current state is valid too
12979 * Similarly with registers. If explored state has register type as invalid
12980 * whereas register type in current state is meaningful, it means that
12981 * the current state will reach 'bpf_exit' instruction safely
12983 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
12984 struct bpf_func_state *cur)
12988 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
12989 for (i = 0; i < MAX_BPF_REG; i++)
12990 if (!regsafe(env, &old->regs[i], &cur->regs[i],
12991 env->idmap_scratch))
12994 if (!stacksafe(env, old, cur, env->idmap_scratch))
12997 if (!refsafe(old, cur))
13003 static bool states_equal(struct bpf_verifier_env *env,
13004 struct bpf_verifier_state *old,
13005 struct bpf_verifier_state *cur)
13009 if (old->curframe != cur->curframe)
13012 /* Verification state from speculative execution simulation
13013 * must never prune a non-speculative execution one.
13015 if (old->speculative && !cur->speculative)
13018 if (old->active_lock.ptr != cur->active_lock.ptr ||
13019 old->active_lock.id != cur->active_lock.id)
13022 /* for states to be equal callsites have to be the same
13023 * and all frame states need to be equivalent
13025 for (i = 0; i <= old->curframe; i++) {
13026 if (old->frame[i]->callsite != cur->frame[i]->callsite)
13028 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
13034 /* Return 0 if no propagation happened. Return negative error code if error
13035 * happened. Otherwise, return the propagated bit.
13037 static int propagate_liveness_reg(struct bpf_verifier_env *env,
13038 struct bpf_reg_state *reg,
13039 struct bpf_reg_state *parent_reg)
13041 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
13042 u8 flag = reg->live & REG_LIVE_READ;
13045 /* When comes here, read flags of PARENT_REG or REG could be any of
13046 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
13047 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
13049 if (parent_flag == REG_LIVE_READ64 ||
13050 /* Or if there is no read flag from REG. */
13052 /* Or if the read flag from REG is the same as PARENT_REG. */
13053 parent_flag == flag)
13056 err = mark_reg_read(env, reg, parent_reg, flag);
13063 /* A write screens off any subsequent reads; but write marks come from the
13064 * straight-line code between a state and its parent. When we arrive at an
13065 * equivalent state (jump target or such) we didn't arrive by the straight-line
13066 * code, so read marks in the state must propagate to the parent regardless
13067 * of the state's write marks. That's what 'parent == state->parent' comparison
13068 * in mark_reg_read() is for.
13070 static int propagate_liveness(struct bpf_verifier_env *env,
13071 const struct bpf_verifier_state *vstate,
13072 struct bpf_verifier_state *vparent)
13074 struct bpf_reg_state *state_reg, *parent_reg;
13075 struct bpf_func_state *state, *parent;
13076 int i, frame, err = 0;
13078 if (vparent->curframe != vstate->curframe) {
13079 WARN(1, "propagate_live: parent frame %d current frame %d\n",
13080 vparent->curframe, vstate->curframe);
13083 /* Propagate read liveness of registers... */
13084 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
13085 for (frame = 0; frame <= vstate->curframe; frame++) {
13086 parent = vparent->frame[frame];
13087 state = vstate->frame[frame];
13088 parent_reg = parent->regs;
13089 state_reg = state->regs;
13090 /* We don't need to worry about FP liveness, it's read-only */
13091 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
13092 err = propagate_liveness_reg(env, &state_reg[i],
13096 if (err == REG_LIVE_READ64)
13097 mark_insn_zext(env, &parent_reg[i]);
13100 /* Propagate stack slots. */
13101 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
13102 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
13103 parent_reg = &parent->stack[i].spilled_ptr;
13104 state_reg = &state->stack[i].spilled_ptr;
13105 err = propagate_liveness_reg(env, state_reg,
13114 /* find precise scalars in the previous equivalent state and
13115 * propagate them into the current state
13117 static int propagate_precision(struct bpf_verifier_env *env,
13118 const struct bpf_verifier_state *old)
13120 struct bpf_reg_state *state_reg;
13121 struct bpf_func_state *state;
13122 int i, err = 0, fr;
13124 for (fr = old->curframe; fr >= 0; fr--) {
13125 state = old->frame[fr];
13126 state_reg = state->regs;
13127 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
13128 if (state_reg->type != SCALAR_VALUE ||
13129 !state_reg->precise)
13131 if (env->log.level & BPF_LOG_LEVEL2)
13132 verbose(env, "frame %d: propagating r%d\n", i, fr);
13133 err = mark_chain_precision_frame(env, fr, i);
13138 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
13139 if (!is_spilled_reg(&state->stack[i]))
13141 state_reg = &state->stack[i].spilled_ptr;
13142 if (state_reg->type != SCALAR_VALUE ||
13143 !state_reg->precise)
13145 if (env->log.level & BPF_LOG_LEVEL2)
13146 verbose(env, "frame %d: propagating fp%d\n",
13147 (-i - 1) * BPF_REG_SIZE, fr);
13148 err = mark_chain_precision_stack_frame(env, fr, i);
13156 static bool states_maybe_looping(struct bpf_verifier_state *old,
13157 struct bpf_verifier_state *cur)
13159 struct bpf_func_state *fold, *fcur;
13160 int i, fr = cur->curframe;
13162 if (old->curframe != fr)
13165 fold = old->frame[fr];
13166 fcur = cur->frame[fr];
13167 for (i = 0; i < MAX_BPF_REG; i++)
13168 if (memcmp(&fold->regs[i], &fcur->regs[i],
13169 offsetof(struct bpf_reg_state, parent)))
13175 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
13177 struct bpf_verifier_state_list *new_sl;
13178 struct bpf_verifier_state_list *sl, **pprev;
13179 struct bpf_verifier_state *cur = env->cur_state, *new;
13180 int i, j, err, states_cnt = 0;
13181 bool add_new_state = env->test_state_freq ? true : false;
13183 cur->last_insn_idx = env->prev_insn_idx;
13184 if (!env->insn_aux_data[insn_idx].prune_point)
13185 /* this 'insn_idx' instruction wasn't marked, so we will not
13186 * be doing state search here
13190 /* bpf progs typically have pruning point every 4 instructions
13191 * http://vger.kernel.org/bpfconf2019.html#session-1
13192 * Do not add new state for future pruning if the verifier hasn't seen
13193 * at least 2 jumps and at least 8 instructions.
13194 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
13195 * In tests that amounts to up to 50% reduction into total verifier
13196 * memory consumption and 20% verifier time speedup.
13198 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
13199 env->insn_processed - env->prev_insn_processed >= 8)
13200 add_new_state = true;
13202 pprev = explored_state(env, insn_idx);
13205 clean_live_states(env, insn_idx, cur);
13209 if (sl->state.insn_idx != insn_idx)
13212 if (sl->state.branches) {
13213 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
13215 if (frame->in_async_callback_fn &&
13216 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
13217 /* Different async_entry_cnt means that the verifier is
13218 * processing another entry into async callback.
13219 * Seeing the same state is not an indication of infinite
13220 * loop or infinite recursion.
13221 * But finding the same state doesn't mean that it's safe
13222 * to stop processing the current state. The previous state
13223 * hasn't yet reached bpf_exit, since state.branches > 0.
13224 * Checking in_async_callback_fn alone is not enough either.
13225 * Since the verifier still needs to catch infinite loops
13226 * inside async callbacks.
13228 } else if (states_maybe_looping(&sl->state, cur) &&
13229 states_equal(env, &sl->state, cur)) {
13230 verbose_linfo(env, insn_idx, "; ");
13231 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
13234 /* if the verifier is processing a loop, avoid adding new state
13235 * too often, since different loop iterations have distinct
13236 * states and may not help future pruning.
13237 * This threshold shouldn't be too low to make sure that
13238 * a loop with large bound will be rejected quickly.
13239 * The most abusive loop will be:
13241 * if r1 < 1000000 goto pc-2
13242 * 1M insn_procssed limit / 100 == 10k peak states.
13243 * This threshold shouldn't be too high either, since states
13244 * at the end of the loop are likely to be useful in pruning.
13246 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
13247 env->insn_processed - env->prev_insn_processed < 100)
13248 add_new_state = false;
13251 if (states_equal(env, &sl->state, cur)) {
13253 /* reached equivalent register/stack state,
13254 * prune the search.
13255 * Registers read by the continuation are read by us.
13256 * If we have any write marks in env->cur_state, they
13257 * will prevent corresponding reads in the continuation
13258 * from reaching our parent (an explored_state). Our
13259 * own state will get the read marks recorded, but
13260 * they'll be immediately forgotten as we're pruning
13261 * this state and will pop a new one.
13263 err = propagate_liveness(env, &sl->state, cur);
13265 /* if previous state reached the exit with precision and
13266 * current state is equivalent to it (except precsion marks)
13267 * the precision needs to be propagated back in
13268 * the current state.
13270 err = err ? : push_jmp_history(env, cur);
13271 err = err ? : propagate_precision(env, &sl->state);
13277 /* when new state is not going to be added do not increase miss count.
13278 * Otherwise several loop iterations will remove the state
13279 * recorded earlier. The goal of these heuristics is to have
13280 * states from some iterations of the loop (some in the beginning
13281 * and some at the end) to help pruning.
13285 /* heuristic to determine whether this state is beneficial
13286 * to keep checking from state equivalence point of view.
13287 * Higher numbers increase max_states_per_insn and verification time,
13288 * but do not meaningfully decrease insn_processed.
13290 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
13291 /* the state is unlikely to be useful. Remove it to
13292 * speed up verification
13295 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
13296 u32 br = sl->state.branches;
13299 "BUG live_done but branches_to_explore %d\n",
13301 free_verifier_state(&sl->state, false);
13303 env->peak_states--;
13305 /* cannot free this state, since parentage chain may
13306 * walk it later. Add it for free_list instead to
13307 * be freed at the end of verification
13309 sl->next = env->free_list;
13310 env->free_list = sl;
13320 if (env->max_states_per_insn < states_cnt)
13321 env->max_states_per_insn = states_cnt;
13323 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
13324 return push_jmp_history(env, cur);
13326 if (!add_new_state)
13327 return push_jmp_history(env, cur);
13329 /* There were no equivalent states, remember the current one.
13330 * Technically the current state is not proven to be safe yet,
13331 * but it will either reach outer most bpf_exit (which means it's safe)
13332 * or it will be rejected. When there are no loops the verifier won't be
13333 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
13334 * again on the way to bpf_exit.
13335 * When looping the sl->state.branches will be > 0 and this state
13336 * will not be considered for equivalence until branches == 0.
13338 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
13341 env->total_states++;
13342 env->peak_states++;
13343 env->prev_jmps_processed = env->jmps_processed;
13344 env->prev_insn_processed = env->insn_processed;
13346 /* forget precise markings we inherited, see __mark_chain_precision */
13347 if (env->bpf_capable)
13348 mark_all_scalars_imprecise(env, cur);
13350 /* add new state to the head of linked list */
13351 new = &new_sl->state;
13352 err = copy_verifier_state(new, cur);
13354 free_verifier_state(new, false);
13358 new->insn_idx = insn_idx;
13359 WARN_ONCE(new->branches != 1,
13360 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
13363 cur->first_insn_idx = insn_idx;
13364 clear_jmp_history(cur);
13365 new_sl->next = *explored_state(env, insn_idx);
13366 *explored_state(env, insn_idx) = new_sl;
13367 /* connect new state to parentage chain. Current frame needs all
13368 * registers connected. Only r6 - r9 of the callers are alive (pushed
13369 * to the stack implicitly by JITs) so in callers' frames connect just
13370 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
13371 * the state of the call instruction (with WRITTEN set), and r0 comes
13372 * from callee with its full parentage chain, anyway.
13374 /* clear write marks in current state: the writes we did are not writes
13375 * our child did, so they don't screen off its reads from us.
13376 * (There are no read marks in current state, because reads always mark
13377 * their parent and current state never has children yet. Only
13378 * explored_states can get read marks.)
13380 for (j = 0; j <= cur->curframe; j++) {
13381 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
13382 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
13383 for (i = 0; i < BPF_REG_FP; i++)
13384 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
13387 /* all stack frames are accessible from callee, clear them all */
13388 for (j = 0; j <= cur->curframe; j++) {
13389 struct bpf_func_state *frame = cur->frame[j];
13390 struct bpf_func_state *newframe = new->frame[j];
13392 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
13393 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
13394 frame->stack[i].spilled_ptr.parent =
13395 &newframe->stack[i].spilled_ptr;
13401 /* Return true if it's OK to have the same insn return a different type. */
13402 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
13404 switch (base_type(type)) {
13406 case PTR_TO_SOCKET:
13407 case PTR_TO_SOCK_COMMON:
13408 case PTR_TO_TCP_SOCK:
13409 case PTR_TO_XDP_SOCK:
13410 case PTR_TO_BTF_ID:
13417 /* If an instruction was previously used with particular pointer types, then we
13418 * need to be careful to avoid cases such as the below, where it may be ok
13419 * for one branch accessing the pointer, but not ok for the other branch:
13424 * R1 = some_other_valid_ptr;
13427 * R2 = *(u32 *)(R1 + 0);
13429 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
13431 return src != prev && (!reg_type_mismatch_ok(src) ||
13432 !reg_type_mismatch_ok(prev));
13435 static int do_check(struct bpf_verifier_env *env)
13437 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13438 struct bpf_verifier_state *state = env->cur_state;
13439 struct bpf_insn *insns = env->prog->insnsi;
13440 struct bpf_reg_state *regs;
13441 int insn_cnt = env->prog->len;
13442 bool do_print_state = false;
13443 int prev_insn_idx = -1;
13446 struct bpf_insn *insn;
13450 env->prev_insn_idx = prev_insn_idx;
13451 if (env->insn_idx >= insn_cnt) {
13452 verbose(env, "invalid insn idx %d insn_cnt %d\n",
13453 env->insn_idx, insn_cnt);
13457 insn = &insns[env->insn_idx];
13458 class = BPF_CLASS(insn->code);
13460 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
13462 "BPF program is too large. Processed %d insn\n",
13463 env->insn_processed);
13467 err = is_state_visited(env, env->insn_idx);
13471 /* found equivalent state, can prune the search */
13472 if (env->log.level & BPF_LOG_LEVEL) {
13473 if (do_print_state)
13474 verbose(env, "\nfrom %d to %d%s: safe\n",
13475 env->prev_insn_idx, env->insn_idx,
13476 env->cur_state->speculative ?
13477 " (speculative execution)" : "");
13479 verbose(env, "%d: safe\n", env->insn_idx);
13481 goto process_bpf_exit;
13484 if (signal_pending(current))
13487 if (need_resched())
13490 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
13491 verbose(env, "\nfrom %d to %d%s:",
13492 env->prev_insn_idx, env->insn_idx,
13493 env->cur_state->speculative ?
13494 " (speculative execution)" : "");
13495 print_verifier_state(env, state->frame[state->curframe], true);
13496 do_print_state = false;
13499 if (env->log.level & BPF_LOG_LEVEL) {
13500 const struct bpf_insn_cbs cbs = {
13501 .cb_call = disasm_kfunc_name,
13502 .cb_print = verbose,
13503 .private_data = env,
13506 if (verifier_state_scratched(env))
13507 print_insn_state(env, state->frame[state->curframe]);
13509 verbose_linfo(env, env->insn_idx, "; ");
13510 env->prev_log_len = env->log.len_used;
13511 verbose(env, "%d: ", env->insn_idx);
13512 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
13513 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
13514 env->prev_log_len = env->log.len_used;
13517 if (bpf_prog_is_dev_bound(env->prog->aux)) {
13518 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
13519 env->prev_insn_idx);
13524 regs = cur_regs(env);
13525 sanitize_mark_insn_seen(env);
13526 prev_insn_idx = env->insn_idx;
13528 if (class == BPF_ALU || class == BPF_ALU64) {
13529 err = check_alu_op(env, insn);
13533 } else if (class == BPF_LDX) {
13534 enum bpf_reg_type *prev_src_type, src_reg_type;
13536 /* check for reserved fields is already done */
13538 /* check src operand */
13539 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13543 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13547 src_reg_type = regs[insn->src_reg].type;
13549 /* check that memory (src_reg + off) is readable,
13550 * the state of dst_reg will be updated by this func
13552 err = check_mem_access(env, env->insn_idx, insn->src_reg,
13553 insn->off, BPF_SIZE(insn->code),
13554 BPF_READ, insn->dst_reg, false);
13558 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13560 if (*prev_src_type == NOT_INIT) {
13561 /* saw a valid insn
13562 * dst_reg = *(u32 *)(src_reg + off)
13563 * save type to validate intersecting paths
13565 *prev_src_type = src_reg_type;
13567 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
13568 /* ABuser program is trying to use the same insn
13569 * dst_reg = *(u32*) (src_reg + off)
13570 * with different pointer types:
13571 * src_reg == ctx in one branch and
13572 * src_reg == stack|map in some other branch.
13575 verbose(env, "same insn cannot be used with different pointers\n");
13579 } else if (class == BPF_STX) {
13580 enum bpf_reg_type *prev_dst_type, dst_reg_type;
13582 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
13583 err = check_atomic(env, env->insn_idx, insn);
13590 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
13591 verbose(env, "BPF_STX uses reserved fields\n");
13595 /* check src1 operand */
13596 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13599 /* check src2 operand */
13600 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13604 dst_reg_type = regs[insn->dst_reg].type;
13606 /* check that memory (dst_reg + off) is writeable */
13607 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13608 insn->off, BPF_SIZE(insn->code),
13609 BPF_WRITE, insn->src_reg, false);
13613 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13615 if (*prev_dst_type == NOT_INIT) {
13616 *prev_dst_type = dst_reg_type;
13617 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
13618 verbose(env, "same insn cannot be used with different pointers\n");
13622 } else if (class == BPF_ST) {
13623 if (BPF_MODE(insn->code) != BPF_MEM ||
13624 insn->src_reg != BPF_REG_0) {
13625 verbose(env, "BPF_ST uses reserved fields\n");
13628 /* check src operand */
13629 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13633 if (is_ctx_reg(env, insn->dst_reg)) {
13634 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
13636 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
13640 /* check that memory (dst_reg + off) is writeable */
13641 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13642 insn->off, BPF_SIZE(insn->code),
13643 BPF_WRITE, -1, false);
13647 } else if (class == BPF_JMP || class == BPF_JMP32) {
13648 u8 opcode = BPF_OP(insn->code);
13650 env->jmps_processed++;
13651 if (opcode == BPF_CALL) {
13652 if (BPF_SRC(insn->code) != BPF_K ||
13653 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
13654 && insn->off != 0) ||
13655 (insn->src_reg != BPF_REG_0 &&
13656 insn->src_reg != BPF_PSEUDO_CALL &&
13657 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
13658 insn->dst_reg != BPF_REG_0 ||
13659 class == BPF_JMP32) {
13660 verbose(env, "BPF_CALL uses reserved fields\n");
13664 if (env->cur_state->active_lock.ptr) {
13665 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
13666 (insn->src_reg == BPF_PSEUDO_CALL) ||
13667 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
13668 (insn->off != 0 || !is_bpf_list_api_kfunc(insn->imm)))) {
13669 verbose(env, "function calls are not allowed while holding a lock\n");
13673 if (insn->src_reg == BPF_PSEUDO_CALL)
13674 err = check_func_call(env, insn, &env->insn_idx);
13675 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
13676 err = check_kfunc_call(env, insn, &env->insn_idx);
13678 err = check_helper_call(env, insn, &env->insn_idx);
13681 } else if (opcode == BPF_JA) {
13682 if (BPF_SRC(insn->code) != BPF_K ||
13684 insn->src_reg != BPF_REG_0 ||
13685 insn->dst_reg != BPF_REG_0 ||
13686 class == BPF_JMP32) {
13687 verbose(env, "BPF_JA uses reserved fields\n");
13691 env->insn_idx += insn->off + 1;
13694 } else if (opcode == BPF_EXIT) {
13695 if (BPF_SRC(insn->code) != BPF_K ||
13697 insn->src_reg != BPF_REG_0 ||
13698 insn->dst_reg != BPF_REG_0 ||
13699 class == BPF_JMP32) {
13700 verbose(env, "BPF_EXIT uses reserved fields\n");
13704 if (env->cur_state->active_lock.ptr) {
13705 verbose(env, "bpf_spin_unlock is missing\n");
13709 /* We must do check_reference_leak here before
13710 * prepare_func_exit to handle the case when
13711 * state->curframe > 0, it may be a callback
13712 * function, for which reference_state must
13713 * match caller reference state when it exits.
13715 err = check_reference_leak(env);
13719 if (state->curframe) {
13720 /* exit from nested function */
13721 err = prepare_func_exit(env, &env->insn_idx);
13724 do_print_state = true;
13728 err = check_return_code(env);
13732 mark_verifier_state_scratched(env);
13733 update_branch_counts(env, env->cur_state);
13734 err = pop_stack(env, &prev_insn_idx,
13735 &env->insn_idx, pop_log);
13737 if (err != -ENOENT)
13741 do_print_state = true;
13745 err = check_cond_jmp_op(env, insn, &env->insn_idx);
13749 } else if (class == BPF_LD) {
13750 u8 mode = BPF_MODE(insn->code);
13752 if (mode == BPF_ABS || mode == BPF_IND) {
13753 err = check_ld_abs(env, insn);
13757 } else if (mode == BPF_IMM) {
13758 err = check_ld_imm(env, insn);
13763 sanitize_mark_insn_seen(env);
13765 verbose(env, "invalid BPF_LD mode\n");
13769 verbose(env, "unknown insn class %d\n", class);
13779 static int find_btf_percpu_datasec(struct btf *btf)
13781 const struct btf_type *t;
13786 * Both vmlinux and module each have their own ".data..percpu"
13787 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
13788 * types to look at only module's own BTF types.
13790 n = btf_nr_types(btf);
13791 if (btf_is_module(btf))
13792 i = btf_nr_types(btf_vmlinux);
13796 for(; i < n; i++) {
13797 t = btf_type_by_id(btf, i);
13798 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
13801 tname = btf_name_by_offset(btf, t->name_off);
13802 if (!strcmp(tname, ".data..percpu"))
13809 /* replace pseudo btf_id with kernel symbol address */
13810 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
13811 struct bpf_insn *insn,
13812 struct bpf_insn_aux_data *aux)
13814 const struct btf_var_secinfo *vsi;
13815 const struct btf_type *datasec;
13816 struct btf_mod_pair *btf_mod;
13817 const struct btf_type *t;
13818 const char *sym_name;
13819 bool percpu = false;
13820 u32 type, id = insn->imm;
13824 int i, btf_fd, err;
13826 btf_fd = insn[1].imm;
13828 btf = btf_get_by_fd(btf_fd);
13830 verbose(env, "invalid module BTF object FD specified.\n");
13834 if (!btf_vmlinux) {
13835 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
13842 t = btf_type_by_id(btf, id);
13844 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
13849 if (!btf_type_is_var(t)) {
13850 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
13855 sym_name = btf_name_by_offset(btf, t->name_off);
13856 addr = kallsyms_lookup_name(sym_name);
13858 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
13864 datasec_id = find_btf_percpu_datasec(btf);
13865 if (datasec_id > 0) {
13866 datasec = btf_type_by_id(btf, datasec_id);
13867 for_each_vsi(i, datasec, vsi) {
13868 if (vsi->type == id) {
13875 insn[0].imm = (u32)addr;
13876 insn[1].imm = addr >> 32;
13879 t = btf_type_skip_modifiers(btf, type, NULL);
13881 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
13882 aux->btf_var.btf = btf;
13883 aux->btf_var.btf_id = type;
13884 } else if (!btf_type_is_struct(t)) {
13885 const struct btf_type *ret;
13889 /* resolve the type size of ksym. */
13890 ret = btf_resolve_size(btf, t, &tsize);
13892 tname = btf_name_by_offset(btf, t->name_off);
13893 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
13894 tname, PTR_ERR(ret));
13898 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
13899 aux->btf_var.mem_size = tsize;
13901 aux->btf_var.reg_type = PTR_TO_BTF_ID;
13902 aux->btf_var.btf = btf;
13903 aux->btf_var.btf_id = type;
13906 /* check whether we recorded this BTF (and maybe module) already */
13907 for (i = 0; i < env->used_btf_cnt; i++) {
13908 if (env->used_btfs[i].btf == btf) {
13914 if (env->used_btf_cnt >= MAX_USED_BTFS) {
13919 btf_mod = &env->used_btfs[env->used_btf_cnt];
13920 btf_mod->btf = btf;
13921 btf_mod->module = NULL;
13923 /* if we reference variables from kernel module, bump its refcount */
13924 if (btf_is_module(btf)) {
13925 btf_mod->module = btf_try_get_module(btf);
13926 if (!btf_mod->module) {
13932 env->used_btf_cnt++;
13940 static bool is_tracing_prog_type(enum bpf_prog_type type)
13943 case BPF_PROG_TYPE_KPROBE:
13944 case BPF_PROG_TYPE_TRACEPOINT:
13945 case BPF_PROG_TYPE_PERF_EVENT:
13946 case BPF_PROG_TYPE_RAW_TRACEPOINT:
13947 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
13954 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
13955 struct bpf_map *map,
13956 struct bpf_prog *prog)
13959 enum bpf_prog_type prog_type = resolve_prog_type(prog);
13961 if (btf_record_has_field(map->record, BPF_LIST_HEAD)) {
13962 if (is_tracing_prog_type(prog_type)) {
13963 verbose(env, "tracing progs cannot use bpf_list_head yet\n");
13968 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
13969 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
13970 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
13974 if (is_tracing_prog_type(prog_type)) {
13975 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
13979 if (prog->aux->sleepable) {
13980 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
13985 if (btf_record_has_field(map->record, BPF_TIMER)) {
13986 if (is_tracing_prog_type(prog_type)) {
13987 verbose(env, "tracing progs cannot use bpf_timer yet\n");
13992 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
13993 !bpf_offload_prog_map_match(prog, map)) {
13994 verbose(env, "offload device mismatch between prog and map\n");
13998 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
13999 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
14003 if (prog->aux->sleepable)
14004 switch (map->map_type) {
14005 case BPF_MAP_TYPE_HASH:
14006 case BPF_MAP_TYPE_LRU_HASH:
14007 case BPF_MAP_TYPE_ARRAY:
14008 case BPF_MAP_TYPE_PERCPU_HASH:
14009 case BPF_MAP_TYPE_PERCPU_ARRAY:
14010 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
14011 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
14012 case BPF_MAP_TYPE_HASH_OF_MAPS:
14013 case BPF_MAP_TYPE_RINGBUF:
14014 case BPF_MAP_TYPE_USER_RINGBUF:
14015 case BPF_MAP_TYPE_INODE_STORAGE:
14016 case BPF_MAP_TYPE_SK_STORAGE:
14017 case BPF_MAP_TYPE_TASK_STORAGE:
14021 "Sleepable programs can only use array, hash, and ringbuf maps\n");
14028 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
14030 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
14031 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
14034 /* find and rewrite pseudo imm in ld_imm64 instructions:
14036 * 1. if it accesses map FD, replace it with actual map pointer.
14037 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
14039 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
14041 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
14043 struct bpf_insn *insn = env->prog->insnsi;
14044 int insn_cnt = env->prog->len;
14047 err = bpf_prog_calc_tag(env->prog);
14051 for (i = 0; i < insn_cnt; i++, insn++) {
14052 if (BPF_CLASS(insn->code) == BPF_LDX &&
14053 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
14054 verbose(env, "BPF_LDX uses reserved fields\n");
14058 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
14059 struct bpf_insn_aux_data *aux;
14060 struct bpf_map *map;
14065 if (i == insn_cnt - 1 || insn[1].code != 0 ||
14066 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
14067 insn[1].off != 0) {
14068 verbose(env, "invalid bpf_ld_imm64 insn\n");
14072 if (insn[0].src_reg == 0)
14073 /* valid generic load 64-bit imm */
14076 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
14077 aux = &env->insn_aux_data[i];
14078 err = check_pseudo_btf_id(env, insn, aux);
14084 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
14085 aux = &env->insn_aux_data[i];
14086 aux->ptr_type = PTR_TO_FUNC;
14090 /* In final convert_pseudo_ld_imm64() step, this is
14091 * converted into regular 64-bit imm load insn.
14093 switch (insn[0].src_reg) {
14094 case BPF_PSEUDO_MAP_VALUE:
14095 case BPF_PSEUDO_MAP_IDX_VALUE:
14097 case BPF_PSEUDO_MAP_FD:
14098 case BPF_PSEUDO_MAP_IDX:
14099 if (insn[1].imm == 0)
14103 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
14107 switch (insn[0].src_reg) {
14108 case BPF_PSEUDO_MAP_IDX_VALUE:
14109 case BPF_PSEUDO_MAP_IDX:
14110 if (bpfptr_is_null(env->fd_array)) {
14111 verbose(env, "fd_idx without fd_array is invalid\n");
14114 if (copy_from_bpfptr_offset(&fd, env->fd_array,
14115 insn[0].imm * sizeof(fd),
14125 map = __bpf_map_get(f);
14127 verbose(env, "fd %d is not pointing to valid bpf_map\n",
14129 return PTR_ERR(map);
14132 err = check_map_prog_compatibility(env, map, env->prog);
14138 aux = &env->insn_aux_data[i];
14139 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
14140 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
14141 addr = (unsigned long)map;
14143 u32 off = insn[1].imm;
14145 if (off >= BPF_MAX_VAR_OFF) {
14146 verbose(env, "direct value offset of %u is not allowed\n", off);
14151 if (!map->ops->map_direct_value_addr) {
14152 verbose(env, "no direct value access support for this map type\n");
14157 err = map->ops->map_direct_value_addr(map, &addr, off);
14159 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
14160 map->value_size, off);
14165 aux->map_off = off;
14169 insn[0].imm = (u32)addr;
14170 insn[1].imm = addr >> 32;
14172 /* check whether we recorded this map already */
14173 for (j = 0; j < env->used_map_cnt; j++) {
14174 if (env->used_maps[j] == map) {
14175 aux->map_index = j;
14181 if (env->used_map_cnt >= MAX_USED_MAPS) {
14186 /* hold the map. If the program is rejected by verifier,
14187 * the map will be released by release_maps() or it
14188 * will be used by the valid program until it's unloaded
14189 * and all maps are released in free_used_maps()
14193 aux->map_index = env->used_map_cnt;
14194 env->used_maps[env->used_map_cnt++] = map;
14196 if (bpf_map_is_cgroup_storage(map) &&
14197 bpf_cgroup_storage_assign(env->prog->aux, map)) {
14198 verbose(env, "only one cgroup storage of each type is allowed\n");
14210 /* Basic sanity check before we invest more work here. */
14211 if (!bpf_opcode_in_insntable(insn->code)) {
14212 verbose(env, "unknown opcode %02x\n", insn->code);
14217 /* now all pseudo BPF_LD_IMM64 instructions load valid
14218 * 'struct bpf_map *' into a register instead of user map_fd.
14219 * These pointers will be used later by verifier to validate map access.
14224 /* drop refcnt of maps used by the rejected program */
14225 static void release_maps(struct bpf_verifier_env *env)
14227 __bpf_free_used_maps(env->prog->aux, env->used_maps,
14228 env->used_map_cnt);
14231 /* drop refcnt of maps used by the rejected program */
14232 static void release_btfs(struct bpf_verifier_env *env)
14234 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
14235 env->used_btf_cnt);
14238 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
14239 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
14241 struct bpf_insn *insn = env->prog->insnsi;
14242 int insn_cnt = env->prog->len;
14245 for (i = 0; i < insn_cnt; i++, insn++) {
14246 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
14248 if (insn->src_reg == BPF_PSEUDO_FUNC)
14254 /* single env->prog->insni[off] instruction was replaced with the range
14255 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
14256 * [0, off) and [off, end) to new locations, so the patched range stays zero
14258 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
14259 struct bpf_insn_aux_data *new_data,
14260 struct bpf_prog *new_prog, u32 off, u32 cnt)
14262 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
14263 struct bpf_insn *insn = new_prog->insnsi;
14264 u32 old_seen = old_data[off].seen;
14268 /* aux info at OFF always needs adjustment, no matter fast path
14269 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
14270 * original insn at old prog.
14272 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
14276 prog_len = new_prog->len;
14278 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
14279 memcpy(new_data + off + cnt - 1, old_data + off,
14280 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
14281 for (i = off; i < off + cnt - 1; i++) {
14282 /* Expand insni[off]'s seen count to the patched range. */
14283 new_data[i].seen = old_seen;
14284 new_data[i].zext_dst = insn_has_def32(env, insn + i);
14286 env->insn_aux_data = new_data;
14290 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
14296 /* NOTE: fake 'exit' subprog should be updated as well. */
14297 for (i = 0; i <= env->subprog_cnt; i++) {
14298 if (env->subprog_info[i].start <= off)
14300 env->subprog_info[i].start += len - 1;
14304 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
14306 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
14307 int i, sz = prog->aux->size_poke_tab;
14308 struct bpf_jit_poke_descriptor *desc;
14310 for (i = 0; i < sz; i++) {
14312 if (desc->insn_idx <= off)
14314 desc->insn_idx += len - 1;
14318 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
14319 const struct bpf_insn *patch, u32 len)
14321 struct bpf_prog *new_prog;
14322 struct bpf_insn_aux_data *new_data = NULL;
14325 new_data = vzalloc(array_size(env->prog->len + len - 1,
14326 sizeof(struct bpf_insn_aux_data)));
14331 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
14332 if (IS_ERR(new_prog)) {
14333 if (PTR_ERR(new_prog) == -ERANGE)
14335 "insn %d cannot be patched due to 16-bit range\n",
14336 env->insn_aux_data[off].orig_idx);
14340 adjust_insn_aux_data(env, new_data, new_prog, off, len);
14341 adjust_subprog_starts(env, off, len);
14342 adjust_poke_descs(new_prog, off, len);
14346 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
14351 /* find first prog starting at or after off (first to remove) */
14352 for (i = 0; i < env->subprog_cnt; i++)
14353 if (env->subprog_info[i].start >= off)
14355 /* find first prog starting at or after off + cnt (first to stay) */
14356 for (j = i; j < env->subprog_cnt; j++)
14357 if (env->subprog_info[j].start >= off + cnt)
14359 /* if j doesn't start exactly at off + cnt, we are just removing
14360 * the front of previous prog
14362 if (env->subprog_info[j].start != off + cnt)
14366 struct bpf_prog_aux *aux = env->prog->aux;
14369 /* move fake 'exit' subprog as well */
14370 move = env->subprog_cnt + 1 - j;
14372 memmove(env->subprog_info + i,
14373 env->subprog_info + j,
14374 sizeof(*env->subprog_info) * move);
14375 env->subprog_cnt -= j - i;
14377 /* remove func_info */
14378 if (aux->func_info) {
14379 move = aux->func_info_cnt - j;
14381 memmove(aux->func_info + i,
14382 aux->func_info + j,
14383 sizeof(*aux->func_info) * move);
14384 aux->func_info_cnt -= j - i;
14385 /* func_info->insn_off is set after all code rewrites,
14386 * in adjust_btf_func() - no need to adjust
14390 /* convert i from "first prog to remove" to "first to adjust" */
14391 if (env->subprog_info[i].start == off)
14395 /* update fake 'exit' subprog as well */
14396 for (; i <= env->subprog_cnt; i++)
14397 env->subprog_info[i].start -= cnt;
14402 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
14405 struct bpf_prog *prog = env->prog;
14406 u32 i, l_off, l_cnt, nr_linfo;
14407 struct bpf_line_info *linfo;
14409 nr_linfo = prog->aux->nr_linfo;
14413 linfo = prog->aux->linfo;
14415 /* find first line info to remove, count lines to be removed */
14416 for (i = 0; i < nr_linfo; i++)
14417 if (linfo[i].insn_off >= off)
14422 for (; i < nr_linfo; i++)
14423 if (linfo[i].insn_off < off + cnt)
14428 /* First live insn doesn't match first live linfo, it needs to "inherit"
14429 * last removed linfo. prog is already modified, so prog->len == off
14430 * means no live instructions after (tail of the program was removed).
14432 if (prog->len != off && l_cnt &&
14433 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
14435 linfo[--i].insn_off = off + cnt;
14438 /* remove the line info which refer to the removed instructions */
14440 memmove(linfo + l_off, linfo + i,
14441 sizeof(*linfo) * (nr_linfo - i));
14443 prog->aux->nr_linfo -= l_cnt;
14444 nr_linfo = prog->aux->nr_linfo;
14447 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
14448 for (i = l_off; i < nr_linfo; i++)
14449 linfo[i].insn_off -= cnt;
14451 /* fix up all subprogs (incl. 'exit') which start >= off */
14452 for (i = 0; i <= env->subprog_cnt; i++)
14453 if (env->subprog_info[i].linfo_idx > l_off) {
14454 /* program may have started in the removed region but
14455 * may not be fully removed
14457 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
14458 env->subprog_info[i].linfo_idx -= l_cnt;
14460 env->subprog_info[i].linfo_idx = l_off;
14466 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
14468 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14469 unsigned int orig_prog_len = env->prog->len;
14472 if (bpf_prog_is_dev_bound(env->prog->aux))
14473 bpf_prog_offload_remove_insns(env, off, cnt);
14475 err = bpf_remove_insns(env->prog, off, cnt);
14479 err = adjust_subprog_starts_after_remove(env, off, cnt);
14483 err = bpf_adj_linfo_after_remove(env, off, cnt);
14487 memmove(aux_data + off, aux_data + off + cnt,
14488 sizeof(*aux_data) * (orig_prog_len - off - cnt));
14493 /* The verifier does more data flow analysis than llvm and will not
14494 * explore branches that are dead at run time. Malicious programs can
14495 * have dead code too. Therefore replace all dead at-run-time code
14498 * Just nops are not optimal, e.g. if they would sit at the end of the
14499 * program and through another bug we would manage to jump there, then
14500 * we'd execute beyond program memory otherwise. Returning exception
14501 * code also wouldn't work since we can have subprogs where the dead
14502 * code could be located.
14504 static void sanitize_dead_code(struct bpf_verifier_env *env)
14506 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14507 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
14508 struct bpf_insn *insn = env->prog->insnsi;
14509 const int insn_cnt = env->prog->len;
14512 for (i = 0; i < insn_cnt; i++) {
14513 if (aux_data[i].seen)
14515 memcpy(insn + i, &trap, sizeof(trap));
14516 aux_data[i].zext_dst = false;
14520 static bool insn_is_cond_jump(u8 code)
14524 if (BPF_CLASS(code) == BPF_JMP32)
14527 if (BPF_CLASS(code) != BPF_JMP)
14531 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
14534 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
14536 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14537 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14538 struct bpf_insn *insn = env->prog->insnsi;
14539 const int insn_cnt = env->prog->len;
14542 for (i = 0; i < insn_cnt; i++, insn++) {
14543 if (!insn_is_cond_jump(insn->code))
14546 if (!aux_data[i + 1].seen)
14547 ja.off = insn->off;
14548 else if (!aux_data[i + 1 + insn->off].seen)
14553 if (bpf_prog_is_dev_bound(env->prog->aux))
14554 bpf_prog_offload_replace_insn(env, i, &ja);
14556 memcpy(insn, &ja, sizeof(ja));
14560 static int opt_remove_dead_code(struct bpf_verifier_env *env)
14562 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14563 int insn_cnt = env->prog->len;
14566 for (i = 0; i < insn_cnt; i++) {
14570 while (i + j < insn_cnt && !aux_data[i + j].seen)
14575 err = verifier_remove_insns(env, i, j);
14578 insn_cnt = env->prog->len;
14584 static int opt_remove_nops(struct bpf_verifier_env *env)
14586 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14587 struct bpf_insn *insn = env->prog->insnsi;
14588 int insn_cnt = env->prog->len;
14591 for (i = 0; i < insn_cnt; i++) {
14592 if (memcmp(&insn[i], &ja, sizeof(ja)))
14595 err = verifier_remove_insns(env, i, 1);
14605 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
14606 const union bpf_attr *attr)
14608 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
14609 struct bpf_insn_aux_data *aux = env->insn_aux_data;
14610 int i, patch_len, delta = 0, len = env->prog->len;
14611 struct bpf_insn *insns = env->prog->insnsi;
14612 struct bpf_prog *new_prog;
14615 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
14616 zext_patch[1] = BPF_ZEXT_REG(0);
14617 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
14618 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
14619 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
14620 for (i = 0; i < len; i++) {
14621 int adj_idx = i + delta;
14622 struct bpf_insn insn;
14625 insn = insns[adj_idx];
14626 load_reg = insn_def_regno(&insn);
14627 if (!aux[adj_idx].zext_dst) {
14635 class = BPF_CLASS(code);
14636 if (load_reg == -1)
14639 /* NOTE: arg "reg" (the fourth one) is only used for
14640 * BPF_STX + SRC_OP, so it is safe to pass NULL
14643 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
14644 if (class == BPF_LD &&
14645 BPF_MODE(code) == BPF_IMM)
14650 /* ctx load could be transformed into wider load. */
14651 if (class == BPF_LDX &&
14652 aux[adj_idx].ptr_type == PTR_TO_CTX)
14655 imm_rnd = get_random_u32();
14656 rnd_hi32_patch[0] = insn;
14657 rnd_hi32_patch[1].imm = imm_rnd;
14658 rnd_hi32_patch[3].dst_reg = load_reg;
14659 patch = rnd_hi32_patch;
14661 goto apply_patch_buffer;
14664 /* Add in an zero-extend instruction if a) the JIT has requested
14665 * it or b) it's a CMPXCHG.
14667 * The latter is because: BPF_CMPXCHG always loads a value into
14668 * R0, therefore always zero-extends. However some archs'
14669 * equivalent instruction only does this load when the
14670 * comparison is successful. This detail of CMPXCHG is
14671 * orthogonal to the general zero-extension behaviour of the
14672 * CPU, so it's treated independently of bpf_jit_needs_zext.
14674 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
14677 if (WARN_ON(load_reg == -1)) {
14678 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
14682 zext_patch[0] = insn;
14683 zext_patch[1].dst_reg = load_reg;
14684 zext_patch[1].src_reg = load_reg;
14685 patch = zext_patch;
14687 apply_patch_buffer:
14688 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
14691 env->prog = new_prog;
14692 insns = new_prog->insnsi;
14693 aux = env->insn_aux_data;
14694 delta += patch_len - 1;
14700 /* convert load instructions that access fields of a context type into a
14701 * sequence of instructions that access fields of the underlying structure:
14702 * struct __sk_buff -> struct sk_buff
14703 * struct bpf_sock_ops -> struct sock
14705 static int convert_ctx_accesses(struct bpf_verifier_env *env)
14707 const struct bpf_verifier_ops *ops = env->ops;
14708 int i, cnt, size, ctx_field_size, delta = 0;
14709 const int insn_cnt = env->prog->len;
14710 struct bpf_insn insn_buf[16], *insn;
14711 u32 target_size, size_default, off;
14712 struct bpf_prog *new_prog;
14713 enum bpf_access_type type;
14714 bool is_narrower_load;
14716 if (ops->gen_prologue || env->seen_direct_write) {
14717 if (!ops->gen_prologue) {
14718 verbose(env, "bpf verifier is misconfigured\n");
14721 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
14723 if (cnt >= ARRAY_SIZE(insn_buf)) {
14724 verbose(env, "bpf verifier is misconfigured\n");
14727 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
14731 env->prog = new_prog;
14736 if (bpf_prog_is_dev_bound(env->prog->aux))
14739 insn = env->prog->insnsi + delta;
14741 for (i = 0; i < insn_cnt; i++, insn++) {
14742 bpf_convert_ctx_access_t convert_ctx_access;
14745 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
14746 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
14747 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
14748 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
14751 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
14752 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
14753 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
14754 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
14755 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
14756 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
14757 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
14758 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
14760 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
14765 if (type == BPF_WRITE &&
14766 env->insn_aux_data[i + delta].sanitize_stack_spill) {
14767 struct bpf_insn patch[] = {
14772 cnt = ARRAY_SIZE(patch);
14773 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
14778 env->prog = new_prog;
14779 insn = new_prog->insnsi + i + delta;
14786 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
14788 if (!ops->convert_ctx_access)
14790 convert_ctx_access = ops->convert_ctx_access;
14792 case PTR_TO_SOCKET:
14793 case PTR_TO_SOCK_COMMON:
14794 convert_ctx_access = bpf_sock_convert_ctx_access;
14796 case PTR_TO_TCP_SOCK:
14797 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
14799 case PTR_TO_XDP_SOCK:
14800 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
14802 case PTR_TO_BTF_ID:
14803 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
14804 case PTR_TO_BTF_ID | PTR_TRUSTED:
14805 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
14806 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
14807 * be said once it is marked PTR_UNTRUSTED, hence we must handle
14808 * any faults for loads into such types. BPF_WRITE is disallowed
14811 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
14812 case PTR_TO_BTF_ID | PTR_UNTRUSTED | PTR_TRUSTED:
14813 case PTR_TO_BTF_ID | PTR_UNTRUSTED | MEM_ALLOC | PTR_TRUSTED:
14814 if (type == BPF_READ) {
14815 insn->code = BPF_LDX | BPF_PROBE_MEM |
14816 BPF_SIZE((insn)->code);
14817 env->prog->aux->num_exentries++;
14824 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
14825 size = BPF_LDST_BYTES(insn);
14827 /* If the read access is a narrower load of the field,
14828 * convert to a 4/8-byte load, to minimum program type specific
14829 * convert_ctx_access changes. If conversion is successful,
14830 * we will apply proper mask to the result.
14832 is_narrower_load = size < ctx_field_size;
14833 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
14835 if (is_narrower_load) {
14838 if (type == BPF_WRITE) {
14839 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
14844 if (ctx_field_size == 4)
14846 else if (ctx_field_size == 8)
14847 size_code = BPF_DW;
14849 insn->off = off & ~(size_default - 1);
14850 insn->code = BPF_LDX | BPF_MEM | size_code;
14854 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
14856 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
14857 (ctx_field_size && !target_size)) {
14858 verbose(env, "bpf verifier is misconfigured\n");
14862 if (is_narrower_load && size < target_size) {
14863 u8 shift = bpf_ctx_narrow_access_offset(
14864 off, size, size_default) * 8;
14865 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
14866 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
14869 if (ctx_field_size <= 4) {
14871 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
14874 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
14875 (1 << size * 8) - 1);
14878 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
14881 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
14882 (1ULL << size * 8) - 1);
14886 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14892 /* keep walking new program and skip insns we just inserted */
14893 env->prog = new_prog;
14894 insn = new_prog->insnsi + i + delta;
14900 static int jit_subprogs(struct bpf_verifier_env *env)
14902 struct bpf_prog *prog = env->prog, **func, *tmp;
14903 int i, j, subprog_start, subprog_end = 0, len, subprog;
14904 struct bpf_map *map_ptr;
14905 struct bpf_insn *insn;
14906 void *old_bpf_func;
14907 int err, num_exentries;
14909 if (env->subprog_cnt <= 1)
14912 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
14913 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
14916 /* Upon error here we cannot fall back to interpreter but
14917 * need a hard reject of the program. Thus -EFAULT is
14918 * propagated in any case.
14920 subprog = find_subprog(env, i + insn->imm + 1);
14922 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
14923 i + insn->imm + 1);
14926 /* temporarily remember subprog id inside insn instead of
14927 * aux_data, since next loop will split up all insns into funcs
14929 insn->off = subprog;
14930 /* remember original imm in case JIT fails and fallback
14931 * to interpreter will be needed
14933 env->insn_aux_data[i].call_imm = insn->imm;
14934 /* point imm to __bpf_call_base+1 from JITs point of view */
14936 if (bpf_pseudo_func(insn))
14937 /* jit (e.g. x86_64) may emit fewer instructions
14938 * if it learns a u32 imm is the same as a u64 imm.
14939 * Force a non zero here.
14944 err = bpf_prog_alloc_jited_linfo(prog);
14946 goto out_undo_insn;
14949 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
14951 goto out_undo_insn;
14953 for (i = 0; i < env->subprog_cnt; i++) {
14954 subprog_start = subprog_end;
14955 subprog_end = env->subprog_info[i + 1].start;
14957 len = subprog_end - subprog_start;
14958 /* bpf_prog_run() doesn't call subprogs directly,
14959 * hence main prog stats include the runtime of subprogs.
14960 * subprogs don't have IDs and not reachable via prog_get_next_id
14961 * func[i]->stats will never be accessed and stays NULL
14963 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
14966 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
14967 len * sizeof(struct bpf_insn));
14968 func[i]->type = prog->type;
14969 func[i]->len = len;
14970 if (bpf_prog_calc_tag(func[i]))
14972 func[i]->is_func = 1;
14973 func[i]->aux->func_idx = i;
14974 /* Below members will be freed only at prog->aux */
14975 func[i]->aux->btf = prog->aux->btf;
14976 func[i]->aux->func_info = prog->aux->func_info;
14977 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
14978 func[i]->aux->poke_tab = prog->aux->poke_tab;
14979 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
14981 for (j = 0; j < prog->aux->size_poke_tab; j++) {
14982 struct bpf_jit_poke_descriptor *poke;
14984 poke = &prog->aux->poke_tab[j];
14985 if (poke->insn_idx < subprog_end &&
14986 poke->insn_idx >= subprog_start)
14987 poke->aux = func[i]->aux;
14990 func[i]->aux->name[0] = 'F';
14991 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
14992 func[i]->jit_requested = 1;
14993 func[i]->blinding_requested = prog->blinding_requested;
14994 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
14995 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
14996 func[i]->aux->linfo = prog->aux->linfo;
14997 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
14998 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
14999 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
15001 insn = func[i]->insnsi;
15002 for (j = 0; j < func[i]->len; j++, insn++) {
15003 if (BPF_CLASS(insn->code) == BPF_LDX &&
15004 BPF_MODE(insn->code) == BPF_PROBE_MEM)
15007 func[i]->aux->num_exentries = num_exentries;
15008 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
15009 func[i] = bpf_int_jit_compile(func[i]);
15010 if (!func[i]->jited) {
15017 /* at this point all bpf functions were successfully JITed
15018 * now populate all bpf_calls with correct addresses and
15019 * run last pass of JIT
15021 for (i = 0; i < env->subprog_cnt; i++) {
15022 insn = func[i]->insnsi;
15023 for (j = 0; j < func[i]->len; j++, insn++) {
15024 if (bpf_pseudo_func(insn)) {
15025 subprog = insn->off;
15026 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
15027 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
15030 if (!bpf_pseudo_call(insn))
15032 subprog = insn->off;
15033 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
15036 /* we use the aux data to keep a list of the start addresses
15037 * of the JITed images for each function in the program
15039 * for some architectures, such as powerpc64, the imm field
15040 * might not be large enough to hold the offset of the start
15041 * address of the callee's JITed image from __bpf_call_base
15043 * in such cases, we can lookup the start address of a callee
15044 * by using its subprog id, available from the off field of
15045 * the call instruction, as an index for this list
15047 func[i]->aux->func = func;
15048 func[i]->aux->func_cnt = env->subprog_cnt;
15050 for (i = 0; i < env->subprog_cnt; i++) {
15051 old_bpf_func = func[i]->bpf_func;
15052 tmp = bpf_int_jit_compile(func[i]);
15053 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
15054 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
15061 /* finally lock prog and jit images for all functions and
15062 * populate kallsysm
15064 for (i = 0; i < env->subprog_cnt; i++) {
15065 bpf_prog_lock_ro(func[i]);
15066 bpf_prog_kallsyms_add(func[i]);
15069 /* Last step: make now unused interpreter insns from main
15070 * prog consistent for later dump requests, so they can
15071 * later look the same as if they were interpreted only.
15073 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15074 if (bpf_pseudo_func(insn)) {
15075 insn[0].imm = env->insn_aux_data[i].call_imm;
15076 insn[1].imm = insn->off;
15080 if (!bpf_pseudo_call(insn))
15082 insn->off = env->insn_aux_data[i].call_imm;
15083 subprog = find_subprog(env, i + insn->off + 1);
15084 insn->imm = subprog;
15088 prog->bpf_func = func[0]->bpf_func;
15089 prog->jited_len = func[0]->jited_len;
15090 prog->aux->func = func;
15091 prog->aux->func_cnt = env->subprog_cnt;
15092 bpf_prog_jit_attempt_done(prog);
15095 /* We failed JIT'ing, so at this point we need to unregister poke
15096 * descriptors from subprogs, so that kernel is not attempting to
15097 * patch it anymore as we're freeing the subprog JIT memory.
15099 for (i = 0; i < prog->aux->size_poke_tab; i++) {
15100 map_ptr = prog->aux->poke_tab[i].tail_call.map;
15101 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
15103 /* At this point we're guaranteed that poke descriptors are not
15104 * live anymore. We can just unlink its descriptor table as it's
15105 * released with the main prog.
15107 for (i = 0; i < env->subprog_cnt; i++) {
15110 func[i]->aux->poke_tab = NULL;
15111 bpf_jit_free(func[i]);
15115 /* cleanup main prog to be interpreted */
15116 prog->jit_requested = 0;
15117 prog->blinding_requested = 0;
15118 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15119 if (!bpf_pseudo_call(insn))
15122 insn->imm = env->insn_aux_data[i].call_imm;
15124 bpf_prog_jit_attempt_done(prog);
15128 static int fixup_call_args(struct bpf_verifier_env *env)
15130 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15131 struct bpf_prog *prog = env->prog;
15132 struct bpf_insn *insn = prog->insnsi;
15133 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
15138 if (env->prog->jit_requested &&
15139 !bpf_prog_is_dev_bound(env->prog->aux)) {
15140 err = jit_subprogs(env);
15143 if (err == -EFAULT)
15146 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15147 if (has_kfunc_call) {
15148 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
15151 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
15152 /* When JIT fails the progs with bpf2bpf calls and tail_calls
15153 * have to be rejected, since interpreter doesn't support them yet.
15155 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
15158 for (i = 0; i < prog->len; i++, insn++) {
15159 if (bpf_pseudo_func(insn)) {
15160 /* When JIT fails the progs with callback calls
15161 * have to be rejected, since interpreter doesn't support them yet.
15163 verbose(env, "callbacks are not allowed in non-JITed programs\n");
15167 if (!bpf_pseudo_call(insn))
15169 depth = get_callee_stack_depth(env, insn, i);
15172 bpf_patch_call_args(insn, depth);
15179 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
15180 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
15182 const struct bpf_kfunc_desc *desc;
15185 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
15189 /* insn->imm has the btf func_id. Replace it with
15190 * an address (relative to __bpf_base_call).
15192 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
15194 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
15200 insn->imm = desc->imm;
15203 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
15204 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15205 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15206 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
15208 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
15209 insn_buf[1] = addr[0];
15210 insn_buf[2] = addr[1];
15211 insn_buf[3] = *insn;
15213 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
15214 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15215 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15217 insn_buf[0] = addr[0];
15218 insn_buf[1] = addr[1];
15219 insn_buf[2] = *insn;
15221 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
15222 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
15223 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
15229 /* Do various post-verification rewrites in a single program pass.
15230 * These rewrites simplify JIT and interpreter implementations.
15232 static int do_misc_fixups(struct bpf_verifier_env *env)
15234 struct bpf_prog *prog = env->prog;
15235 enum bpf_attach_type eatype = prog->expected_attach_type;
15236 enum bpf_prog_type prog_type = resolve_prog_type(prog);
15237 struct bpf_insn *insn = prog->insnsi;
15238 const struct bpf_func_proto *fn;
15239 const int insn_cnt = prog->len;
15240 const struct bpf_map_ops *ops;
15241 struct bpf_insn_aux_data *aux;
15242 struct bpf_insn insn_buf[16];
15243 struct bpf_prog *new_prog;
15244 struct bpf_map *map_ptr;
15245 int i, ret, cnt, delta = 0;
15247 for (i = 0; i < insn_cnt; i++, insn++) {
15248 /* Make divide-by-zero exceptions impossible. */
15249 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
15250 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
15251 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
15252 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
15253 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
15254 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
15255 struct bpf_insn *patchlet;
15256 struct bpf_insn chk_and_div[] = {
15257 /* [R,W]x div 0 -> 0 */
15258 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15259 BPF_JNE | BPF_K, insn->src_reg,
15261 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
15262 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15265 struct bpf_insn chk_and_mod[] = {
15266 /* [R,W]x mod 0 -> [R,W]x */
15267 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15268 BPF_JEQ | BPF_K, insn->src_reg,
15269 0, 1 + (is64 ? 0 : 1), 0),
15271 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15272 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
15275 patchlet = isdiv ? chk_and_div : chk_and_mod;
15276 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
15277 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
15279 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
15284 env->prog = prog = new_prog;
15285 insn = new_prog->insnsi + i + delta;
15289 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
15290 if (BPF_CLASS(insn->code) == BPF_LD &&
15291 (BPF_MODE(insn->code) == BPF_ABS ||
15292 BPF_MODE(insn->code) == BPF_IND)) {
15293 cnt = env->ops->gen_ld_abs(insn, insn_buf);
15294 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15295 verbose(env, "bpf verifier is misconfigured\n");
15299 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15304 env->prog = prog = new_prog;
15305 insn = new_prog->insnsi + i + delta;
15309 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
15310 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
15311 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
15312 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
15313 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
15314 struct bpf_insn *patch = &insn_buf[0];
15315 bool issrc, isneg, isimm;
15318 aux = &env->insn_aux_data[i + delta];
15319 if (!aux->alu_state ||
15320 aux->alu_state == BPF_ALU_NON_POINTER)
15323 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
15324 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
15325 BPF_ALU_SANITIZE_SRC;
15326 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
15328 off_reg = issrc ? insn->src_reg : insn->dst_reg;
15330 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15333 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15334 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15335 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
15336 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
15337 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
15338 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
15339 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
15342 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
15343 insn->src_reg = BPF_REG_AX;
15345 insn->code = insn->code == code_add ?
15346 code_sub : code_add;
15348 if (issrc && isneg && !isimm)
15349 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15350 cnt = patch - insn_buf;
15352 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15357 env->prog = prog = new_prog;
15358 insn = new_prog->insnsi + i + delta;
15362 if (insn->code != (BPF_JMP | BPF_CALL))
15364 if (insn->src_reg == BPF_PSEUDO_CALL)
15366 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15367 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
15373 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15378 env->prog = prog = new_prog;
15379 insn = new_prog->insnsi + i + delta;
15383 if (insn->imm == BPF_FUNC_get_route_realm)
15384 prog->dst_needed = 1;
15385 if (insn->imm == BPF_FUNC_get_prandom_u32)
15386 bpf_user_rnd_init_once();
15387 if (insn->imm == BPF_FUNC_override_return)
15388 prog->kprobe_override = 1;
15389 if (insn->imm == BPF_FUNC_tail_call) {
15390 /* If we tail call into other programs, we
15391 * cannot make any assumptions since they can
15392 * be replaced dynamically during runtime in
15393 * the program array.
15395 prog->cb_access = 1;
15396 if (!allow_tail_call_in_subprogs(env))
15397 prog->aux->stack_depth = MAX_BPF_STACK;
15398 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
15400 /* mark bpf_tail_call as different opcode to avoid
15401 * conditional branch in the interpreter for every normal
15402 * call and to prevent accidental JITing by JIT compiler
15403 * that doesn't support bpf_tail_call yet
15406 insn->code = BPF_JMP | BPF_TAIL_CALL;
15408 aux = &env->insn_aux_data[i + delta];
15409 if (env->bpf_capable && !prog->blinding_requested &&
15410 prog->jit_requested &&
15411 !bpf_map_key_poisoned(aux) &&
15412 !bpf_map_ptr_poisoned(aux) &&
15413 !bpf_map_ptr_unpriv(aux)) {
15414 struct bpf_jit_poke_descriptor desc = {
15415 .reason = BPF_POKE_REASON_TAIL_CALL,
15416 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
15417 .tail_call.key = bpf_map_key_immediate(aux),
15418 .insn_idx = i + delta,
15421 ret = bpf_jit_add_poke_descriptor(prog, &desc);
15423 verbose(env, "adding tail call poke descriptor failed\n");
15427 insn->imm = ret + 1;
15431 if (!bpf_map_ptr_unpriv(aux))
15434 /* instead of changing every JIT dealing with tail_call
15435 * emit two extra insns:
15436 * if (index >= max_entries) goto out;
15437 * index &= array->index_mask;
15438 * to avoid out-of-bounds cpu speculation
15440 if (bpf_map_ptr_poisoned(aux)) {
15441 verbose(env, "tail_call abusing map_ptr\n");
15445 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15446 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
15447 map_ptr->max_entries, 2);
15448 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
15449 container_of(map_ptr,
15452 insn_buf[2] = *insn;
15454 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15459 env->prog = prog = new_prog;
15460 insn = new_prog->insnsi + i + delta;
15464 if (insn->imm == BPF_FUNC_timer_set_callback) {
15465 /* The verifier will process callback_fn as many times as necessary
15466 * with different maps and the register states prepared by
15467 * set_timer_callback_state will be accurate.
15469 * The following use case is valid:
15470 * map1 is shared by prog1, prog2, prog3.
15471 * prog1 calls bpf_timer_init for some map1 elements
15472 * prog2 calls bpf_timer_set_callback for some map1 elements.
15473 * Those that were not bpf_timer_init-ed will return -EINVAL.
15474 * prog3 calls bpf_timer_start for some map1 elements.
15475 * Those that were not both bpf_timer_init-ed and
15476 * bpf_timer_set_callback-ed will return -EINVAL.
15478 struct bpf_insn ld_addrs[2] = {
15479 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
15482 insn_buf[0] = ld_addrs[0];
15483 insn_buf[1] = ld_addrs[1];
15484 insn_buf[2] = *insn;
15487 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15492 env->prog = prog = new_prog;
15493 insn = new_prog->insnsi + i + delta;
15494 goto patch_call_imm;
15497 if (insn->imm == BPF_FUNC_task_storage_get ||
15498 insn->imm == BPF_FUNC_sk_storage_get ||
15499 insn->imm == BPF_FUNC_inode_storage_get ||
15500 insn->imm == BPF_FUNC_cgrp_storage_get) {
15501 if (env->prog->aux->sleepable)
15502 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
15504 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
15505 insn_buf[1] = *insn;
15508 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15513 env->prog = prog = new_prog;
15514 insn = new_prog->insnsi + i + delta;
15515 goto patch_call_imm;
15518 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
15519 * and other inlining handlers are currently limited to 64 bit
15522 if (prog->jit_requested && BITS_PER_LONG == 64 &&
15523 (insn->imm == BPF_FUNC_map_lookup_elem ||
15524 insn->imm == BPF_FUNC_map_update_elem ||
15525 insn->imm == BPF_FUNC_map_delete_elem ||
15526 insn->imm == BPF_FUNC_map_push_elem ||
15527 insn->imm == BPF_FUNC_map_pop_elem ||
15528 insn->imm == BPF_FUNC_map_peek_elem ||
15529 insn->imm == BPF_FUNC_redirect_map ||
15530 insn->imm == BPF_FUNC_for_each_map_elem ||
15531 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
15532 aux = &env->insn_aux_data[i + delta];
15533 if (bpf_map_ptr_poisoned(aux))
15534 goto patch_call_imm;
15536 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15537 ops = map_ptr->ops;
15538 if (insn->imm == BPF_FUNC_map_lookup_elem &&
15539 ops->map_gen_lookup) {
15540 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
15541 if (cnt == -EOPNOTSUPP)
15542 goto patch_map_ops_generic;
15543 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15544 verbose(env, "bpf verifier is misconfigured\n");
15548 new_prog = bpf_patch_insn_data(env, i + delta,
15554 env->prog = prog = new_prog;
15555 insn = new_prog->insnsi + i + delta;
15559 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
15560 (void *(*)(struct bpf_map *map, void *key))NULL));
15561 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
15562 (int (*)(struct bpf_map *map, void *key))NULL));
15563 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
15564 (int (*)(struct bpf_map *map, void *key, void *value,
15566 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
15567 (int (*)(struct bpf_map *map, void *value,
15569 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
15570 (int (*)(struct bpf_map *map, void *value))NULL));
15571 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
15572 (int (*)(struct bpf_map *map, void *value))NULL));
15573 BUILD_BUG_ON(!__same_type(ops->map_redirect,
15574 (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
15575 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
15576 (int (*)(struct bpf_map *map,
15577 bpf_callback_t callback_fn,
15578 void *callback_ctx,
15580 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
15581 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
15583 patch_map_ops_generic:
15584 switch (insn->imm) {
15585 case BPF_FUNC_map_lookup_elem:
15586 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
15588 case BPF_FUNC_map_update_elem:
15589 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
15591 case BPF_FUNC_map_delete_elem:
15592 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
15594 case BPF_FUNC_map_push_elem:
15595 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
15597 case BPF_FUNC_map_pop_elem:
15598 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
15600 case BPF_FUNC_map_peek_elem:
15601 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
15603 case BPF_FUNC_redirect_map:
15604 insn->imm = BPF_CALL_IMM(ops->map_redirect);
15606 case BPF_FUNC_for_each_map_elem:
15607 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
15609 case BPF_FUNC_map_lookup_percpu_elem:
15610 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
15614 goto patch_call_imm;
15617 /* Implement bpf_jiffies64 inline. */
15618 if (prog->jit_requested && BITS_PER_LONG == 64 &&
15619 insn->imm == BPF_FUNC_jiffies64) {
15620 struct bpf_insn ld_jiffies_addr[2] = {
15621 BPF_LD_IMM64(BPF_REG_0,
15622 (unsigned long)&jiffies),
15625 insn_buf[0] = ld_jiffies_addr[0];
15626 insn_buf[1] = ld_jiffies_addr[1];
15627 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
15631 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
15637 env->prog = prog = new_prog;
15638 insn = new_prog->insnsi + i + delta;
15642 /* Implement bpf_get_func_arg inline. */
15643 if (prog_type == BPF_PROG_TYPE_TRACING &&
15644 insn->imm == BPF_FUNC_get_func_arg) {
15645 /* Load nr_args from ctx - 8 */
15646 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15647 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
15648 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
15649 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
15650 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
15651 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15652 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
15653 insn_buf[7] = BPF_JMP_A(1);
15654 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
15657 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15662 env->prog = prog = new_prog;
15663 insn = new_prog->insnsi + i + delta;
15667 /* Implement bpf_get_func_ret inline. */
15668 if (prog_type == BPF_PROG_TYPE_TRACING &&
15669 insn->imm == BPF_FUNC_get_func_ret) {
15670 if (eatype == BPF_TRACE_FEXIT ||
15671 eatype == BPF_MODIFY_RETURN) {
15672 /* Load nr_args from ctx - 8 */
15673 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15674 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
15675 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
15676 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15677 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
15678 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
15681 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
15685 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15690 env->prog = prog = new_prog;
15691 insn = new_prog->insnsi + i + delta;
15695 /* Implement get_func_arg_cnt inline. */
15696 if (prog_type == BPF_PROG_TYPE_TRACING &&
15697 insn->imm == BPF_FUNC_get_func_arg_cnt) {
15698 /* Load nr_args from ctx - 8 */
15699 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15701 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
15705 env->prog = prog = new_prog;
15706 insn = new_prog->insnsi + i + delta;
15710 /* Implement bpf_get_func_ip inline. */
15711 if (prog_type == BPF_PROG_TYPE_TRACING &&
15712 insn->imm == BPF_FUNC_get_func_ip) {
15713 /* Load IP address from ctx - 16 */
15714 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
15716 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
15720 env->prog = prog = new_prog;
15721 insn = new_prog->insnsi + i + delta;
15726 fn = env->ops->get_func_proto(insn->imm, env->prog);
15727 /* all functions that have prototype and verifier allowed
15728 * programs to call them, must be real in-kernel functions
15732 "kernel subsystem misconfigured func %s#%d\n",
15733 func_id_name(insn->imm), insn->imm);
15736 insn->imm = fn->func - __bpf_call_base;
15739 /* Since poke tab is now finalized, publish aux to tracker. */
15740 for (i = 0; i < prog->aux->size_poke_tab; i++) {
15741 map_ptr = prog->aux->poke_tab[i].tail_call.map;
15742 if (!map_ptr->ops->map_poke_track ||
15743 !map_ptr->ops->map_poke_untrack ||
15744 !map_ptr->ops->map_poke_run) {
15745 verbose(env, "bpf verifier is misconfigured\n");
15749 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
15751 verbose(env, "tracking tail call prog failed\n");
15756 sort_kfunc_descs_by_imm(env->prog);
15761 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
15764 u32 callback_subprogno,
15767 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
15768 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
15769 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
15770 int reg_loop_max = BPF_REG_6;
15771 int reg_loop_cnt = BPF_REG_7;
15772 int reg_loop_ctx = BPF_REG_8;
15774 struct bpf_prog *new_prog;
15775 u32 callback_start;
15776 u32 call_insn_offset;
15777 s32 callback_offset;
15779 /* This represents an inlined version of bpf_iter.c:bpf_loop,
15780 * be careful to modify this code in sync.
15782 struct bpf_insn insn_buf[] = {
15783 /* Return error and jump to the end of the patch if
15784 * expected number of iterations is too big.
15786 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
15787 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
15788 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
15789 /* spill R6, R7, R8 to use these as loop vars */
15790 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
15791 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
15792 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
15793 /* initialize loop vars */
15794 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
15795 BPF_MOV32_IMM(reg_loop_cnt, 0),
15796 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
15798 * if reg_loop_cnt >= reg_loop_max skip the loop body
15800 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
15802 * correct callback offset would be set after patching
15804 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
15805 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
15807 /* increment loop counter */
15808 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
15809 /* jump to loop header if callback returned 0 */
15810 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
15811 /* return value of bpf_loop,
15812 * set R0 to the number of iterations
15814 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
15815 /* restore original values of R6, R7, R8 */
15816 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
15817 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
15818 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
15821 *cnt = ARRAY_SIZE(insn_buf);
15822 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
15826 /* callback start is known only after patching */
15827 callback_start = env->subprog_info[callback_subprogno].start;
15828 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
15829 call_insn_offset = position + 12;
15830 callback_offset = callback_start - call_insn_offset - 1;
15831 new_prog->insnsi[call_insn_offset].imm = callback_offset;
15836 static bool is_bpf_loop_call(struct bpf_insn *insn)
15838 return insn->code == (BPF_JMP | BPF_CALL) &&
15839 insn->src_reg == 0 &&
15840 insn->imm == BPF_FUNC_loop;
15843 /* For all sub-programs in the program (including main) check
15844 * insn_aux_data to see if there are bpf_loop calls that require
15845 * inlining. If such calls are found the calls are replaced with a
15846 * sequence of instructions produced by `inline_bpf_loop` function and
15847 * subprog stack_depth is increased by the size of 3 registers.
15848 * This stack space is used to spill values of the R6, R7, R8. These
15849 * registers are used to store the loop bound, counter and context
15852 static int optimize_bpf_loop(struct bpf_verifier_env *env)
15854 struct bpf_subprog_info *subprogs = env->subprog_info;
15855 int i, cur_subprog = 0, cnt, delta = 0;
15856 struct bpf_insn *insn = env->prog->insnsi;
15857 int insn_cnt = env->prog->len;
15858 u16 stack_depth = subprogs[cur_subprog].stack_depth;
15859 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
15860 u16 stack_depth_extra = 0;
15862 for (i = 0; i < insn_cnt; i++, insn++) {
15863 struct bpf_loop_inline_state *inline_state =
15864 &env->insn_aux_data[i + delta].loop_inline_state;
15866 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
15867 struct bpf_prog *new_prog;
15869 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
15870 new_prog = inline_bpf_loop(env,
15872 -(stack_depth + stack_depth_extra),
15873 inline_state->callback_subprogno,
15879 env->prog = new_prog;
15880 insn = new_prog->insnsi + i + delta;
15883 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
15884 subprogs[cur_subprog].stack_depth += stack_depth_extra;
15886 stack_depth = subprogs[cur_subprog].stack_depth;
15887 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
15888 stack_depth_extra = 0;
15892 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
15897 static void free_states(struct bpf_verifier_env *env)
15899 struct bpf_verifier_state_list *sl, *sln;
15902 sl = env->free_list;
15905 free_verifier_state(&sl->state, false);
15909 env->free_list = NULL;
15911 if (!env->explored_states)
15914 for (i = 0; i < state_htab_size(env); i++) {
15915 sl = env->explored_states[i];
15919 free_verifier_state(&sl->state, false);
15923 env->explored_states[i] = NULL;
15927 static int do_check_common(struct bpf_verifier_env *env, int subprog)
15929 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
15930 struct bpf_verifier_state *state;
15931 struct bpf_reg_state *regs;
15934 env->prev_linfo = NULL;
15937 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
15940 state->curframe = 0;
15941 state->speculative = false;
15942 state->branches = 1;
15943 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
15944 if (!state->frame[0]) {
15948 env->cur_state = state;
15949 init_func_state(env, state->frame[0],
15950 BPF_MAIN_FUNC /* callsite */,
15953 state->first_insn_idx = env->subprog_info[subprog].start;
15954 state->last_insn_idx = -1;
15956 regs = state->frame[state->curframe]->regs;
15957 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
15958 ret = btf_prepare_func_args(env, subprog, regs);
15961 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
15962 if (regs[i].type == PTR_TO_CTX)
15963 mark_reg_known_zero(env, regs, i);
15964 else if (regs[i].type == SCALAR_VALUE)
15965 mark_reg_unknown(env, regs, i);
15966 else if (base_type(regs[i].type) == PTR_TO_MEM) {
15967 const u32 mem_size = regs[i].mem_size;
15969 mark_reg_known_zero(env, regs, i);
15970 regs[i].mem_size = mem_size;
15971 regs[i].id = ++env->id_gen;
15975 /* 1st arg to a function */
15976 regs[BPF_REG_1].type = PTR_TO_CTX;
15977 mark_reg_known_zero(env, regs, BPF_REG_1);
15978 ret = btf_check_subprog_arg_match(env, subprog, regs);
15979 if (ret == -EFAULT)
15980 /* unlikely verifier bug. abort.
15981 * ret == 0 and ret < 0 are sadly acceptable for
15982 * main() function due to backward compatibility.
15983 * Like socket filter program may be written as:
15984 * int bpf_prog(struct pt_regs *ctx)
15985 * and never dereference that ctx in the program.
15986 * 'struct pt_regs' is a type mismatch for socket
15987 * filter that should be using 'struct __sk_buff'.
15992 ret = do_check(env);
15994 /* check for NULL is necessary, since cur_state can be freed inside
15995 * do_check() under memory pressure.
15997 if (env->cur_state) {
15998 free_verifier_state(env->cur_state, true);
15999 env->cur_state = NULL;
16001 while (!pop_stack(env, NULL, NULL, false));
16002 if (!ret && pop_log)
16003 bpf_vlog_reset(&env->log, 0);
16008 /* Verify all global functions in a BPF program one by one based on their BTF.
16009 * All global functions must pass verification. Otherwise the whole program is rejected.
16020 * foo() will be verified first for R1=any_scalar_value. During verification it
16021 * will be assumed that bar() already verified successfully and call to bar()
16022 * from foo() will be checked for type match only. Later bar() will be verified
16023 * independently to check that it's safe for R1=any_scalar_value.
16025 static int do_check_subprogs(struct bpf_verifier_env *env)
16027 struct bpf_prog_aux *aux = env->prog->aux;
16030 if (!aux->func_info)
16033 for (i = 1; i < env->subprog_cnt; i++) {
16034 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
16036 env->insn_idx = env->subprog_info[i].start;
16037 WARN_ON_ONCE(env->insn_idx == 0);
16038 ret = do_check_common(env, i);
16041 } else if (env->log.level & BPF_LOG_LEVEL) {
16043 "Func#%d is safe for any args that match its prototype\n",
16050 static int do_check_main(struct bpf_verifier_env *env)
16055 ret = do_check_common(env, 0);
16057 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16062 static void print_verification_stats(struct bpf_verifier_env *env)
16066 if (env->log.level & BPF_LOG_STATS) {
16067 verbose(env, "verification time %lld usec\n",
16068 div_u64(env->verification_time, 1000));
16069 verbose(env, "stack depth ");
16070 for (i = 0; i < env->subprog_cnt; i++) {
16071 u32 depth = env->subprog_info[i].stack_depth;
16073 verbose(env, "%d", depth);
16074 if (i + 1 < env->subprog_cnt)
16077 verbose(env, "\n");
16079 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
16080 "total_states %d peak_states %d mark_read %d\n",
16081 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
16082 env->max_states_per_insn, env->total_states,
16083 env->peak_states, env->longest_mark_read_walk);
16086 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
16088 const struct btf_type *t, *func_proto;
16089 const struct bpf_struct_ops *st_ops;
16090 const struct btf_member *member;
16091 struct bpf_prog *prog = env->prog;
16092 u32 btf_id, member_idx;
16095 if (!prog->gpl_compatible) {
16096 verbose(env, "struct ops programs must have a GPL compatible license\n");
16100 btf_id = prog->aux->attach_btf_id;
16101 st_ops = bpf_struct_ops_find(btf_id);
16103 verbose(env, "attach_btf_id %u is not a supported struct\n",
16109 member_idx = prog->expected_attach_type;
16110 if (member_idx >= btf_type_vlen(t)) {
16111 verbose(env, "attach to invalid member idx %u of struct %s\n",
16112 member_idx, st_ops->name);
16116 member = &btf_type_member(t)[member_idx];
16117 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
16118 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
16121 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
16122 mname, member_idx, st_ops->name);
16126 if (st_ops->check_member) {
16127 int err = st_ops->check_member(t, member);
16130 verbose(env, "attach to unsupported member %s of struct %s\n",
16131 mname, st_ops->name);
16136 prog->aux->attach_func_proto = func_proto;
16137 prog->aux->attach_func_name = mname;
16138 env->ops = st_ops->verifier_ops;
16142 #define SECURITY_PREFIX "security_"
16144 static int check_attach_modify_return(unsigned long addr, const char *func_name)
16146 if (within_error_injection_list(addr) ||
16147 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
16153 /* list of non-sleepable functions that are otherwise on
16154 * ALLOW_ERROR_INJECTION list
16156 BTF_SET_START(btf_non_sleepable_error_inject)
16157 /* Three functions below can be called from sleepable and non-sleepable context.
16158 * Assume non-sleepable from bpf safety point of view.
16160 BTF_ID(func, __filemap_add_folio)
16161 BTF_ID(func, should_fail_alloc_page)
16162 BTF_ID(func, should_failslab)
16163 BTF_SET_END(btf_non_sleepable_error_inject)
16165 static int check_non_sleepable_error_inject(u32 btf_id)
16167 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
16170 int bpf_check_attach_target(struct bpf_verifier_log *log,
16171 const struct bpf_prog *prog,
16172 const struct bpf_prog *tgt_prog,
16174 struct bpf_attach_target_info *tgt_info)
16176 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
16177 const char prefix[] = "btf_trace_";
16178 int ret = 0, subprog = -1, i;
16179 const struct btf_type *t;
16180 bool conservative = true;
16186 bpf_log(log, "Tracing programs must provide btf_id\n");
16189 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
16192 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
16195 t = btf_type_by_id(btf, btf_id);
16197 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
16200 tname = btf_name_by_offset(btf, t->name_off);
16202 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
16206 struct bpf_prog_aux *aux = tgt_prog->aux;
16208 for (i = 0; i < aux->func_info_cnt; i++)
16209 if (aux->func_info[i].type_id == btf_id) {
16213 if (subprog == -1) {
16214 bpf_log(log, "Subprog %s doesn't exist\n", tname);
16217 conservative = aux->func_info_aux[subprog].unreliable;
16218 if (prog_extension) {
16219 if (conservative) {
16221 "Cannot replace static functions\n");
16224 if (!prog->jit_requested) {
16226 "Extension programs should be JITed\n");
16230 if (!tgt_prog->jited) {
16231 bpf_log(log, "Can attach to only JITed progs\n");
16234 if (tgt_prog->type == prog->type) {
16235 /* Cannot fentry/fexit another fentry/fexit program.
16236 * Cannot attach program extension to another extension.
16237 * It's ok to attach fentry/fexit to extension program.
16239 bpf_log(log, "Cannot recursively attach\n");
16242 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
16244 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
16245 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
16246 /* Program extensions can extend all program types
16247 * except fentry/fexit. The reason is the following.
16248 * The fentry/fexit programs are used for performance
16249 * analysis, stats and can be attached to any program
16250 * type except themselves. When extension program is
16251 * replacing XDP function it is necessary to allow
16252 * performance analysis of all functions. Both original
16253 * XDP program and its program extension. Hence
16254 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
16255 * allowed. If extending of fentry/fexit was allowed it
16256 * would be possible to create long call chain
16257 * fentry->extension->fentry->extension beyond
16258 * reasonable stack size. Hence extending fentry is not
16261 bpf_log(log, "Cannot extend fentry/fexit\n");
16265 if (prog_extension) {
16266 bpf_log(log, "Cannot replace kernel functions\n");
16271 switch (prog->expected_attach_type) {
16272 case BPF_TRACE_RAW_TP:
16275 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
16278 if (!btf_type_is_typedef(t)) {
16279 bpf_log(log, "attach_btf_id %u is not a typedef\n",
16283 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
16284 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
16288 tname += sizeof(prefix) - 1;
16289 t = btf_type_by_id(btf, t->type);
16290 if (!btf_type_is_ptr(t))
16291 /* should never happen in valid vmlinux build */
16293 t = btf_type_by_id(btf, t->type);
16294 if (!btf_type_is_func_proto(t))
16295 /* should never happen in valid vmlinux build */
16299 case BPF_TRACE_ITER:
16300 if (!btf_type_is_func(t)) {
16301 bpf_log(log, "attach_btf_id %u is not a function\n",
16305 t = btf_type_by_id(btf, t->type);
16306 if (!btf_type_is_func_proto(t))
16308 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16313 if (!prog_extension)
16316 case BPF_MODIFY_RETURN:
16318 case BPF_LSM_CGROUP:
16319 case BPF_TRACE_FENTRY:
16320 case BPF_TRACE_FEXIT:
16321 if (!btf_type_is_func(t)) {
16322 bpf_log(log, "attach_btf_id %u is not a function\n",
16326 if (prog_extension &&
16327 btf_check_type_match(log, prog, btf, t))
16329 t = btf_type_by_id(btf, t->type);
16330 if (!btf_type_is_func_proto(t))
16333 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
16334 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
16335 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
16338 if (tgt_prog && conservative)
16341 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16347 addr = (long) tgt_prog->bpf_func;
16349 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
16351 addr = kallsyms_lookup_name(tname);
16354 "The address of function %s cannot be found\n",
16360 if (prog->aux->sleepable) {
16362 switch (prog->type) {
16363 case BPF_PROG_TYPE_TRACING:
16364 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
16365 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
16367 if (!check_non_sleepable_error_inject(btf_id) &&
16368 within_error_injection_list(addr))
16371 case BPF_PROG_TYPE_LSM:
16372 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
16373 * Only some of them are sleepable.
16375 if (bpf_lsm_is_sleepable_hook(btf_id))
16382 bpf_log(log, "%s is not sleepable\n", tname);
16385 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
16387 bpf_log(log, "can't modify return codes of BPF programs\n");
16390 ret = check_attach_modify_return(addr, tname);
16392 bpf_log(log, "%s() is not modifiable\n", tname);
16399 tgt_info->tgt_addr = addr;
16400 tgt_info->tgt_name = tname;
16401 tgt_info->tgt_type = t;
16405 BTF_SET_START(btf_id_deny)
16408 BTF_ID(func, migrate_disable)
16409 BTF_ID(func, migrate_enable)
16411 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
16412 BTF_ID(func, rcu_read_unlock_strict)
16414 BTF_SET_END(btf_id_deny)
16416 static int check_attach_btf_id(struct bpf_verifier_env *env)
16418 struct bpf_prog *prog = env->prog;
16419 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
16420 struct bpf_attach_target_info tgt_info = {};
16421 u32 btf_id = prog->aux->attach_btf_id;
16422 struct bpf_trampoline *tr;
16426 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
16427 if (prog->aux->sleepable)
16428 /* attach_btf_id checked to be zero already */
16430 verbose(env, "Syscall programs can only be sleepable\n");
16434 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
16435 prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
16436 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
16440 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
16441 return check_struct_ops_btf_id(env);
16443 if (prog->type != BPF_PROG_TYPE_TRACING &&
16444 prog->type != BPF_PROG_TYPE_LSM &&
16445 prog->type != BPF_PROG_TYPE_EXT)
16448 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
16452 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
16453 /* to make freplace equivalent to their targets, they need to
16454 * inherit env->ops and expected_attach_type for the rest of the
16457 env->ops = bpf_verifier_ops[tgt_prog->type];
16458 prog->expected_attach_type = tgt_prog->expected_attach_type;
16461 /* store info about the attachment target that will be used later */
16462 prog->aux->attach_func_proto = tgt_info.tgt_type;
16463 prog->aux->attach_func_name = tgt_info.tgt_name;
16466 prog->aux->saved_dst_prog_type = tgt_prog->type;
16467 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
16470 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
16471 prog->aux->attach_btf_trace = true;
16473 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
16474 if (!bpf_iter_prog_supported(prog))
16479 if (prog->type == BPF_PROG_TYPE_LSM) {
16480 ret = bpf_lsm_verify_prog(&env->log, prog);
16483 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
16484 btf_id_set_contains(&btf_id_deny, btf_id)) {
16488 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
16489 tr = bpf_trampoline_get(key, &tgt_info);
16493 prog->aux->dst_trampoline = tr;
16497 struct btf *bpf_get_btf_vmlinux(void)
16499 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
16500 mutex_lock(&bpf_verifier_lock);
16502 btf_vmlinux = btf_parse_vmlinux();
16503 mutex_unlock(&bpf_verifier_lock);
16505 return btf_vmlinux;
16508 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
16510 u64 start_time = ktime_get_ns();
16511 struct bpf_verifier_env *env;
16512 struct bpf_verifier_log *log;
16513 int i, len, ret = -EINVAL;
16516 /* no program is valid */
16517 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
16520 /* 'struct bpf_verifier_env' can be global, but since it's not small,
16521 * allocate/free it every time bpf_check() is called
16523 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
16528 len = (*prog)->len;
16529 env->insn_aux_data =
16530 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
16532 if (!env->insn_aux_data)
16534 for (i = 0; i < len; i++)
16535 env->insn_aux_data[i].orig_idx = i;
16537 env->ops = bpf_verifier_ops[env->prog->type];
16538 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
16539 is_priv = bpf_capable();
16541 bpf_get_btf_vmlinux();
16543 /* grab the mutex to protect few globals used by verifier */
16545 mutex_lock(&bpf_verifier_lock);
16547 if (attr->log_level || attr->log_buf || attr->log_size) {
16548 /* user requested verbose verifier output
16549 * and supplied buffer to store the verification trace
16551 log->level = attr->log_level;
16552 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
16553 log->len_total = attr->log_size;
16555 /* log attributes have to be sane */
16556 if (!bpf_verifier_log_attr_valid(log)) {
16562 mark_verifier_state_clean(env);
16564 if (IS_ERR(btf_vmlinux)) {
16565 /* Either gcc or pahole or kernel are broken. */
16566 verbose(env, "in-kernel BTF is malformed\n");
16567 ret = PTR_ERR(btf_vmlinux);
16568 goto skip_full_check;
16571 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
16572 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
16573 env->strict_alignment = true;
16574 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
16575 env->strict_alignment = false;
16577 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
16578 env->allow_uninit_stack = bpf_allow_uninit_stack();
16579 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
16580 env->bypass_spec_v1 = bpf_bypass_spec_v1();
16581 env->bypass_spec_v4 = bpf_bypass_spec_v4();
16582 env->bpf_capable = bpf_capable();
16585 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
16587 env->explored_states = kvcalloc(state_htab_size(env),
16588 sizeof(struct bpf_verifier_state_list *),
16591 if (!env->explored_states)
16592 goto skip_full_check;
16594 ret = add_subprog_and_kfunc(env);
16596 goto skip_full_check;
16598 ret = check_subprogs(env);
16600 goto skip_full_check;
16602 ret = check_btf_info(env, attr, uattr);
16604 goto skip_full_check;
16606 ret = check_attach_btf_id(env);
16608 goto skip_full_check;
16610 ret = resolve_pseudo_ldimm64(env);
16612 goto skip_full_check;
16614 if (bpf_prog_is_dev_bound(env->prog->aux)) {
16615 ret = bpf_prog_offload_verifier_prep(env->prog);
16617 goto skip_full_check;
16620 ret = check_cfg(env);
16622 goto skip_full_check;
16624 ret = do_check_subprogs(env);
16625 ret = ret ?: do_check_main(env);
16627 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
16628 ret = bpf_prog_offload_finalize(env);
16631 kvfree(env->explored_states);
16634 ret = check_max_stack_depth(env);
16636 /* instruction rewrites happen after this point */
16638 ret = optimize_bpf_loop(env);
16642 opt_hard_wire_dead_code_branches(env);
16644 ret = opt_remove_dead_code(env);
16646 ret = opt_remove_nops(env);
16649 sanitize_dead_code(env);
16653 /* program is valid, convert *(u32*)(ctx + off) accesses */
16654 ret = convert_ctx_accesses(env);
16657 ret = do_misc_fixups(env);
16659 /* do 32-bit optimization after insn patching has done so those patched
16660 * insns could be handled correctly.
16662 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
16663 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
16664 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
16669 ret = fixup_call_args(env);
16671 env->verification_time = ktime_get_ns() - start_time;
16672 print_verification_stats(env);
16673 env->prog->aux->verified_insns = env->insn_processed;
16675 if (log->level && bpf_verifier_log_full(log))
16677 if (log->level && !log->ubuf) {
16679 goto err_release_maps;
16683 goto err_release_maps;
16685 if (env->used_map_cnt) {
16686 /* if program passed verifier, update used_maps in bpf_prog_info */
16687 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
16688 sizeof(env->used_maps[0]),
16691 if (!env->prog->aux->used_maps) {
16693 goto err_release_maps;
16696 memcpy(env->prog->aux->used_maps, env->used_maps,
16697 sizeof(env->used_maps[0]) * env->used_map_cnt);
16698 env->prog->aux->used_map_cnt = env->used_map_cnt;
16700 if (env->used_btf_cnt) {
16701 /* if program passed verifier, update used_btfs in bpf_prog_aux */
16702 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
16703 sizeof(env->used_btfs[0]),
16705 if (!env->prog->aux->used_btfs) {
16707 goto err_release_maps;
16710 memcpy(env->prog->aux->used_btfs, env->used_btfs,
16711 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
16712 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
16714 if (env->used_map_cnt || env->used_btf_cnt) {
16715 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
16716 * bpf_ld_imm64 instructions
16718 convert_pseudo_ld_imm64(env);
16721 adjust_btf_func(env);
16724 if (!env->prog->aux->used_maps)
16725 /* if we didn't copy map pointers into bpf_prog_info, release
16726 * them now. Otherwise free_used_maps() will release them.
16729 if (!env->prog->aux->used_btfs)
16732 /* extension progs temporarily inherit the attach_type of their targets
16733 for verification purposes, so set it back to zero before returning
16735 if (env->prog->type == BPF_PROG_TYPE_EXT)
16736 env->prog->expected_attach_type = 0;
16741 mutex_unlock(&bpf_verifier_lock);
16742 vfree(env->insn_aux_data);