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 is_storage_get_function(enum bpf_func_id func_id)
532 return func_id == BPF_FUNC_sk_storage_get ||
533 func_id == BPF_FUNC_inode_storage_get ||
534 func_id == BPF_FUNC_task_storage_get ||
535 func_id == BPF_FUNC_cgrp_storage_get;
538 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
539 const struct bpf_map *map)
541 int ref_obj_uses = 0;
543 if (is_ptr_cast_function(func_id))
545 if (is_acquire_function(func_id, map))
547 if (is_dynptr_ref_function(func_id))
550 return ref_obj_uses > 1;
553 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
555 return BPF_CLASS(insn->code) == BPF_STX &&
556 BPF_MODE(insn->code) == BPF_ATOMIC &&
557 insn->imm == BPF_CMPXCHG;
560 /* string representation of 'enum bpf_reg_type'
562 * Note that reg_type_str() can not appear more than once in a single verbose()
565 static const char *reg_type_str(struct bpf_verifier_env *env,
566 enum bpf_reg_type type)
568 char postfix[16] = {0}, prefix[64] = {0};
569 static const char * const str[] = {
571 [SCALAR_VALUE] = "scalar",
572 [PTR_TO_CTX] = "ctx",
573 [CONST_PTR_TO_MAP] = "map_ptr",
574 [PTR_TO_MAP_VALUE] = "map_value",
575 [PTR_TO_STACK] = "fp",
576 [PTR_TO_PACKET] = "pkt",
577 [PTR_TO_PACKET_META] = "pkt_meta",
578 [PTR_TO_PACKET_END] = "pkt_end",
579 [PTR_TO_FLOW_KEYS] = "flow_keys",
580 [PTR_TO_SOCKET] = "sock",
581 [PTR_TO_SOCK_COMMON] = "sock_common",
582 [PTR_TO_TCP_SOCK] = "tcp_sock",
583 [PTR_TO_TP_BUFFER] = "tp_buffer",
584 [PTR_TO_XDP_SOCK] = "xdp_sock",
585 [PTR_TO_BTF_ID] = "ptr_",
586 [PTR_TO_MEM] = "mem",
587 [PTR_TO_BUF] = "buf",
588 [PTR_TO_FUNC] = "func",
589 [PTR_TO_MAP_KEY] = "map_key",
590 [PTR_TO_DYNPTR] = "dynptr_ptr",
593 if (type & PTR_MAYBE_NULL) {
594 if (base_type(type) == PTR_TO_BTF_ID)
595 strncpy(postfix, "or_null_", 16);
597 strncpy(postfix, "_or_null", 16);
600 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
601 type & MEM_RDONLY ? "rdonly_" : "",
602 type & MEM_RINGBUF ? "ringbuf_" : "",
603 type & MEM_USER ? "user_" : "",
604 type & MEM_PERCPU ? "percpu_" : "",
605 type & MEM_RCU ? "rcu_" : "",
606 type & PTR_UNTRUSTED ? "untrusted_" : "",
607 type & PTR_TRUSTED ? "trusted_" : ""
610 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
611 prefix, str[base_type(type)], postfix);
612 return env->type_str_buf;
615 static char slot_type_char[] = {
616 [STACK_INVALID] = '?',
620 [STACK_DYNPTR] = 'd',
623 static void print_liveness(struct bpf_verifier_env *env,
624 enum bpf_reg_liveness live)
626 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
628 if (live & REG_LIVE_READ)
630 if (live & REG_LIVE_WRITTEN)
632 if (live & REG_LIVE_DONE)
636 static int get_spi(s32 off)
638 return (-off - 1) / BPF_REG_SIZE;
641 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
643 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
645 /* We need to check that slots between [spi - nr_slots + 1, spi] are
646 * within [0, allocated_stack).
648 * Please note that the spi grows downwards. For example, a dynptr
649 * takes the size of two stack slots; the first slot will be at
650 * spi and the second slot will be at spi - 1.
652 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
655 static struct bpf_func_state *func(struct bpf_verifier_env *env,
656 const struct bpf_reg_state *reg)
658 struct bpf_verifier_state *cur = env->cur_state;
660 return cur->frame[reg->frameno];
663 static const char *kernel_type_name(const struct btf* btf, u32 id)
665 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
668 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
670 env->scratched_regs |= 1U << regno;
673 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
675 env->scratched_stack_slots |= 1ULL << spi;
678 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
680 return (env->scratched_regs >> regno) & 1;
683 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
685 return (env->scratched_stack_slots >> regno) & 1;
688 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
690 return env->scratched_regs || env->scratched_stack_slots;
693 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
695 env->scratched_regs = 0U;
696 env->scratched_stack_slots = 0ULL;
699 /* Used for printing the entire verifier state. */
700 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
702 env->scratched_regs = ~0U;
703 env->scratched_stack_slots = ~0ULL;
706 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
708 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
709 case DYNPTR_TYPE_LOCAL:
710 return BPF_DYNPTR_TYPE_LOCAL;
711 case DYNPTR_TYPE_RINGBUF:
712 return BPF_DYNPTR_TYPE_RINGBUF;
714 return BPF_DYNPTR_TYPE_INVALID;
718 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
720 return type == BPF_DYNPTR_TYPE_RINGBUF;
723 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
724 enum bpf_arg_type arg_type, int insn_idx)
726 struct bpf_func_state *state = func(env, reg);
727 enum bpf_dynptr_type type;
730 spi = get_spi(reg->off);
732 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
735 for (i = 0; i < BPF_REG_SIZE; i++) {
736 state->stack[spi].slot_type[i] = STACK_DYNPTR;
737 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
740 type = arg_to_dynptr_type(arg_type);
741 if (type == BPF_DYNPTR_TYPE_INVALID)
744 state->stack[spi].spilled_ptr.dynptr.first_slot = true;
745 state->stack[spi].spilled_ptr.dynptr.type = type;
746 state->stack[spi - 1].spilled_ptr.dynptr.type = type;
748 if (dynptr_type_refcounted(type)) {
749 /* The id is used to track proper releasing */
750 id = acquire_reference_state(env, insn_idx);
754 state->stack[spi].spilled_ptr.id = id;
755 state->stack[spi - 1].spilled_ptr.id = id;
761 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
763 struct bpf_func_state *state = func(env, reg);
766 spi = get_spi(reg->off);
768 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
771 for (i = 0; i < BPF_REG_SIZE; i++) {
772 state->stack[spi].slot_type[i] = STACK_INVALID;
773 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
776 /* Invalidate any slices associated with this dynptr */
777 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
778 release_reference(env, state->stack[spi].spilled_ptr.id);
779 state->stack[spi].spilled_ptr.id = 0;
780 state->stack[spi - 1].spilled_ptr.id = 0;
783 state->stack[spi].spilled_ptr.dynptr.first_slot = false;
784 state->stack[spi].spilled_ptr.dynptr.type = 0;
785 state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
790 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
792 struct bpf_func_state *state = func(env, reg);
793 int spi = get_spi(reg->off);
796 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
799 for (i = 0; i < BPF_REG_SIZE; i++) {
800 if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
801 state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
808 bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
809 struct bpf_reg_state *reg)
811 struct bpf_func_state *state = func(env, reg);
812 int spi = get_spi(reg->off);
815 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
816 !state->stack[spi].spilled_ptr.dynptr.first_slot)
819 for (i = 0; i < BPF_REG_SIZE; i++) {
820 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
821 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
828 bool is_dynptr_type_expected(struct bpf_verifier_env *env,
829 struct bpf_reg_state *reg,
830 enum bpf_arg_type arg_type)
832 struct bpf_func_state *state = func(env, reg);
833 enum bpf_dynptr_type dynptr_type;
834 int spi = get_spi(reg->off);
836 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
837 if (arg_type == ARG_PTR_TO_DYNPTR)
840 dynptr_type = arg_to_dynptr_type(arg_type);
842 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
845 /* The reg state of a pointer or a bounded scalar was saved when
846 * it was spilled to the stack.
848 static bool is_spilled_reg(const struct bpf_stack_state *stack)
850 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
853 static void scrub_spilled_slot(u8 *stype)
855 if (*stype != STACK_INVALID)
859 static void print_verifier_state(struct bpf_verifier_env *env,
860 const struct bpf_func_state *state,
863 const struct bpf_reg_state *reg;
868 verbose(env, " frame%d:", state->frameno);
869 for (i = 0; i < MAX_BPF_REG; i++) {
870 reg = &state->regs[i];
874 if (!print_all && !reg_scratched(env, i))
876 verbose(env, " R%d", i);
877 print_liveness(env, reg->live);
879 if (t == SCALAR_VALUE && reg->precise)
881 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
882 tnum_is_const(reg->var_off)) {
883 /* reg->off should be 0 for SCALAR_VALUE */
884 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
885 verbose(env, "%lld", reg->var_off.value + reg->off);
887 const char *sep = "";
889 verbose(env, "%s", reg_type_str(env, t));
890 if (base_type(t) == PTR_TO_BTF_ID)
891 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
894 * _a stands for append, was shortened to avoid multiline statements below.
895 * This macro is used to output a comma separated list of attributes.
897 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
900 verbose_a("id=%d", reg->id);
902 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
903 if (t != SCALAR_VALUE)
904 verbose_a("off=%d", reg->off);
905 if (type_is_pkt_pointer(t))
906 verbose_a("r=%d", reg->range);
907 else if (base_type(t) == CONST_PTR_TO_MAP ||
908 base_type(t) == PTR_TO_MAP_KEY ||
909 base_type(t) == PTR_TO_MAP_VALUE)
910 verbose_a("ks=%d,vs=%d",
911 reg->map_ptr->key_size,
912 reg->map_ptr->value_size);
913 if (tnum_is_const(reg->var_off)) {
914 /* Typically an immediate SCALAR_VALUE, but
915 * could be a pointer whose offset is too big
918 verbose_a("imm=%llx", reg->var_off.value);
920 if (reg->smin_value != reg->umin_value &&
921 reg->smin_value != S64_MIN)
922 verbose_a("smin=%lld", (long long)reg->smin_value);
923 if (reg->smax_value != reg->umax_value &&
924 reg->smax_value != S64_MAX)
925 verbose_a("smax=%lld", (long long)reg->smax_value);
926 if (reg->umin_value != 0)
927 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
928 if (reg->umax_value != U64_MAX)
929 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
930 if (!tnum_is_unknown(reg->var_off)) {
933 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
934 verbose_a("var_off=%s", tn_buf);
936 if (reg->s32_min_value != reg->smin_value &&
937 reg->s32_min_value != S32_MIN)
938 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
939 if (reg->s32_max_value != reg->smax_value &&
940 reg->s32_max_value != S32_MAX)
941 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
942 if (reg->u32_min_value != reg->umin_value &&
943 reg->u32_min_value != U32_MIN)
944 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
945 if (reg->u32_max_value != reg->umax_value &&
946 reg->u32_max_value != U32_MAX)
947 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
954 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
955 char types_buf[BPF_REG_SIZE + 1];
959 for (j = 0; j < BPF_REG_SIZE; j++) {
960 if (state->stack[i].slot_type[j] != STACK_INVALID)
962 types_buf[j] = slot_type_char[
963 state->stack[i].slot_type[j]];
965 types_buf[BPF_REG_SIZE] = 0;
968 if (!print_all && !stack_slot_scratched(env, i))
970 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
971 print_liveness(env, state->stack[i].spilled_ptr.live);
972 if (is_spilled_reg(&state->stack[i])) {
973 reg = &state->stack[i].spilled_ptr;
975 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
976 if (t == SCALAR_VALUE && reg->precise)
978 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
979 verbose(env, "%lld", reg->var_off.value + reg->off);
981 verbose(env, "=%s", types_buf);
984 if (state->acquired_refs && state->refs[0].id) {
985 verbose(env, " refs=%d", state->refs[0].id);
986 for (i = 1; i < state->acquired_refs; i++)
987 if (state->refs[i].id)
988 verbose(env, ",%d", state->refs[i].id);
990 if (state->in_callback_fn)
992 if (state->in_async_callback_fn)
993 verbose(env, " async_cb");
995 mark_verifier_state_clean(env);
998 static inline u32 vlog_alignment(u32 pos)
1000 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1001 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1004 static void print_insn_state(struct bpf_verifier_env *env,
1005 const struct bpf_func_state *state)
1007 if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
1008 /* remove new line character */
1009 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1010 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1012 verbose(env, "%d:", env->insn_idx);
1014 print_verifier_state(env, state, false);
1017 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1018 * small to hold src. This is different from krealloc since we don't want to preserve
1019 * the contents of dst.
1021 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1024 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1028 if (ZERO_OR_NULL_PTR(src))
1031 if (unlikely(check_mul_overflow(n, size, &bytes)))
1034 if (ksize(dst) < ksize(src)) {
1036 dst = kmalloc_track_caller(kmalloc_size_roundup(bytes), flags);
1041 memcpy(dst, src, bytes);
1043 return dst ? dst : ZERO_SIZE_PTR;
1046 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1047 * small to hold new_n items. new items are zeroed out if the array grows.
1049 * Contrary to krealloc_array, does not free arr if new_n is zero.
1051 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1056 if (!new_n || old_n == new_n)
1059 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1060 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1068 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1071 return arr ? arr : ZERO_SIZE_PTR;
1074 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1076 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1077 sizeof(struct bpf_reference_state), GFP_KERNEL);
1081 dst->acquired_refs = src->acquired_refs;
1085 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1087 size_t n = src->allocated_stack / BPF_REG_SIZE;
1089 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1094 dst->allocated_stack = src->allocated_stack;
1098 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1100 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1101 sizeof(struct bpf_reference_state));
1105 state->acquired_refs = n;
1109 static int grow_stack_state(struct bpf_func_state *state, int size)
1111 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1116 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1120 state->allocated_stack = size;
1124 /* Acquire a pointer id from the env and update the state->refs to include
1125 * this new pointer reference.
1126 * On success, returns a valid pointer id to associate with the register
1127 * On failure, returns a negative errno.
1129 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1131 struct bpf_func_state *state = cur_func(env);
1132 int new_ofs = state->acquired_refs;
1135 err = resize_reference_state(state, state->acquired_refs + 1);
1139 state->refs[new_ofs].id = id;
1140 state->refs[new_ofs].insn_idx = insn_idx;
1141 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1146 /* release function corresponding to acquire_reference_state(). Idempotent. */
1147 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1151 last_idx = state->acquired_refs - 1;
1152 for (i = 0; i < state->acquired_refs; i++) {
1153 if (state->refs[i].id == ptr_id) {
1154 /* Cannot release caller references in callbacks */
1155 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1157 if (last_idx && i != last_idx)
1158 memcpy(&state->refs[i], &state->refs[last_idx],
1159 sizeof(*state->refs));
1160 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1161 state->acquired_refs--;
1168 static void free_func_state(struct bpf_func_state *state)
1173 kfree(state->stack);
1177 static void clear_jmp_history(struct bpf_verifier_state *state)
1179 kfree(state->jmp_history);
1180 state->jmp_history = NULL;
1181 state->jmp_history_cnt = 0;
1184 static void free_verifier_state(struct bpf_verifier_state *state,
1189 for (i = 0; i <= state->curframe; i++) {
1190 free_func_state(state->frame[i]);
1191 state->frame[i] = NULL;
1193 clear_jmp_history(state);
1198 /* copy verifier state from src to dst growing dst stack space
1199 * when necessary to accommodate larger src stack
1201 static int copy_func_state(struct bpf_func_state *dst,
1202 const struct bpf_func_state *src)
1206 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1207 err = copy_reference_state(dst, src);
1210 return copy_stack_state(dst, src);
1213 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1214 const struct bpf_verifier_state *src)
1216 struct bpf_func_state *dst;
1219 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1220 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1222 if (!dst_state->jmp_history)
1224 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1226 /* if dst has more stack frames then src frame, free them */
1227 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1228 free_func_state(dst_state->frame[i]);
1229 dst_state->frame[i] = NULL;
1231 dst_state->speculative = src->speculative;
1232 dst_state->active_rcu_lock = src->active_rcu_lock;
1233 dst_state->curframe = src->curframe;
1234 dst_state->active_lock.ptr = src->active_lock.ptr;
1235 dst_state->active_lock.id = src->active_lock.id;
1236 dst_state->branches = src->branches;
1237 dst_state->parent = src->parent;
1238 dst_state->first_insn_idx = src->first_insn_idx;
1239 dst_state->last_insn_idx = src->last_insn_idx;
1240 for (i = 0; i <= src->curframe; i++) {
1241 dst = dst_state->frame[i];
1243 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1246 dst_state->frame[i] = dst;
1248 err = copy_func_state(dst, src->frame[i]);
1255 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1258 u32 br = --st->branches;
1260 /* WARN_ON(br > 1) technically makes sense here,
1261 * but see comment in push_stack(), hence:
1263 WARN_ONCE((int)br < 0,
1264 "BUG update_branch_counts:branches_to_explore=%d\n",
1272 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1273 int *insn_idx, bool pop_log)
1275 struct bpf_verifier_state *cur = env->cur_state;
1276 struct bpf_verifier_stack_elem *elem, *head = env->head;
1279 if (env->head == NULL)
1283 err = copy_verifier_state(cur, &head->st);
1288 bpf_vlog_reset(&env->log, head->log_pos);
1290 *insn_idx = head->insn_idx;
1292 *prev_insn_idx = head->prev_insn_idx;
1294 free_verifier_state(&head->st, false);
1301 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1302 int insn_idx, int prev_insn_idx,
1305 struct bpf_verifier_state *cur = env->cur_state;
1306 struct bpf_verifier_stack_elem *elem;
1309 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1313 elem->insn_idx = insn_idx;
1314 elem->prev_insn_idx = prev_insn_idx;
1315 elem->next = env->head;
1316 elem->log_pos = env->log.len_used;
1319 err = copy_verifier_state(&elem->st, cur);
1322 elem->st.speculative |= speculative;
1323 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1324 verbose(env, "The sequence of %d jumps is too complex.\n",
1328 if (elem->st.parent) {
1329 ++elem->st.parent->branches;
1330 /* WARN_ON(branches > 2) technically makes sense here,
1332 * 1. speculative states will bump 'branches' for non-branch
1334 * 2. is_state_visited() heuristics may decide not to create
1335 * a new state for a sequence of branches and all such current
1336 * and cloned states will be pointing to a single parent state
1337 * which might have large 'branches' count.
1342 free_verifier_state(env->cur_state, true);
1343 env->cur_state = NULL;
1344 /* pop all elements and return */
1345 while (!pop_stack(env, NULL, NULL, false));
1349 #define CALLER_SAVED_REGS 6
1350 static const int caller_saved[CALLER_SAVED_REGS] = {
1351 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1354 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1355 struct bpf_reg_state *reg);
1357 /* This helper doesn't clear reg->id */
1358 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1360 reg->var_off = tnum_const(imm);
1361 reg->smin_value = (s64)imm;
1362 reg->smax_value = (s64)imm;
1363 reg->umin_value = imm;
1364 reg->umax_value = imm;
1366 reg->s32_min_value = (s32)imm;
1367 reg->s32_max_value = (s32)imm;
1368 reg->u32_min_value = (u32)imm;
1369 reg->u32_max_value = (u32)imm;
1372 /* Mark the unknown part of a register (variable offset or scalar value) as
1373 * known to have the value @imm.
1375 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1377 /* Clear id, off, and union(map_ptr, range) */
1378 memset(((u8 *)reg) + sizeof(reg->type), 0,
1379 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1380 ___mark_reg_known(reg, imm);
1383 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1385 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1386 reg->s32_min_value = (s32)imm;
1387 reg->s32_max_value = (s32)imm;
1388 reg->u32_min_value = (u32)imm;
1389 reg->u32_max_value = (u32)imm;
1392 /* Mark the 'variable offset' part of a register as zero. This should be
1393 * used only on registers holding a pointer type.
1395 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1397 __mark_reg_known(reg, 0);
1400 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1402 __mark_reg_known(reg, 0);
1403 reg->type = SCALAR_VALUE;
1406 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1407 struct bpf_reg_state *regs, u32 regno)
1409 if (WARN_ON(regno >= MAX_BPF_REG)) {
1410 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1411 /* Something bad happened, let's kill all regs */
1412 for (regno = 0; regno < MAX_BPF_REG; regno++)
1413 __mark_reg_not_init(env, regs + regno);
1416 __mark_reg_known_zero(regs + regno);
1419 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1421 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1422 const struct bpf_map *map = reg->map_ptr;
1424 if (map->inner_map_meta) {
1425 reg->type = CONST_PTR_TO_MAP;
1426 reg->map_ptr = map->inner_map_meta;
1427 /* transfer reg's id which is unique for every map_lookup_elem
1428 * as UID of the inner map.
1430 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1431 reg->map_uid = reg->id;
1432 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1433 reg->type = PTR_TO_XDP_SOCK;
1434 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1435 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1436 reg->type = PTR_TO_SOCKET;
1438 reg->type = PTR_TO_MAP_VALUE;
1443 reg->type &= ~PTR_MAYBE_NULL;
1446 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1448 return type_is_pkt_pointer(reg->type);
1451 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1453 return reg_is_pkt_pointer(reg) ||
1454 reg->type == PTR_TO_PACKET_END;
1457 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1458 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1459 enum bpf_reg_type which)
1461 /* The register can already have a range from prior markings.
1462 * This is fine as long as it hasn't been advanced from its
1465 return reg->type == which &&
1468 tnum_equals_const(reg->var_off, 0);
1471 /* Reset the min/max bounds of a register */
1472 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1474 reg->smin_value = S64_MIN;
1475 reg->smax_value = S64_MAX;
1476 reg->umin_value = 0;
1477 reg->umax_value = U64_MAX;
1479 reg->s32_min_value = S32_MIN;
1480 reg->s32_max_value = S32_MAX;
1481 reg->u32_min_value = 0;
1482 reg->u32_max_value = U32_MAX;
1485 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1487 reg->smin_value = S64_MIN;
1488 reg->smax_value = S64_MAX;
1489 reg->umin_value = 0;
1490 reg->umax_value = U64_MAX;
1493 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1495 reg->s32_min_value = S32_MIN;
1496 reg->s32_max_value = S32_MAX;
1497 reg->u32_min_value = 0;
1498 reg->u32_max_value = U32_MAX;
1501 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1503 struct tnum var32_off = tnum_subreg(reg->var_off);
1505 /* min signed is max(sign bit) | min(other bits) */
1506 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1507 var32_off.value | (var32_off.mask & S32_MIN));
1508 /* max signed is min(sign bit) | max(other bits) */
1509 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1510 var32_off.value | (var32_off.mask & S32_MAX));
1511 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1512 reg->u32_max_value = min(reg->u32_max_value,
1513 (u32)(var32_off.value | var32_off.mask));
1516 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1518 /* min signed is max(sign bit) | min(other bits) */
1519 reg->smin_value = max_t(s64, reg->smin_value,
1520 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1521 /* max signed is min(sign bit) | max(other bits) */
1522 reg->smax_value = min_t(s64, reg->smax_value,
1523 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1524 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1525 reg->umax_value = min(reg->umax_value,
1526 reg->var_off.value | reg->var_off.mask);
1529 static void __update_reg_bounds(struct bpf_reg_state *reg)
1531 __update_reg32_bounds(reg);
1532 __update_reg64_bounds(reg);
1535 /* Uses signed min/max values to inform unsigned, and vice-versa */
1536 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1538 /* Learn sign from signed bounds.
1539 * If we cannot cross the sign boundary, then signed and unsigned bounds
1540 * are the same, so combine. This works even in the negative case, e.g.
1541 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1543 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1544 reg->s32_min_value = reg->u32_min_value =
1545 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1546 reg->s32_max_value = reg->u32_max_value =
1547 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1550 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1551 * boundary, so we must be careful.
1553 if ((s32)reg->u32_max_value >= 0) {
1554 /* Positive. We can't learn anything from the smin, but smax
1555 * is positive, hence safe.
1557 reg->s32_min_value = reg->u32_min_value;
1558 reg->s32_max_value = reg->u32_max_value =
1559 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1560 } else if ((s32)reg->u32_min_value < 0) {
1561 /* Negative. We can't learn anything from the smax, but smin
1562 * is negative, hence safe.
1564 reg->s32_min_value = reg->u32_min_value =
1565 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1566 reg->s32_max_value = reg->u32_max_value;
1570 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1572 /* Learn sign from signed bounds.
1573 * If we cannot cross the sign boundary, then signed and unsigned bounds
1574 * are the same, so combine. This works even in the negative case, e.g.
1575 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1577 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1578 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1580 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1584 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1585 * boundary, so we must be careful.
1587 if ((s64)reg->umax_value >= 0) {
1588 /* Positive. We can't learn anything from the smin, but smax
1589 * is positive, hence safe.
1591 reg->smin_value = reg->umin_value;
1592 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1594 } else if ((s64)reg->umin_value < 0) {
1595 /* Negative. We can't learn anything from the smax, but smin
1596 * is negative, hence safe.
1598 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1600 reg->smax_value = reg->umax_value;
1604 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1606 __reg32_deduce_bounds(reg);
1607 __reg64_deduce_bounds(reg);
1610 /* Attempts to improve var_off based on unsigned min/max information */
1611 static void __reg_bound_offset(struct bpf_reg_state *reg)
1613 struct tnum var64_off = tnum_intersect(reg->var_off,
1614 tnum_range(reg->umin_value,
1616 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1617 tnum_range(reg->u32_min_value,
1618 reg->u32_max_value));
1620 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1623 static void reg_bounds_sync(struct bpf_reg_state *reg)
1625 /* We might have learned new bounds from the var_off. */
1626 __update_reg_bounds(reg);
1627 /* We might have learned something about the sign bit. */
1628 __reg_deduce_bounds(reg);
1629 /* We might have learned some bits from the bounds. */
1630 __reg_bound_offset(reg);
1631 /* Intersecting with the old var_off might have improved our bounds
1632 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1633 * then new var_off is (0; 0x7f...fc) which improves our umax.
1635 __update_reg_bounds(reg);
1638 static bool __reg32_bound_s64(s32 a)
1640 return a >= 0 && a <= S32_MAX;
1643 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1645 reg->umin_value = reg->u32_min_value;
1646 reg->umax_value = reg->u32_max_value;
1648 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1649 * be positive otherwise set to worse case bounds and refine later
1652 if (__reg32_bound_s64(reg->s32_min_value) &&
1653 __reg32_bound_s64(reg->s32_max_value)) {
1654 reg->smin_value = reg->s32_min_value;
1655 reg->smax_value = reg->s32_max_value;
1657 reg->smin_value = 0;
1658 reg->smax_value = U32_MAX;
1662 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1664 /* special case when 64-bit register has upper 32-bit register
1665 * zeroed. Typically happens after zext or <<32, >>32 sequence
1666 * allowing us to use 32-bit bounds directly,
1668 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1669 __reg_assign_32_into_64(reg);
1671 /* Otherwise the best we can do is push lower 32bit known and
1672 * unknown bits into register (var_off set from jmp logic)
1673 * then learn as much as possible from the 64-bit tnum
1674 * known and unknown bits. The previous smin/smax bounds are
1675 * invalid here because of jmp32 compare so mark them unknown
1676 * so they do not impact tnum bounds calculation.
1678 __mark_reg64_unbounded(reg);
1680 reg_bounds_sync(reg);
1683 static bool __reg64_bound_s32(s64 a)
1685 return a >= S32_MIN && a <= S32_MAX;
1688 static bool __reg64_bound_u32(u64 a)
1690 return a >= U32_MIN && a <= U32_MAX;
1693 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1695 __mark_reg32_unbounded(reg);
1696 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1697 reg->s32_min_value = (s32)reg->smin_value;
1698 reg->s32_max_value = (s32)reg->smax_value;
1700 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1701 reg->u32_min_value = (u32)reg->umin_value;
1702 reg->u32_max_value = (u32)reg->umax_value;
1704 reg_bounds_sync(reg);
1707 /* Mark a register as having a completely unknown (scalar) value. */
1708 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1709 struct bpf_reg_state *reg)
1712 * Clear type, id, off, and union(map_ptr, range) and
1713 * padding between 'type' and union
1715 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1716 reg->type = SCALAR_VALUE;
1717 reg->var_off = tnum_unknown;
1719 reg->precise = !env->bpf_capable;
1720 __mark_reg_unbounded(reg);
1723 static void mark_reg_unknown(struct bpf_verifier_env *env,
1724 struct bpf_reg_state *regs, u32 regno)
1726 if (WARN_ON(regno >= MAX_BPF_REG)) {
1727 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1728 /* Something bad happened, let's kill all regs except FP */
1729 for (regno = 0; regno < BPF_REG_FP; regno++)
1730 __mark_reg_not_init(env, regs + regno);
1733 __mark_reg_unknown(env, regs + regno);
1736 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1737 struct bpf_reg_state *reg)
1739 __mark_reg_unknown(env, reg);
1740 reg->type = NOT_INIT;
1743 static void mark_reg_not_init(struct bpf_verifier_env *env,
1744 struct bpf_reg_state *regs, u32 regno)
1746 if (WARN_ON(regno >= MAX_BPF_REG)) {
1747 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1748 /* Something bad happened, let's kill all regs except FP */
1749 for (regno = 0; regno < BPF_REG_FP; regno++)
1750 __mark_reg_not_init(env, regs + regno);
1753 __mark_reg_not_init(env, regs + regno);
1756 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1757 struct bpf_reg_state *regs, u32 regno,
1758 enum bpf_reg_type reg_type,
1759 struct btf *btf, u32 btf_id,
1760 enum bpf_type_flag flag)
1762 if (reg_type == SCALAR_VALUE) {
1763 mark_reg_unknown(env, regs, regno);
1766 mark_reg_known_zero(env, regs, regno);
1767 regs[regno].type = PTR_TO_BTF_ID | flag;
1768 regs[regno].btf = btf;
1769 regs[regno].btf_id = btf_id;
1772 #define DEF_NOT_SUBREG (0)
1773 static void init_reg_state(struct bpf_verifier_env *env,
1774 struct bpf_func_state *state)
1776 struct bpf_reg_state *regs = state->regs;
1779 for (i = 0; i < MAX_BPF_REG; i++) {
1780 mark_reg_not_init(env, regs, i);
1781 regs[i].live = REG_LIVE_NONE;
1782 regs[i].parent = NULL;
1783 regs[i].subreg_def = DEF_NOT_SUBREG;
1787 regs[BPF_REG_FP].type = PTR_TO_STACK;
1788 mark_reg_known_zero(env, regs, BPF_REG_FP);
1789 regs[BPF_REG_FP].frameno = state->frameno;
1792 #define BPF_MAIN_FUNC (-1)
1793 static void init_func_state(struct bpf_verifier_env *env,
1794 struct bpf_func_state *state,
1795 int callsite, int frameno, int subprogno)
1797 state->callsite = callsite;
1798 state->frameno = frameno;
1799 state->subprogno = subprogno;
1800 state->callback_ret_range = tnum_range(0, 0);
1801 init_reg_state(env, state);
1802 mark_verifier_state_scratched(env);
1805 /* Similar to push_stack(), but for async callbacks */
1806 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1807 int insn_idx, int prev_insn_idx,
1810 struct bpf_verifier_stack_elem *elem;
1811 struct bpf_func_state *frame;
1813 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1817 elem->insn_idx = insn_idx;
1818 elem->prev_insn_idx = prev_insn_idx;
1819 elem->next = env->head;
1820 elem->log_pos = env->log.len_used;
1823 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1825 "The sequence of %d jumps is too complex for async cb.\n",
1829 /* Unlike push_stack() do not copy_verifier_state().
1830 * The caller state doesn't matter.
1831 * This is async callback. It starts in a fresh stack.
1832 * Initialize it similar to do_check_common().
1834 elem->st.branches = 1;
1835 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1838 init_func_state(env, frame,
1839 BPF_MAIN_FUNC /* callsite */,
1840 0 /* frameno within this callchain */,
1841 subprog /* subprog number within this prog */);
1842 elem->st.frame[0] = frame;
1845 free_verifier_state(env->cur_state, true);
1846 env->cur_state = NULL;
1847 /* pop all elements and return */
1848 while (!pop_stack(env, NULL, NULL, false));
1854 SRC_OP, /* register is used as source operand */
1855 DST_OP, /* register is used as destination operand */
1856 DST_OP_NO_MARK /* same as above, check only, don't mark */
1859 static int cmp_subprogs(const void *a, const void *b)
1861 return ((struct bpf_subprog_info *)a)->start -
1862 ((struct bpf_subprog_info *)b)->start;
1865 static int find_subprog(struct bpf_verifier_env *env, int off)
1867 struct bpf_subprog_info *p;
1869 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1870 sizeof(env->subprog_info[0]), cmp_subprogs);
1873 return p - env->subprog_info;
1877 static int add_subprog(struct bpf_verifier_env *env, int off)
1879 int insn_cnt = env->prog->len;
1882 if (off >= insn_cnt || off < 0) {
1883 verbose(env, "call to invalid destination\n");
1886 ret = find_subprog(env, off);
1889 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1890 verbose(env, "too many subprograms\n");
1893 /* determine subprog starts. The end is one before the next starts */
1894 env->subprog_info[env->subprog_cnt++].start = off;
1895 sort(env->subprog_info, env->subprog_cnt,
1896 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1897 return env->subprog_cnt - 1;
1900 #define MAX_KFUNC_DESCS 256
1901 #define MAX_KFUNC_BTFS 256
1903 struct bpf_kfunc_desc {
1904 struct btf_func_model func_model;
1910 struct bpf_kfunc_btf {
1912 struct module *module;
1916 struct bpf_kfunc_desc_tab {
1917 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1921 struct bpf_kfunc_btf_tab {
1922 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1926 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1928 const struct bpf_kfunc_desc *d0 = a;
1929 const struct bpf_kfunc_desc *d1 = b;
1931 /* func_id is not greater than BTF_MAX_TYPE */
1932 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1935 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1937 const struct bpf_kfunc_btf *d0 = a;
1938 const struct bpf_kfunc_btf *d1 = b;
1940 return d0->offset - d1->offset;
1943 static const struct bpf_kfunc_desc *
1944 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1946 struct bpf_kfunc_desc desc = {
1950 struct bpf_kfunc_desc_tab *tab;
1952 tab = prog->aux->kfunc_tab;
1953 return bsearch(&desc, tab->descs, tab->nr_descs,
1954 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1957 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1960 struct bpf_kfunc_btf kf_btf = { .offset = offset };
1961 struct bpf_kfunc_btf_tab *tab;
1962 struct bpf_kfunc_btf *b;
1967 tab = env->prog->aux->kfunc_btf_tab;
1968 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1969 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1971 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1972 verbose(env, "too many different module BTFs\n");
1973 return ERR_PTR(-E2BIG);
1976 if (bpfptr_is_null(env->fd_array)) {
1977 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1978 return ERR_PTR(-EPROTO);
1981 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1982 offset * sizeof(btf_fd),
1984 return ERR_PTR(-EFAULT);
1986 btf = btf_get_by_fd(btf_fd);
1988 verbose(env, "invalid module BTF fd specified\n");
1992 if (!btf_is_module(btf)) {
1993 verbose(env, "BTF fd for kfunc is not a module BTF\n");
1995 return ERR_PTR(-EINVAL);
1998 mod = btf_try_get_module(btf);
2001 return ERR_PTR(-ENXIO);
2004 b = &tab->descs[tab->nr_descs++];
2009 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2010 kfunc_btf_cmp_by_off, NULL);
2015 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2020 while (tab->nr_descs--) {
2021 module_put(tab->descs[tab->nr_descs].module);
2022 btf_put(tab->descs[tab->nr_descs].btf);
2027 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2031 /* In the future, this can be allowed to increase limit
2032 * of fd index into fd_array, interpreted as u16.
2034 verbose(env, "negative offset disallowed for kernel module function call\n");
2035 return ERR_PTR(-EINVAL);
2038 return __find_kfunc_desc_btf(env, offset);
2040 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2043 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2045 const struct btf_type *func, *func_proto;
2046 struct bpf_kfunc_btf_tab *btf_tab;
2047 struct bpf_kfunc_desc_tab *tab;
2048 struct bpf_prog_aux *prog_aux;
2049 struct bpf_kfunc_desc *desc;
2050 const char *func_name;
2051 struct btf *desc_btf;
2052 unsigned long call_imm;
2056 prog_aux = env->prog->aux;
2057 tab = prog_aux->kfunc_tab;
2058 btf_tab = prog_aux->kfunc_btf_tab;
2061 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2065 if (!env->prog->jit_requested) {
2066 verbose(env, "JIT is required for calling kernel function\n");
2070 if (!bpf_jit_supports_kfunc_call()) {
2071 verbose(env, "JIT does not support calling kernel function\n");
2075 if (!env->prog->gpl_compatible) {
2076 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2080 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2083 prog_aux->kfunc_tab = tab;
2086 /* func_id == 0 is always invalid, but instead of returning an error, be
2087 * conservative and wait until the code elimination pass before returning
2088 * error, so that invalid calls that get pruned out can be in BPF programs
2089 * loaded from userspace. It is also required that offset be untouched
2092 if (!func_id && !offset)
2095 if (!btf_tab && offset) {
2096 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2099 prog_aux->kfunc_btf_tab = btf_tab;
2102 desc_btf = find_kfunc_desc_btf(env, offset);
2103 if (IS_ERR(desc_btf)) {
2104 verbose(env, "failed to find BTF for kernel function\n");
2105 return PTR_ERR(desc_btf);
2108 if (find_kfunc_desc(env->prog, func_id, offset))
2111 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2112 verbose(env, "too many different kernel function calls\n");
2116 func = btf_type_by_id(desc_btf, func_id);
2117 if (!func || !btf_type_is_func(func)) {
2118 verbose(env, "kernel btf_id %u is not a function\n",
2122 func_proto = btf_type_by_id(desc_btf, func->type);
2123 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2124 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2129 func_name = btf_name_by_offset(desc_btf, func->name_off);
2130 addr = kallsyms_lookup_name(func_name);
2132 verbose(env, "cannot find address for kernel function %s\n",
2137 call_imm = BPF_CALL_IMM(addr);
2138 /* Check whether or not the relative offset overflows desc->imm */
2139 if ((unsigned long)(s32)call_imm != call_imm) {
2140 verbose(env, "address of kernel function %s is out of range\n",
2145 desc = &tab->descs[tab->nr_descs++];
2146 desc->func_id = func_id;
2147 desc->imm = call_imm;
2148 desc->offset = offset;
2149 err = btf_distill_func_proto(&env->log, desc_btf,
2150 func_proto, func_name,
2153 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2154 kfunc_desc_cmp_by_id_off, NULL);
2158 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2160 const struct bpf_kfunc_desc *d0 = a;
2161 const struct bpf_kfunc_desc *d1 = b;
2163 if (d0->imm > d1->imm)
2165 else if (d0->imm < d1->imm)
2170 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2172 struct bpf_kfunc_desc_tab *tab;
2174 tab = prog->aux->kfunc_tab;
2178 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2179 kfunc_desc_cmp_by_imm, NULL);
2182 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2184 return !!prog->aux->kfunc_tab;
2187 const struct btf_func_model *
2188 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2189 const struct bpf_insn *insn)
2191 const struct bpf_kfunc_desc desc = {
2194 const struct bpf_kfunc_desc *res;
2195 struct bpf_kfunc_desc_tab *tab;
2197 tab = prog->aux->kfunc_tab;
2198 res = bsearch(&desc, tab->descs, tab->nr_descs,
2199 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2201 return res ? &res->func_model : NULL;
2204 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2206 struct bpf_subprog_info *subprog = env->subprog_info;
2207 struct bpf_insn *insn = env->prog->insnsi;
2208 int i, ret, insn_cnt = env->prog->len;
2210 /* Add entry function. */
2211 ret = add_subprog(env, 0);
2215 for (i = 0; i < insn_cnt; i++, insn++) {
2216 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2217 !bpf_pseudo_kfunc_call(insn))
2220 if (!env->bpf_capable) {
2221 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2225 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2226 ret = add_subprog(env, i + insn->imm + 1);
2228 ret = add_kfunc_call(env, insn->imm, insn->off);
2234 /* Add a fake 'exit' subprog which could simplify subprog iteration
2235 * logic. 'subprog_cnt' should not be increased.
2237 subprog[env->subprog_cnt].start = insn_cnt;
2239 if (env->log.level & BPF_LOG_LEVEL2)
2240 for (i = 0; i < env->subprog_cnt; i++)
2241 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2246 static int check_subprogs(struct bpf_verifier_env *env)
2248 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2249 struct bpf_subprog_info *subprog = env->subprog_info;
2250 struct bpf_insn *insn = env->prog->insnsi;
2251 int insn_cnt = env->prog->len;
2253 /* now check that all jumps are within the same subprog */
2254 subprog_start = subprog[cur_subprog].start;
2255 subprog_end = subprog[cur_subprog + 1].start;
2256 for (i = 0; i < insn_cnt; i++) {
2257 u8 code = insn[i].code;
2259 if (code == (BPF_JMP | BPF_CALL) &&
2260 insn[i].imm == BPF_FUNC_tail_call &&
2261 insn[i].src_reg != BPF_PSEUDO_CALL)
2262 subprog[cur_subprog].has_tail_call = true;
2263 if (BPF_CLASS(code) == BPF_LD &&
2264 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2265 subprog[cur_subprog].has_ld_abs = true;
2266 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2268 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2270 off = i + insn[i].off + 1;
2271 if (off < subprog_start || off >= subprog_end) {
2272 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2276 if (i == subprog_end - 1) {
2277 /* to avoid fall-through from one subprog into another
2278 * the last insn of the subprog should be either exit
2279 * or unconditional jump back
2281 if (code != (BPF_JMP | BPF_EXIT) &&
2282 code != (BPF_JMP | BPF_JA)) {
2283 verbose(env, "last insn is not an exit or jmp\n");
2286 subprog_start = subprog_end;
2288 if (cur_subprog < env->subprog_cnt)
2289 subprog_end = subprog[cur_subprog + 1].start;
2295 /* Parentage chain of this register (or stack slot) should take care of all
2296 * issues like callee-saved registers, stack slot allocation time, etc.
2298 static int mark_reg_read(struct bpf_verifier_env *env,
2299 const struct bpf_reg_state *state,
2300 struct bpf_reg_state *parent, u8 flag)
2302 bool writes = parent == state->parent; /* Observe write marks */
2306 /* if read wasn't screened by an earlier write ... */
2307 if (writes && state->live & REG_LIVE_WRITTEN)
2309 if (parent->live & REG_LIVE_DONE) {
2310 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2311 reg_type_str(env, parent->type),
2312 parent->var_off.value, parent->off);
2315 /* The first condition is more likely to be true than the
2316 * second, checked it first.
2318 if ((parent->live & REG_LIVE_READ) == flag ||
2319 parent->live & REG_LIVE_READ64)
2320 /* The parentage chain never changes and
2321 * this parent was already marked as LIVE_READ.
2322 * There is no need to keep walking the chain again and
2323 * keep re-marking all parents as LIVE_READ.
2324 * This case happens when the same register is read
2325 * multiple times without writes into it in-between.
2326 * Also, if parent has the stronger REG_LIVE_READ64 set,
2327 * then no need to set the weak REG_LIVE_READ32.
2330 /* ... then we depend on parent's value */
2331 parent->live |= flag;
2332 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2333 if (flag == REG_LIVE_READ64)
2334 parent->live &= ~REG_LIVE_READ32;
2336 parent = state->parent;
2341 if (env->longest_mark_read_walk < cnt)
2342 env->longest_mark_read_walk = cnt;
2346 /* This function is supposed to be used by the following 32-bit optimization
2347 * code only. It returns TRUE if the source or destination register operates
2348 * on 64-bit, otherwise return FALSE.
2350 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2351 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2356 class = BPF_CLASS(code);
2358 if (class == BPF_JMP) {
2359 /* BPF_EXIT for "main" will reach here. Return TRUE
2364 if (op == BPF_CALL) {
2365 /* BPF to BPF call will reach here because of marking
2366 * caller saved clobber with DST_OP_NO_MARK for which we
2367 * don't care the register def because they are anyway
2368 * marked as NOT_INIT already.
2370 if (insn->src_reg == BPF_PSEUDO_CALL)
2372 /* Helper call will reach here because of arg type
2373 * check, conservatively return TRUE.
2382 if (class == BPF_ALU64 || class == BPF_JMP ||
2383 /* BPF_END always use BPF_ALU class. */
2384 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2387 if (class == BPF_ALU || class == BPF_JMP32)
2390 if (class == BPF_LDX) {
2392 return BPF_SIZE(code) == BPF_DW;
2393 /* LDX source must be ptr. */
2397 if (class == BPF_STX) {
2398 /* BPF_STX (including atomic variants) has multiple source
2399 * operands, one of which is a ptr. Check whether the caller is
2402 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2404 return BPF_SIZE(code) == BPF_DW;
2407 if (class == BPF_LD) {
2408 u8 mode = BPF_MODE(code);
2411 if (mode == BPF_IMM)
2414 /* Both LD_IND and LD_ABS return 32-bit data. */
2418 /* Implicit ctx ptr. */
2419 if (regno == BPF_REG_6)
2422 /* Explicit source could be any width. */
2426 if (class == BPF_ST)
2427 /* The only source register for BPF_ST is a ptr. */
2430 /* Conservatively return true at default. */
2434 /* Return the regno defined by the insn, or -1. */
2435 static int insn_def_regno(const struct bpf_insn *insn)
2437 switch (BPF_CLASS(insn->code)) {
2443 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2444 (insn->imm & BPF_FETCH)) {
2445 if (insn->imm == BPF_CMPXCHG)
2448 return insn->src_reg;
2453 return insn->dst_reg;
2457 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2458 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2460 int dst_reg = insn_def_regno(insn);
2465 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2468 static void mark_insn_zext(struct bpf_verifier_env *env,
2469 struct bpf_reg_state *reg)
2471 s32 def_idx = reg->subreg_def;
2473 if (def_idx == DEF_NOT_SUBREG)
2476 env->insn_aux_data[def_idx - 1].zext_dst = true;
2477 /* The dst will be zero extended, so won't be sub-register anymore. */
2478 reg->subreg_def = DEF_NOT_SUBREG;
2481 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2482 enum reg_arg_type t)
2484 struct bpf_verifier_state *vstate = env->cur_state;
2485 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2486 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2487 struct bpf_reg_state *reg, *regs = state->regs;
2490 if (regno >= MAX_BPF_REG) {
2491 verbose(env, "R%d is invalid\n", regno);
2495 mark_reg_scratched(env, regno);
2498 rw64 = is_reg64(env, insn, regno, reg, t);
2500 /* check whether register used as source operand can be read */
2501 if (reg->type == NOT_INIT) {
2502 verbose(env, "R%d !read_ok\n", regno);
2505 /* We don't need to worry about FP liveness because it's read-only */
2506 if (regno == BPF_REG_FP)
2510 mark_insn_zext(env, reg);
2512 return mark_reg_read(env, reg, reg->parent,
2513 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2515 /* check whether register used as dest operand can be written to */
2516 if (regno == BPF_REG_FP) {
2517 verbose(env, "frame pointer is read only\n");
2520 reg->live |= REG_LIVE_WRITTEN;
2521 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2523 mark_reg_unknown(env, regs, regno);
2528 /* for any branch, call, exit record the history of jmps in the given state */
2529 static int push_jmp_history(struct bpf_verifier_env *env,
2530 struct bpf_verifier_state *cur)
2532 u32 cnt = cur->jmp_history_cnt;
2533 struct bpf_idx_pair *p;
2537 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2538 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2541 p[cnt - 1].idx = env->insn_idx;
2542 p[cnt - 1].prev_idx = env->prev_insn_idx;
2543 cur->jmp_history = p;
2544 cur->jmp_history_cnt = cnt;
2548 /* Backtrack one insn at a time. If idx is not at the top of recorded
2549 * history then previous instruction came from straight line execution.
2551 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2556 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2557 i = st->jmp_history[cnt - 1].prev_idx;
2565 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2567 const struct btf_type *func;
2568 struct btf *desc_btf;
2570 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2573 desc_btf = find_kfunc_desc_btf(data, insn->off);
2574 if (IS_ERR(desc_btf))
2577 func = btf_type_by_id(desc_btf, insn->imm);
2578 return btf_name_by_offset(desc_btf, func->name_off);
2581 /* For given verifier state backtrack_insn() is called from the last insn to
2582 * the first insn. Its purpose is to compute a bitmask of registers and
2583 * stack slots that needs precision in the parent verifier state.
2585 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2586 u32 *reg_mask, u64 *stack_mask)
2588 const struct bpf_insn_cbs cbs = {
2589 .cb_call = disasm_kfunc_name,
2590 .cb_print = verbose,
2591 .private_data = env,
2593 struct bpf_insn *insn = env->prog->insnsi + idx;
2594 u8 class = BPF_CLASS(insn->code);
2595 u8 opcode = BPF_OP(insn->code);
2596 u8 mode = BPF_MODE(insn->code);
2597 u32 dreg = 1u << insn->dst_reg;
2598 u32 sreg = 1u << insn->src_reg;
2601 if (insn->code == 0)
2603 if (env->log.level & BPF_LOG_LEVEL2) {
2604 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2605 verbose(env, "%d: ", idx);
2606 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2609 if (class == BPF_ALU || class == BPF_ALU64) {
2610 if (!(*reg_mask & dreg))
2612 if (opcode == BPF_MOV) {
2613 if (BPF_SRC(insn->code) == BPF_X) {
2615 * dreg needs precision after this insn
2616 * sreg needs precision before this insn
2622 * dreg needs precision after this insn.
2623 * Corresponding register is already marked
2624 * as precise=true in this verifier state.
2625 * No further markings in parent are necessary
2630 if (BPF_SRC(insn->code) == BPF_X) {
2632 * both dreg and sreg need precision
2637 * dreg still needs precision before this insn
2640 } else if (class == BPF_LDX) {
2641 if (!(*reg_mask & dreg))
2645 /* scalars can only be spilled into stack w/o losing precision.
2646 * Load from any other memory can be zero extended.
2647 * The desire to keep that precision is already indicated
2648 * by 'precise' mark in corresponding register of this state.
2649 * No further tracking necessary.
2651 if (insn->src_reg != BPF_REG_FP)
2654 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2655 * that [fp - off] slot contains scalar that needs to be
2656 * tracked with precision
2658 spi = (-insn->off - 1) / BPF_REG_SIZE;
2660 verbose(env, "BUG spi %d\n", spi);
2661 WARN_ONCE(1, "verifier backtracking bug");
2664 *stack_mask |= 1ull << spi;
2665 } else if (class == BPF_STX || class == BPF_ST) {
2666 if (*reg_mask & dreg)
2667 /* stx & st shouldn't be using _scalar_ dst_reg
2668 * to access memory. It means backtracking
2669 * encountered a case of pointer subtraction.
2672 /* scalars can only be spilled into stack */
2673 if (insn->dst_reg != BPF_REG_FP)
2675 spi = (-insn->off - 1) / BPF_REG_SIZE;
2677 verbose(env, "BUG spi %d\n", spi);
2678 WARN_ONCE(1, "verifier backtracking bug");
2681 if (!(*stack_mask & (1ull << spi)))
2683 *stack_mask &= ~(1ull << spi);
2684 if (class == BPF_STX)
2686 } else if (class == BPF_JMP || class == BPF_JMP32) {
2687 if (opcode == BPF_CALL) {
2688 if (insn->src_reg == BPF_PSEUDO_CALL)
2690 /* BPF helpers that invoke callback subprogs are
2691 * equivalent to BPF_PSEUDO_CALL above
2693 if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2695 /* regular helper call sets R0 */
2697 if (*reg_mask & 0x3f) {
2698 /* if backtracing was looking for registers R1-R5
2699 * they should have been found already.
2701 verbose(env, "BUG regs %x\n", *reg_mask);
2702 WARN_ONCE(1, "verifier backtracking bug");
2705 } else if (opcode == BPF_EXIT) {
2708 } else if (class == BPF_LD) {
2709 if (!(*reg_mask & dreg))
2712 /* It's ld_imm64 or ld_abs or ld_ind.
2713 * For ld_imm64 no further tracking of precision
2714 * into parent is necessary
2716 if (mode == BPF_IND || mode == BPF_ABS)
2717 /* to be analyzed */
2723 /* the scalar precision tracking algorithm:
2724 * . at the start all registers have precise=false.
2725 * . scalar ranges are tracked as normal through alu and jmp insns.
2726 * . once precise value of the scalar register is used in:
2727 * . ptr + scalar alu
2728 * . if (scalar cond K|scalar)
2729 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2730 * backtrack through the verifier states and mark all registers and
2731 * stack slots with spilled constants that these scalar regisers
2732 * should be precise.
2733 * . during state pruning two registers (or spilled stack slots)
2734 * are equivalent if both are not precise.
2736 * Note the verifier cannot simply walk register parentage chain,
2737 * since many different registers and stack slots could have been
2738 * used to compute single precise scalar.
2740 * The approach of starting with precise=true for all registers and then
2741 * backtrack to mark a register as not precise when the verifier detects
2742 * that program doesn't care about specific value (e.g., when helper
2743 * takes register as ARG_ANYTHING parameter) is not safe.
2745 * It's ok to walk single parentage chain of the verifier states.
2746 * It's possible that this backtracking will go all the way till 1st insn.
2747 * All other branches will be explored for needing precision later.
2749 * The backtracking needs to deal with cases like:
2750 * 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)
2753 * if r5 > 0x79f goto pc+7
2754 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2757 * call bpf_perf_event_output#25
2758 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2762 * call foo // uses callee's r6 inside to compute r0
2766 * to track above reg_mask/stack_mask needs to be independent for each frame.
2768 * Also if parent's curframe > frame where backtracking started,
2769 * the verifier need to mark registers in both frames, otherwise callees
2770 * may incorrectly prune callers. This is similar to
2771 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2773 * For now backtracking falls back into conservative marking.
2775 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2776 struct bpf_verifier_state *st)
2778 struct bpf_func_state *func;
2779 struct bpf_reg_state *reg;
2782 /* big hammer: mark all scalars precise in this path.
2783 * pop_stack may still get !precise scalars.
2784 * We also skip current state and go straight to first parent state,
2785 * because precision markings in current non-checkpointed state are
2786 * not needed. See why in the comment in __mark_chain_precision below.
2788 for (st = st->parent; st; st = st->parent) {
2789 for (i = 0; i <= st->curframe; i++) {
2790 func = st->frame[i];
2791 for (j = 0; j < BPF_REG_FP; j++) {
2792 reg = &func->regs[j];
2793 if (reg->type != SCALAR_VALUE)
2795 reg->precise = true;
2797 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2798 if (!is_spilled_reg(&func->stack[j]))
2800 reg = &func->stack[j].spilled_ptr;
2801 if (reg->type != SCALAR_VALUE)
2803 reg->precise = true;
2809 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2811 struct bpf_func_state *func;
2812 struct bpf_reg_state *reg;
2815 for (i = 0; i <= st->curframe; i++) {
2816 func = st->frame[i];
2817 for (j = 0; j < BPF_REG_FP; j++) {
2818 reg = &func->regs[j];
2819 if (reg->type != SCALAR_VALUE)
2821 reg->precise = false;
2823 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2824 if (!is_spilled_reg(&func->stack[j]))
2826 reg = &func->stack[j].spilled_ptr;
2827 if (reg->type != SCALAR_VALUE)
2829 reg->precise = false;
2835 * __mark_chain_precision() backtracks BPF program instruction sequence and
2836 * chain of verifier states making sure that register *regno* (if regno >= 0)
2837 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2838 * SCALARS, as well as any other registers and slots that contribute to
2839 * a tracked state of given registers/stack slots, depending on specific BPF
2840 * assembly instructions (see backtrack_insns() for exact instruction handling
2841 * logic). This backtracking relies on recorded jmp_history and is able to
2842 * traverse entire chain of parent states. This process ends only when all the
2843 * necessary registers/slots and their transitive dependencies are marked as
2846 * One important and subtle aspect is that precise marks *do not matter* in
2847 * the currently verified state (current state). It is important to understand
2848 * why this is the case.
2850 * First, note that current state is the state that is not yet "checkpointed",
2851 * i.e., it is not yet put into env->explored_states, and it has no children
2852 * states as well. It's ephemeral, and can end up either a) being discarded if
2853 * compatible explored state is found at some point or BPF_EXIT instruction is
2854 * reached or b) checkpointed and put into env->explored_states, branching out
2855 * into one or more children states.
2857 * In the former case, precise markings in current state are completely
2858 * ignored by state comparison code (see regsafe() for details). Only
2859 * checkpointed ("old") state precise markings are important, and if old
2860 * state's register/slot is precise, regsafe() assumes current state's
2861 * register/slot as precise and checks value ranges exactly and precisely. If
2862 * states turn out to be compatible, current state's necessary precise
2863 * markings and any required parent states' precise markings are enforced
2864 * after the fact with propagate_precision() logic, after the fact. But it's
2865 * important to realize that in this case, even after marking current state
2866 * registers/slots as precise, we immediately discard current state. So what
2867 * actually matters is any of the precise markings propagated into current
2868 * state's parent states, which are always checkpointed (due to b) case above).
2869 * As such, for scenario a) it doesn't matter if current state has precise
2870 * markings set or not.
2872 * Now, for the scenario b), checkpointing and forking into child(ren)
2873 * state(s). Note that before current state gets to checkpointing step, any
2874 * processed instruction always assumes precise SCALAR register/slot
2875 * knowledge: if precise value or range is useful to prune jump branch, BPF
2876 * verifier takes this opportunity enthusiastically. Similarly, when
2877 * register's value is used to calculate offset or memory address, exact
2878 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2879 * what we mentioned above about state comparison ignoring precise markings
2880 * during state comparison, BPF verifier ignores and also assumes precise
2881 * markings *at will* during instruction verification process. But as verifier
2882 * assumes precision, it also propagates any precision dependencies across
2883 * parent states, which are not yet finalized, so can be further restricted
2884 * based on new knowledge gained from restrictions enforced by their children
2885 * states. This is so that once those parent states are finalized, i.e., when
2886 * they have no more active children state, state comparison logic in
2887 * is_state_visited() would enforce strict and precise SCALAR ranges, if
2888 * required for correctness.
2890 * To build a bit more intuition, note also that once a state is checkpointed,
2891 * the path we took to get to that state is not important. This is crucial
2892 * property for state pruning. When state is checkpointed and finalized at
2893 * some instruction index, it can be correctly and safely used to "short
2894 * circuit" any *compatible* state that reaches exactly the same instruction
2895 * index. I.e., if we jumped to that instruction from a completely different
2896 * code path than original finalized state was derived from, it doesn't
2897 * matter, current state can be discarded because from that instruction
2898 * forward having a compatible state will ensure we will safely reach the
2899 * exit. States describe preconditions for further exploration, but completely
2900 * forget the history of how we got here.
2902 * This also means that even if we needed precise SCALAR range to get to
2903 * finalized state, but from that point forward *that same* SCALAR register is
2904 * never used in a precise context (i.e., it's precise value is not needed for
2905 * correctness), it's correct and safe to mark such register as "imprecise"
2906 * (i.e., precise marking set to false). This is what we rely on when we do
2907 * not set precise marking in current state. If no child state requires
2908 * precision for any given SCALAR register, it's safe to dictate that it can
2909 * be imprecise. If any child state does require this register to be precise,
2910 * we'll mark it precise later retroactively during precise markings
2911 * propagation from child state to parent states.
2913 * Skipping precise marking setting in current state is a mild version of
2914 * relying on the above observation. But we can utilize this property even
2915 * more aggressively by proactively forgetting any precise marking in the
2916 * current state (which we inherited from the parent state), right before we
2917 * checkpoint it and branch off into new child state. This is done by
2918 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2919 * finalized states which help in short circuiting more future states.
2921 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2924 struct bpf_verifier_state *st = env->cur_state;
2925 int first_idx = st->first_insn_idx;
2926 int last_idx = env->insn_idx;
2927 struct bpf_func_state *func;
2928 struct bpf_reg_state *reg;
2929 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2930 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2931 bool skip_first = true;
2932 bool new_marks = false;
2935 if (!env->bpf_capable)
2938 /* Do sanity checks against current state of register and/or stack
2939 * slot, but don't set precise flag in current state, as precision
2940 * tracking in the current state is unnecessary.
2942 func = st->frame[frame];
2944 reg = &func->regs[regno];
2945 if (reg->type != SCALAR_VALUE) {
2946 WARN_ONCE(1, "backtracing misuse");
2953 if (!is_spilled_reg(&func->stack[spi])) {
2957 reg = &func->stack[spi].spilled_ptr;
2958 if (reg->type != SCALAR_VALUE) {
2968 if (!reg_mask && !stack_mask)
2972 DECLARE_BITMAP(mask, 64);
2973 u32 history = st->jmp_history_cnt;
2975 if (env->log.level & BPF_LOG_LEVEL2)
2976 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2979 /* we are at the entry into subprog, which
2980 * is expected for global funcs, but only if
2981 * requested precise registers are R1-R5
2982 * (which are global func's input arguments)
2984 if (st->curframe == 0 &&
2985 st->frame[0]->subprogno > 0 &&
2986 st->frame[0]->callsite == BPF_MAIN_FUNC &&
2987 stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
2988 bitmap_from_u64(mask, reg_mask);
2989 for_each_set_bit(i, mask, 32) {
2990 reg = &st->frame[0]->regs[i];
2991 if (reg->type != SCALAR_VALUE) {
2992 reg_mask &= ~(1u << i);
2995 reg->precise = true;
3000 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3001 st->frame[0]->subprogno, reg_mask, stack_mask);
3002 WARN_ONCE(1, "verifier backtracking bug");
3006 for (i = last_idx;;) {
3011 err = backtrack_insn(env, i, ®_mask, &stack_mask);
3013 if (err == -ENOTSUPP) {
3014 mark_all_scalars_precise(env, st);
3019 if (!reg_mask && !stack_mask)
3020 /* Found assignment(s) into tracked register in this state.
3021 * Since this state is already marked, just return.
3022 * Nothing to be tracked further in the parent state.
3027 i = get_prev_insn_idx(st, i, &history);
3028 if (i >= env->prog->len) {
3029 /* This can happen if backtracking reached insn 0
3030 * and there are still reg_mask or stack_mask
3032 * It means the backtracking missed the spot where
3033 * particular register was initialized with a constant.
3035 verbose(env, "BUG backtracking idx %d\n", i);
3036 WARN_ONCE(1, "verifier backtracking bug");
3045 func = st->frame[frame];
3046 bitmap_from_u64(mask, reg_mask);
3047 for_each_set_bit(i, mask, 32) {
3048 reg = &func->regs[i];
3049 if (reg->type != SCALAR_VALUE) {
3050 reg_mask &= ~(1u << i);
3055 reg->precise = true;
3058 bitmap_from_u64(mask, stack_mask);
3059 for_each_set_bit(i, mask, 64) {
3060 if (i >= func->allocated_stack / BPF_REG_SIZE) {
3061 /* the sequence of instructions:
3063 * 3: (7b) *(u64 *)(r3 -8) = r0
3064 * 4: (79) r4 = *(u64 *)(r10 -8)
3065 * doesn't contain jmps. It's backtracked
3066 * as a single block.
3067 * During backtracking insn 3 is not recognized as
3068 * stack access, so at the end of backtracking
3069 * stack slot fp-8 is still marked in stack_mask.
3070 * However the parent state may not have accessed
3071 * fp-8 and it's "unallocated" stack space.
3072 * In such case fallback to conservative.
3074 mark_all_scalars_precise(env, st);
3078 if (!is_spilled_reg(&func->stack[i])) {
3079 stack_mask &= ~(1ull << i);
3082 reg = &func->stack[i].spilled_ptr;
3083 if (reg->type != SCALAR_VALUE) {
3084 stack_mask &= ~(1ull << i);
3089 reg->precise = true;
3091 if (env->log.level & BPF_LOG_LEVEL2) {
3092 verbose(env, "parent %s regs=%x stack=%llx marks:",
3093 new_marks ? "didn't have" : "already had",
3094 reg_mask, stack_mask);
3095 print_verifier_state(env, func, true);
3098 if (!reg_mask && !stack_mask)
3103 last_idx = st->last_insn_idx;
3104 first_idx = st->first_insn_idx;
3109 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3111 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3114 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3116 return __mark_chain_precision(env, frame, regno, -1);
3119 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3121 return __mark_chain_precision(env, frame, -1, spi);
3124 static bool is_spillable_regtype(enum bpf_reg_type type)
3126 switch (base_type(type)) {
3127 case PTR_TO_MAP_VALUE:
3131 case PTR_TO_PACKET_META:
3132 case PTR_TO_PACKET_END:
3133 case PTR_TO_FLOW_KEYS:
3134 case CONST_PTR_TO_MAP:
3136 case PTR_TO_SOCK_COMMON:
3137 case PTR_TO_TCP_SOCK:
3138 case PTR_TO_XDP_SOCK:
3143 case PTR_TO_MAP_KEY:
3150 /* Does this register contain a constant zero? */
3151 static bool register_is_null(struct bpf_reg_state *reg)
3153 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3156 static bool register_is_const(struct bpf_reg_state *reg)
3158 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3161 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3163 return tnum_is_unknown(reg->var_off) &&
3164 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3165 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3166 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3167 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3170 static bool register_is_bounded(struct bpf_reg_state *reg)
3172 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3175 static bool __is_pointer_value(bool allow_ptr_leaks,
3176 const struct bpf_reg_state *reg)
3178 if (allow_ptr_leaks)
3181 return reg->type != SCALAR_VALUE;
3184 static void save_register_state(struct bpf_func_state *state,
3185 int spi, struct bpf_reg_state *reg,
3190 state->stack[spi].spilled_ptr = *reg;
3191 if (size == BPF_REG_SIZE)
3192 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3194 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3195 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3197 /* size < 8 bytes spill */
3199 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3202 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3203 * stack boundary and alignment are checked in check_mem_access()
3205 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3206 /* stack frame we're writing to */
3207 struct bpf_func_state *state,
3208 int off, int size, int value_regno,
3211 struct bpf_func_state *cur; /* state of the current function */
3212 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3213 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3214 struct bpf_reg_state *reg = NULL;
3216 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3219 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3220 * so it's aligned access and [off, off + size) are within stack limits
3222 if (!env->allow_ptr_leaks &&
3223 state->stack[spi].slot_type[0] == STACK_SPILL &&
3224 size != BPF_REG_SIZE) {
3225 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3229 cur = env->cur_state->frame[env->cur_state->curframe];
3230 if (value_regno >= 0)
3231 reg = &cur->regs[value_regno];
3232 if (!env->bypass_spec_v4) {
3233 bool sanitize = reg && is_spillable_regtype(reg->type);
3235 for (i = 0; i < size; i++) {
3236 if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3243 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3246 mark_stack_slot_scratched(env, spi);
3247 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3248 !register_is_null(reg) && env->bpf_capable) {
3249 if (dst_reg != BPF_REG_FP) {
3250 /* The backtracking logic can only recognize explicit
3251 * stack slot address like [fp - 8]. Other spill of
3252 * scalar via different register has to be conservative.
3253 * Backtrack from here and mark all registers as precise
3254 * that contributed into 'reg' being a constant.
3256 err = mark_chain_precision(env, value_regno);
3260 save_register_state(state, spi, reg, size);
3261 } else if (reg && is_spillable_regtype(reg->type)) {
3262 /* register containing pointer is being spilled into stack */
3263 if (size != BPF_REG_SIZE) {
3264 verbose_linfo(env, insn_idx, "; ");
3265 verbose(env, "invalid size of register spill\n");
3268 if (state != cur && reg->type == PTR_TO_STACK) {
3269 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3272 save_register_state(state, spi, reg, size);
3274 u8 type = STACK_MISC;
3276 /* regular write of data into stack destroys any spilled ptr */
3277 state->stack[spi].spilled_ptr.type = NOT_INIT;
3278 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3279 if (is_spilled_reg(&state->stack[spi]))
3280 for (i = 0; i < BPF_REG_SIZE; i++)
3281 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3283 /* only mark the slot as written if all 8 bytes were written
3284 * otherwise read propagation may incorrectly stop too soon
3285 * when stack slots are partially written.
3286 * This heuristic means that read propagation will be
3287 * conservative, since it will add reg_live_read marks
3288 * to stack slots all the way to first state when programs
3289 * writes+reads less than 8 bytes
3291 if (size == BPF_REG_SIZE)
3292 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3294 /* when we zero initialize stack slots mark them as such */
3295 if (reg && register_is_null(reg)) {
3296 /* backtracking doesn't work for STACK_ZERO yet. */
3297 err = mark_chain_precision(env, value_regno);
3303 /* Mark slots affected by this stack write. */
3304 for (i = 0; i < size; i++)
3305 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3311 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3312 * known to contain a variable offset.
3313 * This function checks whether the write is permitted and conservatively
3314 * tracks the effects of the write, considering that each stack slot in the
3315 * dynamic range is potentially written to.
3317 * 'off' includes 'regno->off'.
3318 * 'value_regno' can be -1, meaning that an unknown value is being written to
3321 * Spilled pointers in range are not marked as written because we don't know
3322 * what's going to be actually written. This means that read propagation for
3323 * future reads cannot be terminated by this write.
3325 * For privileged programs, uninitialized stack slots are considered
3326 * initialized by this write (even though we don't know exactly what offsets
3327 * are going to be written to). The idea is that we don't want the verifier to
3328 * reject future reads that access slots written to through variable offsets.
3330 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3331 /* func where register points to */
3332 struct bpf_func_state *state,
3333 int ptr_regno, int off, int size,
3334 int value_regno, int insn_idx)
3336 struct bpf_func_state *cur; /* state of the current function */
3337 int min_off, max_off;
3339 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3340 bool writing_zero = false;
3341 /* set if the fact that we're writing a zero is used to let any
3342 * stack slots remain STACK_ZERO
3344 bool zero_used = false;
3346 cur = env->cur_state->frame[env->cur_state->curframe];
3347 ptr_reg = &cur->regs[ptr_regno];
3348 min_off = ptr_reg->smin_value + off;
3349 max_off = ptr_reg->smax_value + off + size;
3350 if (value_regno >= 0)
3351 value_reg = &cur->regs[value_regno];
3352 if (value_reg && register_is_null(value_reg))
3353 writing_zero = true;
3355 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3360 /* Variable offset writes destroy any spilled pointers in range. */
3361 for (i = min_off; i < max_off; i++) {
3362 u8 new_type, *stype;
3366 spi = slot / BPF_REG_SIZE;
3367 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3368 mark_stack_slot_scratched(env, spi);
3370 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3371 /* Reject the write if range we may write to has not
3372 * been initialized beforehand. If we didn't reject
3373 * here, the ptr status would be erased below (even
3374 * though not all slots are actually overwritten),
3375 * possibly opening the door to leaks.
3377 * We do however catch STACK_INVALID case below, and
3378 * only allow reading possibly uninitialized memory
3379 * later for CAP_PERFMON, as the write may not happen to
3382 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3387 /* Erase all spilled pointers. */
3388 state->stack[spi].spilled_ptr.type = NOT_INIT;
3390 /* Update the slot type. */
3391 new_type = STACK_MISC;
3392 if (writing_zero && *stype == STACK_ZERO) {
3393 new_type = STACK_ZERO;
3396 /* If the slot is STACK_INVALID, we check whether it's OK to
3397 * pretend that it will be initialized by this write. The slot
3398 * might not actually be written to, and so if we mark it as
3399 * initialized future reads might leak uninitialized memory.
3400 * For privileged programs, we will accept such reads to slots
3401 * that may or may not be written because, if we're reject
3402 * them, the error would be too confusing.
3404 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3405 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3412 /* backtracking doesn't work for STACK_ZERO yet. */
3413 err = mark_chain_precision(env, value_regno);
3420 /* When register 'dst_regno' is assigned some values from stack[min_off,
3421 * max_off), we set the register's type according to the types of the
3422 * respective stack slots. If all the stack values are known to be zeros, then
3423 * so is the destination reg. Otherwise, the register is considered to be
3424 * SCALAR. This function does not deal with register filling; the caller must
3425 * ensure that all spilled registers in the stack range have been marked as
3428 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3429 /* func where src register points to */
3430 struct bpf_func_state *ptr_state,
3431 int min_off, int max_off, int dst_regno)
3433 struct bpf_verifier_state *vstate = env->cur_state;
3434 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3439 for (i = min_off; i < max_off; i++) {
3441 spi = slot / BPF_REG_SIZE;
3442 stype = ptr_state->stack[spi].slot_type;
3443 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3447 if (zeros == max_off - min_off) {
3448 /* any access_size read into register is zero extended,
3449 * so the whole register == const_zero
3451 __mark_reg_const_zero(&state->regs[dst_regno]);
3452 /* backtracking doesn't support STACK_ZERO yet,
3453 * so mark it precise here, so that later
3454 * backtracking can stop here.
3455 * Backtracking may not need this if this register
3456 * doesn't participate in pointer adjustment.
3457 * Forward propagation of precise flag is not
3458 * necessary either. This mark is only to stop
3459 * backtracking. Any register that contributed
3460 * to const 0 was marked precise before spill.
3462 state->regs[dst_regno].precise = true;
3464 /* have read misc data from the stack */
3465 mark_reg_unknown(env, state->regs, dst_regno);
3467 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3470 /* Read the stack at 'off' and put the results into the register indicated by
3471 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3474 * 'dst_regno' can be -1, meaning that the read value is not going to a
3477 * The access is assumed to be within the current stack bounds.
3479 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3480 /* func where src register points to */
3481 struct bpf_func_state *reg_state,
3482 int off, int size, int dst_regno)
3484 struct bpf_verifier_state *vstate = env->cur_state;
3485 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3486 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3487 struct bpf_reg_state *reg;
3490 stype = reg_state->stack[spi].slot_type;
3491 reg = ®_state->stack[spi].spilled_ptr;
3493 if (is_spilled_reg(®_state->stack[spi])) {
3496 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3499 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3500 if (reg->type != SCALAR_VALUE) {
3501 verbose_linfo(env, env->insn_idx, "; ");
3502 verbose(env, "invalid size of register fill\n");
3506 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3510 if (!(off % BPF_REG_SIZE) && size == spill_size) {
3511 /* The earlier check_reg_arg() has decided the
3512 * subreg_def for this insn. Save it first.
3514 s32 subreg_def = state->regs[dst_regno].subreg_def;
3516 state->regs[dst_regno] = *reg;
3517 state->regs[dst_regno].subreg_def = subreg_def;
3519 for (i = 0; i < size; i++) {
3520 type = stype[(slot - i) % BPF_REG_SIZE];
3521 if (type == STACK_SPILL)
3523 if (type == STACK_MISC)
3525 verbose(env, "invalid read from stack off %d+%d size %d\n",
3529 mark_reg_unknown(env, state->regs, dst_regno);
3531 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3535 if (dst_regno >= 0) {
3536 /* restore register state from stack */
3537 state->regs[dst_regno] = *reg;
3538 /* mark reg as written since spilled pointer state likely
3539 * has its liveness marks cleared by is_state_visited()
3540 * which resets stack/reg liveness for state transitions
3542 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3543 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3544 /* If dst_regno==-1, the caller is asking us whether
3545 * it is acceptable to use this value as a SCALAR_VALUE
3547 * We must not allow unprivileged callers to do that
3548 * with spilled pointers.
3550 verbose(env, "leaking pointer from stack off %d\n",
3554 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3556 for (i = 0; i < size; i++) {
3557 type = stype[(slot - i) % BPF_REG_SIZE];
3558 if (type == STACK_MISC)
3560 if (type == STACK_ZERO)
3562 verbose(env, "invalid read from stack off %d+%d size %d\n",
3566 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3568 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3573 enum bpf_access_src {
3574 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
3575 ACCESS_HELPER = 2, /* the access is performed by a helper */
3578 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3579 int regno, int off, int access_size,
3580 bool zero_size_allowed,
3581 enum bpf_access_src type,
3582 struct bpf_call_arg_meta *meta);
3584 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3586 return cur_regs(env) + regno;
3589 /* Read the stack at 'ptr_regno + off' and put the result into the register
3591 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3592 * but not its variable offset.
3593 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3595 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3596 * filling registers (i.e. reads of spilled register cannot be detected when
3597 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3598 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3599 * offset; for a fixed offset check_stack_read_fixed_off should be used
3602 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3603 int ptr_regno, int off, int size, int dst_regno)
3605 /* The state of the source register. */
3606 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3607 struct bpf_func_state *ptr_state = func(env, reg);
3609 int min_off, max_off;
3611 /* Note that we pass a NULL meta, so raw access will not be permitted.
3613 err = check_stack_range_initialized(env, ptr_regno, off, size,
3614 false, ACCESS_DIRECT, NULL);
3618 min_off = reg->smin_value + off;
3619 max_off = reg->smax_value + off;
3620 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3624 /* check_stack_read dispatches to check_stack_read_fixed_off or
3625 * check_stack_read_var_off.
3627 * The caller must ensure that the offset falls within the allocated stack
3630 * 'dst_regno' is a register which will receive the value from the stack. It
3631 * can be -1, meaning that the read value is not going to a register.
3633 static int check_stack_read(struct bpf_verifier_env *env,
3634 int ptr_regno, int off, int size,
3637 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3638 struct bpf_func_state *state = func(env, reg);
3640 /* Some accesses are only permitted with a static offset. */
3641 bool var_off = !tnum_is_const(reg->var_off);
3643 /* The offset is required to be static when reads don't go to a
3644 * register, in order to not leak pointers (see
3645 * check_stack_read_fixed_off).
3647 if (dst_regno < 0 && var_off) {
3650 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3651 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3655 /* Variable offset is prohibited for unprivileged mode for simplicity
3656 * since it requires corresponding support in Spectre masking for stack
3657 * ALU. See also retrieve_ptr_limit().
3659 if (!env->bypass_spec_v1 && var_off) {
3662 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3663 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3669 off += reg->var_off.value;
3670 err = check_stack_read_fixed_off(env, state, off, size,
3673 /* Variable offset stack reads need more conservative handling
3674 * than fixed offset ones. Note that dst_regno >= 0 on this
3677 err = check_stack_read_var_off(env, ptr_regno, off, size,
3684 /* check_stack_write dispatches to check_stack_write_fixed_off or
3685 * check_stack_write_var_off.
3687 * 'ptr_regno' is the register used as a pointer into the stack.
3688 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3689 * 'value_regno' is the register whose value we're writing to the stack. It can
3690 * be -1, meaning that we're not writing from a register.
3692 * The caller must ensure that the offset falls within the maximum stack size.
3694 static int check_stack_write(struct bpf_verifier_env *env,
3695 int ptr_regno, int off, int size,
3696 int value_regno, int insn_idx)
3698 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3699 struct bpf_func_state *state = func(env, reg);
3702 if (tnum_is_const(reg->var_off)) {
3703 off += reg->var_off.value;
3704 err = check_stack_write_fixed_off(env, state, off, size,
3705 value_regno, insn_idx);
3707 /* Variable offset stack reads need more conservative handling
3708 * than fixed offset ones.
3710 err = check_stack_write_var_off(env, state,
3711 ptr_regno, off, size,
3712 value_regno, insn_idx);
3717 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3718 int off, int size, enum bpf_access_type type)
3720 struct bpf_reg_state *regs = cur_regs(env);
3721 struct bpf_map *map = regs[regno].map_ptr;
3722 u32 cap = bpf_map_flags_to_cap(map);
3724 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3725 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3726 map->value_size, off, size);
3730 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3731 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3732 map->value_size, off, size);
3739 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3740 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3741 int off, int size, u32 mem_size,
3742 bool zero_size_allowed)
3744 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3745 struct bpf_reg_state *reg;
3747 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3750 reg = &cur_regs(env)[regno];
3751 switch (reg->type) {
3752 case PTR_TO_MAP_KEY:
3753 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3754 mem_size, off, size);
3756 case PTR_TO_MAP_VALUE:
3757 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3758 mem_size, off, size);
3761 case PTR_TO_PACKET_META:
3762 case PTR_TO_PACKET_END:
3763 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3764 off, size, regno, reg->id, off, mem_size);
3768 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3769 mem_size, off, size);
3775 /* check read/write into a memory region with possible variable offset */
3776 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3777 int off, int size, u32 mem_size,
3778 bool zero_size_allowed)
3780 struct bpf_verifier_state *vstate = env->cur_state;
3781 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3782 struct bpf_reg_state *reg = &state->regs[regno];
3785 /* We may have adjusted the register pointing to memory region, so we
3786 * need to try adding each of min_value and max_value to off
3787 * to make sure our theoretical access will be safe.
3789 * The minimum value is only important with signed
3790 * comparisons where we can't assume the floor of a
3791 * value is 0. If we are using signed variables for our
3792 * index'es we need to make sure that whatever we use
3793 * will have a set floor within our range.
3795 if (reg->smin_value < 0 &&
3796 (reg->smin_value == S64_MIN ||
3797 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3798 reg->smin_value + off < 0)) {
3799 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3803 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3804 mem_size, zero_size_allowed);
3806 verbose(env, "R%d min value is outside of the allowed memory range\n",
3811 /* If we haven't set a max value then we need to bail since we can't be
3812 * sure we won't do bad things.
3813 * If reg->umax_value + off could overflow, treat that as unbounded too.
3815 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3816 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3820 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3821 mem_size, zero_size_allowed);
3823 verbose(env, "R%d max value is outside of the allowed memory range\n",
3831 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3832 const struct bpf_reg_state *reg, int regno,
3835 /* Access to this pointer-typed register or passing it to a helper
3836 * is only allowed in its original, unmodified form.
3840 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3841 reg_type_str(env, reg->type), regno, reg->off);
3845 if (!fixed_off_ok && reg->off) {
3846 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3847 reg_type_str(env, reg->type), regno, reg->off);
3851 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3854 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3855 verbose(env, "variable %s access var_off=%s disallowed\n",
3856 reg_type_str(env, reg->type), tn_buf);
3863 int check_ptr_off_reg(struct bpf_verifier_env *env,
3864 const struct bpf_reg_state *reg, int regno)
3866 return __check_ptr_off_reg(env, reg, regno, false);
3869 static int map_kptr_match_type(struct bpf_verifier_env *env,
3870 struct btf_field *kptr_field,
3871 struct bpf_reg_state *reg, u32 regno)
3873 const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
3874 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED;
3875 const char *reg_name = "";
3877 /* Only unreferenced case accepts untrusted pointers */
3878 if (kptr_field->type == BPF_KPTR_UNREF)
3879 perm_flags |= PTR_UNTRUSTED;
3881 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3884 if (!btf_is_kernel(reg->btf)) {
3885 verbose(env, "R%d must point to kernel BTF\n", regno);
3888 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3889 reg_name = kernel_type_name(reg->btf, reg->btf_id);
3891 /* For ref_ptr case, release function check should ensure we get one
3892 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3893 * normal store of unreferenced kptr, we must ensure var_off is zero.
3894 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3895 * reg->off and reg->ref_obj_id are not needed here.
3897 if (__check_ptr_off_reg(env, reg, regno, true))
3900 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3901 * we also need to take into account the reg->off.
3903 * We want to support cases like:
3911 * v = func(); // PTR_TO_BTF_ID
3912 * val->foo = v; // reg->off is zero, btf and btf_id match type
3913 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3914 * // first member type of struct after comparison fails
3915 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3918 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3919 * is zero. We must also ensure that btf_struct_ids_match does not walk
3920 * the struct to match type against first member of struct, i.e. reject
3921 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3922 * strict mode to true for type match.
3924 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3925 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
3926 kptr_field->type == BPF_KPTR_REF))
3930 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3931 reg_type_str(env, reg->type), reg_name);
3932 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3933 if (kptr_field->type == BPF_KPTR_UNREF)
3934 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3941 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3942 int value_regno, int insn_idx,
3943 struct btf_field *kptr_field)
3945 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3946 int class = BPF_CLASS(insn->code);
3947 struct bpf_reg_state *val_reg;
3949 /* Things we already checked for in check_map_access and caller:
3950 * - Reject cases where variable offset may touch kptr
3951 * - size of access (must be BPF_DW)
3952 * - tnum_is_const(reg->var_off)
3953 * - kptr_field->offset == off + reg->var_off.value
3955 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3956 if (BPF_MODE(insn->code) != BPF_MEM) {
3957 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3961 /* We only allow loading referenced kptr, since it will be marked as
3962 * untrusted, similar to unreferenced kptr.
3964 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
3965 verbose(env, "store to referenced kptr disallowed\n");
3969 if (class == BPF_LDX) {
3970 val_reg = reg_state(env, value_regno);
3971 /* We can simply mark the value_regno receiving the pointer
3972 * value from map as PTR_TO_BTF_ID, with the correct type.
3974 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
3975 kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3976 /* For mark_ptr_or_null_reg */
3977 val_reg->id = ++env->id_gen;
3978 } else if (class == BPF_STX) {
3979 val_reg = reg_state(env, value_regno);
3980 if (!register_is_null(val_reg) &&
3981 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
3983 } else if (class == BPF_ST) {
3985 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3986 kptr_field->offset);
3990 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3996 /* check read/write into a map element with possible variable offset */
3997 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3998 int off, int size, bool zero_size_allowed,
3999 enum bpf_access_src src)
4001 struct bpf_verifier_state *vstate = env->cur_state;
4002 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4003 struct bpf_reg_state *reg = &state->regs[regno];
4004 struct bpf_map *map = reg->map_ptr;
4005 struct btf_record *rec;
4008 err = check_mem_region_access(env, regno, off, size, map->value_size,
4013 if (IS_ERR_OR_NULL(map->record))
4016 for (i = 0; i < rec->cnt; i++) {
4017 struct btf_field *field = &rec->fields[i];
4018 u32 p = field->offset;
4020 /* If any part of a field can be touched by load/store, reject
4021 * this program. To check that [x1, x2) overlaps with [y1, y2),
4022 * it is sufficient to check x1 < y2 && y1 < x2.
4024 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4025 p < reg->umax_value + off + size) {
4026 switch (field->type) {
4027 case BPF_KPTR_UNREF:
4029 if (src != ACCESS_DIRECT) {
4030 verbose(env, "kptr cannot be accessed indirectly by helper\n");
4033 if (!tnum_is_const(reg->var_off)) {
4034 verbose(env, "kptr access cannot have variable offset\n");
4037 if (p != off + reg->var_off.value) {
4038 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4039 p, off + reg->var_off.value);
4042 if (size != bpf_size_to_bytes(BPF_DW)) {
4043 verbose(env, "kptr access size must be BPF_DW\n");
4048 verbose(env, "%s cannot be accessed directly by load/store\n",
4049 btf_field_type_name(field->type));
4057 #define MAX_PACKET_OFF 0xffff
4059 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4060 const struct bpf_call_arg_meta *meta,
4061 enum bpf_access_type t)
4063 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4065 switch (prog_type) {
4066 /* Program types only with direct read access go here! */
4067 case BPF_PROG_TYPE_LWT_IN:
4068 case BPF_PROG_TYPE_LWT_OUT:
4069 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4070 case BPF_PROG_TYPE_SK_REUSEPORT:
4071 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4072 case BPF_PROG_TYPE_CGROUP_SKB:
4077 /* Program types with direct read + write access go here! */
4078 case BPF_PROG_TYPE_SCHED_CLS:
4079 case BPF_PROG_TYPE_SCHED_ACT:
4080 case BPF_PROG_TYPE_XDP:
4081 case BPF_PROG_TYPE_LWT_XMIT:
4082 case BPF_PROG_TYPE_SK_SKB:
4083 case BPF_PROG_TYPE_SK_MSG:
4085 return meta->pkt_access;
4087 env->seen_direct_write = true;
4090 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4092 env->seen_direct_write = true;
4101 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4102 int size, bool zero_size_allowed)
4104 struct bpf_reg_state *regs = cur_regs(env);
4105 struct bpf_reg_state *reg = ®s[regno];
4108 /* We may have added a variable offset to the packet pointer; but any
4109 * reg->range we have comes after that. We are only checking the fixed
4113 /* We don't allow negative numbers, because we aren't tracking enough
4114 * detail to prove they're safe.
4116 if (reg->smin_value < 0) {
4117 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4122 err = reg->range < 0 ? -EINVAL :
4123 __check_mem_access(env, regno, off, size, reg->range,
4126 verbose(env, "R%d offset is outside of the packet\n", regno);
4130 /* __check_mem_access has made sure "off + size - 1" is within u16.
4131 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4132 * otherwise find_good_pkt_pointers would have refused to set range info
4133 * that __check_mem_access would have rejected this pkt access.
4134 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4136 env->prog->aux->max_pkt_offset =
4137 max_t(u32, env->prog->aux->max_pkt_offset,
4138 off + reg->umax_value + size - 1);
4143 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
4144 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4145 enum bpf_access_type t, enum bpf_reg_type *reg_type,
4146 struct btf **btf, u32 *btf_id)
4148 struct bpf_insn_access_aux info = {
4149 .reg_type = *reg_type,
4153 if (env->ops->is_valid_access &&
4154 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4155 /* A non zero info.ctx_field_size indicates that this field is a
4156 * candidate for later verifier transformation to load the whole
4157 * field and then apply a mask when accessed with a narrower
4158 * access than actual ctx access size. A zero info.ctx_field_size
4159 * will only allow for whole field access and rejects any other
4160 * type of narrower access.
4162 *reg_type = info.reg_type;
4164 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4166 *btf_id = info.btf_id;
4168 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4170 /* remember the offset of last byte accessed in ctx */
4171 if (env->prog->aux->max_ctx_offset < off + size)
4172 env->prog->aux->max_ctx_offset = off + size;
4176 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4180 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4183 if (size < 0 || off < 0 ||
4184 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4185 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4192 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4193 u32 regno, int off, int size,
4194 enum bpf_access_type t)
4196 struct bpf_reg_state *regs = cur_regs(env);
4197 struct bpf_reg_state *reg = ®s[regno];
4198 struct bpf_insn_access_aux info = {};
4201 if (reg->smin_value < 0) {
4202 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4207 switch (reg->type) {
4208 case PTR_TO_SOCK_COMMON:
4209 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4212 valid = bpf_sock_is_valid_access(off, size, t, &info);
4214 case PTR_TO_TCP_SOCK:
4215 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4217 case PTR_TO_XDP_SOCK:
4218 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4226 env->insn_aux_data[insn_idx].ctx_field_size =
4227 info.ctx_field_size;
4231 verbose(env, "R%d invalid %s access off=%d size=%d\n",
4232 regno, reg_type_str(env, reg->type), off, size);
4237 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4239 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4242 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4244 const struct bpf_reg_state *reg = reg_state(env, regno);
4246 return reg->type == PTR_TO_CTX;
4249 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4251 const struct bpf_reg_state *reg = reg_state(env, regno);
4253 return type_is_sk_pointer(reg->type);
4256 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4258 const struct bpf_reg_state *reg = reg_state(env, regno);
4260 return type_is_pkt_pointer(reg->type);
4263 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4265 const struct bpf_reg_state *reg = reg_state(env, regno);
4267 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4268 return reg->type == PTR_TO_FLOW_KEYS;
4271 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4273 /* A referenced register is always trusted. */
4274 if (reg->ref_obj_id)
4277 /* If a register is not referenced, it is trusted if it has the
4278 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4279 * other type modifiers may be safe, but we elect to take an opt-in
4280 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4283 * Eventually, we should make PTR_TRUSTED the single source of truth
4284 * for whether a register is trusted.
4286 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4287 !bpf_type_has_unsafe_modifiers(reg->type);
4290 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4292 return reg->type & MEM_RCU;
4295 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4296 const struct bpf_reg_state *reg,
4297 int off, int size, bool strict)
4299 struct tnum reg_off;
4302 /* Byte size accesses are always allowed. */
4303 if (!strict || size == 1)
4306 /* For platforms that do not have a Kconfig enabling
4307 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4308 * NET_IP_ALIGN is universally set to '2'. And on platforms
4309 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4310 * to this code only in strict mode where we want to emulate
4311 * the NET_IP_ALIGN==2 checking. Therefore use an
4312 * unconditional IP align value of '2'.
4316 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4317 if (!tnum_is_aligned(reg_off, size)) {
4320 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4322 "misaligned packet access off %d+%s+%d+%d size %d\n",
4323 ip_align, tn_buf, reg->off, off, size);
4330 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4331 const struct bpf_reg_state *reg,
4332 const char *pointer_desc,
4333 int off, int size, bool strict)
4335 struct tnum reg_off;
4337 /* Byte size accesses are always allowed. */
4338 if (!strict || size == 1)
4341 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4342 if (!tnum_is_aligned(reg_off, size)) {
4345 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4346 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4347 pointer_desc, tn_buf, reg->off, off, size);
4354 static int check_ptr_alignment(struct bpf_verifier_env *env,
4355 const struct bpf_reg_state *reg, int off,
4356 int size, bool strict_alignment_once)
4358 bool strict = env->strict_alignment || strict_alignment_once;
4359 const char *pointer_desc = "";
4361 switch (reg->type) {
4363 case PTR_TO_PACKET_META:
4364 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4365 * right in front, treat it the very same way.
4367 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4368 case PTR_TO_FLOW_KEYS:
4369 pointer_desc = "flow keys ";
4371 case PTR_TO_MAP_KEY:
4372 pointer_desc = "key ";
4374 case PTR_TO_MAP_VALUE:
4375 pointer_desc = "value ";
4378 pointer_desc = "context ";
4381 pointer_desc = "stack ";
4382 /* The stack spill tracking logic in check_stack_write_fixed_off()
4383 * and check_stack_read_fixed_off() relies on stack accesses being
4389 pointer_desc = "sock ";
4391 case PTR_TO_SOCK_COMMON:
4392 pointer_desc = "sock_common ";
4394 case PTR_TO_TCP_SOCK:
4395 pointer_desc = "tcp_sock ";
4397 case PTR_TO_XDP_SOCK:
4398 pointer_desc = "xdp_sock ";
4403 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4407 static int update_stack_depth(struct bpf_verifier_env *env,
4408 const struct bpf_func_state *func,
4411 u16 stack = env->subprog_info[func->subprogno].stack_depth;
4416 /* update known max for given subprogram */
4417 env->subprog_info[func->subprogno].stack_depth = -off;
4421 /* starting from main bpf function walk all instructions of the function
4422 * and recursively walk all callees that given function can call.
4423 * Ignore jump and exit insns.
4424 * Since recursion is prevented by check_cfg() this algorithm
4425 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4427 static int check_max_stack_depth(struct bpf_verifier_env *env)
4429 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4430 struct bpf_subprog_info *subprog = env->subprog_info;
4431 struct bpf_insn *insn = env->prog->insnsi;
4432 bool tail_call_reachable = false;
4433 int ret_insn[MAX_CALL_FRAMES];
4434 int ret_prog[MAX_CALL_FRAMES];
4438 /* protect against potential stack overflow that might happen when
4439 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4440 * depth for such case down to 256 so that the worst case scenario
4441 * would result in 8k stack size (32 which is tailcall limit * 256 =
4444 * To get the idea what might happen, see an example:
4445 * func1 -> sub rsp, 128
4446 * subfunc1 -> sub rsp, 256
4447 * tailcall1 -> add rsp, 256
4448 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4449 * subfunc2 -> sub rsp, 64
4450 * subfunc22 -> sub rsp, 128
4451 * tailcall2 -> add rsp, 128
4452 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4454 * tailcall will unwind the current stack frame but it will not get rid
4455 * of caller's stack as shown on the example above.
4457 if (idx && subprog[idx].has_tail_call && depth >= 256) {
4459 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4463 /* round up to 32-bytes, since this is granularity
4464 * of interpreter stack size
4466 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4467 if (depth > MAX_BPF_STACK) {
4468 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4473 subprog_end = subprog[idx + 1].start;
4474 for (; i < subprog_end; i++) {
4477 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4479 /* remember insn and function to return to */
4480 ret_insn[frame] = i + 1;
4481 ret_prog[frame] = idx;
4483 /* find the callee */
4484 next_insn = i + insn[i].imm + 1;
4485 idx = find_subprog(env, next_insn);
4487 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4491 if (subprog[idx].is_async_cb) {
4492 if (subprog[idx].has_tail_call) {
4493 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4496 /* async callbacks don't increase bpf prog stack size */
4501 if (subprog[idx].has_tail_call)
4502 tail_call_reachable = true;
4505 if (frame >= MAX_CALL_FRAMES) {
4506 verbose(env, "the call stack of %d frames is too deep !\n",
4512 /* if tail call got detected across bpf2bpf calls then mark each of the
4513 * currently present subprog frames as tail call reachable subprogs;
4514 * this info will be utilized by JIT so that we will be preserving the
4515 * tail call counter throughout bpf2bpf calls combined with tailcalls
4517 if (tail_call_reachable)
4518 for (j = 0; j < frame; j++)
4519 subprog[ret_prog[j]].tail_call_reachable = true;
4520 if (subprog[0].tail_call_reachable)
4521 env->prog->aux->tail_call_reachable = true;
4523 /* end of for() loop means the last insn of the 'subprog'
4524 * was reached. Doesn't matter whether it was JA or EXIT
4528 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4530 i = ret_insn[frame];
4531 idx = ret_prog[frame];
4535 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4536 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4537 const struct bpf_insn *insn, int idx)
4539 int start = idx + insn->imm + 1, subprog;
4541 subprog = find_subprog(env, start);
4543 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4547 return env->subprog_info[subprog].stack_depth;
4551 static int __check_buffer_access(struct bpf_verifier_env *env,
4552 const char *buf_info,
4553 const struct bpf_reg_state *reg,
4554 int regno, int off, int size)
4558 "R%d invalid %s buffer access: off=%d, size=%d\n",
4559 regno, buf_info, off, size);
4562 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4565 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4567 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4568 regno, off, tn_buf);
4575 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4576 const struct bpf_reg_state *reg,
4577 int regno, int off, int size)
4581 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4585 if (off + size > env->prog->aux->max_tp_access)
4586 env->prog->aux->max_tp_access = off + size;
4591 static int check_buffer_access(struct bpf_verifier_env *env,
4592 const struct bpf_reg_state *reg,
4593 int regno, int off, int size,
4594 bool zero_size_allowed,
4597 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4600 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4604 if (off + size > *max_access)
4605 *max_access = off + size;
4610 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4611 static void zext_32_to_64(struct bpf_reg_state *reg)
4613 reg->var_off = tnum_subreg(reg->var_off);
4614 __reg_assign_32_into_64(reg);
4617 /* truncate register to smaller size (in bytes)
4618 * must be called with size < BPF_REG_SIZE
4620 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4624 /* clear high bits in bit representation */
4625 reg->var_off = tnum_cast(reg->var_off, size);
4627 /* fix arithmetic bounds */
4628 mask = ((u64)1 << (size * 8)) - 1;
4629 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4630 reg->umin_value &= mask;
4631 reg->umax_value &= mask;
4633 reg->umin_value = 0;
4634 reg->umax_value = mask;
4636 reg->smin_value = reg->umin_value;
4637 reg->smax_value = reg->umax_value;
4639 /* If size is smaller than 32bit register the 32bit register
4640 * values are also truncated so we push 64-bit bounds into
4641 * 32-bit bounds. Above were truncated < 32-bits already.
4645 __reg_combine_64_into_32(reg);
4648 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4650 /* A map is considered read-only if the following condition are true:
4652 * 1) BPF program side cannot change any of the map content. The
4653 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4654 * and was set at map creation time.
4655 * 2) The map value(s) have been initialized from user space by a
4656 * loader and then "frozen", such that no new map update/delete
4657 * operations from syscall side are possible for the rest of
4658 * the map's lifetime from that point onwards.
4659 * 3) Any parallel/pending map update/delete operations from syscall
4660 * side have been completed. Only after that point, it's safe to
4661 * assume that map value(s) are immutable.
4663 return (map->map_flags & BPF_F_RDONLY_PROG) &&
4664 READ_ONCE(map->frozen) &&
4665 !bpf_map_write_active(map);
4668 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4674 err = map->ops->map_direct_value_addr(map, &addr, off);
4677 ptr = (void *)(long)addr + off;
4681 *val = (u64)*(u8 *)ptr;
4684 *val = (u64)*(u16 *)ptr;
4687 *val = (u64)*(u32 *)ptr;
4698 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4699 struct bpf_reg_state *regs,
4700 int regno, int off, int size,
4701 enum bpf_access_type atype,
4704 struct bpf_reg_state *reg = regs + regno;
4705 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4706 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4707 enum bpf_type_flag flag = 0;
4711 if (!env->allow_ptr_leaks) {
4713 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4717 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
4719 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
4725 "R%d is ptr_%s invalid negative access: off=%d\n",
4729 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4732 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4734 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4735 regno, tname, off, tn_buf);
4739 if (reg->type & MEM_USER) {
4741 "R%d is ptr_%s access user memory: off=%d\n",
4746 if (reg->type & MEM_PERCPU) {
4748 "R%d is ptr_%s access percpu memory: off=%d\n",
4753 if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
4754 if (!btf_is_kernel(reg->btf)) {
4755 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
4758 ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4760 /* Writes are permitted with default btf_struct_access for
4761 * program allocated objects (which always have ref_obj_id > 0),
4762 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
4764 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
4765 verbose(env, "only read is supported\n");
4769 if (type_is_alloc(reg->type) && !reg->ref_obj_id) {
4770 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
4774 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4780 /* If this is an untrusted pointer, all pointers formed by walking it
4781 * also inherit the untrusted flag.
4783 if (type_flag(reg->type) & PTR_UNTRUSTED)
4784 flag |= PTR_UNTRUSTED;
4786 /* By default any pointer obtained from walking a trusted pointer is
4787 * no longer trusted except the rcu case below.
4789 flag &= ~PTR_TRUSTED;
4791 if (flag & MEM_RCU) {
4792 /* Mark value register as MEM_RCU only if it is protected by
4793 * bpf_rcu_read_lock() and the ptr reg is rcu or trusted. MEM_RCU
4794 * itself can already indicate trustedness inside the rcu
4795 * read lock region. Also mark rcu pointer as PTR_MAYBE_NULL since
4796 * it could be null in some cases.
4798 if (!env->cur_state->active_rcu_lock ||
4799 !(is_trusted_reg(reg) || is_rcu_reg(reg)))
4802 flag |= PTR_MAYBE_NULL;
4803 } else if (reg->type & MEM_RCU) {
4804 /* ptr (reg) is marked as MEM_RCU, but the struct field is not tagged
4805 * with __rcu. Mark the flag as PTR_UNTRUSTED conservatively.
4807 flag |= PTR_UNTRUSTED;
4810 if (atype == BPF_READ && value_regno >= 0)
4811 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4816 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4817 struct bpf_reg_state *regs,
4818 int regno, int off, int size,
4819 enum bpf_access_type atype,
4822 struct bpf_reg_state *reg = regs + regno;
4823 struct bpf_map *map = reg->map_ptr;
4824 struct bpf_reg_state map_reg;
4825 enum bpf_type_flag flag = 0;
4826 const struct btf_type *t;
4832 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4836 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4837 verbose(env, "map_ptr access not supported for map type %d\n",
4842 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4843 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4845 if (!env->allow_ptr_leaks) {
4847 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4853 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4858 if (atype != BPF_READ) {
4859 verbose(env, "only read from %s is supported\n", tname);
4863 /* Simulate access to a PTR_TO_BTF_ID */
4864 memset(&map_reg, 0, sizeof(map_reg));
4865 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
4866 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
4870 if (value_regno >= 0)
4871 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4876 /* Check that the stack access at the given offset is within bounds. The
4877 * maximum valid offset is -1.
4879 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4880 * -state->allocated_stack for reads.
4882 static int check_stack_slot_within_bounds(int off,
4883 struct bpf_func_state *state,
4884 enum bpf_access_type t)
4889 min_valid_off = -MAX_BPF_STACK;
4891 min_valid_off = -state->allocated_stack;
4893 if (off < min_valid_off || off > -1)
4898 /* Check that the stack access at 'regno + off' falls within the maximum stack
4901 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4903 static int check_stack_access_within_bounds(
4904 struct bpf_verifier_env *env,
4905 int regno, int off, int access_size,
4906 enum bpf_access_src src, enum bpf_access_type type)
4908 struct bpf_reg_state *regs = cur_regs(env);
4909 struct bpf_reg_state *reg = regs + regno;
4910 struct bpf_func_state *state = func(env, reg);
4911 int min_off, max_off;
4915 if (src == ACCESS_HELPER)
4916 /* We don't know if helpers are reading or writing (or both). */
4917 err_extra = " indirect access to";
4918 else if (type == BPF_READ)
4919 err_extra = " read from";
4921 err_extra = " write to";
4923 if (tnum_is_const(reg->var_off)) {
4924 min_off = reg->var_off.value + off;
4925 if (access_size > 0)
4926 max_off = min_off + access_size - 1;
4930 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4931 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4932 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4936 min_off = reg->smin_value + off;
4937 if (access_size > 0)
4938 max_off = reg->smax_value + off + access_size - 1;
4943 err = check_stack_slot_within_bounds(min_off, state, type);
4945 err = check_stack_slot_within_bounds(max_off, state, type);
4948 if (tnum_is_const(reg->var_off)) {
4949 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4950 err_extra, regno, off, access_size);
4954 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4955 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4956 err_extra, regno, tn_buf, access_size);
4962 /* check whether memory at (regno + off) is accessible for t = (read | write)
4963 * if t==write, value_regno is a register which value is stored into memory
4964 * if t==read, value_regno is a register which will receive the value from memory
4965 * if t==write && value_regno==-1, some unknown value is stored into memory
4966 * if t==read && value_regno==-1, don't care what we read from memory
4968 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4969 int off, int bpf_size, enum bpf_access_type t,
4970 int value_regno, bool strict_alignment_once)
4972 struct bpf_reg_state *regs = cur_regs(env);
4973 struct bpf_reg_state *reg = regs + regno;
4974 struct bpf_func_state *state;
4977 size = bpf_size_to_bytes(bpf_size);
4981 /* alignment checks will add in reg->off themselves */
4982 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4986 /* for access checks, reg->off is just part of off */
4989 if (reg->type == PTR_TO_MAP_KEY) {
4990 if (t == BPF_WRITE) {
4991 verbose(env, "write to change key R%d not allowed\n", regno);
4995 err = check_mem_region_access(env, regno, off, size,
4996 reg->map_ptr->key_size, false);
4999 if (value_regno >= 0)
5000 mark_reg_unknown(env, regs, value_regno);
5001 } else if (reg->type == PTR_TO_MAP_VALUE) {
5002 struct btf_field *kptr_field = NULL;
5004 if (t == BPF_WRITE && value_regno >= 0 &&
5005 is_pointer_value(env, value_regno)) {
5006 verbose(env, "R%d leaks addr into map\n", value_regno);
5009 err = check_map_access_type(env, regno, off, size, t);
5012 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5015 if (tnum_is_const(reg->var_off))
5016 kptr_field = btf_record_find(reg->map_ptr->record,
5017 off + reg->var_off.value, BPF_KPTR);
5019 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5020 } else if (t == BPF_READ && value_regno >= 0) {
5021 struct bpf_map *map = reg->map_ptr;
5023 /* if map is read-only, track its contents as scalars */
5024 if (tnum_is_const(reg->var_off) &&
5025 bpf_map_is_rdonly(map) &&
5026 map->ops->map_direct_value_addr) {
5027 int map_off = off + reg->var_off.value;
5030 err = bpf_map_direct_read(map, map_off, size,
5035 regs[value_regno].type = SCALAR_VALUE;
5036 __mark_reg_known(®s[value_regno], val);
5038 mark_reg_unknown(env, regs, value_regno);
5041 } else if (base_type(reg->type) == PTR_TO_MEM) {
5042 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5044 if (type_may_be_null(reg->type)) {
5045 verbose(env, "R%d invalid mem access '%s'\n", regno,
5046 reg_type_str(env, reg->type));
5050 if (t == BPF_WRITE && rdonly_mem) {
5051 verbose(env, "R%d cannot write into %s\n",
5052 regno, reg_type_str(env, reg->type));
5056 if (t == BPF_WRITE && value_regno >= 0 &&
5057 is_pointer_value(env, value_regno)) {
5058 verbose(env, "R%d leaks addr into mem\n", value_regno);
5062 err = check_mem_region_access(env, regno, off, size,
5063 reg->mem_size, false);
5064 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5065 mark_reg_unknown(env, regs, value_regno);
5066 } else if (reg->type == PTR_TO_CTX) {
5067 enum bpf_reg_type reg_type = SCALAR_VALUE;
5068 struct btf *btf = NULL;
5071 if (t == BPF_WRITE && value_regno >= 0 &&
5072 is_pointer_value(env, value_regno)) {
5073 verbose(env, "R%d leaks addr into ctx\n", value_regno);
5077 err = check_ptr_off_reg(env, reg, regno);
5081 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
5084 verbose_linfo(env, insn_idx, "; ");
5085 if (!err && t == BPF_READ && value_regno >= 0) {
5086 /* ctx access returns either a scalar, or a
5087 * PTR_TO_PACKET[_META,_END]. In the latter
5088 * case, we know the offset is zero.
5090 if (reg_type == SCALAR_VALUE) {
5091 mark_reg_unknown(env, regs, value_regno);
5093 mark_reg_known_zero(env, regs,
5095 if (type_may_be_null(reg_type))
5096 regs[value_regno].id = ++env->id_gen;
5097 /* A load of ctx field could have different
5098 * actual load size with the one encoded in the
5099 * insn. When the dst is PTR, it is for sure not
5102 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5103 if (base_type(reg_type) == PTR_TO_BTF_ID) {
5104 regs[value_regno].btf = btf;
5105 regs[value_regno].btf_id = btf_id;
5108 regs[value_regno].type = reg_type;
5111 } else if (reg->type == PTR_TO_STACK) {
5112 /* Basic bounds checks. */
5113 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5117 state = func(env, reg);
5118 err = update_stack_depth(env, state, off);
5123 err = check_stack_read(env, regno, off, size,
5126 err = check_stack_write(env, regno, off, size,
5127 value_regno, insn_idx);
5128 } else if (reg_is_pkt_pointer(reg)) {
5129 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5130 verbose(env, "cannot write into packet\n");
5133 if (t == BPF_WRITE && value_regno >= 0 &&
5134 is_pointer_value(env, value_regno)) {
5135 verbose(env, "R%d leaks addr into packet\n",
5139 err = check_packet_access(env, regno, off, size, false);
5140 if (!err && t == BPF_READ && value_regno >= 0)
5141 mark_reg_unknown(env, regs, value_regno);
5142 } else if (reg->type == PTR_TO_FLOW_KEYS) {
5143 if (t == BPF_WRITE && value_regno >= 0 &&
5144 is_pointer_value(env, value_regno)) {
5145 verbose(env, "R%d leaks addr into flow keys\n",
5150 err = check_flow_keys_access(env, off, size);
5151 if (!err && t == BPF_READ && value_regno >= 0)
5152 mark_reg_unknown(env, regs, value_regno);
5153 } else if (type_is_sk_pointer(reg->type)) {
5154 if (t == BPF_WRITE) {
5155 verbose(env, "R%d cannot write into %s\n",
5156 regno, reg_type_str(env, reg->type));
5159 err = check_sock_access(env, insn_idx, regno, off, size, t);
5160 if (!err && value_regno >= 0)
5161 mark_reg_unknown(env, regs, value_regno);
5162 } else if (reg->type == PTR_TO_TP_BUFFER) {
5163 err = check_tp_buffer_access(env, reg, regno, off, size);
5164 if (!err && t == BPF_READ && value_regno >= 0)
5165 mark_reg_unknown(env, regs, value_regno);
5166 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5167 !type_may_be_null(reg->type)) {
5168 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5170 } else if (reg->type == CONST_PTR_TO_MAP) {
5171 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5173 } else if (base_type(reg->type) == PTR_TO_BUF) {
5174 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5178 if (t == BPF_WRITE) {
5179 verbose(env, "R%d cannot write into %s\n",
5180 regno, reg_type_str(env, reg->type));
5183 max_access = &env->prog->aux->max_rdonly_access;
5185 max_access = &env->prog->aux->max_rdwr_access;
5188 err = check_buffer_access(env, reg, regno, off, size, false,
5191 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5192 mark_reg_unknown(env, regs, value_regno);
5194 verbose(env, "R%d invalid mem access '%s'\n", regno,
5195 reg_type_str(env, reg->type));
5199 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5200 regs[value_regno].type == SCALAR_VALUE) {
5201 /* b/h/w load zero-extends, mark upper bits as known 0 */
5202 coerce_reg_to_size(®s[value_regno], size);
5207 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5212 switch (insn->imm) {
5214 case BPF_ADD | BPF_FETCH:
5216 case BPF_AND | BPF_FETCH:
5218 case BPF_OR | BPF_FETCH:
5220 case BPF_XOR | BPF_FETCH:
5225 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5229 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5230 verbose(env, "invalid atomic operand size\n");
5234 /* check src1 operand */
5235 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5239 /* check src2 operand */
5240 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5244 if (insn->imm == BPF_CMPXCHG) {
5245 /* Check comparison of R0 with memory location */
5246 const u32 aux_reg = BPF_REG_0;
5248 err = check_reg_arg(env, aux_reg, SRC_OP);
5252 if (is_pointer_value(env, aux_reg)) {
5253 verbose(env, "R%d leaks addr into mem\n", aux_reg);
5258 if (is_pointer_value(env, insn->src_reg)) {
5259 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5263 if (is_ctx_reg(env, insn->dst_reg) ||
5264 is_pkt_reg(env, insn->dst_reg) ||
5265 is_flow_key_reg(env, insn->dst_reg) ||
5266 is_sk_reg(env, insn->dst_reg)) {
5267 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5269 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5273 if (insn->imm & BPF_FETCH) {
5274 if (insn->imm == BPF_CMPXCHG)
5275 load_reg = BPF_REG_0;
5277 load_reg = insn->src_reg;
5279 /* check and record load of old value */
5280 err = check_reg_arg(env, load_reg, DST_OP);
5284 /* This instruction accesses a memory location but doesn't
5285 * actually load it into a register.
5290 /* Check whether we can read the memory, with second call for fetch
5291 * case to simulate the register fill.
5293 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5294 BPF_SIZE(insn->code), BPF_READ, -1, true);
5295 if (!err && load_reg >= 0)
5296 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5297 BPF_SIZE(insn->code), BPF_READ, load_reg,
5302 /* Check whether we can write into the same memory. */
5303 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5304 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5311 /* When register 'regno' is used to read the stack (either directly or through
5312 * a helper function) make sure that it's within stack boundary and, depending
5313 * on the access type, that all elements of the stack are initialized.
5315 * 'off' includes 'regno->off', but not its dynamic part (if any).
5317 * All registers that have been spilled on the stack in the slots within the
5318 * read offsets are marked as read.
5320 static int check_stack_range_initialized(
5321 struct bpf_verifier_env *env, int regno, int off,
5322 int access_size, bool zero_size_allowed,
5323 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5325 struct bpf_reg_state *reg = reg_state(env, regno);
5326 struct bpf_func_state *state = func(env, reg);
5327 int err, min_off, max_off, i, j, slot, spi;
5328 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5329 enum bpf_access_type bounds_check_type;
5330 /* Some accesses can write anything into the stack, others are
5333 bool clobber = false;
5335 if (access_size == 0 && !zero_size_allowed) {
5336 verbose(env, "invalid zero-sized read\n");
5340 if (type == ACCESS_HELPER) {
5341 /* The bounds checks for writes are more permissive than for
5342 * reads. However, if raw_mode is not set, we'll do extra
5345 bounds_check_type = BPF_WRITE;
5348 bounds_check_type = BPF_READ;
5350 err = check_stack_access_within_bounds(env, regno, off, access_size,
5351 type, bounds_check_type);
5356 if (tnum_is_const(reg->var_off)) {
5357 min_off = max_off = reg->var_off.value + off;
5359 /* Variable offset is prohibited for unprivileged mode for
5360 * simplicity since it requires corresponding support in
5361 * Spectre masking for stack ALU.
5362 * See also retrieve_ptr_limit().
5364 if (!env->bypass_spec_v1) {
5367 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5368 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5369 regno, err_extra, tn_buf);
5372 /* Only initialized buffer on stack is allowed to be accessed
5373 * with variable offset. With uninitialized buffer it's hard to
5374 * guarantee that whole memory is marked as initialized on
5375 * helper return since specific bounds are unknown what may
5376 * cause uninitialized stack leaking.
5378 if (meta && meta->raw_mode)
5381 min_off = reg->smin_value + off;
5382 max_off = reg->smax_value + off;
5385 if (meta && meta->raw_mode) {
5386 meta->access_size = access_size;
5387 meta->regno = regno;
5391 for (i = min_off; i < max_off + access_size; i++) {
5395 spi = slot / BPF_REG_SIZE;
5396 if (state->allocated_stack <= slot)
5398 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5399 if (*stype == STACK_MISC)
5401 if (*stype == STACK_ZERO) {
5403 /* helper can write anything into the stack */
5404 *stype = STACK_MISC;
5409 if (is_spilled_reg(&state->stack[spi]) &&
5410 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5411 env->allow_ptr_leaks)) {
5413 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5414 for (j = 0; j < BPF_REG_SIZE; j++)
5415 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5421 if (tnum_is_const(reg->var_off)) {
5422 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5423 err_extra, regno, min_off, i - min_off, access_size);
5427 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5428 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5429 err_extra, regno, tn_buf, i - min_off, access_size);
5433 /* reading any byte out of 8-byte 'spill_slot' will cause
5434 * the whole slot to be marked as 'read'
5436 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5437 state->stack[spi].spilled_ptr.parent,
5439 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5440 * be sure that whether stack slot is written to or not. Hence,
5441 * we must still conservatively propagate reads upwards even if
5442 * helper may write to the entire memory range.
5445 return update_stack_depth(env, state, min_off);
5448 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5449 int access_size, bool zero_size_allowed,
5450 struct bpf_call_arg_meta *meta)
5452 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5455 switch (base_type(reg->type)) {
5457 case PTR_TO_PACKET_META:
5458 return check_packet_access(env, regno, reg->off, access_size,
5460 case PTR_TO_MAP_KEY:
5461 if (meta && meta->raw_mode) {
5462 verbose(env, "R%d cannot write into %s\n", regno,
5463 reg_type_str(env, reg->type));
5466 return check_mem_region_access(env, regno, reg->off, access_size,
5467 reg->map_ptr->key_size, false);
5468 case PTR_TO_MAP_VALUE:
5469 if (check_map_access_type(env, regno, reg->off, access_size,
5470 meta && meta->raw_mode ? BPF_WRITE :
5473 return check_map_access(env, regno, reg->off, access_size,
5474 zero_size_allowed, ACCESS_HELPER);
5476 if (type_is_rdonly_mem(reg->type)) {
5477 if (meta && meta->raw_mode) {
5478 verbose(env, "R%d cannot write into %s\n", regno,
5479 reg_type_str(env, reg->type));
5483 return check_mem_region_access(env, regno, reg->off,
5484 access_size, reg->mem_size,
5487 if (type_is_rdonly_mem(reg->type)) {
5488 if (meta && meta->raw_mode) {
5489 verbose(env, "R%d cannot write into %s\n", regno,
5490 reg_type_str(env, reg->type));
5494 max_access = &env->prog->aux->max_rdonly_access;
5496 max_access = &env->prog->aux->max_rdwr_access;
5498 return check_buffer_access(env, reg, regno, reg->off,
5499 access_size, zero_size_allowed,
5502 return check_stack_range_initialized(
5504 regno, reg->off, access_size,
5505 zero_size_allowed, ACCESS_HELPER, meta);
5507 /* in case the function doesn't know how to access the context,
5508 * (because we are in a program of type SYSCALL for example), we
5509 * can not statically check its size.
5510 * Dynamically check it now.
5512 if (!env->ops->convert_ctx_access) {
5513 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5514 int offset = access_size - 1;
5516 /* Allow zero-byte read from PTR_TO_CTX */
5517 if (access_size == 0)
5518 return zero_size_allowed ? 0 : -EACCES;
5520 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5525 default: /* scalar_value or invalid ptr */
5526 /* Allow zero-byte read from NULL, regardless of pointer type */
5527 if (zero_size_allowed && access_size == 0 &&
5528 register_is_null(reg))
5531 verbose(env, "R%d type=%s ", regno,
5532 reg_type_str(env, reg->type));
5533 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5538 static int check_mem_size_reg(struct bpf_verifier_env *env,
5539 struct bpf_reg_state *reg, u32 regno,
5540 bool zero_size_allowed,
5541 struct bpf_call_arg_meta *meta)
5545 /* This is used to refine r0 return value bounds for helpers
5546 * that enforce this value as an upper bound on return values.
5547 * See do_refine_retval_range() for helpers that can refine
5548 * the return value. C type of helper is u32 so we pull register
5549 * bound from umax_value however, if negative verifier errors
5550 * out. Only upper bounds can be learned because retval is an
5551 * int type and negative retvals are allowed.
5553 meta->msize_max_value = reg->umax_value;
5555 /* The register is SCALAR_VALUE; the access check
5556 * happens using its boundaries.
5558 if (!tnum_is_const(reg->var_off))
5559 /* For unprivileged variable accesses, disable raw
5560 * mode so that the program is required to
5561 * initialize all the memory that the helper could
5562 * just partially fill up.
5566 if (reg->smin_value < 0) {
5567 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5572 if (reg->umin_value == 0) {
5573 err = check_helper_mem_access(env, regno - 1, 0,
5580 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5581 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5585 err = check_helper_mem_access(env, regno - 1,
5587 zero_size_allowed, meta);
5589 err = mark_chain_precision(env, regno);
5593 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5594 u32 regno, u32 mem_size)
5596 bool may_be_null = type_may_be_null(reg->type);
5597 struct bpf_reg_state saved_reg;
5598 struct bpf_call_arg_meta meta;
5601 if (register_is_null(reg))
5604 memset(&meta, 0, sizeof(meta));
5605 /* Assuming that the register contains a value check if the memory
5606 * access is safe. Temporarily save and restore the register's state as
5607 * the conversion shouldn't be visible to a caller.
5611 mark_ptr_not_null_reg(reg);
5614 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5615 /* Check access for BPF_WRITE */
5616 meta.raw_mode = true;
5617 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5625 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5628 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5629 bool may_be_null = type_may_be_null(mem_reg->type);
5630 struct bpf_reg_state saved_reg;
5631 struct bpf_call_arg_meta meta;
5634 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5636 memset(&meta, 0, sizeof(meta));
5639 saved_reg = *mem_reg;
5640 mark_ptr_not_null_reg(mem_reg);
5643 err = check_mem_size_reg(env, reg, regno, true, &meta);
5644 /* Check access for BPF_WRITE */
5645 meta.raw_mode = true;
5646 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5649 *mem_reg = saved_reg;
5653 /* Implementation details:
5654 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
5655 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
5656 * Two bpf_map_lookups (even with the same key) will have different reg->id.
5657 * Two separate bpf_obj_new will also have different reg->id.
5658 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
5659 * clears reg->id after value_or_null->value transition, since the verifier only
5660 * cares about the range of access to valid map value pointer and doesn't care
5661 * about actual address of the map element.
5662 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5663 * reg->id > 0 after value_or_null->value transition. By doing so
5664 * two bpf_map_lookups will be considered two different pointers that
5665 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
5666 * returned from bpf_obj_new.
5667 * The verifier allows taking only one bpf_spin_lock at a time to avoid
5669 * Since only one bpf_spin_lock is allowed the checks are simpler than
5670 * reg_is_refcounted() logic. The verifier needs to remember only
5671 * one spin_lock instead of array of acquired_refs.
5672 * cur_state->active_lock remembers which map value element or allocated
5673 * object got locked and clears it after bpf_spin_unlock.
5675 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5678 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5679 struct bpf_verifier_state *cur = env->cur_state;
5680 bool is_const = tnum_is_const(reg->var_off);
5681 u64 val = reg->var_off.value;
5682 struct bpf_map *map = NULL;
5683 struct btf *btf = NULL;
5684 struct btf_record *rec;
5688 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5692 if (reg->type == PTR_TO_MAP_VALUE) {
5696 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5704 rec = reg_btf_record(reg);
5705 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
5706 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
5707 map ? map->name : "kptr");
5710 if (rec->spin_lock_off != val + reg->off) {
5711 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
5712 val + reg->off, rec->spin_lock_off);
5716 if (cur->active_lock.ptr) {
5718 "Locking two bpf_spin_locks are not allowed\n");
5722 cur->active_lock.ptr = map;
5724 cur->active_lock.ptr = btf;
5725 cur->active_lock.id = reg->id;
5727 struct bpf_func_state *fstate = cur_func(env);
5736 if (!cur->active_lock.ptr) {
5737 verbose(env, "bpf_spin_unlock without taking a lock\n");
5740 if (cur->active_lock.ptr != ptr ||
5741 cur->active_lock.id != reg->id) {
5742 verbose(env, "bpf_spin_unlock of different lock\n");
5745 cur->active_lock.ptr = NULL;
5746 cur->active_lock.id = 0;
5748 for (i = fstate->acquired_refs - 1; i >= 0; i--) {
5751 /* Complain on error because this reference state cannot
5752 * be freed before this point, as bpf_spin_lock critical
5753 * section does not allow functions that release the
5754 * allocated object immediately.
5756 if (!fstate->refs[i].release_on_unlock)
5758 err = release_reference(env, fstate->refs[i].id);
5760 verbose(env, "failed to release release_on_unlock reference");
5768 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5769 struct bpf_call_arg_meta *meta)
5771 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5772 bool is_const = tnum_is_const(reg->var_off);
5773 struct bpf_map *map = reg->map_ptr;
5774 u64 val = reg->var_off.value;
5778 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5783 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5787 if (!btf_record_has_field(map->record, BPF_TIMER)) {
5788 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
5791 if (map->record->timer_off != val + reg->off) {
5792 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5793 val + reg->off, map->record->timer_off);
5796 if (meta->map_ptr) {
5797 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5800 meta->map_uid = reg->map_uid;
5801 meta->map_ptr = map;
5805 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5806 struct bpf_call_arg_meta *meta)
5808 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5809 struct bpf_map *map_ptr = reg->map_ptr;
5810 struct btf_field *kptr_field;
5813 if (!tnum_is_const(reg->var_off)) {
5815 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5819 if (!map_ptr->btf) {
5820 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5824 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
5825 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5829 meta->map_ptr = map_ptr;
5830 kptr_off = reg->off + reg->var_off.value;
5831 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
5833 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5836 if (kptr_field->type != BPF_KPTR_REF) {
5837 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5840 meta->kptr_field = kptr_field;
5844 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5846 return type == ARG_CONST_SIZE ||
5847 type == ARG_CONST_SIZE_OR_ZERO;
5850 static bool arg_type_is_release(enum bpf_arg_type type)
5852 return type & OBJ_RELEASE;
5855 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5857 return base_type(type) == ARG_PTR_TO_DYNPTR;
5860 static int int_ptr_type_to_size(enum bpf_arg_type type)
5862 if (type == ARG_PTR_TO_INT)
5864 else if (type == ARG_PTR_TO_LONG)
5870 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5871 const struct bpf_call_arg_meta *meta,
5872 enum bpf_arg_type *arg_type)
5874 if (!meta->map_ptr) {
5875 /* kernel subsystem misconfigured verifier */
5876 verbose(env, "invalid map_ptr to access map->type\n");
5880 switch (meta->map_ptr->map_type) {
5881 case BPF_MAP_TYPE_SOCKMAP:
5882 case BPF_MAP_TYPE_SOCKHASH:
5883 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5884 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5886 verbose(env, "invalid arg_type for sockmap/sockhash\n");
5890 case BPF_MAP_TYPE_BLOOM_FILTER:
5891 if (meta->func_id == BPF_FUNC_map_peek_elem)
5892 *arg_type = ARG_PTR_TO_MAP_VALUE;
5900 struct bpf_reg_types {
5901 const enum bpf_reg_type types[10];
5905 static const struct bpf_reg_types sock_types = {
5915 static const struct bpf_reg_types btf_id_sock_common_types = {
5922 PTR_TO_BTF_ID | PTR_TRUSTED,
5924 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5928 static const struct bpf_reg_types mem_types = {
5936 PTR_TO_MEM | MEM_RINGBUF,
5941 static const struct bpf_reg_types int_ptr_types = {
5951 static const struct bpf_reg_types spin_lock_types = {
5954 PTR_TO_BTF_ID | MEM_ALLOC,
5958 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5959 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5960 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5961 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
5962 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5963 static const struct bpf_reg_types btf_ptr_types = {
5966 PTR_TO_BTF_ID | PTR_TRUSTED,
5967 PTR_TO_BTF_ID | MEM_RCU,
5970 static const struct bpf_reg_types percpu_btf_ptr_types = {
5972 PTR_TO_BTF_ID | MEM_PERCPU,
5973 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
5976 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5977 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5978 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5979 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5980 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5981 static const struct bpf_reg_types dynptr_types = {
5984 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5988 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5989 [ARG_PTR_TO_MAP_KEY] = &mem_types,
5990 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
5991 [ARG_CONST_SIZE] = &scalar_types,
5992 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
5993 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
5994 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
5995 [ARG_PTR_TO_CTX] = &context_types,
5996 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
5998 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
6000 [ARG_PTR_TO_SOCKET] = &fullsock_types,
6001 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
6002 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
6003 [ARG_PTR_TO_MEM] = &mem_types,
6004 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
6005 [ARG_PTR_TO_INT] = &int_ptr_types,
6006 [ARG_PTR_TO_LONG] = &int_ptr_types,
6007 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
6008 [ARG_PTR_TO_FUNC] = &func_ptr_types,
6009 [ARG_PTR_TO_STACK] = &stack_ptr_types,
6010 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
6011 [ARG_PTR_TO_TIMER] = &timer_types,
6012 [ARG_PTR_TO_KPTR] = &kptr_types,
6013 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
6016 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
6017 enum bpf_arg_type arg_type,
6018 const u32 *arg_btf_id,
6019 struct bpf_call_arg_meta *meta)
6021 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6022 enum bpf_reg_type expected, type = reg->type;
6023 const struct bpf_reg_types *compatible;
6026 compatible = compatible_reg_types[base_type(arg_type)];
6028 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
6032 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
6033 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
6035 * Same for MAYBE_NULL:
6037 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
6038 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
6040 * Therefore we fold these flags depending on the arg_type before comparison.
6042 if (arg_type & MEM_RDONLY)
6043 type &= ~MEM_RDONLY;
6044 if (arg_type & PTR_MAYBE_NULL)
6045 type &= ~PTR_MAYBE_NULL;
6047 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
6048 expected = compatible->types[i];
6049 if (expected == NOT_INIT)
6052 if (type == expected)
6056 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
6057 for (j = 0; j + 1 < i; j++)
6058 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
6059 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
6063 if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) {
6064 /* For bpf_sk_release, it needs to match against first member
6065 * 'struct sock_common', hence make an exception for it. This
6066 * allows bpf_sk_release to work for multiple socket types.
6068 bool strict_type_match = arg_type_is_release(arg_type) &&
6069 meta->func_id != BPF_FUNC_sk_release;
6072 if (!compatible->btf_id) {
6073 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6076 arg_btf_id = compatible->btf_id;
6079 if (meta->func_id == BPF_FUNC_kptr_xchg) {
6080 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6083 if (arg_btf_id == BPF_PTR_POISON) {
6084 verbose(env, "verifier internal error:");
6085 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6090 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6091 btf_vmlinux, *arg_btf_id,
6092 strict_type_match)) {
6093 verbose(env, "R%d is of type %s but %s is expected\n",
6094 regno, kernel_type_name(reg->btf, reg->btf_id),
6095 kernel_type_name(btf_vmlinux, *arg_btf_id));
6099 } else if (type_is_alloc(reg->type)) {
6100 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6101 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6109 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6110 const struct bpf_reg_state *reg, int regno,
6111 enum bpf_arg_type arg_type)
6113 enum bpf_reg_type type = reg->type;
6114 bool fixed_off_ok = false;
6116 switch ((u32)type) {
6117 /* Pointer types where reg offset is explicitly allowed: */
6119 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
6120 verbose(env, "cannot pass in dynptr at an offset\n");
6125 case PTR_TO_PACKET_META:
6126 case PTR_TO_MAP_KEY:
6127 case PTR_TO_MAP_VALUE:
6129 case PTR_TO_MEM | MEM_RDONLY:
6130 case PTR_TO_MEM | MEM_RINGBUF:
6132 case PTR_TO_BUF | MEM_RDONLY:
6134 /* Some of the argument types nevertheless require a
6135 * zero register offset.
6137 if (base_type(arg_type) != ARG_PTR_TO_RINGBUF_MEM)
6140 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6144 case PTR_TO_BTF_ID | MEM_ALLOC:
6145 case PTR_TO_BTF_ID | PTR_TRUSTED:
6146 case PTR_TO_BTF_ID | MEM_RCU:
6147 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
6148 /* When referenced PTR_TO_BTF_ID is passed to release function,
6149 * it's fixed offset must be 0. In the other cases, fixed offset
6152 if (arg_type_is_release(arg_type) && reg->off) {
6153 verbose(env, "R%d must have zero offset when passed to release func\n",
6157 /* For arg is release pointer, fixed_off_ok must be false, but
6158 * we already checked and rejected reg->off != 0 above, so set
6159 * to true to allow fixed offset for all other cases.
6161 fixed_off_ok = true;
6166 return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
6169 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6171 struct bpf_func_state *state = func(env, reg);
6172 int spi = get_spi(reg->off);
6174 return state->stack[spi].spilled_ptr.id;
6177 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6178 struct bpf_call_arg_meta *meta,
6179 const struct bpf_func_proto *fn)
6181 u32 regno = BPF_REG_1 + arg;
6182 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6183 enum bpf_arg_type arg_type = fn->arg_type[arg];
6184 enum bpf_reg_type type = reg->type;
6185 u32 *arg_btf_id = NULL;
6188 if (arg_type == ARG_DONTCARE)
6191 err = check_reg_arg(env, regno, SRC_OP);
6195 if (arg_type == ARG_ANYTHING) {
6196 if (is_pointer_value(env, regno)) {
6197 verbose(env, "R%d leaks addr into helper function\n",
6204 if (type_is_pkt_pointer(type) &&
6205 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6206 verbose(env, "helper access to the packet is not allowed\n");
6210 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6211 err = resolve_map_arg_type(env, meta, &arg_type);
6216 if (register_is_null(reg) && type_may_be_null(arg_type))
6217 /* A NULL register has a SCALAR_VALUE type, so skip
6220 goto skip_type_check;
6222 /* arg_btf_id and arg_size are in a union. */
6223 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6224 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6225 arg_btf_id = fn->arg_btf_id[arg];
6227 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6231 err = check_func_arg_reg_off(env, reg, regno, arg_type);
6236 if (arg_type_is_release(arg_type)) {
6237 if (arg_type_is_dynptr(arg_type)) {
6238 struct bpf_func_state *state = func(env, reg);
6239 int spi = get_spi(reg->off);
6241 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6242 !state->stack[spi].spilled_ptr.id) {
6243 verbose(env, "arg %d is an unacquired reference\n", regno);
6246 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
6247 verbose(env, "R%d must be referenced when passed to release function\n",
6251 if (meta->release_regno) {
6252 verbose(env, "verifier internal error: more than one release argument\n");
6255 meta->release_regno = regno;
6258 if (reg->ref_obj_id) {
6259 if (meta->ref_obj_id) {
6260 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6261 regno, reg->ref_obj_id,
6265 meta->ref_obj_id = reg->ref_obj_id;
6268 switch (base_type(arg_type)) {
6269 case ARG_CONST_MAP_PTR:
6270 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6271 if (meta->map_ptr) {
6272 /* Use map_uid (which is unique id of inner map) to reject:
6273 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6274 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6275 * if (inner_map1 && inner_map2) {
6276 * timer = bpf_map_lookup_elem(inner_map1);
6278 * // mismatch would have been allowed
6279 * bpf_timer_init(timer, inner_map2);
6282 * Comparing map_ptr is enough to distinguish normal and outer maps.
6284 if (meta->map_ptr != reg->map_ptr ||
6285 meta->map_uid != reg->map_uid) {
6287 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6288 meta->map_uid, reg->map_uid);
6292 meta->map_ptr = reg->map_ptr;
6293 meta->map_uid = reg->map_uid;
6295 case ARG_PTR_TO_MAP_KEY:
6296 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6297 * check that [key, key + map->key_size) are within
6298 * stack limits and initialized
6300 if (!meta->map_ptr) {
6301 /* in function declaration map_ptr must come before
6302 * map_key, so that it's verified and known before
6303 * we have to check map_key here. Otherwise it means
6304 * that kernel subsystem misconfigured verifier
6306 verbose(env, "invalid map_ptr to access map->key\n");
6309 err = check_helper_mem_access(env, regno,
6310 meta->map_ptr->key_size, false,
6313 case ARG_PTR_TO_MAP_VALUE:
6314 if (type_may_be_null(arg_type) && register_is_null(reg))
6317 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6318 * check [value, value + map->value_size) validity
6320 if (!meta->map_ptr) {
6321 /* kernel subsystem misconfigured verifier */
6322 verbose(env, "invalid map_ptr to access map->value\n");
6325 meta->raw_mode = arg_type & MEM_UNINIT;
6326 err = check_helper_mem_access(env, regno,
6327 meta->map_ptr->value_size, false,
6330 case ARG_PTR_TO_PERCPU_BTF_ID:
6332 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6335 meta->ret_btf = reg->btf;
6336 meta->ret_btf_id = reg->btf_id;
6338 case ARG_PTR_TO_SPIN_LOCK:
6339 if (meta->func_id == BPF_FUNC_spin_lock) {
6340 if (process_spin_lock(env, regno, true))
6342 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6343 if (process_spin_lock(env, regno, false))
6346 verbose(env, "verifier internal error\n");
6350 case ARG_PTR_TO_TIMER:
6351 if (process_timer_func(env, regno, meta))
6354 case ARG_PTR_TO_FUNC:
6355 meta->subprogno = reg->subprogno;
6357 case ARG_PTR_TO_MEM:
6358 /* The access to this pointer is only checked when we hit the
6359 * next is_mem_size argument below.
6361 meta->raw_mode = arg_type & MEM_UNINIT;
6362 if (arg_type & MEM_FIXED_SIZE) {
6363 err = check_helper_mem_access(env, regno,
6364 fn->arg_size[arg], false,
6368 case ARG_CONST_SIZE:
6369 err = check_mem_size_reg(env, reg, regno, false, meta);
6371 case ARG_CONST_SIZE_OR_ZERO:
6372 err = check_mem_size_reg(env, reg, regno, true, meta);
6374 case ARG_PTR_TO_DYNPTR:
6375 /* We only need to check for initialized / uninitialized helper
6376 * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6377 * assumption is that if it is, that a helper function
6378 * initialized the dynptr on behalf of the BPF program.
6380 if (base_type(reg->type) == PTR_TO_DYNPTR)
6382 if (arg_type & MEM_UNINIT) {
6383 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6384 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6388 /* We only support one dynptr being uninitialized at the moment,
6389 * which is sufficient for the helper functions we have right now.
6391 if (meta->uninit_dynptr_regno) {
6392 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6396 meta->uninit_dynptr_regno = regno;
6397 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6399 "Expected an initialized dynptr as arg #%d\n",
6402 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6403 const char *err_extra = "";
6405 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6406 case DYNPTR_TYPE_LOCAL:
6407 err_extra = "local";
6409 case DYNPTR_TYPE_RINGBUF:
6410 err_extra = "ringbuf";
6413 err_extra = "<unknown>";
6417 "Expected a dynptr of type %s as arg #%d\n",
6418 err_extra, arg + 1);
6422 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6423 if (!tnum_is_const(reg->var_off)) {
6424 verbose(env, "R%d is not a known constant'\n",
6428 meta->mem_size = reg->var_off.value;
6429 err = mark_chain_precision(env, regno);
6433 case ARG_PTR_TO_INT:
6434 case ARG_PTR_TO_LONG:
6436 int size = int_ptr_type_to_size(arg_type);
6438 err = check_helper_mem_access(env, regno, size, false, meta);
6441 err = check_ptr_alignment(env, reg, 0, size, true);
6444 case ARG_PTR_TO_CONST_STR:
6446 struct bpf_map *map = reg->map_ptr;
6451 if (!bpf_map_is_rdonly(map)) {
6452 verbose(env, "R%d does not point to a readonly map'\n", regno);
6456 if (!tnum_is_const(reg->var_off)) {
6457 verbose(env, "R%d is not a constant address'\n", regno);
6461 if (!map->ops->map_direct_value_addr) {
6462 verbose(env, "no direct value access support for this map type\n");
6466 err = check_map_access(env, regno, reg->off,
6467 map->value_size - reg->off, false,
6472 map_off = reg->off + reg->var_off.value;
6473 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6475 verbose(env, "direct value access on string failed\n");
6479 str_ptr = (char *)(long)(map_addr);
6480 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6481 verbose(env, "string is not zero-terminated\n");
6486 case ARG_PTR_TO_KPTR:
6487 if (process_kptr_func(env, regno, meta))
6495 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6497 enum bpf_attach_type eatype = env->prog->expected_attach_type;
6498 enum bpf_prog_type type = resolve_prog_type(env->prog);
6500 if (func_id != BPF_FUNC_map_update_elem)
6503 /* It's not possible to get access to a locked struct sock in these
6504 * contexts, so updating is safe.
6507 case BPF_PROG_TYPE_TRACING:
6508 if (eatype == BPF_TRACE_ITER)
6511 case BPF_PROG_TYPE_SOCKET_FILTER:
6512 case BPF_PROG_TYPE_SCHED_CLS:
6513 case BPF_PROG_TYPE_SCHED_ACT:
6514 case BPF_PROG_TYPE_XDP:
6515 case BPF_PROG_TYPE_SK_REUSEPORT:
6516 case BPF_PROG_TYPE_FLOW_DISSECTOR:
6517 case BPF_PROG_TYPE_SK_LOOKUP:
6523 verbose(env, "cannot update sockmap in this context\n");
6527 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6529 return env->prog->jit_requested &&
6530 bpf_jit_supports_subprog_tailcalls();
6533 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6534 struct bpf_map *map, int func_id)
6539 /* We need a two way check, first is from map perspective ... */
6540 switch (map->map_type) {
6541 case BPF_MAP_TYPE_PROG_ARRAY:
6542 if (func_id != BPF_FUNC_tail_call)
6545 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6546 if (func_id != BPF_FUNC_perf_event_read &&
6547 func_id != BPF_FUNC_perf_event_output &&
6548 func_id != BPF_FUNC_skb_output &&
6549 func_id != BPF_FUNC_perf_event_read_value &&
6550 func_id != BPF_FUNC_xdp_output)
6553 case BPF_MAP_TYPE_RINGBUF:
6554 if (func_id != BPF_FUNC_ringbuf_output &&
6555 func_id != BPF_FUNC_ringbuf_reserve &&
6556 func_id != BPF_FUNC_ringbuf_query &&
6557 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6558 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6559 func_id != BPF_FUNC_ringbuf_discard_dynptr)
6562 case BPF_MAP_TYPE_USER_RINGBUF:
6563 if (func_id != BPF_FUNC_user_ringbuf_drain)
6566 case BPF_MAP_TYPE_STACK_TRACE:
6567 if (func_id != BPF_FUNC_get_stackid)
6570 case BPF_MAP_TYPE_CGROUP_ARRAY:
6571 if (func_id != BPF_FUNC_skb_under_cgroup &&
6572 func_id != BPF_FUNC_current_task_under_cgroup)
6575 case BPF_MAP_TYPE_CGROUP_STORAGE:
6576 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6577 if (func_id != BPF_FUNC_get_local_storage)
6580 case BPF_MAP_TYPE_DEVMAP:
6581 case BPF_MAP_TYPE_DEVMAP_HASH:
6582 if (func_id != BPF_FUNC_redirect_map &&
6583 func_id != BPF_FUNC_map_lookup_elem)
6586 /* Restrict bpf side of cpumap and xskmap, open when use-cases
6589 case BPF_MAP_TYPE_CPUMAP:
6590 if (func_id != BPF_FUNC_redirect_map)
6593 case BPF_MAP_TYPE_XSKMAP:
6594 if (func_id != BPF_FUNC_redirect_map &&
6595 func_id != BPF_FUNC_map_lookup_elem)
6598 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6599 case BPF_MAP_TYPE_HASH_OF_MAPS:
6600 if (func_id != BPF_FUNC_map_lookup_elem)
6603 case BPF_MAP_TYPE_SOCKMAP:
6604 if (func_id != BPF_FUNC_sk_redirect_map &&
6605 func_id != BPF_FUNC_sock_map_update &&
6606 func_id != BPF_FUNC_map_delete_elem &&
6607 func_id != BPF_FUNC_msg_redirect_map &&
6608 func_id != BPF_FUNC_sk_select_reuseport &&
6609 func_id != BPF_FUNC_map_lookup_elem &&
6610 !may_update_sockmap(env, func_id))
6613 case BPF_MAP_TYPE_SOCKHASH:
6614 if (func_id != BPF_FUNC_sk_redirect_hash &&
6615 func_id != BPF_FUNC_sock_hash_update &&
6616 func_id != BPF_FUNC_map_delete_elem &&
6617 func_id != BPF_FUNC_msg_redirect_hash &&
6618 func_id != BPF_FUNC_sk_select_reuseport &&
6619 func_id != BPF_FUNC_map_lookup_elem &&
6620 !may_update_sockmap(env, func_id))
6623 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6624 if (func_id != BPF_FUNC_sk_select_reuseport)
6627 case BPF_MAP_TYPE_QUEUE:
6628 case BPF_MAP_TYPE_STACK:
6629 if (func_id != BPF_FUNC_map_peek_elem &&
6630 func_id != BPF_FUNC_map_pop_elem &&
6631 func_id != BPF_FUNC_map_push_elem)
6634 case BPF_MAP_TYPE_SK_STORAGE:
6635 if (func_id != BPF_FUNC_sk_storage_get &&
6636 func_id != BPF_FUNC_sk_storage_delete)
6639 case BPF_MAP_TYPE_INODE_STORAGE:
6640 if (func_id != BPF_FUNC_inode_storage_get &&
6641 func_id != BPF_FUNC_inode_storage_delete)
6644 case BPF_MAP_TYPE_TASK_STORAGE:
6645 if (func_id != BPF_FUNC_task_storage_get &&
6646 func_id != BPF_FUNC_task_storage_delete)
6649 case BPF_MAP_TYPE_CGRP_STORAGE:
6650 if (func_id != BPF_FUNC_cgrp_storage_get &&
6651 func_id != BPF_FUNC_cgrp_storage_delete)
6654 case BPF_MAP_TYPE_BLOOM_FILTER:
6655 if (func_id != BPF_FUNC_map_peek_elem &&
6656 func_id != BPF_FUNC_map_push_elem)
6663 /* ... and second from the function itself. */
6665 case BPF_FUNC_tail_call:
6666 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6668 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6669 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6673 case BPF_FUNC_perf_event_read:
6674 case BPF_FUNC_perf_event_output:
6675 case BPF_FUNC_perf_event_read_value:
6676 case BPF_FUNC_skb_output:
6677 case BPF_FUNC_xdp_output:
6678 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6681 case BPF_FUNC_ringbuf_output:
6682 case BPF_FUNC_ringbuf_reserve:
6683 case BPF_FUNC_ringbuf_query:
6684 case BPF_FUNC_ringbuf_reserve_dynptr:
6685 case BPF_FUNC_ringbuf_submit_dynptr:
6686 case BPF_FUNC_ringbuf_discard_dynptr:
6687 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6690 case BPF_FUNC_user_ringbuf_drain:
6691 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6694 case BPF_FUNC_get_stackid:
6695 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6698 case BPF_FUNC_current_task_under_cgroup:
6699 case BPF_FUNC_skb_under_cgroup:
6700 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6703 case BPF_FUNC_redirect_map:
6704 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6705 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6706 map->map_type != BPF_MAP_TYPE_CPUMAP &&
6707 map->map_type != BPF_MAP_TYPE_XSKMAP)
6710 case BPF_FUNC_sk_redirect_map:
6711 case BPF_FUNC_msg_redirect_map:
6712 case BPF_FUNC_sock_map_update:
6713 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6716 case BPF_FUNC_sk_redirect_hash:
6717 case BPF_FUNC_msg_redirect_hash:
6718 case BPF_FUNC_sock_hash_update:
6719 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6722 case BPF_FUNC_get_local_storage:
6723 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6724 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6727 case BPF_FUNC_sk_select_reuseport:
6728 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6729 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6730 map->map_type != BPF_MAP_TYPE_SOCKHASH)
6733 case BPF_FUNC_map_pop_elem:
6734 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6735 map->map_type != BPF_MAP_TYPE_STACK)
6738 case BPF_FUNC_map_peek_elem:
6739 case BPF_FUNC_map_push_elem:
6740 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6741 map->map_type != BPF_MAP_TYPE_STACK &&
6742 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6745 case BPF_FUNC_map_lookup_percpu_elem:
6746 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6747 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6748 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6751 case BPF_FUNC_sk_storage_get:
6752 case BPF_FUNC_sk_storage_delete:
6753 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6756 case BPF_FUNC_inode_storage_get:
6757 case BPF_FUNC_inode_storage_delete:
6758 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6761 case BPF_FUNC_task_storage_get:
6762 case BPF_FUNC_task_storage_delete:
6763 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6766 case BPF_FUNC_cgrp_storage_get:
6767 case BPF_FUNC_cgrp_storage_delete:
6768 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
6777 verbose(env, "cannot pass map_type %d into func %s#%d\n",
6778 map->map_type, func_id_name(func_id), func_id);
6782 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6786 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6788 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6790 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6792 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6794 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6797 /* We only support one arg being in raw mode at the moment,
6798 * which is sufficient for the helper functions we have
6804 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6806 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6807 bool has_size = fn->arg_size[arg] != 0;
6808 bool is_next_size = false;
6810 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6811 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6813 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6814 return is_next_size;
6816 return has_size == is_next_size || is_next_size == is_fixed;
6819 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6821 /* bpf_xxx(..., buf, len) call will access 'len'
6822 * bytes from memory 'buf'. Both arg types need
6823 * to be paired, so make sure there's no buggy
6824 * helper function specification.
6826 if (arg_type_is_mem_size(fn->arg1_type) ||
6827 check_args_pair_invalid(fn, 0) ||
6828 check_args_pair_invalid(fn, 1) ||
6829 check_args_pair_invalid(fn, 2) ||
6830 check_args_pair_invalid(fn, 3) ||
6831 check_args_pair_invalid(fn, 4))
6837 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6841 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6842 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
6843 return !!fn->arg_btf_id[i];
6844 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
6845 return fn->arg_btf_id[i] == BPF_PTR_POISON;
6846 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6847 /* arg_btf_id and arg_size are in a union. */
6848 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6849 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6856 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6858 return check_raw_mode_ok(fn) &&
6859 check_arg_pair_ok(fn) &&
6860 check_btf_id_ok(fn) ? 0 : -EINVAL;
6863 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6864 * are now invalid, so turn them into unknown SCALAR_VALUE.
6866 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6868 struct bpf_func_state *state;
6869 struct bpf_reg_state *reg;
6871 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6872 if (reg_is_pkt_pointer_any(reg))
6873 __mark_reg_unknown(env, reg);
6879 BEYOND_PKT_END = -2,
6882 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6884 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6885 struct bpf_reg_state *reg = &state->regs[regn];
6887 if (reg->type != PTR_TO_PACKET)
6888 /* PTR_TO_PACKET_META is not supported yet */
6891 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6892 * How far beyond pkt_end it goes is unknown.
6893 * if (!range_open) it's the case of pkt >= pkt_end
6894 * if (range_open) it's the case of pkt > pkt_end
6895 * hence this pointer is at least 1 byte bigger than pkt_end
6898 reg->range = BEYOND_PKT_END;
6900 reg->range = AT_PKT_END;
6903 /* The pointer with the specified id has released its reference to kernel
6904 * resources. Identify all copies of the same pointer and clear the reference.
6906 static int release_reference(struct bpf_verifier_env *env,
6909 struct bpf_func_state *state;
6910 struct bpf_reg_state *reg;
6913 err = release_reference_state(cur_func(env), ref_obj_id);
6917 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6918 if (reg->ref_obj_id == ref_obj_id) {
6919 if (!env->allow_ptr_leaks)
6920 __mark_reg_not_init(env, reg);
6922 __mark_reg_unknown(env, reg);
6929 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6930 struct bpf_reg_state *regs)
6934 /* after the call registers r0 - r5 were scratched */
6935 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6936 mark_reg_not_init(env, regs, caller_saved[i]);
6937 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6941 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6942 struct bpf_func_state *caller,
6943 struct bpf_func_state *callee,
6946 static int set_callee_state(struct bpf_verifier_env *env,
6947 struct bpf_func_state *caller,
6948 struct bpf_func_state *callee, int insn_idx);
6950 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6951 int *insn_idx, int subprog,
6952 set_callee_state_fn set_callee_state_cb)
6954 struct bpf_verifier_state *state = env->cur_state;
6955 struct bpf_func_info_aux *func_info_aux;
6956 struct bpf_func_state *caller, *callee;
6958 bool is_global = false;
6960 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6961 verbose(env, "the call stack of %d frames is too deep\n",
6962 state->curframe + 2);
6966 caller = state->frame[state->curframe];
6967 if (state->frame[state->curframe + 1]) {
6968 verbose(env, "verifier bug. Frame %d already allocated\n",
6969 state->curframe + 1);
6973 func_info_aux = env->prog->aux->func_info_aux;
6975 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6976 err = btf_check_subprog_call(env, subprog, caller->regs);
6981 verbose(env, "Caller passes invalid args into func#%d\n",
6985 if (env->log.level & BPF_LOG_LEVEL)
6987 "Func#%d is global and valid. Skipping.\n",
6989 clear_caller_saved_regs(env, caller->regs);
6991 /* All global functions return a 64-bit SCALAR_VALUE */
6992 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6993 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6995 /* continue with next insn after call */
7000 /* set_callee_state is used for direct subprog calls, but we are
7001 * interested in validating only BPF helpers that can call subprogs as
7004 if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
7005 verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
7006 func_id_name(insn->imm), insn->imm);
7010 if (insn->code == (BPF_JMP | BPF_CALL) &&
7011 insn->src_reg == 0 &&
7012 insn->imm == BPF_FUNC_timer_set_callback) {
7013 struct bpf_verifier_state *async_cb;
7015 /* there is no real recursion here. timer callbacks are async */
7016 env->subprog_info[subprog].is_async_cb = true;
7017 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
7018 *insn_idx, subprog);
7021 callee = async_cb->frame[0];
7022 callee->async_entry_cnt = caller->async_entry_cnt + 1;
7024 /* Convert bpf_timer_set_callback() args into timer callback args */
7025 err = set_callee_state_cb(env, caller, callee, *insn_idx);
7029 clear_caller_saved_regs(env, caller->regs);
7030 mark_reg_unknown(env, caller->regs, BPF_REG_0);
7031 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7032 /* continue with next insn after call */
7036 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
7039 state->frame[state->curframe + 1] = callee;
7041 /* callee cannot access r0, r6 - r9 for reading and has to write
7042 * into its own stack before reading from it.
7043 * callee can read/write into caller's stack
7045 init_func_state(env, callee,
7046 /* remember the callsite, it will be used by bpf_exit */
7047 *insn_idx /* callsite */,
7048 state->curframe + 1 /* frameno within this callchain */,
7049 subprog /* subprog number within this prog */);
7051 /* Transfer references to the callee */
7052 err = copy_reference_state(callee, caller);
7056 err = set_callee_state_cb(env, caller, callee, *insn_idx);
7060 clear_caller_saved_regs(env, caller->regs);
7062 /* only increment it after check_reg_arg() finished */
7065 /* and go analyze first insn of the callee */
7066 *insn_idx = env->subprog_info[subprog].start - 1;
7068 if (env->log.level & BPF_LOG_LEVEL) {
7069 verbose(env, "caller:\n");
7070 print_verifier_state(env, caller, true);
7071 verbose(env, "callee:\n");
7072 print_verifier_state(env, callee, true);
7077 free_func_state(callee);
7078 state->frame[state->curframe + 1] = NULL;
7082 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7083 struct bpf_func_state *caller,
7084 struct bpf_func_state *callee)
7086 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7087 * void *callback_ctx, u64 flags);
7088 * callback_fn(struct bpf_map *map, void *key, void *value,
7089 * void *callback_ctx);
7091 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7093 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7094 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7095 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7097 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7098 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7099 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7101 /* pointer to stack or null */
7102 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7105 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7109 static int set_callee_state(struct bpf_verifier_env *env,
7110 struct bpf_func_state *caller,
7111 struct bpf_func_state *callee, int insn_idx)
7115 /* copy r1 - r5 args that callee can access. The copy includes parent
7116 * pointers, which connects us up to the liveness chain
7118 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7119 callee->regs[i] = caller->regs[i];
7123 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7126 int subprog, target_insn;
7128 target_insn = *insn_idx + insn->imm + 1;
7129 subprog = find_subprog(env, target_insn);
7131 verbose(env, "verifier bug. No program starts at insn %d\n",
7136 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7139 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7140 struct bpf_func_state *caller,
7141 struct bpf_func_state *callee,
7144 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7145 struct bpf_map *map;
7148 if (bpf_map_ptr_poisoned(insn_aux)) {
7149 verbose(env, "tail_call abusing map_ptr\n");
7153 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7154 if (!map->ops->map_set_for_each_callback_args ||
7155 !map->ops->map_for_each_callback) {
7156 verbose(env, "callback function not allowed for map\n");
7160 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7164 callee->in_callback_fn = true;
7165 callee->callback_ret_range = tnum_range(0, 1);
7169 static int set_loop_callback_state(struct bpf_verifier_env *env,
7170 struct bpf_func_state *caller,
7171 struct bpf_func_state *callee,
7174 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7176 * callback_fn(u32 index, void *callback_ctx);
7178 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7179 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7182 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7183 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7184 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7186 callee->in_callback_fn = true;
7187 callee->callback_ret_range = tnum_range(0, 1);
7191 static int set_timer_callback_state(struct bpf_verifier_env *env,
7192 struct bpf_func_state *caller,
7193 struct bpf_func_state *callee,
7196 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7198 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7199 * callback_fn(struct bpf_map *map, void *key, void *value);
7201 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7202 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7203 callee->regs[BPF_REG_1].map_ptr = map_ptr;
7205 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7206 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7207 callee->regs[BPF_REG_2].map_ptr = map_ptr;
7209 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7210 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7211 callee->regs[BPF_REG_3].map_ptr = map_ptr;
7214 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7215 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7216 callee->in_async_callback_fn = true;
7217 callee->callback_ret_range = tnum_range(0, 1);
7221 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7222 struct bpf_func_state *caller,
7223 struct bpf_func_state *callee,
7226 /* bpf_find_vma(struct task_struct *task, u64 addr,
7227 * void *callback_fn, void *callback_ctx, u64 flags)
7228 * (callback_fn)(struct task_struct *task,
7229 * struct vm_area_struct *vma, void *callback_ctx);
7231 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7233 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7234 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7235 callee->regs[BPF_REG_2].btf = btf_vmlinux;
7236 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7238 /* pointer to stack or null */
7239 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7242 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7243 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7244 callee->in_callback_fn = true;
7245 callee->callback_ret_range = tnum_range(0, 1);
7249 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7250 struct bpf_func_state *caller,
7251 struct bpf_func_state *callee,
7254 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7255 * callback_ctx, u64 flags);
7256 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
7258 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7259 callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
7260 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7261 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7264 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7265 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7266 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7268 callee->in_callback_fn = true;
7269 callee->callback_ret_range = tnum_range(0, 1);
7273 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7275 struct bpf_verifier_state *state = env->cur_state;
7276 struct bpf_func_state *caller, *callee;
7277 struct bpf_reg_state *r0;
7280 callee = state->frame[state->curframe];
7281 r0 = &callee->regs[BPF_REG_0];
7282 if (r0->type == PTR_TO_STACK) {
7283 /* technically it's ok to return caller's stack pointer
7284 * (or caller's caller's pointer) back to the caller,
7285 * since these pointers are valid. Only current stack
7286 * pointer will be invalid as soon as function exits,
7287 * but let's be conservative
7289 verbose(env, "cannot return stack pointer to the caller\n");
7293 caller = state->frame[state->curframe - 1];
7294 if (callee->in_callback_fn) {
7295 /* enforce R0 return value range [0, 1]. */
7296 struct tnum range = callee->callback_ret_range;
7298 if (r0->type != SCALAR_VALUE) {
7299 verbose(env, "R0 not a scalar value\n");
7302 if (!tnum_in(range, r0->var_off)) {
7303 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7307 /* return to the caller whatever r0 had in the callee */
7308 caller->regs[BPF_REG_0] = *r0;
7311 /* callback_fn frame should have released its own additions to parent's
7312 * reference state at this point, or check_reference_leak would
7313 * complain, hence it must be the same as the caller. There is no need
7316 if (!callee->in_callback_fn) {
7317 /* Transfer references to the caller */
7318 err = copy_reference_state(caller, callee);
7323 *insn_idx = callee->callsite + 1;
7324 if (env->log.level & BPF_LOG_LEVEL) {
7325 verbose(env, "returning from callee:\n");
7326 print_verifier_state(env, callee, true);
7327 verbose(env, "to caller at %d:\n", *insn_idx);
7328 print_verifier_state(env, caller, true);
7330 /* clear everything in the callee */
7331 free_func_state(callee);
7332 state->frame[state->curframe--] = NULL;
7336 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7338 struct bpf_call_arg_meta *meta)
7340 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
7342 if (ret_type != RET_INTEGER ||
7343 (func_id != BPF_FUNC_get_stack &&
7344 func_id != BPF_FUNC_get_task_stack &&
7345 func_id != BPF_FUNC_probe_read_str &&
7346 func_id != BPF_FUNC_probe_read_kernel_str &&
7347 func_id != BPF_FUNC_probe_read_user_str))
7350 ret_reg->smax_value = meta->msize_max_value;
7351 ret_reg->s32_max_value = meta->msize_max_value;
7352 ret_reg->smin_value = -MAX_ERRNO;
7353 ret_reg->s32_min_value = -MAX_ERRNO;
7354 reg_bounds_sync(ret_reg);
7358 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7359 int func_id, int insn_idx)
7361 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7362 struct bpf_map *map = meta->map_ptr;
7364 if (func_id != BPF_FUNC_tail_call &&
7365 func_id != BPF_FUNC_map_lookup_elem &&
7366 func_id != BPF_FUNC_map_update_elem &&
7367 func_id != BPF_FUNC_map_delete_elem &&
7368 func_id != BPF_FUNC_map_push_elem &&
7369 func_id != BPF_FUNC_map_pop_elem &&
7370 func_id != BPF_FUNC_map_peek_elem &&
7371 func_id != BPF_FUNC_for_each_map_elem &&
7372 func_id != BPF_FUNC_redirect_map &&
7373 func_id != BPF_FUNC_map_lookup_percpu_elem)
7377 verbose(env, "kernel subsystem misconfigured verifier\n");
7381 /* In case of read-only, some additional restrictions
7382 * need to be applied in order to prevent altering the
7383 * state of the map from program side.
7385 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7386 (func_id == BPF_FUNC_map_delete_elem ||
7387 func_id == BPF_FUNC_map_update_elem ||
7388 func_id == BPF_FUNC_map_push_elem ||
7389 func_id == BPF_FUNC_map_pop_elem)) {
7390 verbose(env, "write into map forbidden\n");
7394 if (!BPF_MAP_PTR(aux->map_ptr_state))
7395 bpf_map_ptr_store(aux, meta->map_ptr,
7396 !meta->map_ptr->bypass_spec_v1);
7397 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7398 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7399 !meta->map_ptr->bypass_spec_v1);
7404 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7405 int func_id, int insn_idx)
7407 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7408 struct bpf_reg_state *regs = cur_regs(env), *reg;
7409 struct bpf_map *map = meta->map_ptr;
7413 if (func_id != BPF_FUNC_tail_call)
7415 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7416 verbose(env, "kernel subsystem misconfigured verifier\n");
7420 reg = ®s[BPF_REG_3];
7421 val = reg->var_off.value;
7422 max = map->max_entries;
7424 if (!(register_is_const(reg) && val < max)) {
7425 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7429 err = mark_chain_precision(env, BPF_REG_3);
7432 if (bpf_map_key_unseen(aux))
7433 bpf_map_key_store(aux, val);
7434 else if (!bpf_map_key_poisoned(aux) &&
7435 bpf_map_key_immediate(aux) != val)
7436 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7440 static int check_reference_leak(struct bpf_verifier_env *env)
7442 struct bpf_func_state *state = cur_func(env);
7443 bool refs_lingering = false;
7446 if (state->frameno && !state->in_callback_fn)
7449 for (i = 0; i < state->acquired_refs; i++) {
7450 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7452 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7453 state->refs[i].id, state->refs[i].insn_idx);
7454 refs_lingering = true;
7456 return refs_lingering ? -EINVAL : 0;
7459 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7460 struct bpf_reg_state *regs)
7462 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
7463 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
7464 struct bpf_map *fmt_map = fmt_reg->map_ptr;
7465 int err, fmt_map_off, num_args;
7469 /* data must be an array of u64 */
7470 if (data_len_reg->var_off.value % 8)
7472 num_args = data_len_reg->var_off.value / 8;
7474 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7475 * and map_direct_value_addr is set.
7477 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7478 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7481 verbose(env, "verifier bug\n");
7484 fmt = (char *)(long)fmt_addr + fmt_map_off;
7486 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7487 * can focus on validating the format specifiers.
7489 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7491 verbose(env, "Invalid format string\n");
7496 static int check_get_func_ip(struct bpf_verifier_env *env)
7498 enum bpf_prog_type type = resolve_prog_type(env->prog);
7499 int func_id = BPF_FUNC_get_func_ip;
7501 if (type == BPF_PROG_TYPE_TRACING) {
7502 if (!bpf_prog_has_trampoline(env->prog)) {
7503 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7504 func_id_name(func_id), func_id);
7508 } else if (type == BPF_PROG_TYPE_KPROBE) {
7512 verbose(env, "func %s#%d not supported for program type %d\n",
7513 func_id_name(func_id), func_id, type);
7517 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7519 return &env->insn_aux_data[env->insn_idx];
7522 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7524 struct bpf_reg_state *regs = cur_regs(env);
7525 struct bpf_reg_state *reg = ®s[BPF_REG_4];
7526 bool reg_is_null = register_is_null(reg);
7529 mark_chain_precision(env, BPF_REG_4);
7534 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7536 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7538 if (!state->initialized) {
7539 state->initialized = 1;
7540 state->fit_for_inline = loop_flag_is_zero(env);
7541 state->callback_subprogno = subprogno;
7545 if (!state->fit_for_inline)
7548 state->fit_for_inline = (loop_flag_is_zero(env) &&
7549 state->callback_subprogno == subprogno);
7552 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7555 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7556 const struct bpf_func_proto *fn = NULL;
7557 enum bpf_return_type ret_type;
7558 enum bpf_type_flag ret_flag;
7559 struct bpf_reg_state *regs;
7560 struct bpf_call_arg_meta meta;
7561 int insn_idx = *insn_idx_p;
7563 int i, err, func_id;
7565 /* find function prototype */
7566 func_id = insn->imm;
7567 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7568 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7573 if (env->ops->get_func_proto)
7574 fn = env->ops->get_func_proto(func_id, env->prog);
7576 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7581 /* eBPF programs must be GPL compatible to use GPL-ed functions */
7582 if (!env->prog->gpl_compatible && fn->gpl_only) {
7583 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7587 if (fn->allowed && !fn->allowed(env->prog)) {
7588 verbose(env, "helper call is not allowed in probe\n");
7592 if (!env->prog->aux->sleepable && fn->might_sleep) {
7593 verbose(env, "helper call might sleep in a non-sleepable prog\n");
7597 /* With LD_ABS/IND some JITs save/restore skb from r1. */
7598 changes_data = bpf_helper_changes_pkt_data(fn->func);
7599 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7600 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7601 func_id_name(func_id), func_id);
7605 memset(&meta, 0, sizeof(meta));
7606 meta.pkt_access = fn->pkt_access;
7608 err = check_func_proto(fn, func_id);
7610 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7611 func_id_name(func_id), func_id);
7615 if (env->cur_state->active_rcu_lock) {
7616 if (fn->might_sleep) {
7617 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
7618 func_id_name(func_id), func_id);
7622 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
7623 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
7626 meta.func_id = func_id;
7628 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7629 err = check_func_arg(env, i, &meta, fn);
7634 err = record_func_map(env, &meta, func_id, insn_idx);
7638 err = record_func_key(env, &meta, func_id, insn_idx);
7642 /* Mark slots with STACK_MISC in case of raw mode, stack offset
7643 * is inferred from register state.
7645 for (i = 0; i < meta.access_size; i++) {
7646 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7647 BPF_WRITE, -1, false);
7652 regs = cur_regs(env);
7654 if (meta.uninit_dynptr_regno) {
7655 /* we write BPF_DW bits (8 bytes) at a time */
7656 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7657 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7658 i, BPF_DW, BPF_WRITE, -1, false);
7663 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno],
7664 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7670 if (meta.release_regno) {
7672 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7673 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
7674 else if (meta.ref_obj_id)
7675 err = release_reference(env, meta.ref_obj_id);
7676 /* meta.ref_obj_id can only be 0 if register that is meant to be
7677 * released is NULL, which must be > R0.
7679 else if (register_is_null(®s[meta.release_regno]))
7682 verbose(env, "func %s#%d reference has not been acquired before\n",
7683 func_id_name(func_id), func_id);
7689 case BPF_FUNC_tail_call:
7690 err = check_reference_leak(env);
7692 verbose(env, "tail_call would lead to reference leak\n");
7696 case BPF_FUNC_get_local_storage:
7697 /* check that flags argument in get_local_storage(map, flags) is 0,
7698 * this is required because get_local_storage() can't return an error.
7700 if (!register_is_null(®s[BPF_REG_2])) {
7701 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7705 case BPF_FUNC_for_each_map_elem:
7706 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7707 set_map_elem_callback_state);
7709 case BPF_FUNC_timer_set_callback:
7710 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7711 set_timer_callback_state);
7713 case BPF_FUNC_find_vma:
7714 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7715 set_find_vma_callback_state);
7717 case BPF_FUNC_snprintf:
7718 err = check_bpf_snprintf_call(env, regs);
7721 update_loop_inline_state(env, meta.subprogno);
7722 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7723 set_loop_callback_state);
7725 case BPF_FUNC_dynptr_from_mem:
7726 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7727 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7728 reg_type_str(env, regs[BPF_REG_1].type));
7732 case BPF_FUNC_set_retval:
7733 if (prog_type == BPF_PROG_TYPE_LSM &&
7734 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7735 if (!env->prog->aux->attach_func_proto->type) {
7736 /* Make sure programs that attach to void
7737 * hooks don't try to modify return value.
7739 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7744 case BPF_FUNC_dynptr_data:
7745 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7746 if (arg_type_is_dynptr(fn->arg_type[i])) {
7747 struct bpf_reg_state *reg = ®s[BPF_REG_1 + i];
7749 if (meta.ref_obj_id) {
7750 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7754 if (base_type(reg->type) != PTR_TO_DYNPTR)
7755 /* Find the id of the dynptr we're
7756 * tracking the reference of
7758 meta.ref_obj_id = stack_slot_get_id(env, reg);
7762 if (i == MAX_BPF_FUNC_REG_ARGS) {
7763 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7767 case BPF_FUNC_user_ringbuf_drain:
7768 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7769 set_user_ringbuf_callback_state);
7776 /* reset caller saved regs */
7777 for (i = 0; i < CALLER_SAVED_REGS; i++) {
7778 mark_reg_not_init(env, regs, caller_saved[i]);
7779 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7782 /* helper call returns 64-bit value. */
7783 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7785 /* update return register (already marked as written above) */
7786 ret_type = fn->ret_type;
7787 ret_flag = type_flag(ret_type);
7789 switch (base_type(ret_type)) {
7791 /* sets type to SCALAR_VALUE */
7792 mark_reg_unknown(env, regs, BPF_REG_0);
7795 regs[BPF_REG_0].type = NOT_INIT;
7797 case RET_PTR_TO_MAP_VALUE:
7798 /* There is no offset yet applied, variable or fixed */
7799 mark_reg_known_zero(env, regs, BPF_REG_0);
7800 /* remember map_ptr, so that check_map_access()
7801 * can check 'value_size' boundary of memory access
7802 * to map element returned from bpf_map_lookup_elem()
7804 if (meta.map_ptr == NULL) {
7806 "kernel subsystem misconfigured verifier\n");
7809 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7810 regs[BPF_REG_0].map_uid = meta.map_uid;
7811 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7812 if (!type_may_be_null(ret_type) &&
7813 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
7814 regs[BPF_REG_0].id = ++env->id_gen;
7817 case RET_PTR_TO_SOCKET:
7818 mark_reg_known_zero(env, regs, BPF_REG_0);
7819 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7821 case RET_PTR_TO_SOCK_COMMON:
7822 mark_reg_known_zero(env, regs, BPF_REG_0);
7823 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7825 case RET_PTR_TO_TCP_SOCK:
7826 mark_reg_known_zero(env, regs, BPF_REG_0);
7827 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7829 case RET_PTR_TO_MEM:
7830 mark_reg_known_zero(env, regs, BPF_REG_0);
7831 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7832 regs[BPF_REG_0].mem_size = meta.mem_size;
7834 case RET_PTR_TO_MEM_OR_BTF_ID:
7836 const struct btf_type *t;
7838 mark_reg_known_zero(env, regs, BPF_REG_0);
7839 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7840 if (!btf_type_is_struct(t)) {
7842 const struct btf_type *ret;
7845 /* resolve the type size of ksym. */
7846 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7848 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7849 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7850 tname, PTR_ERR(ret));
7853 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7854 regs[BPF_REG_0].mem_size = tsize;
7856 /* MEM_RDONLY may be carried from ret_flag, but it
7857 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7858 * it will confuse the check of PTR_TO_BTF_ID in
7859 * check_mem_access().
7861 ret_flag &= ~MEM_RDONLY;
7863 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7864 regs[BPF_REG_0].btf = meta.ret_btf;
7865 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7869 case RET_PTR_TO_BTF_ID:
7871 struct btf *ret_btf;
7874 mark_reg_known_zero(env, regs, BPF_REG_0);
7875 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7876 if (func_id == BPF_FUNC_kptr_xchg) {
7877 ret_btf = meta.kptr_field->kptr.btf;
7878 ret_btf_id = meta.kptr_field->kptr.btf_id;
7880 if (fn->ret_btf_id == BPF_PTR_POISON) {
7881 verbose(env, "verifier internal error:");
7882 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7883 func_id_name(func_id));
7886 ret_btf = btf_vmlinux;
7887 ret_btf_id = *fn->ret_btf_id;
7889 if (ret_btf_id == 0) {
7890 verbose(env, "invalid return type %u of func %s#%d\n",
7891 base_type(ret_type), func_id_name(func_id),
7895 regs[BPF_REG_0].btf = ret_btf;
7896 regs[BPF_REG_0].btf_id = ret_btf_id;
7900 verbose(env, "unknown return type %u of func %s#%d\n",
7901 base_type(ret_type), func_id_name(func_id), func_id);
7905 if (type_may_be_null(regs[BPF_REG_0].type))
7906 regs[BPF_REG_0].id = ++env->id_gen;
7908 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7909 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7910 func_id_name(func_id), func_id);
7914 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7915 /* For release_reference() */
7916 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7917 } else if (is_acquire_function(func_id, meta.map_ptr)) {
7918 int id = acquire_reference_state(env, insn_idx);
7922 /* For mark_ptr_or_null_reg() */
7923 regs[BPF_REG_0].id = id;
7924 /* For release_reference() */
7925 regs[BPF_REG_0].ref_obj_id = id;
7928 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7930 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7934 if ((func_id == BPF_FUNC_get_stack ||
7935 func_id == BPF_FUNC_get_task_stack) &&
7936 !env->prog->has_callchain_buf) {
7937 const char *err_str;
7939 #ifdef CONFIG_PERF_EVENTS
7940 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7941 err_str = "cannot get callchain buffer for func %s#%d\n";
7944 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7947 verbose(env, err_str, func_id_name(func_id), func_id);
7951 env->prog->has_callchain_buf = true;
7954 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7955 env->prog->call_get_stack = true;
7957 if (func_id == BPF_FUNC_get_func_ip) {
7958 if (check_get_func_ip(env))
7960 env->prog->call_get_func_ip = true;
7964 clear_all_pkt_pointers(env);
7968 /* mark_btf_func_reg_size() is used when the reg size is determined by
7969 * the BTF func_proto's return value size and argument.
7971 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7974 struct bpf_reg_state *reg = &cur_regs(env)[regno];
7976 if (regno == BPF_REG_0) {
7977 /* Function return value */
7978 reg->live |= REG_LIVE_WRITTEN;
7979 reg->subreg_def = reg_size == sizeof(u64) ?
7980 DEF_NOT_SUBREG : env->insn_idx + 1;
7982 /* Function argument */
7983 if (reg_size == sizeof(u64)) {
7984 mark_insn_zext(env, reg);
7985 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7987 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7992 struct bpf_kfunc_call_arg_meta {
7997 const struct btf_type *func_proto;
7998 const char *func_name;
7999 /* Out parameters */
8014 struct btf_field *field;
8018 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
8020 return meta->kfunc_flags & KF_ACQUIRE;
8023 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
8025 return meta->kfunc_flags & KF_RET_NULL;
8028 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
8030 return meta->kfunc_flags & KF_RELEASE;
8033 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
8035 return meta->kfunc_flags & KF_TRUSTED_ARGS;
8038 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
8040 return meta->kfunc_flags & KF_SLEEPABLE;
8043 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
8045 return meta->kfunc_flags & KF_DESTRUCTIVE;
8048 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
8050 return meta->kfunc_flags & KF_RCU;
8053 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
8055 return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
8058 static bool __kfunc_param_match_suffix(const struct btf *btf,
8059 const struct btf_param *arg,
8062 int suffix_len = strlen(suffix), len;
8063 const char *param_name;
8065 /* In the future, this can be ported to use BTF tagging */
8066 param_name = btf_name_by_offset(btf, arg->name_off);
8067 if (str_is_empty(param_name))
8069 len = strlen(param_name);
8070 if (len < suffix_len)
8072 param_name += len - suffix_len;
8073 return !strncmp(param_name, suffix, suffix_len);
8076 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8077 const struct btf_param *arg,
8078 const struct bpf_reg_state *reg)
8080 const struct btf_type *t;
8082 t = btf_type_skip_modifiers(btf, arg->type, NULL);
8083 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8086 return __kfunc_param_match_suffix(btf, arg, "__sz");
8089 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8091 return __kfunc_param_match_suffix(btf, arg, "__k");
8094 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8096 return __kfunc_param_match_suffix(btf, arg, "__ign");
8099 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8101 return __kfunc_param_match_suffix(btf, arg, "__alloc");
8104 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8105 const struct btf_param *arg,
8108 int len, target_len = strlen(name);
8109 const char *param_name;
8111 param_name = btf_name_by_offset(btf, arg->name_off);
8112 if (str_is_empty(param_name))
8114 len = strlen(param_name);
8115 if (len != target_len)
8117 if (strcmp(param_name, name))
8125 KF_ARG_LIST_HEAD_ID,
8126 KF_ARG_LIST_NODE_ID,
8129 BTF_ID_LIST(kf_arg_btf_ids)
8130 BTF_ID(struct, bpf_dynptr_kern)
8131 BTF_ID(struct, bpf_list_head)
8132 BTF_ID(struct, bpf_list_node)
8134 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8135 const struct btf_param *arg, int type)
8137 const struct btf_type *t;
8140 t = btf_type_skip_modifiers(btf, arg->type, NULL);
8143 if (!btf_type_is_ptr(t))
8145 t = btf_type_skip_modifiers(btf, t->type, &res_id);
8148 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
8151 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
8153 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
8156 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
8158 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
8161 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
8163 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
8166 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
8167 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
8168 const struct btf *btf,
8169 const struct btf_type *t, int rec)
8171 const struct btf_type *member_type;
8172 const struct btf_member *member;
8175 if (!btf_type_is_struct(t))
8178 for_each_member(i, t, member) {
8179 const struct btf_array *array;
8181 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
8182 if (btf_type_is_struct(member_type)) {
8184 verbose(env, "max struct nesting depth exceeded\n");
8187 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
8191 if (btf_type_is_array(member_type)) {
8192 array = btf_array(member_type);
8195 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
8196 if (!btf_type_is_scalar(member_type))
8200 if (!btf_type_is_scalar(member_type))
8207 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
8209 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
8210 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8211 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
8215 enum kfunc_ptr_arg_type {
8217 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
8218 KF_ARG_PTR_TO_KPTR, /* PTR_TO_KPTR but type specific */
8219 KF_ARG_PTR_TO_DYNPTR,
8220 KF_ARG_PTR_TO_LIST_HEAD,
8221 KF_ARG_PTR_TO_LIST_NODE,
8222 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
8224 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
8227 enum special_kfunc_type {
8228 KF_bpf_obj_new_impl,
8229 KF_bpf_obj_drop_impl,
8230 KF_bpf_list_push_front,
8231 KF_bpf_list_push_back,
8232 KF_bpf_list_pop_front,
8233 KF_bpf_list_pop_back,
8234 KF_bpf_cast_to_kern_ctx,
8236 KF_bpf_rcu_read_lock,
8237 KF_bpf_rcu_read_unlock,
8240 BTF_SET_START(special_kfunc_set)
8241 BTF_ID(func, bpf_obj_new_impl)
8242 BTF_ID(func, bpf_obj_drop_impl)
8243 BTF_ID(func, bpf_list_push_front)
8244 BTF_ID(func, bpf_list_push_back)
8245 BTF_ID(func, bpf_list_pop_front)
8246 BTF_ID(func, bpf_list_pop_back)
8247 BTF_ID(func, bpf_cast_to_kern_ctx)
8248 BTF_ID(func, bpf_rdonly_cast)
8249 BTF_SET_END(special_kfunc_set)
8251 BTF_ID_LIST(special_kfunc_list)
8252 BTF_ID(func, bpf_obj_new_impl)
8253 BTF_ID(func, bpf_obj_drop_impl)
8254 BTF_ID(func, bpf_list_push_front)
8255 BTF_ID(func, bpf_list_push_back)
8256 BTF_ID(func, bpf_list_pop_front)
8257 BTF_ID(func, bpf_list_pop_back)
8258 BTF_ID(func, bpf_cast_to_kern_ctx)
8259 BTF_ID(func, bpf_rdonly_cast)
8260 BTF_ID(func, bpf_rcu_read_lock)
8261 BTF_ID(func, bpf_rcu_read_unlock)
8263 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
8265 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
8268 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
8270 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
8273 static enum kfunc_ptr_arg_type
8274 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
8275 struct bpf_kfunc_call_arg_meta *meta,
8276 const struct btf_type *t, const struct btf_type *ref_t,
8277 const char *ref_tname, const struct btf_param *args,
8278 int argno, int nargs)
8280 u32 regno = argno + 1;
8281 struct bpf_reg_state *regs = cur_regs(env);
8282 struct bpf_reg_state *reg = ®s[regno];
8283 bool arg_mem_size = false;
8285 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
8286 return KF_ARG_PTR_TO_CTX;
8288 /* In this function, we verify the kfunc's BTF as per the argument type,
8289 * leaving the rest of the verification with respect to the register
8290 * type to our caller. When a set of conditions hold in the BTF type of
8291 * arguments, we resolve it to a known kfunc_ptr_arg_type.
8293 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
8294 return KF_ARG_PTR_TO_CTX;
8296 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
8297 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
8299 if (is_kfunc_arg_kptr_get(meta, argno)) {
8300 if (!btf_type_is_ptr(ref_t)) {
8301 verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
8304 ref_t = btf_type_by_id(meta->btf, ref_t->type);
8305 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
8306 if (!btf_type_is_struct(ref_t)) {
8307 verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
8308 meta->func_name, btf_type_str(ref_t), ref_tname);
8311 return KF_ARG_PTR_TO_KPTR;
8314 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
8315 return KF_ARG_PTR_TO_DYNPTR;
8317 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
8318 return KF_ARG_PTR_TO_LIST_HEAD;
8320 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
8321 return KF_ARG_PTR_TO_LIST_NODE;
8323 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
8324 if (!btf_type_is_struct(ref_t)) {
8325 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
8326 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8329 return KF_ARG_PTR_TO_BTF_ID;
8332 if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))
8333 arg_mem_size = true;
8335 /* This is the catch all argument type of register types supported by
8336 * check_helper_mem_access. However, we only allow when argument type is
8337 * pointer to scalar, or struct composed (recursively) of scalars. When
8338 * arg_mem_size is true, the pointer can be void *.
8340 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
8341 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
8342 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
8343 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
8346 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
8349 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
8350 struct bpf_reg_state *reg,
8351 const struct btf_type *ref_t,
8352 const char *ref_tname, u32 ref_id,
8353 struct bpf_kfunc_call_arg_meta *meta,
8356 const struct btf_type *reg_ref_t;
8357 bool strict_type_match = false;
8358 const struct btf *reg_btf;
8359 const char *reg_ref_tname;
8362 if (base_type(reg->type) == PTR_TO_BTF_ID) {
8364 reg_ref_id = reg->btf_id;
8366 reg_btf = btf_vmlinux;
8367 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
8370 if (is_kfunc_trusted_args(meta) || (is_kfunc_release(meta) && reg->ref_obj_id))
8371 strict_type_match = true;
8373 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
8374 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
8375 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
8376 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
8377 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
8378 btf_type_str(reg_ref_t), reg_ref_tname);
8384 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
8385 struct bpf_reg_state *reg,
8386 const struct btf_type *ref_t,
8387 const char *ref_tname,
8388 struct bpf_kfunc_call_arg_meta *meta,
8391 struct btf_field *kptr_field;
8393 /* check_func_arg_reg_off allows var_off for
8394 * PTR_TO_MAP_VALUE, but we need fixed offset to find
8397 if (!tnum_is_const(reg->var_off)) {
8398 verbose(env, "arg#0 must have constant offset\n");
8402 kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
8403 if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
8404 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
8405 reg->off + reg->var_off.value);
8409 if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
8410 kptr_field->kptr.btf_id, true)) {
8411 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
8412 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8418 static int ref_set_release_on_unlock(struct bpf_verifier_env *env, u32 ref_obj_id)
8420 struct bpf_func_state *state = cur_func(env);
8421 struct bpf_reg_state *reg;
8424 /* bpf_spin_lock only allows calling list_push and list_pop, no BPF
8425 * subprogs, no global functions. This means that the references would
8426 * not be released inside the critical section but they may be added to
8427 * the reference state, and the acquired_refs are never copied out for a
8428 * different frame as BPF to BPF calls don't work in bpf_spin_lock
8429 * critical sections.
8432 verbose(env, "verifier internal error: ref_obj_id is zero for release_on_unlock\n");
8435 for (i = 0; i < state->acquired_refs; i++) {
8436 if (state->refs[i].id == ref_obj_id) {
8437 if (state->refs[i].release_on_unlock) {
8438 verbose(env, "verifier internal error: expected false release_on_unlock");
8441 state->refs[i].release_on_unlock = true;
8442 /* Now mark everyone sharing same ref_obj_id as untrusted */
8443 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8444 if (reg->ref_obj_id == ref_obj_id)
8445 reg->type |= PTR_UNTRUSTED;
8450 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
8454 /* Implementation details:
8456 * Each register points to some region of memory, which we define as an
8457 * allocation. Each allocation may embed a bpf_spin_lock which protects any
8458 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
8459 * allocation. The lock and the data it protects are colocated in the same
8462 * Hence, everytime a register holds a pointer value pointing to such
8463 * allocation, the verifier preserves a unique reg->id for it.
8465 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
8466 * bpf_spin_lock is called.
8468 * To enable this, lock state in the verifier captures two values:
8469 * active_lock.ptr = Register's type specific pointer
8470 * active_lock.id = A unique ID for each register pointer value
8472 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
8473 * supported register types.
8475 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
8476 * allocated objects is the reg->btf pointer.
8478 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
8479 * can establish the provenance of the map value statically for each distinct
8480 * lookup into such maps. They always contain a single map value hence unique
8481 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
8483 * So, in case of global variables, they use array maps with max_entries = 1,
8484 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
8485 * into the same map value as max_entries is 1, as described above).
8487 * In case of inner map lookups, the inner map pointer has same map_ptr as the
8488 * outer map pointer (in verifier context), but each lookup into an inner map
8489 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
8490 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
8491 * will get different reg->id assigned to each lookup, hence different
8494 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
8495 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
8496 * returned from bpf_obj_new. Each allocation receives a new reg->id.
8498 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8503 switch ((int)reg->type) {
8504 case PTR_TO_MAP_VALUE:
8507 case PTR_TO_BTF_ID | MEM_ALLOC:
8508 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
8512 verbose(env, "verifier internal error: unknown reg type for lock check\n");
8517 if (!env->cur_state->active_lock.ptr)
8519 if (env->cur_state->active_lock.ptr != ptr ||
8520 env->cur_state->active_lock.id != id) {
8521 verbose(env, "held lock and object are not in the same allocation\n");
8527 static bool is_bpf_list_api_kfunc(u32 btf_id)
8529 return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
8530 btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
8531 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
8532 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
8535 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
8536 struct bpf_reg_state *reg, u32 regno,
8537 struct bpf_kfunc_call_arg_meta *meta)
8539 struct btf_field *field;
8540 struct btf_record *rec;
8543 if (meta->btf != btf_vmlinux || !is_bpf_list_api_kfunc(meta->func_id)) {
8544 verbose(env, "verifier internal error: bpf_list_head argument for unknown kfunc\n");
8548 if (!tnum_is_const(reg->var_off)) {
8550 "R%d doesn't have constant offset. bpf_list_head has to be at the constant offset\n",
8555 rec = reg_btf_record(reg);
8556 list_head_off = reg->off + reg->var_off.value;
8557 field = btf_record_find(rec, list_head_off, BPF_LIST_HEAD);
8559 verbose(env, "bpf_list_head not found at offset=%u\n", list_head_off);
8563 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
8564 if (check_reg_allocation_locked(env, reg)) {
8565 verbose(env, "bpf_spin_lock at off=%d must be held for bpf_list_head\n",
8566 rec->spin_lock_off);
8570 if (meta->arg_list_head.field) {
8571 verbose(env, "verifier internal error: repeating bpf_list_head arg\n");
8574 meta->arg_list_head.field = field;
8578 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
8579 struct bpf_reg_state *reg, u32 regno,
8580 struct bpf_kfunc_call_arg_meta *meta)
8582 const struct btf_type *et, *t;
8583 struct btf_field *field;
8584 struct btf_record *rec;
8587 if (meta->btf != btf_vmlinux ||
8588 (meta->func_id != special_kfunc_list[KF_bpf_list_push_front] &&
8589 meta->func_id != special_kfunc_list[KF_bpf_list_push_back])) {
8590 verbose(env, "verifier internal error: bpf_list_node argument for unknown kfunc\n");
8594 if (!tnum_is_const(reg->var_off)) {
8596 "R%d doesn't have constant offset. bpf_list_node has to be at the constant offset\n",
8601 rec = reg_btf_record(reg);
8602 list_node_off = reg->off + reg->var_off.value;
8603 field = btf_record_find(rec, list_node_off, BPF_LIST_NODE);
8604 if (!field || field->offset != list_node_off) {
8605 verbose(env, "bpf_list_node not found at offset=%u\n", list_node_off);
8609 field = meta->arg_list_head.field;
8611 et = btf_type_by_id(field->list_head.btf, field->list_head.value_btf_id);
8612 t = btf_type_by_id(reg->btf, reg->btf_id);
8613 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->list_head.btf,
8614 field->list_head.value_btf_id, true)) {
8615 verbose(env, "operation on bpf_list_head expects arg#1 bpf_list_node at offset=%d "
8616 "in struct %s, but arg is at offset=%d in struct %s\n",
8617 field->list_head.node_offset, btf_name_by_offset(field->list_head.btf, et->name_off),
8618 list_node_off, btf_name_by_offset(reg->btf, t->name_off));
8622 if (list_node_off != field->list_head.node_offset) {
8623 verbose(env, "arg#1 offset=%d, but expected bpf_list_node at offset=%d in struct %s\n",
8624 list_node_off, field->list_head.node_offset,
8625 btf_name_by_offset(field->list_head.btf, et->name_off));
8628 /* Set arg#1 for expiration after unlock */
8629 return ref_set_release_on_unlock(env, reg->ref_obj_id);
8632 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
8634 const char *func_name = meta->func_name, *ref_tname;
8635 const struct btf *btf = meta->btf;
8636 const struct btf_param *args;
8640 args = (const struct btf_param *)(meta->func_proto + 1);
8641 nargs = btf_type_vlen(meta->func_proto);
8642 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
8643 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
8644 MAX_BPF_FUNC_REG_ARGS);
8648 /* Check that BTF function arguments match actual types that the
8651 for (i = 0; i < nargs; i++) {
8652 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
8653 const struct btf_type *t, *ref_t, *resolve_ret;
8654 enum bpf_arg_type arg_type = ARG_DONTCARE;
8655 u32 regno = i + 1, ref_id, type_size;
8656 bool is_ret_buf_sz = false;
8659 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
8661 if (is_kfunc_arg_ignore(btf, &args[i]))
8664 if (btf_type_is_scalar(t)) {
8665 if (reg->type != SCALAR_VALUE) {
8666 verbose(env, "R%d is not a scalar\n", regno);
8670 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
8671 if (meta->arg_constant.found) {
8672 verbose(env, "verifier internal error: only one constant argument permitted\n");
8675 if (!tnum_is_const(reg->var_off)) {
8676 verbose(env, "R%d must be a known constant\n", regno);
8679 ret = mark_chain_precision(env, regno);
8682 meta->arg_constant.found = true;
8683 meta->arg_constant.value = reg->var_off.value;
8684 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
8685 meta->r0_rdonly = true;
8686 is_ret_buf_sz = true;
8687 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
8688 is_ret_buf_sz = true;
8691 if (is_ret_buf_sz) {
8692 if (meta->r0_size) {
8693 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
8697 if (!tnum_is_const(reg->var_off)) {
8698 verbose(env, "R%d is not a const\n", regno);
8702 meta->r0_size = reg->var_off.value;
8703 ret = mark_chain_precision(env, regno);
8710 if (!btf_type_is_ptr(t)) {
8711 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
8715 if (reg->ref_obj_id) {
8716 if (is_kfunc_release(meta) && meta->ref_obj_id) {
8717 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8718 regno, reg->ref_obj_id,
8722 meta->ref_obj_id = reg->ref_obj_id;
8723 if (is_kfunc_release(meta))
8724 meta->release_regno = regno;
8727 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
8728 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
8730 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
8731 if (kf_arg_type < 0)
8734 switch (kf_arg_type) {
8735 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8736 case KF_ARG_PTR_TO_BTF_ID:
8737 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
8740 if (!is_trusted_reg(reg)) {
8741 if (!is_kfunc_rcu(meta)) {
8742 verbose(env, "R%d must be referenced or trusted\n", regno);
8745 if (!is_rcu_reg(reg)) {
8746 verbose(env, "R%d must be a rcu pointer\n", regno);
8752 case KF_ARG_PTR_TO_CTX:
8753 /* Trusted arguments have the same offset checks as release arguments */
8754 arg_type |= OBJ_RELEASE;
8756 case KF_ARG_PTR_TO_KPTR:
8757 case KF_ARG_PTR_TO_DYNPTR:
8758 case KF_ARG_PTR_TO_LIST_HEAD:
8759 case KF_ARG_PTR_TO_LIST_NODE:
8760 case KF_ARG_PTR_TO_MEM:
8761 case KF_ARG_PTR_TO_MEM_SIZE:
8762 /* Trusted by default */
8769 if (is_kfunc_release(meta) && reg->ref_obj_id)
8770 arg_type |= OBJ_RELEASE;
8771 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
8775 switch (kf_arg_type) {
8776 case KF_ARG_PTR_TO_CTX:
8777 if (reg->type != PTR_TO_CTX) {
8778 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
8782 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
8783 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
8786 meta->ret_btf_id = ret;
8789 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8790 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8791 verbose(env, "arg#%d expected pointer to allocated object\n", i);
8794 if (!reg->ref_obj_id) {
8795 verbose(env, "allocated object must be referenced\n");
8798 if (meta->btf == btf_vmlinux &&
8799 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
8800 meta->arg_obj_drop.btf = reg->btf;
8801 meta->arg_obj_drop.btf_id = reg->btf_id;
8804 case KF_ARG_PTR_TO_KPTR:
8805 if (reg->type != PTR_TO_MAP_VALUE) {
8806 verbose(env, "arg#0 expected pointer to map value\n");
8809 ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
8813 case KF_ARG_PTR_TO_DYNPTR:
8814 if (reg->type != PTR_TO_STACK) {
8815 verbose(env, "arg#%d expected pointer to stack\n", i);
8819 if (!is_dynptr_reg_valid_init(env, reg)) {
8820 verbose(env, "arg#%d pointer type %s %s must be valid and initialized\n",
8821 i, btf_type_str(ref_t), ref_tname);
8825 if (!is_dynptr_type_expected(env, reg, ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL)) {
8826 verbose(env, "arg#%d pointer type %s %s points to unsupported dynamic pointer type\n",
8827 i, btf_type_str(ref_t), ref_tname);
8831 case KF_ARG_PTR_TO_LIST_HEAD:
8832 if (reg->type != PTR_TO_MAP_VALUE &&
8833 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8834 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
8837 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
8838 verbose(env, "allocated object must be referenced\n");
8841 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
8845 case KF_ARG_PTR_TO_LIST_NODE:
8846 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8847 verbose(env, "arg#%d expected pointer to allocated object\n", i);
8850 if (!reg->ref_obj_id) {
8851 verbose(env, "allocated object must be referenced\n");
8854 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
8858 case KF_ARG_PTR_TO_BTF_ID:
8859 /* Only base_type is checked, further checks are done here */
8860 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
8861 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
8862 !reg2btf_ids[base_type(reg->type)]) {
8863 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
8864 verbose(env, "expected %s or socket\n",
8865 reg_type_str(env, base_type(reg->type) |
8866 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
8869 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
8873 case KF_ARG_PTR_TO_MEM:
8874 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
8875 if (IS_ERR(resolve_ret)) {
8876 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
8877 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
8880 ret = check_mem_reg(env, reg, regno, type_size);
8884 case KF_ARG_PTR_TO_MEM_SIZE:
8885 ret = check_kfunc_mem_size_reg(env, ®s[regno + 1], regno + 1);
8887 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
8890 /* Skip next '__sz' argument */
8896 if (is_kfunc_release(meta) && !meta->release_regno) {
8897 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
8905 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8908 const struct btf_type *t, *func, *func_proto, *ptr_type;
8909 struct bpf_reg_state *regs = cur_regs(env);
8910 const char *func_name, *ptr_type_name;
8911 bool sleepable, rcu_lock, rcu_unlock;
8912 struct bpf_kfunc_call_arg_meta meta;
8913 u32 i, nargs, func_id, ptr_type_id;
8914 int err, insn_idx = *insn_idx_p;
8915 const struct btf_param *args;
8916 const struct btf_type *ret_t;
8917 struct btf *desc_btf;
8920 /* skip for now, but return error when we find this in fixup_kfunc_call */
8924 desc_btf = find_kfunc_desc_btf(env, insn->off);
8925 if (IS_ERR(desc_btf))
8926 return PTR_ERR(desc_btf);
8928 func_id = insn->imm;
8929 func = btf_type_by_id(desc_btf, func_id);
8930 func_name = btf_name_by_offset(desc_btf, func->name_off);
8931 func_proto = btf_type_by_id(desc_btf, func->type);
8933 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
8935 verbose(env, "calling kernel function %s is not allowed\n",
8940 /* Prepare kfunc call metadata */
8941 memset(&meta, 0, sizeof(meta));
8942 meta.btf = desc_btf;
8943 meta.func_id = func_id;
8944 meta.kfunc_flags = *kfunc_flags;
8945 meta.func_proto = func_proto;
8946 meta.func_name = func_name;
8948 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
8949 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
8953 sleepable = is_kfunc_sleepable(&meta);
8954 if (sleepable && !env->prog->aux->sleepable) {
8955 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
8959 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
8960 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
8961 if ((rcu_lock || rcu_unlock) && !env->rcu_tag_supported) {
8962 verbose(env, "no vmlinux btf rcu tag support for kfunc %s\n", func_name);
8966 if (env->cur_state->active_rcu_lock) {
8967 struct bpf_func_state *state;
8968 struct bpf_reg_state *reg;
8971 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
8973 } else if (rcu_unlock) {
8974 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8975 if (reg->type & MEM_RCU) {
8976 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
8977 reg->type |= PTR_UNTRUSTED;
8980 env->cur_state->active_rcu_lock = false;
8981 } else if (sleepable) {
8982 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
8985 } else if (rcu_lock) {
8986 env->cur_state->active_rcu_lock = true;
8987 } else if (rcu_unlock) {
8988 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
8992 /* Check the arguments */
8993 err = check_kfunc_args(env, &meta);
8996 /* In case of release function, we get register number of refcounted
8997 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
8999 if (meta.release_regno) {
9000 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
9002 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
9003 func_name, func_id);
9008 for (i = 0; i < CALLER_SAVED_REGS; i++)
9009 mark_reg_not_init(env, regs, caller_saved[i]);
9011 /* Check return type */
9012 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
9014 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
9015 /* Only exception is bpf_obj_new_impl */
9016 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
9017 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
9022 if (btf_type_is_scalar(t)) {
9023 mark_reg_unknown(env, regs, BPF_REG_0);
9024 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
9025 } else if (btf_type_is_ptr(t)) {
9026 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
9028 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
9029 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
9030 struct btf *ret_btf;
9033 if (unlikely(!bpf_global_ma_set))
9036 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
9037 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
9041 ret_btf = env->prog->aux->btf;
9042 ret_btf_id = meta.arg_constant.value;
9044 /* This may be NULL due to user not supplying a BTF */
9046 verbose(env, "bpf_obj_new requires prog BTF\n");
9050 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
9051 if (!ret_t || !__btf_type_is_struct(ret_t)) {
9052 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
9056 mark_reg_known_zero(env, regs, BPF_REG_0);
9057 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9058 regs[BPF_REG_0].btf = ret_btf;
9059 regs[BPF_REG_0].btf_id = ret_btf_id;
9061 env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
9062 env->insn_aux_data[insn_idx].kptr_struct_meta =
9063 btf_find_struct_meta(ret_btf, ret_btf_id);
9064 } else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9065 env->insn_aux_data[insn_idx].kptr_struct_meta =
9066 btf_find_struct_meta(meta.arg_obj_drop.btf,
9067 meta.arg_obj_drop.btf_id);
9068 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9069 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
9070 struct btf_field *field = meta.arg_list_head.field;
9072 mark_reg_known_zero(env, regs, BPF_REG_0);
9073 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9074 regs[BPF_REG_0].btf = field->list_head.btf;
9075 regs[BPF_REG_0].btf_id = field->list_head.value_btf_id;
9076 regs[BPF_REG_0].off = field->list_head.node_offset;
9077 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9078 mark_reg_known_zero(env, regs, BPF_REG_0);
9079 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
9080 regs[BPF_REG_0].btf = desc_btf;
9081 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9082 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
9083 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
9084 if (!ret_t || !btf_type_is_struct(ret_t)) {
9086 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
9090 mark_reg_known_zero(env, regs, BPF_REG_0);
9091 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
9092 regs[BPF_REG_0].btf = desc_btf;
9093 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
9095 verbose(env, "kernel function %s unhandled dynamic return type\n",
9099 } else if (!__btf_type_is_struct(ptr_type)) {
9100 if (!meta.r0_size) {
9101 ptr_type_name = btf_name_by_offset(desc_btf,
9102 ptr_type->name_off);
9104 "kernel function %s returns pointer type %s %s is not supported\n",
9106 btf_type_str(ptr_type),
9111 mark_reg_known_zero(env, regs, BPF_REG_0);
9112 regs[BPF_REG_0].type = PTR_TO_MEM;
9113 regs[BPF_REG_0].mem_size = meta.r0_size;
9116 regs[BPF_REG_0].type |= MEM_RDONLY;
9118 /* Ensures we don't access the memory after a release_reference() */
9119 if (meta.ref_obj_id)
9120 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9122 mark_reg_known_zero(env, regs, BPF_REG_0);
9123 regs[BPF_REG_0].btf = desc_btf;
9124 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
9125 regs[BPF_REG_0].btf_id = ptr_type_id;
9128 if (is_kfunc_ret_null(&meta)) {
9129 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
9130 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
9131 regs[BPF_REG_0].id = ++env->id_gen;
9133 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
9134 if (is_kfunc_acquire(&meta)) {
9135 int id = acquire_reference_state(env, insn_idx);
9139 if (is_kfunc_ret_null(&meta))
9140 regs[BPF_REG_0].id = id;
9141 regs[BPF_REG_0].ref_obj_id = id;
9143 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
9144 regs[BPF_REG_0].id = ++env->id_gen;
9145 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
9147 nargs = btf_type_vlen(func_proto);
9148 args = (const struct btf_param *)(func_proto + 1);
9149 for (i = 0; i < nargs; i++) {
9152 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
9153 if (btf_type_is_ptr(t))
9154 mark_btf_func_reg_size(env, regno, sizeof(void *));
9156 /* scalar. ensured by btf_check_kfunc_arg_match() */
9157 mark_btf_func_reg_size(env, regno, t->size);
9163 static bool signed_add_overflows(s64 a, s64 b)
9165 /* Do the add in u64, where overflow is well-defined */
9166 s64 res = (s64)((u64)a + (u64)b);
9173 static bool signed_add32_overflows(s32 a, s32 b)
9175 /* Do the add in u32, where overflow is well-defined */
9176 s32 res = (s32)((u32)a + (u32)b);
9183 static bool signed_sub_overflows(s64 a, s64 b)
9185 /* Do the sub in u64, where overflow is well-defined */
9186 s64 res = (s64)((u64)a - (u64)b);
9193 static bool signed_sub32_overflows(s32 a, s32 b)
9195 /* Do the sub in u32, where overflow is well-defined */
9196 s32 res = (s32)((u32)a - (u32)b);
9203 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
9204 const struct bpf_reg_state *reg,
9205 enum bpf_reg_type type)
9207 bool known = tnum_is_const(reg->var_off);
9208 s64 val = reg->var_off.value;
9209 s64 smin = reg->smin_value;
9211 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
9212 verbose(env, "math between %s pointer and %lld is not allowed\n",
9213 reg_type_str(env, type), val);
9217 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
9218 verbose(env, "%s pointer offset %d is not allowed\n",
9219 reg_type_str(env, type), reg->off);
9223 if (smin == S64_MIN) {
9224 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
9225 reg_type_str(env, type));
9229 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
9230 verbose(env, "value %lld makes %s pointer be out of bounds\n",
9231 smin, reg_type_str(env, type));
9246 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
9247 u32 *alu_limit, bool mask_to_left)
9249 u32 max = 0, ptr_limit = 0;
9251 switch (ptr_reg->type) {
9253 /* Offset 0 is out-of-bounds, but acceptable start for the
9254 * left direction, see BPF_REG_FP. Also, unknown scalar
9255 * offset where we would need to deal with min/max bounds is
9256 * currently prohibited for unprivileged.
9258 max = MAX_BPF_STACK + mask_to_left;
9259 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
9261 case PTR_TO_MAP_VALUE:
9262 max = ptr_reg->map_ptr->value_size;
9263 ptr_limit = (mask_to_left ?
9264 ptr_reg->smin_value :
9265 ptr_reg->umax_value) + ptr_reg->off;
9271 if (ptr_limit >= max)
9272 return REASON_LIMIT;
9273 *alu_limit = ptr_limit;
9277 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
9278 const struct bpf_insn *insn)
9280 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
9283 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
9284 u32 alu_state, u32 alu_limit)
9286 /* If we arrived here from different branches with different
9287 * state or limits to sanitize, then this won't work.
9289 if (aux->alu_state &&
9290 (aux->alu_state != alu_state ||
9291 aux->alu_limit != alu_limit))
9292 return REASON_PATHS;
9294 /* Corresponding fixup done in do_misc_fixups(). */
9295 aux->alu_state = alu_state;
9296 aux->alu_limit = alu_limit;
9300 static int sanitize_val_alu(struct bpf_verifier_env *env,
9301 struct bpf_insn *insn)
9303 struct bpf_insn_aux_data *aux = cur_aux(env);
9305 if (can_skip_alu_sanitation(env, insn))
9308 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
9311 static bool sanitize_needed(u8 opcode)
9313 return opcode == BPF_ADD || opcode == BPF_SUB;
9316 struct bpf_sanitize_info {
9317 struct bpf_insn_aux_data aux;
9321 static struct bpf_verifier_state *
9322 sanitize_speculative_path(struct bpf_verifier_env *env,
9323 const struct bpf_insn *insn,
9324 u32 next_idx, u32 curr_idx)
9326 struct bpf_verifier_state *branch;
9327 struct bpf_reg_state *regs;
9329 branch = push_stack(env, next_idx, curr_idx, true);
9330 if (branch && insn) {
9331 regs = branch->frame[branch->curframe]->regs;
9332 if (BPF_SRC(insn->code) == BPF_K) {
9333 mark_reg_unknown(env, regs, insn->dst_reg);
9334 } else if (BPF_SRC(insn->code) == BPF_X) {
9335 mark_reg_unknown(env, regs, insn->dst_reg);
9336 mark_reg_unknown(env, regs, insn->src_reg);
9342 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
9343 struct bpf_insn *insn,
9344 const struct bpf_reg_state *ptr_reg,
9345 const struct bpf_reg_state *off_reg,
9346 struct bpf_reg_state *dst_reg,
9347 struct bpf_sanitize_info *info,
9348 const bool commit_window)
9350 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
9351 struct bpf_verifier_state *vstate = env->cur_state;
9352 bool off_is_imm = tnum_is_const(off_reg->var_off);
9353 bool off_is_neg = off_reg->smin_value < 0;
9354 bool ptr_is_dst_reg = ptr_reg == dst_reg;
9355 u8 opcode = BPF_OP(insn->code);
9356 u32 alu_state, alu_limit;
9357 struct bpf_reg_state tmp;
9361 if (can_skip_alu_sanitation(env, insn))
9364 /* We already marked aux for masking from non-speculative
9365 * paths, thus we got here in the first place. We only care
9366 * to explore bad access from here.
9368 if (vstate->speculative)
9371 if (!commit_window) {
9372 if (!tnum_is_const(off_reg->var_off) &&
9373 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
9374 return REASON_BOUNDS;
9376 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
9377 (opcode == BPF_SUB && !off_is_neg);
9380 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
9384 if (commit_window) {
9385 /* In commit phase we narrow the masking window based on
9386 * the observed pointer move after the simulated operation.
9388 alu_state = info->aux.alu_state;
9389 alu_limit = abs(info->aux.alu_limit - alu_limit);
9391 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
9392 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
9393 alu_state |= ptr_is_dst_reg ?
9394 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
9396 /* Limit pruning on unknown scalars to enable deep search for
9397 * potential masking differences from other program paths.
9400 env->explore_alu_limits = true;
9403 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
9407 /* If we're in commit phase, we're done here given we already
9408 * pushed the truncated dst_reg into the speculative verification
9411 * Also, when register is a known constant, we rewrite register-based
9412 * operation to immediate-based, and thus do not need masking (and as
9413 * a consequence, do not need to simulate the zero-truncation either).
9415 if (commit_window || off_is_imm)
9418 /* Simulate and find potential out-of-bounds access under
9419 * speculative execution from truncation as a result of
9420 * masking when off was not within expected range. If off
9421 * sits in dst, then we temporarily need to move ptr there
9422 * to simulate dst (== 0) +/-= ptr. Needed, for example,
9423 * for cases where we use K-based arithmetic in one direction
9424 * and truncated reg-based in the other in order to explore
9427 if (!ptr_is_dst_reg) {
9429 *dst_reg = *ptr_reg;
9431 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
9433 if (!ptr_is_dst_reg && ret)
9435 return !ret ? REASON_STACK : 0;
9438 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
9440 struct bpf_verifier_state *vstate = env->cur_state;
9442 /* If we simulate paths under speculation, we don't update the
9443 * insn as 'seen' such that when we verify unreachable paths in
9444 * the non-speculative domain, sanitize_dead_code() can still
9445 * rewrite/sanitize them.
9447 if (!vstate->speculative)
9448 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9451 static int sanitize_err(struct bpf_verifier_env *env,
9452 const struct bpf_insn *insn, int reason,
9453 const struct bpf_reg_state *off_reg,
9454 const struct bpf_reg_state *dst_reg)
9456 static const char *err = "pointer arithmetic with it prohibited for !root";
9457 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
9458 u32 dst = insn->dst_reg, src = insn->src_reg;
9462 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
9463 off_reg == dst_reg ? dst : src, err);
9466 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
9467 off_reg == dst_reg ? src : dst, err);
9470 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
9474 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
9478 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
9482 verbose(env, "verifier internal error: unknown reason (%d)\n",
9490 /* check that stack access falls within stack limits and that 'reg' doesn't
9491 * have a variable offset.
9493 * Variable offset is prohibited for unprivileged mode for simplicity since it
9494 * requires corresponding support in Spectre masking for stack ALU. See also
9495 * retrieve_ptr_limit().
9498 * 'off' includes 'reg->off'.
9500 static int check_stack_access_for_ptr_arithmetic(
9501 struct bpf_verifier_env *env,
9503 const struct bpf_reg_state *reg,
9506 if (!tnum_is_const(reg->var_off)) {
9509 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
9510 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
9511 regno, tn_buf, off);
9515 if (off >= 0 || off < -MAX_BPF_STACK) {
9516 verbose(env, "R%d stack pointer arithmetic goes out of range, "
9517 "prohibited for !root; off=%d\n", regno, off);
9524 static int sanitize_check_bounds(struct bpf_verifier_env *env,
9525 const struct bpf_insn *insn,
9526 const struct bpf_reg_state *dst_reg)
9528 u32 dst = insn->dst_reg;
9530 /* For unprivileged we require that resulting offset must be in bounds
9531 * in order to be able to sanitize access later on.
9533 if (env->bypass_spec_v1)
9536 switch (dst_reg->type) {
9538 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
9539 dst_reg->off + dst_reg->var_off.value))
9542 case PTR_TO_MAP_VALUE:
9543 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
9544 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
9545 "prohibited for !root\n", dst);
9556 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
9557 * Caller should also handle BPF_MOV case separately.
9558 * If we return -EACCES, caller may want to try again treating pointer as a
9559 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
9561 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
9562 struct bpf_insn *insn,
9563 const struct bpf_reg_state *ptr_reg,
9564 const struct bpf_reg_state *off_reg)
9566 struct bpf_verifier_state *vstate = env->cur_state;
9567 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9568 struct bpf_reg_state *regs = state->regs, *dst_reg;
9569 bool known = tnum_is_const(off_reg->var_off);
9570 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
9571 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
9572 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
9573 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9574 struct bpf_sanitize_info info = {};
9575 u8 opcode = BPF_OP(insn->code);
9576 u32 dst = insn->dst_reg;
9579 dst_reg = ®s[dst];
9581 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
9582 smin_val > smax_val || umin_val > umax_val) {
9583 /* Taint dst register if offset had invalid bounds derived from
9584 * e.g. dead branches.
9586 __mark_reg_unknown(env, dst_reg);
9590 if (BPF_CLASS(insn->code) != BPF_ALU64) {
9591 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
9592 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9593 __mark_reg_unknown(env, dst_reg);
9598 "R%d 32-bit pointer arithmetic prohibited\n",
9603 if (ptr_reg->type & PTR_MAYBE_NULL) {
9604 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
9605 dst, reg_type_str(env, ptr_reg->type));
9609 switch (base_type(ptr_reg->type)) {
9610 case CONST_PTR_TO_MAP:
9611 /* smin_val represents the known value */
9612 if (known && smin_val == 0 && opcode == BPF_ADD)
9615 case PTR_TO_PACKET_END:
9617 case PTR_TO_SOCK_COMMON:
9618 case PTR_TO_TCP_SOCK:
9619 case PTR_TO_XDP_SOCK:
9620 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
9621 dst, reg_type_str(env, ptr_reg->type));
9627 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
9628 * The id may be overwritten later if we create a new variable offset.
9630 dst_reg->type = ptr_reg->type;
9631 dst_reg->id = ptr_reg->id;
9633 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
9634 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
9637 /* pointer types do not carry 32-bit bounds at the moment. */
9638 __mark_reg32_unbounded(dst_reg);
9640 if (sanitize_needed(opcode)) {
9641 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
9644 return sanitize_err(env, insn, ret, off_reg, dst_reg);
9649 /* We can take a fixed offset as long as it doesn't overflow
9650 * the s32 'off' field
9652 if (known && (ptr_reg->off + smin_val ==
9653 (s64)(s32)(ptr_reg->off + smin_val))) {
9654 /* pointer += K. Accumulate it into fixed offset */
9655 dst_reg->smin_value = smin_ptr;
9656 dst_reg->smax_value = smax_ptr;
9657 dst_reg->umin_value = umin_ptr;
9658 dst_reg->umax_value = umax_ptr;
9659 dst_reg->var_off = ptr_reg->var_off;
9660 dst_reg->off = ptr_reg->off + smin_val;
9661 dst_reg->raw = ptr_reg->raw;
9664 /* A new variable offset is created. Note that off_reg->off
9665 * == 0, since it's a scalar.
9666 * dst_reg gets the pointer type and since some positive
9667 * integer value was added to the pointer, give it a new 'id'
9668 * if it's a PTR_TO_PACKET.
9669 * this creates a new 'base' pointer, off_reg (variable) gets
9670 * added into the variable offset, and we copy the fixed offset
9673 if (signed_add_overflows(smin_ptr, smin_val) ||
9674 signed_add_overflows(smax_ptr, smax_val)) {
9675 dst_reg->smin_value = S64_MIN;
9676 dst_reg->smax_value = S64_MAX;
9678 dst_reg->smin_value = smin_ptr + smin_val;
9679 dst_reg->smax_value = smax_ptr + smax_val;
9681 if (umin_ptr + umin_val < umin_ptr ||
9682 umax_ptr + umax_val < umax_ptr) {
9683 dst_reg->umin_value = 0;
9684 dst_reg->umax_value = U64_MAX;
9686 dst_reg->umin_value = umin_ptr + umin_val;
9687 dst_reg->umax_value = umax_ptr + umax_val;
9689 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
9690 dst_reg->off = ptr_reg->off;
9691 dst_reg->raw = ptr_reg->raw;
9692 if (reg_is_pkt_pointer(ptr_reg)) {
9693 dst_reg->id = ++env->id_gen;
9694 /* something was added to pkt_ptr, set range to zero */
9695 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9699 if (dst_reg == off_reg) {
9700 /* scalar -= pointer. Creates an unknown scalar */
9701 verbose(env, "R%d tried to subtract pointer from scalar\n",
9705 /* We don't allow subtraction from FP, because (according to
9706 * test_verifier.c test "invalid fp arithmetic", JITs might not
9707 * be able to deal with it.
9709 if (ptr_reg->type == PTR_TO_STACK) {
9710 verbose(env, "R%d subtraction from stack pointer prohibited\n",
9714 if (known && (ptr_reg->off - smin_val ==
9715 (s64)(s32)(ptr_reg->off - smin_val))) {
9716 /* pointer -= K. Subtract it from fixed offset */
9717 dst_reg->smin_value = smin_ptr;
9718 dst_reg->smax_value = smax_ptr;
9719 dst_reg->umin_value = umin_ptr;
9720 dst_reg->umax_value = umax_ptr;
9721 dst_reg->var_off = ptr_reg->var_off;
9722 dst_reg->id = ptr_reg->id;
9723 dst_reg->off = ptr_reg->off - smin_val;
9724 dst_reg->raw = ptr_reg->raw;
9727 /* A new variable offset is created. If the subtrahend is known
9728 * nonnegative, then any reg->range we had before is still good.
9730 if (signed_sub_overflows(smin_ptr, smax_val) ||
9731 signed_sub_overflows(smax_ptr, smin_val)) {
9732 /* Overflow possible, we know nothing */
9733 dst_reg->smin_value = S64_MIN;
9734 dst_reg->smax_value = S64_MAX;
9736 dst_reg->smin_value = smin_ptr - smax_val;
9737 dst_reg->smax_value = smax_ptr - smin_val;
9739 if (umin_ptr < umax_val) {
9740 /* Overflow possible, we know nothing */
9741 dst_reg->umin_value = 0;
9742 dst_reg->umax_value = U64_MAX;
9744 /* Cannot overflow (as long as bounds are consistent) */
9745 dst_reg->umin_value = umin_ptr - umax_val;
9746 dst_reg->umax_value = umax_ptr - umin_val;
9748 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
9749 dst_reg->off = ptr_reg->off;
9750 dst_reg->raw = ptr_reg->raw;
9751 if (reg_is_pkt_pointer(ptr_reg)) {
9752 dst_reg->id = ++env->id_gen;
9753 /* something was added to pkt_ptr, set range to zero */
9755 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9761 /* bitwise ops on pointers are troublesome, prohibit. */
9762 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
9763 dst, bpf_alu_string[opcode >> 4]);
9766 /* other operators (e.g. MUL,LSH) produce non-pointer results */
9767 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
9768 dst, bpf_alu_string[opcode >> 4]);
9772 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
9774 reg_bounds_sync(dst_reg);
9775 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
9777 if (sanitize_needed(opcode)) {
9778 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
9781 return sanitize_err(env, insn, ret, off_reg, dst_reg);
9787 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
9788 struct bpf_reg_state *src_reg)
9790 s32 smin_val = src_reg->s32_min_value;
9791 s32 smax_val = src_reg->s32_max_value;
9792 u32 umin_val = src_reg->u32_min_value;
9793 u32 umax_val = src_reg->u32_max_value;
9795 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
9796 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
9797 dst_reg->s32_min_value = S32_MIN;
9798 dst_reg->s32_max_value = S32_MAX;
9800 dst_reg->s32_min_value += smin_val;
9801 dst_reg->s32_max_value += smax_val;
9803 if (dst_reg->u32_min_value + umin_val < umin_val ||
9804 dst_reg->u32_max_value + umax_val < umax_val) {
9805 dst_reg->u32_min_value = 0;
9806 dst_reg->u32_max_value = U32_MAX;
9808 dst_reg->u32_min_value += umin_val;
9809 dst_reg->u32_max_value += umax_val;
9813 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
9814 struct bpf_reg_state *src_reg)
9816 s64 smin_val = src_reg->smin_value;
9817 s64 smax_val = src_reg->smax_value;
9818 u64 umin_val = src_reg->umin_value;
9819 u64 umax_val = src_reg->umax_value;
9821 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
9822 signed_add_overflows(dst_reg->smax_value, smax_val)) {
9823 dst_reg->smin_value = S64_MIN;
9824 dst_reg->smax_value = S64_MAX;
9826 dst_reg->smin_value += smin_val;
9827 dst_reg->smax_value += smax_val;
9829 if (dst_reg->umin_value + umin_val < umin_val ||
9830 dst_reg->umax_value + umax_val < umax_val) {
9831 dst_reg->umin_value = 0;
9832 dst_reg->umax_value = U64_MAX;
9834 dst_reg->umin_value += umin_val;
9835 dst_reg->umax_value += umax_val;
9839 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
9840 struct bpf_reg_state *src_reg)
9842 s32 smin_val = src_reg->s32_min_value;
9843 s32 smax_val = src_reg->s32_max_value;
9844 u32 umin_val = src_reg->u32_min_value;
9845 u32 umax_val = src_reg->u32_max_value;
9847 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
9848 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
9849 /* Overflow possible, we know nothing */
9850 dst_reg->s32_min_value = S32_MIN;
9851 dst_reg->s32_max_value = S32_MAX;
9853 dst_reg->s32_min_value -= smax_val;
9854 dst_reg->s32_max_value -= smin_val;
9856 if (dst_reg->u32_min_value < umax_val) {
9857 /* Overflow possible, we know nothing */
9858 dst_reg->u32_min_value = 0;
9859 dst_reg->u32_max_value = U32_MAX;
9861 /* Cannot overflow (as long as bounds are consistent) */
9862 dst_reg->u32_min_value -= umax_val;
9863 dst_reg->u32_max_value -= umin_val;
9867 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
9868 struct bpf_reg_state *src_reg)
9870 s64 smin_val = src_reg->smin_value;
9871 s64 smax_val = src_reg->smax_value;
9872 u64 umin_val = src_reg->umin_value;
9873 u64 umax_val = src_reg->umax_value;
9875 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
9876 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
9877 /* Overflow possible, we know nothing */
9878 dst_reg->smin_value = S64_MIN;
9879 dst_reg->smax_value = S64_MAX;
9881 dst_reg->smin_value -= smax_val;
9882 dst_reg->smax_value -= smin_val;
9884 if (dst_reg->umin_value < umax_val) {
9885 /* Overflow possible, we know nothing */
9886 dst_reg->umin_value = 0;
9887 dst_reg->umax_value = U64_MAX;
9889 /* Cannot overflow (as long as bounds are consistent) */
9890 dst_reg->umin_value -= umax_val;
9891 dst_reg->umax_value -= umin_val;
9895 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
9896 struct bpf_reg_state *src_reg)
9898 s32 smin_val = src_reg->s32_min_value;
9899 u32 umin_val = src_reg->u32_min_value;
9900 u32 umax_val = src_reg->u32_max_value;
9902 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
9903 /* Ain't nobody got time to multiply that sign */
9904 __mark_reg32_unbounded(dst_reg);
9907 /* Both values are positive, so we can work with unsigned and
9908 * copy the result to signed (unless it exceeds S32_MAX).
9910 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
9911 /* Potential overflow, we know nothing */
9912 __mark_reg32_unbounded(dst_reg);
9915 dst_reg->u32_min_value *= umin_val;
9916 dst_reg->u32_max_value *= umax_val;
9917 if (dst_reg->u32_max_value > S32_MAX) {
9918 /* Overflow possible, we know nothing */
9919 dst_reg->s32_min_value = S32_MIN;
9920 dst_reg->s32_max_value = S32_MAX;
9922 dst_reg->s32_min_value = dst_reg->u32_min_value;
9923 dst_reg->s32_max_value = dst_reg->u32_max_value;
9927 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
9928 struct bpf_reg_state *src_reg)
9930 s64 smin_val = src_reg->smin_value;
9931 u64 umin_val = src_reg->umin_value;
9932 u64 umax_val = src_reg->umax_value;
9934 if (smin_val < 0 || dst_reg->smin_value < 0) {
9935 /* Ain't nobody got time to multiply that sign */
9936 __mark_reg64_unbounded(dst_reg);
9939 /* Both values are positive, so we can work with unsigned and
9940 * copy the result to signed (unless it exceeds S64_MAX).
9942 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
9943 /* Potential overflow, we know nothing */
9944 __mark_reg64_unbounded(dst_reg);
9947 dst_reg->umin_value *= umin_val;
9948 dst_reg->umax_value *= umax_val;
9949 if (dst_reg->umax_value > S64_MAX) {
9950 /* Overflow possible, we know nothing */
9951 dst_reg->smin_value = S64_MIN;
9952 dst_reg->smax_value = S64_MAX;
9954 dst_reg->smin_value = dst_reg->umin_value;
9955 dst_reg->smax_value = dst_reg->umax_value;
9959 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
9960 struct bpf_reg_state *src_reg)
9962 bool src_known = tnum_subreg_is_const(src_reg->var_off);
9963 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9964 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
9965 s32 smin_val = src_reg->s32_min_value;
9966 u32 umax_val = src_reg->u32_max_value;
9968 if (src_known && dst_known) {
9969 __mark_reg32_known(dst_reg, var32_off.value);
9973 /* We get our minimum from the var_off, since that's inherently
9974 * bitwise. Our maximum is the minimum of the operands' maxima.
9976 dst_reg->u32_min_value = var32_off.value;
9977 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
9978 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
9979 /* Lose signed bounds when ANDing negative numbers,
9980 * ain't nobody got time for that.
9982 dst_reg->s32_min_value = S32_MIN;
9983 dst_reg->s32_max_value = S32_MAX;
9985 /* ANDing two positives gives a positive, so safe to
9986 * cast result into s64.
9988 dst_reg->s32_min_value = dst_reg->u32_min_value;
9989 dst_reg->s32_max_value = dst_reg->u32_max_value;
9993 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
9994 struct bpf_reg_state *src_reg)
9996 bool src_known = tnum_is_const(src_reg->var_off);
9997 bool dst_known = tnum_is_const(dst_reg->var_off);
9998 s64 smin_val = src_reg->smin_value;
9999 u64 umax_val = src_reg->umax_value;
10001 if (src_known && dst_known) {
10002 __mark_reg_known(dst_reg, dst_reg->var_off.value);
10006 /* We get our minimum from the var_off, since that's inherently
10007 * bitwise. Our maximum is the minimum of the operands' maxima.
10009 dst_reg->umin_value = dst_reg->var_off.value;
10010 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
10011 if (dst_reg->smin_value < 0 || smin_val < 0) {
10012 /* Lose signed bounds when ANDing negative numbers,
10013 * ain't nobody got time for that.
10015 dst_reg->smin_value = S64_MIN;
10016 dst_reg->smax_value = S64_MAX;
10018 /* ANDing two positives gives a positive, so safe to
10019 * cast result into s64.
10021 dst_reg->smin_value = dst_reg->umin_value;
10022 dst_reg->smax_value = dst_reg->umax_value;
10024 /* We may learn something more from the var_off */
10025 __update_reg_bounds(dst_reg);
10028 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
10029 struct bpf_reg_state *src_reg)
10031 bool src_known = tnum_subreg_is_const(src_reg->var_off);
10032 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10033 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10034 s32 smin_val = src_reg->s32_min_value;
10035 u32 umin_val = src_reg->u32_min_value;
10037 if (src_known && dst_known) {
10038 __mark_reg32_known(dst_reg, var32_off.value);
10042 /* We get our maximum from the var_off, and our minimum is the
10043 * maximum of the operands' minima
10045 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
10046 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10047 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10048 /* Lose signed bounds when ORing negative numbers,
10049 * ain't nobody got time for that.
10051 dst_reg->s32_min_value = S32_MIN;
10052 dst_reg->s32_max_value = S32_MAX;
10054 /* ORing two positives gives a positive, so safe to
10055 * cast result into s64.
10057 dst_reg->s32_min_value = dst_reg->u32_min_value;
10058 dst_reg->s32_max_value = dst_reg->u32_max_value;
10062 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
10063 struct bpf_reg_state *src_reg)
10065 bool src_known = tnum_is_const(src_reg->var_off);
10066 bool dst_known = tnum_is_const(dst_reg->var_off);
10067 s64 smin_val = src_reg->smin_value;
10068 u64 umin_val = src_reg->umin_value;
10070 if (src_known && dst_known) {
10071 __mark_reg_known(dst_reg, dst_reg->var_off.value);
10075 /* We get our maximum from the var_off, and our minimum is the
10076 * maximum of the operands' minima
10078 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
10079 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10080 if (dst_reg->smin_value < 0 || smin_val < 0) {
10081 /* Lose signed bounds when ORing negative numbers,
10082 * ain't nobody got time for that.
10084 dst_reg->smin_value = S64_MIN;
10085 dst_reg->smax_value = S64_MAX;
10087 /* ORing two positives gives a positive, so safe to
10088 * cast result into s64.
10090 dst_reg->smin_value = dst_reg->umin_value;
10091 dst_reg->smax_value = dst_reg->umax_value;
10093 /* We may learn something more from the var_off */
10094 __update_reg_bounds(dst_reg);
10097 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
10098 struct bpf_reg_state *src_reg)
10100 bool src_known = tnum_subreg_is_const(src_reg->var_off);
10101 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10102 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10103 s32 smin_val = src_reg->s32_min_value;
10105 if (src_known && dst_known) {
10106 __mark_reg32_known(dst_reg, var32_off.value);
10110 /* We get both minimum and maximum from the var32_off. */
10111 dst_reg->u32_min_value = var32_off.value;
10112 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10114 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
10115 /* XORing two positive sign numbers gives a positive,
10116 * so safe to cast u32 result into s32.
10118 dst_reg->s32_min_value = dst_reg->u32_min_value;
10119 dst_reg->s32_max_value = dst_reg->u32_max_value;
10121 dst_reg->s32_min_value = S32_MIN;
10122 dst_reg->s32_max_value = S32_MAX;
10126 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
10127 struct bpf_reg_state *src_reg)
10129 bool src_known = tnum_is_const(src_reg->var_off);
10130 bool dst_known = tnum_is_const(dst_reg->var_off);
10131 s64 smin_val = src_reg->smin_value;
10133 if (src_known && dst_known) {
10134 /* dst_reg->var_off.value has been updated earlier */
10135 __mark_reg_known(dst_reg, dst_reg->var_off.value);
10139 /* We get both minimum and maximum from the var_off. */
10140 dst_reg->umin_value = dst_reg->var_off.value;
10141 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10143 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
10144 /* XORing two positive sign numbers gives a positive,
10145 * so safe to cast u64 result into s64.
10147 dst_reg->smin_value = dst_reg->umin_value;
10148 dst_reg->smax_value = dst_reg->umax_value;
10150 dst_reg->smin_value = S64_MIN;
10151 dst_reg->smax_value = S64_MAX;
10154 __update_reg_bounds(dst_reg);
10157 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10158 u64 umin_val, u64 umax_val)
10160 /* We lose all sign bit information (except what we can pick
10163 dst_reg->s32_min_value = S32_MIN;
10164 dst_reg->s32_max_value = S32_MAX;
10165 /* If we might shift our top bit out, then we know nothing */
10166 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
10167 dst_reg->u32_min_value = 0;
10168 dst_reg->u32_max_value = U32_MAX;
10170 dst_reg->u32_min_value <<= umin_val;
10171 dst_reg->u32_max_value <<= umax_val;
10175 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10176 struct bpf_reg_state *src_reg)
10178 u32 umax_val = src_reg->u32_max_value;
10179 u32 umin_val = src_reg->u32_min_value;
10180 /* u32 alu operation will zext upper bits */
10181 struct tnum subreg = tnum_subreg(dst_reg->var_off);
10183 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10184 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
10185 /* Not required but being careful mark reg64 bounds as unknown so
10186 * that we are forced to pick them up from tnum and zext later and
10187 * if some path skips this step we are still safe.
10189 __mark_reg64_unbounded(dst_reg);
10190 __update_reg32_bounds(dst_reg);
10193 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
10194 u64 umin_val, u64 umax_val)
10196 /* Special case <<32 because it is a common compiler pattern to sign
10197 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
10198 * positive we know this shift will also be positive so we can track
10199 * bounds correctly. Otherwise we lose all sign bit information except
10200 * what we can pick up from var_off. Perhaps we can generalize this
10201 * later to shifts of any length.
10203 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
10204 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
10206 dst_reg->smax_value = S64_MAX;
10208 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
10209 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
10211 dst_reg->smin_value = S64_MIN;
10213 /* If we might shift our top bit out, then we know nothing */
10214 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
10215 dst_reg->umin_value = 0;
10216 dst_reg->umax_value = U64_MAX;
10218 dst_reg->umin_value <<= umin_val;
10219 dst_reg->umax_value <<= umax_val;
10223 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
10224 struct bpf_reg_state *src_reg)
10226 u64 umax_val = src_reg->umax_value;
10227 u64 umin_val = src_reg->umin_value;
10229 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
10230 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
10231 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10233 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
10234 /* We may learn something more from the var_off */
10235 __update_reg_bounds(dst_reg);
10238 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
10239 struct bpf_reg_state *src_reg)
10241 struct tnum subreg = tnum_subreg(dst_reg->var_off);
10242 u32 umax_val = src_reg->u32_max_value;
10243 u32 umin_val = src_reg->u32_min_value;
10245 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
10246 * be negative, then either:
10247 * 1) src_reg might be zero, so the sign bit of the result is
10248 * unknown, so we lose our signed bounds
10249 * 2) it's known negative, thus the unsigned bounds capture the
10251 * 3) the signed bounds cross zero, so they tell us nothing
10253 * If the value in dst_reg is known nonnegative, then again the
10254 * unsigned bounds capture the signed bounds.
10255 * Thus, in all cases it suffices to blow away our signed bounds
10256 * and rely on inferring new ones from the unsigned bounds and
10257 * var_off of the result.
10259 dst_reg->s32_min_value = S32_MIN;
10260 dst_reg->s32_max_value = S32_MAX;
10262 dst_reg->var_off = tnum_rshift(subreg, umin_val);
10263 dst_reg->u32_min_value >>= umax_val;
10264 dst_reg->u32_max_value >>= umin_val;
10266 __mark_reg64_unbounded(dst_reg);
10267 __update_reg32_bounds(dst_reg);
10270 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
10271 struct bpf_reg_state *src_reg)
10273 u64 umax_val = src_reg->umax_value;
10274 u64 umin_val = src_reg->umin_value;
10276 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
10277 * be negative, then either:
10278 * 1) src_reg might be zero, so the sign bit of the result is
10279 * unknown, so we lose our signed bounds
10280 * 2) it's known negative, thus the unsigned bounds capture the
10282 * 3) the signed bounds cross zero, so they tell us nothing
10284 * If the value in dst_reg is known nonnegative, then again the
10285 * unsigned bounds capture the signed bounds.
10286 * Thus, in all cases it suffices to blow away our signed bounds
10287 * and rely on inferring new ones from the unsigned bounds and
10288 * var_off of the result.
10290 dst_reg->smin_value = S64_MIN;
10291 dst_reg->smax_value = S64_MAX;
10292 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
10293 dst_reg->umin_value >>= umax_val;
10294 dst_reg->umax_value >>= umin_val;
10296 /* Its not easy to operate on alu32 bounds here because it depends
10297 * on bits being shifted in. Take easy way out and mark unbounded
10298 * so we can recalculate later from tnum.
10300 __mark_reg32_unbounded(dst_reg);
10301 __update_reg_bounds(dst_reg);
10304 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
10305 struct bpf_reg_state *src_reg)
10307 u64 umin_val = src_reg->u32_min_value;
10309 /* Upon reaching here, src_known is true and
10310 * umax_val is equal to umin_val.
10312 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
10313 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
10315 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
10317 /* blow away the dst_reg umin_value/umax_value and rely on
10318 * dst_reg var_off to refine the result.
10320 dst_reg->u32_min_value = 0;
10321 dst_reg->u32_max_value = U32_MAX;
10323 __mark_reg64_unbounded(dst_reg);
10324 __update_reg32_bounds(dst_reg);
10327 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
10328 struct bpf_reg_state *src_reg)
10330 u64 umin_val = src_reg->umin_value;
10332 /* Upon reaching here, src_known is true and umax_val is equal
10335 dst_reg->smin_value >>= umin_val;
10336 dst_reg->smax_value >>= umin_val;
10338 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
10340 /* blow away the dst_reg umin_value/umax_value and rely on
10341 * dst_reg var_off to refine the result.
10343 dst_reg->umin_value = 0;
10344 dst_reg->umax_value = U64_MAX;
10346 /* Its not easy to operate on alu32 bounds here because it depends
10347 * on bits being shifted in from upper 32-bits. Take easy way out
10348 * and mark unbounded so we can recalculate later from tnum.
10350 __mark_reg32_unbounded(dst_reg);
10351 __update_reg_bounds(dst_reg);
10354 /* WARNING: This function does calculations on 64-bit values, but the actual
10355 * execution may occur on 32-bit values. Therefore, things like bitshifts
10356 * need extra checks in the 32-bit case.
10358 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
10359 struct bpf_insn *insn,
10360 struct bpf_reg_state *dst_reg,
10361 struct bpf_reg_state src_reg)
10363 struct bpf_reg_state *regs = cur_regs(env);
10364 u8 opcode = BPF_OP(insn->code);
10366 s64 smin_val, smax_val;
10367 u64 umin_val, umax_val;
10368 s32 s32_min_val, s32_max_val;
10369 u32 u32_min_val, u32_max_val;
10370 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
10371 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
10374 smin_val = src_reg.smin_value;
10375 smax_val = src_reg.smax_value;
10376 umin_val = src_reg.umin_value;
10377 umax_val = src_reg.umax_value;
10379 s32_min_val = src_reg.s32_min_value;
10380 s32_max_val = src_reg.s32_max_value;
10381 u32_min_val = src_reg.u32_min_value;
10382 u32_max_val = src_reg.u32_max_value;
10385 src_known = tnum_subreg_is_const(src_reg.var_off);
10387 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
10388 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
10389 /* Taint dst register if offset had invalid bounds
10390 * derived from e.g. dead branches.
10392 __mark_reg_unknown(env, dst_reg);
10396 src_known = tnum_is_const(src_reg.var_off);
10398 (smin_val != smax_val || umin_val != umax_val)) ||
10399 smin_val > smax_val || umin_val > umax_val) {
10400 /* Taint dst register if offset had invalid bounds
10401 * derived from e.g. dead branches.
10403 __mark_reg_unknown(env, dst_reg);
10409 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
10410 __mark_reg_unknown(env, dst_reg);
10414 if (sanitize_needed(opcode)) {
10415 ret = sanitize_val_alu(env, insn);
10417 return sanitize_err(env, insn, ret, NULL, NULL);
10420 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
10421 * There are two classes of instructions: The first class we track both
10422 * alu32 and alu64 sign/unsigned bounds independently this provides the
10423 * greatest amount of precision when alu operations are mixed with jmp32
10424 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
10425 * and BPF_OR. This is possible because these ops have fairly easy to
10426 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
10427 * See alu32 verifier tests for examples. The second class of
10428 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
10429 * with regards to tracking sign/unsigned bounds because the bits may
10430 * cross subreg boundaries in the alu64 case. When this happens we mark
10431 * the reg unbounded in the subreg bound space and use the resulting
10432 * tnum to calculate an approximation of the sign/unsigned bounds.
10436 scalar32_min_max_add(dst_reg, &src_reg);
10437 scalar_min_max_add(dst_reg, &src_reg);
10438 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
10441 scalar32_min_max_sub(dst_reg, &src_reg);
10442 scalar_min_max_sub(dst_reg, &src_reg);
10443 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
10446 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
10447 scalar32_min_max_mul(dst_reg, &src_reg);
10448 scalar_min_max_mul(dst_reg, &src_reg);
10451 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
10452 scalar32_min_max_and(dst_reg, &src_reg);
10453 scalar_min_max_and(dst_reg, &src_reg);
10456 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
10457 scalar32_min_max_or(dst_reg, &src_reg);
10458 scalar_min_max_or(dst_reg, &src_reg);
10461 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
10462 scalar32_min_max_xor(dst_reg, &src_reg);
10463 scalar_min_max_xor(dst_reg, &src_reg);
10466 if (umax_val >= insn_bitness) {
10467 /* Shifts greater than 31 or 63 are undefined.
10468 * This includes shifts by a negative number.
10470 mark_reg_unknown(env, regs, insn->dst_reg);
10474 scalar32_min_max_lsh(dst_reg, &src_reg);
10476 scalar_min_max_lsh(dst_reg, &src_reg);
10479 if (umax_val >= insn_bitness) {
10480 /* Shifts greater than 31 or 63 are undefined.
10481 * This includes shifts by a negative number.
10483 mark_reg_unknown(env, regs, insn->dst_reg);
10487 scalar32_min_max_rsh(dst_reg, &src_reg);
10489 scalar_min_max_rsh(dst_reg, &src_reg);
10492 if (umax_val >= insn_bitness) {
10493 /* Shifts greater than 31 or 63 are undefined.
10494 * This includes shifts by a negative number.
10496 mark_reg_unknown(env, regs, insn->dst_reg);
10500 scalar32_min_max_arsh(dst_reg, &src_reg);
10502 scalar_min_max_arsh(dst_reg, &src_reg);
10505 mark_reg_unknown(env, regs, insn->dst_reg);
10509 /* ALU32 ops are zero extended into 64bit register */
10511 zext_32_to_64(dst_reg);
10512 reg_bounds_sync(dst_reg);
10516 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
10519 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
10520 struct bpf_insn *insn)
10522 struct bpf_verifier_state *vstate = env->cur_state;
10523 struct bpf_func_state *state = vstate->frame[vstate->curframe];
10524 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
10525 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
10526 u8 opcode = BPF_OP(insn->code);
10529 dst_reg = ®s[insn->dst_reg];
10531 if (dst_reg->type != SCALAR_VALUE)
10534 /* Make sure ID is cleared otherwise dst_reg min/max could be
10535 * incorrectly propagated into other registers by find_equal_scalars()
10538 if (BPF_SRC(insn->code) == BPF_X) {
10539 src_reg = ®s[insn->src_reg];
10540 if (src_reg->type != SCALAR_VALUE) {
10541 if (dst_reg->type != SCALAR_VALUE) {
10542 /* Combining two pointers by any ALU op yields
10543 * an arbitrary scalar. Disallow all math except
10544 * pointer subtraction
10546 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10547 mark_reg_unknown(env, regs, insn->dst_reg);
10550 verbose(env, "R%d pointer %s pointer prohibited\n",
10552 bpf_alu_string[opcode >> 4]);
10555 /* scalar += pointer
10556 * This is legal, but we have to reverse our
10557 * src/dest handling in computing the range
10559 err = mark_chain_precision(env, insn->dst_reg);
10562 return adjust_ptr_min_max_vals(env, insn,
10565 } else if (ptr_reg) {
10566 /* pointer += scalar */
10567 err = mark_chain_precision(env, insn->src_reg);
10570 return adjust_ptr_min_max_vals(env, insn,
10572 } else if (dst_reg->precise) {
10573 /* if dst_reg is precise, src_reg should be precise as well */
10574 err = mark_chain_precision(env, insn->src_reg);
10579 /* Pretend the src is a reg with a known value, since we only
10580 * need to be able to read from this state.
10582 off_reg.type = SCALAR_VALUE;
10583 __mark_reg_known(&off_reg, insn->imm);
10584 src_reg = &off_reg;
10585 if (ptr_reg) /* pointer += K */
10586 return adjust_ptr_min_max_vals(env, insn,
10590 /* Got here implies adding two SCALAR_VALUEs */
10591 if (WARN_ON_ONCE(ptr_reg)) {
10592 print_verifier_state(env, state, true);
10593 verbose(env, "verifier internal error: unexpected ptr_reg\n");
10596 if (WARN_ON(!src_reg)) {
10597 print_verifier_state(env, state, true);
10598 verbose(env, "verifier internal error: no src_reg\n");
10601 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
10604 /* check validity of 32-bit and 64-bit arithmetic operations */
10605 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
10607 struct bpf_reg_state *regs = cur_regs(env);
10608 u8 opcode = BPF_OP(insn->code);
10611 if (opcode == BPF_END || opcode == BPF_NEG) {
10612 if (opcode == BPF_NEG) {
10613 if (BPF_SRC(insn->code) != BPF_K ||
10614 insn->src_reg != BPF_REG_0 ||
10615 insn->off != 0 || insn->imm != 0) {
10616 verbose(env, "BPF_NEG uses reserved fields\n");
10620 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
10621 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
10622 BPF_CLASS(insn->code) == BPF_ALU64) {
10623 verbose(env, "BPF_END uses reserved fields\n");
10628 /* check src operand */
10629 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10633 if (is_pointer_value(env, insn->dst_reg)) {
10634 verbose(env, "R%d pointer arithmetic prohibited\n",
10639 /* check dest operand */
10640 err = check_reg_arg(env, insn->dst_reg, DST_OP);
10644 } else if (opcode == BPF_MOV) {
10646 if (BPF_SRC(insn->code) == BPF_X) {
10647 if (insn->imm != 0 || insn->off != 0) {
10648 verbose(env, "BPF_MOV uses reserved fields\n");
10652 /* check src operand */
10653 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10657 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10658 verbose(env, "BPF_MOV uses reserved fields\n");
10663 /* check dest operand, mark as required later */
10664 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10668 if (BPF_SRC(insn->code) == BPF_X) {
10669 struct bpf_reg_state *src_reg = regs + insn->src_reg;
10670 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
10672 if (BPF_CLASS(insn->code) == BPF_ALU64) {
10674 * copy register state to dest reg
10676 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
10677 /* Assign src and dst registers the same ID
10678 * that will be used by find_equal_scalars()
10679 * to propagate min/max range.
10681 src_reg->id = ++env->id_gen;
10682 *dst_reg = *src_reg;
10683 dst_reg->live |= REG_LIVE_WRITTEN;
10684 dst_reg->subreg_def = DEF_NOT_SUBREG;
10686 /* R1 = (u32) R2 */
10687 if (is_pointer_value(env, insn->src_reg)) {
10689 "R%d partial copy of pointer\n",
10692 } else if (src_reg->type == SCALAR_VALUE) {
10693 *dst_reg = *src_reg;
10694 /* Make sure ID is cleared otherwise
10695 * dst_reg min/max could be incorrectly
10696 * propagated into src_reg by find_equal_scalars()
10699 dst_reg->live |= REG_LIVE_WRITTEN;
10700 dst_reg->subreg_def = env->insn_idx + 1;
10702 mark_reg_unknown(env, regs,
10705 zext_32_to_64(dst_reg);
10706 reg_bounds_sync(dst_reg);
10710 * remember the value we stored into this reg
10712 /* clear any state __mark_reg_known doesn't set */
10713 mark_reg_unknown(env, regs, insn->dst_reg);
10714 regs[insn->dst_reg].type = SCALAR_VALUE;
10715 if (BPF_CLASS(insn->code) == BPF_ALU64) {
10716 __mark_reg_known(regs + insn->dst_reg,
10719 __mark_reg_known(regs + insn->dst_reg,
10724 } else if (opcode > BPF_END) {
10725 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
10728 } else { /* all other ALU ops: and, sub, xor, add, ... */
10730 if (BPF_SRC(insn->code) == BPF_X) {
10731 if (insn->imm != 0 || insn->off != 0) {
10732 verbose(env, "BPF_ALU uses reserved fields\n");
10735 /* check src1 operand */
10736 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10740 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10741 verbose(env, "BPF_ALU uses reserved fields\n");
10746 /* check src2 operand */
10747 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10751 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
10752 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
10753 verbose(env, "div by zero\n");
10757 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
10758 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
10759 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
10761 if (insn->imm < 0 || insn->imm >= size) {
10762 verbose(env, "invalid shift %d\n", insn->imm);
10767 /* check dest operand */
10768 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10772 return adjust_reg_min_max_vals(env, insn);
10778 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
10779 struct bpf_reg_state *dst_reg,
10780 enum bpf_reg_type type,
10781 bool range_right_open)
10783 struct bpf_func_state *state;
10784 struct bpf_reg_state *reg;
10787 if (dst_reg->off < 0 ||
10788 (dst_reg->off == 0 && range_right_open))
10789 /* This doesn't give us any range */
10792 if (dst_reg->umax_value > MAX_PACKET_OFF ||
10793 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
10794 /* Risk of overflow. For instance, ptr + (1<<63) may be less
10795 * than pkt_end, but that's because it's also less than pkt.
10799 new_range = dst_reg->off;
10800 if (range_right_open)
10803 /* Examples for register markings:
10805 * pkt_data in dst register:
10809 * if (r2 > pkt_end) goto <handle exception>
10814 * if (r2 < pkt_end) goto <access okay>
10815 * <handle exception>
10818 * r2 == dst_reg, pkt_end == src_reg
10819 * r2=pkt(id=n,off=8,r=0)
10820 * r3=pkt(id=n,off=0,r=0)
10822 * pkt_data in src register:
10826 * if (pkt_end >= r2) goto <access okay>
10827 * <handle exception>
10831 * if (pkt_end <= r2) goto <handle exception>
10835 * pkt_end == dst_reg, r2 == src_reg
10836 * r2=pkt(id=n,off=8,r=0)
10837 * r3=pkt(id=n,off=0,r=0)
10839 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
10840 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
10841 * and [r3, r3 + 8-1) respectively is safe to access depending on
10845 /* If our ids match, then we must have the same max_value. And we
10846 * don't care about the other reg's fixed offset, since if it's too big
10847 * the range won't allow anything.
10848 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
10850 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10851 if (reg->type == type && reg->id == dst_reg->id)
10852 /* keep the maximum range already checked */
10853 reg->range = max(reg->range, new_range);
10857 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
10859 struct tnum subreg = tnum_subreg(reg->var_off);
10860 s32 sval = (s32)val;
10864 if (tnum_is_const(subreg))
10865 return !!tnum_equals_const(subreg, val);
10868 if (tnum_is_const(subreg))
10869 return !tnum_equals_const(subreg, val);
10872 if ((~subreg.mask & subreg.value) & val)
10874 if (!((subreg.mask | subreg.value) & val))
10878 if (reg->u32_min_value > val)
10880 else if (reg->u32_max_value <= val)
10884 if (reg->s32_min_value > sval)
10886 else if (reg->s32_max_value <= sval)
10890 if (reg->u32_max_value < val)
10892 else if (reg->u32_min_value >= val)
10896 if (reg->s32_max_value < sval)
10898 else if (reg->s32_min_value >= sval)
10902 if (reg->u32_min_value >= val)
10904 else if (reg->u32_max_value < val)
10908 if (reg->s32_min_value >= sval)
10910 else if (reg->s32_max_value < sval)
10914 if (reg->u32_max_value <= val)
10916 else if (reg->u32_min_value > val)
10920 if (reg->s32_max_value <= sval)
10922 else if (reg->s32_min_value > sval)
10931 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
10933 s64 sval = (s64)val;
10937 if (tnum_is_const(reg->var_off))
10938 return !!tnum_equals_const(reg->var_off, val);
10941 if (tnum_is_const(reg->var_off))
10942 return !tnum_equals_const(reg->var_off, val);
10945 if ((~reg->var_off.mask & reg->var_off.value) & val)
10947 if (!((reg->var_off.mask | reg->var_off.value) & val))
10951 if (reg->umin_value > val)
10953 else if (reg->umax_value <= val)
10957 if (reg->smin_value > sval)
10959 else if (reg->smax_value <= sval)
10963 if (reg->umax_value < val)
10965 else if (reg->umin_value >= val)
10969 if (reg->smax_value < sval)
10971 else if (reg->smin_value >= sval)
10975 if (reg->umin_value >= val)
10977 else if (reg->umax_value < val)
10981 if (reg->smin_value >= sval)
10983 else if (reg->smax_value < sval)
10987 if (reg->umax_value <= val)
10989 else if (reg->umin_value > val)
10993 if (reg->smax_value <= sval)
10995 else if (reg->smin_value > sval)
11003 /* compute branch direction of the expression "if (reg opcode val) goto target;"
11005 * 1 - branch will be taken and "goto target" will be executed
11006 * 0 - branch will not be taken and fall-through to next insn
11007 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
11010 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
11013 if (__is_pointer_value(false, reg)) {
11014 if (!reg_type_not_null(reg->type))
11017 /* If pointer is valid tests against zero will fail so we can
11018 * use this to direct branch taken.
11034 return is_branch32_taken(reg, val, opcode);
11035 return is_branch64_taken(reg, val, opcode);
11038 static int flip_opcode(u32 opcode)
11040 /* How can we transform "a <op> b" into "b <op> a"? */
11041 static const u8 opcode_flip[16] = {
11042 /* these stay the same */
11043 [BPF_JEQ >> 4] = BPF_JEQ,
11044 [BPF_JNE >> 4] = BPF_JNE,
11045 [BPF_JSET >> 4] = BPF_JSET,
11046 /* these swap "lesser" and "greater" (L and G in the opcodes) */
11047 [BPF_JGE >> 4] = BPF_JLE,
11048 [BPF_JGT >> 4] = BPF_JLT,
11049 [BPF_JLE >> 4] = BPF_JGE,
11050 [BPF_JLT >> 4] = BPF_JGT,
11051 [BPF_JSGE >> 4] = BPF_JSLE,
11052 [BPF_JSGT >> 4] = BPF_JSLT,
11053 [BPF_JSLE >> 4] = BPF_JSGE,
11054 [BPF_JSLT >> 4] = BPF_JSGT
11056 return opcode_flip[opcode >> 4];
11059 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
11060 struct bpf_reg_state *src_reg,
11063 struct bpf_reg_state *pkt;
11065 if (src_reg->type == PTR_TO_PACKET_END) {
11067 } else if (dst_reg->type == PTR_TO_PACKET_END) {
11069 opcode = flip_opcode(opcode);
11074 if (pkt->range >= 0)
11079 /* pkt <= pkt_end */
11082 /* pkt > pkt_end */
11083 if (pkt->range == BEYOND_PKT_END)
11084 /* pkt has at last one extra byte beyond pkt_end */
11085 return opcode == BPF_JGT;
11088 /* pkt < pkt_end */
11091 /* pkt >= pkt_end */
11092 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
11093 return opcode == BPF_JGE;
11099 /* Adjusts the register min/max values in the case that the dst_reg is the
11100 * variable register that we are working on, and src_reg is a constant or we're
11101 * simply doing a BPF_K check.
11102 * In JEQ/JNE cases we also adjust the var_off values.
11104 static void reg_set_min_max(struct bpf_reg_state *true_reg,
11105 struct bpf_reg_state *false_reg,
11106 u64 val, u32 val32,
11107 u8 opcode, bool is_jmp32)
11109 struct tnum false_32off = tnum_subreg(false_reg->var_off);
11110 struct tnum false_64off = false_reg->var_off;
11111 struct tnum true_32off = tnum_subreg(true_reg->var_off);
11112 struct tnum true_64off = true_reg->var_off;
11113 s64 sval = (s64)val;
11114 s32 sval32 = (s32)val32;
11116 /* If the dst_reg is a pointer, we can't learn anything about its
11117 * variable offset from the compare (unless src_reg were a pointer into
11118 * the same object, but we don't bother with that.
11119 * Since false_reg and true_reg have the same type by construction, we
11120 * only need to check one of them for pointerness.
11122 if (__is_pointer_value(false, false_reg))
11126 /* JEQ/JNE comparison doesn't change the register equivalence.
11129 * if (r1 == 42) goto label;
11131 * label: // here both r1 and r2 are known to be 42.
11133 * Hence when marking register as known preserve it's ID.
11137 __mark_reg32_known(true_reg, val32);
11138 true_32off = tnum_subreg(true_reg->var_off);
11140 ___mark_reg_known(true_reg, val);
11141 true_64off = true_reg->var_off;
11146 __mark_reg32_known(false_reg, val32);
11147 false_32off = tnum_subreg(false_reg->var_off);
11149 ___mark_reg_known(false_reg, val);
11150 false_64off = false_reg->var_off;
11155 false_32off = tnum_and(false_32off, tnum_const(~val32));
11156 if (is_power_of_2(val32))
11157 true_32off = tnum_or(true_32off,
11158 tnum_const(val32));
11160 false_64off = tnum_and(false_64off, tnum_const(~val));
11161 if (is_power_of_2(val))
11162 true_64off = tnum_or(true_64off,
11170 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
11171 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
11173 false_reg->u32_max_value = min(false_reg->u32_max_value,
11175 true_reg->u32_min_value = max(true_reg->u32_min_value,
11178 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
11179 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
11181 false_reg->umax_value = min(false_reg->umax_value, false_umax);
11182 true_reg->umin_value = max(true_reg->umin_value, true_umin);
11190 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
11191 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
11193 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
11194 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
11196 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
11197 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
11199 false_reg->smax_value = min(false_reg->smax_value, false_smax);
11200 true_reg->smin_value = max(true_reg->smin_value, true_smin);
11208 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
11209 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
11211 false_reg->u32_min_value = max(false_reg->u32_min_value,
11213 true_reg->u32_max_value = min(true_reg->u32_max_value,
11216 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
11217 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
11219 false_reg->umin_value = max(false_reg->umin_value, false_umin);
11220 true_reg->umax_value = min(true_reg->umax_value, true_umax);
11228 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
11229 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
11231 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
11232 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
11234 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
11235 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
11237 false_reg->smin_value = max(false_reg->smin_value, false_smin);
11238 true_reg->smax_value = min(true_reg->smax_value, true_smax);
11247 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
11248 tnum_subreg(false_32off));
11249 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
11250 tnum_subreg(true_32off));
11251 __reg_combine_32_into_64(false_reg);
11252 __reg_combine_32_into_64(true_reg);
11254 false_reg->var_off = false_64off;
11255 true_reg->var_off = true_64off;
11256 __reg_combine_64_into_32(false_reg);
11257 __reg_combine_64_into_32(true_reg);
11261 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
11262 * the variable reg.
11264 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
11265 struct bpf_reg_state *false_reg,
11266 u64 val, u32 val32,
11267 u8 opcode, bool is_jmp32)
11269 opcode = flip_opcode(opcode);
11270 /* This uses zero as "not present in table"; luckily the zero opcode,
11271 * BPF_JA, can't get here.
11274 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
11277 /* Regs are known to be equal, so intersect their min/max/var_off */
11278 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
11279 struct bpf_reg_state *dst_reg)
11281 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
11282 dst_reg->umin_value);
11283 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
11284 dst_reg->umax_value);
11285 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
11286 dst_reg->smin_value);
11287 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
11288 dst_reg->smax_value);
11289 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
11291 reg_bounds_sync(src_reg);
11292 reg_bounds_sync(dst_reg);
11295 static void reg_combine_min_max(struct bpf_reg_state *true_src,
11296 struct bpf_reg_state *true_dst,
11297 struct bpf_reg_state *false_src,
11298 struct bpf_reg_state *false_dst,
11303 __reg_combine_min_max(true_src, true_dst);
11306 __reg_combine_min_max(false_src, false_dst);
11311 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
11312 struct bpf_reg_state *reg, u32 id,
11315 if (type_may_be_null(reg->type) && reg->id == id &&
11316 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
11317 /* Old offset (both fixed and variable parts) should have been
11318 * known-zero, because we don't allow pointer arithmetic on
11319 * pointers that might be NULL. If we see this happening, don't
11320 * convert the register.
11322 * But in some cases, some helpers that return local kptrs
11323 * advance offset for the returned pointer. In those cases, it
11324 * is fine to expect to see reg->off.
11326 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
11328 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL) && WARN_ON_ONCE(reg->off))
11331 reg->type = SCALAR_VALUE;
11332 /* We don't need id and ref_obj_id from this point
11333 * onwards anymore, thus we should better reset it,
11334 * so that state pruning has chances to take effect.
11337 reg->ref_obj_id = 0;
11342 mark_ptr_not_null_reg(reg);
11344 if (!reg_may_point_to_spin_lock(reg)) {
11345 /* For not-NULL ptr, reg->ref_obj_id will be reset
11346 * in release_reference().
11348 * reg->id is still used by spin_lock ptr. Other
11349 * than spin_lock ptr type, reg->id can be reset.
11356 /* The logic is similar to find_good_pkt_pointers(), both could eventually
11357 * be folded together at some point.
11359 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
11362 struct bpf_func_state *state = vstate->frame[vstate->curframe];
11363 struct bpf_reg_state *regs = state->regs, *reg;
11364 u32 ref_obj_id = regs[regno].ref_obj_id;
11365 u32 id = regs[regno].id;
11367 if (ref_obj_id && ref_obj_id == id && is_null)
11368 /* regs[regno] is in the " == NULL" branch.
11369 * No one could have freed the reference state before
11370 * doing the NULL check.
11372 WARN_ON_ONCE(release_reference_state(state, id));
11374 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11375 mark_ptr_or_null_reg(state, reg, id, is_null);
11379 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
11380 struct bpf_reg_state *dst_reg,
11381 struct bpf_reg_state *src_reg,
11382 struct bpf_verifier_state *this_branch,
11383 struct bpf_verifier_state *other_branch)
11385 if (BPF_SRC(insn->code) != BPF_X)
11388 /* Pointers are always 64-bit. */
11389 if (BPF_CLASS(insn->code) == BPF_JMP32)
11392 switch (BPF_OP(insn->code)) {
11394 if ((dst_reg->type == PTR_TO_PACKET &&
11395 src_reg->type == PTR_TO_PACKET_END) ||
11396 (dst_reg->type == PTR_TO_PACKET_META &&
11397 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11398 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
11399 find_good_pkt_pointers(this_branch, dst_reg,
11400 dst_reg->type, false);
11401 mark_pkt_end(other_branch, insn->dst_reg, true);
11402 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11403 src_reg->type == PTR_TO_PACKET) ||
11404 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11405 src_reg->type == PTR_TO_PACKET_META)) {
11406 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
11407 find_good_pkt_pointers(other_branch, src_reg,
11408 src_reg->type, true);
11409 mark_pkt_end(this_branch, insn->src_reg, false);
11415 if ((dst_reg->type == PTR_TO_PACKET &&
11416 src_reg->type == PTR_TO_PACKET_END) ||
11417 (dst_reg->type == PTR_TO_PACKET_META &&
11418 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11419 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
11420 find_good_pkt_pointers(other_branch, dst_reg,
11421 dst_reg->type, true);
11422 mark_pkt_end(this_branch, insn->dst_reg, false);
11423 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11424 src_reg->type == PTR_TO_PACKET) ||
11425 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11426 src_reg->type == PTR_TO_PACKET_META)) {
11427 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
11428 find_good_pkt_pointers(this_branch, src_reg,
11429 src_reg->type, false);
11430 mark_pkt_end(other_branch, insn->src_reg, true);
11436 if ((dst_reg->type == PTR_TO_PACKET &&
11437 src_reg->type == PTR_TO_PACKET_END) ||
11438 (dst_reg->type == PTR_TO_PACKET_META &&
11439 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11440 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
11441 find_good_pkt_pointers(this_branch, dst_reg,
11442 dst_reg->type, true);
11443 mark_pkt_end(other_branch, insn->dst_reg, false);
11444 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11445 src_reg->type == PTR_TO_PACKET) ||
11446 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11447 src_reg->type == PTR_TO_PACKET_META)) {
11448 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
11449 find_good_pkt_pointers(other_branch, src_reg,
11450 src_reg->type, false);
11451 mark_pkt_end(this_branch, insn->src_reg, true);
11457 if ((dst_reg->type == PTR_TO_PACKET &&
11458 src_reg->type == PTR_TO_PACKET_END) ||
11459 (dst_reg->type == PTR_TO_PACKET_META &&
11460 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11461 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
11462 find_good_pkt_pointers(other_branch, dst_reg,
11463 dst_reg->type, false);
11464 mark_pkt_end(this_branch, insn->dst_reg, true);
11465 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11466 src_reg->type == PTR_TO_PACKET) ||
11467 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11468 src_reg->type == PTR_TO_PACKET_META)) {
11469 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
11470 find_good_pkt_pointers(this_branch, src_reg,
11471 src_reg->type, true);
11472 mark_pkt_end(other_branch, insn->src_reg, false);
11484 static void find_equal_scalars(struct bpf_verifier_state *vstate,
11485 struct bpf_reg_state *known_reg)
11487 struct bpf_func_state *state;
11488 struct bpf_reg_state *reg;
11490 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11491 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
11496 static int check_cond_jmp_op(struct bpf_verifier_env *env,
11497 struct bpf_insn *insn, int *insn_idx)
11499 struct bpf_verifier_state *this_branch = env->cur_state;
11500 struct bpf_verifier_state *other_branch;
11501 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
11502 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
11503 struct bpf_reg_state *eq_branch_regs;
11504 u8 opcode = BPF_OP(insn->code);
11509 /* Only conditional jumps are expected to reach here. */
11510 if (opcode == BPF_JA || opcode > BPF_JSLE) {
11511 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
11515 if (BPF_SRC(insn->code) == BPF_X) {
11516 if (insn->imm != 0) {
11517 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11521 /* check src1 operand */
11522 err = check_reg_arg(env, insn->src_reg, SRC_OP);
11526 if (is_pointer_value(env, insn->src_reg)) {
11527 verbose(env, "R%d pointer comparison prohibited\n",
11531 src_reg = ®s[insn->src_reg];
11533 if (insn->src_reg != BPF_REG_0) {
11534 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11539 /* check src2 operand */
11540 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11544 dst_reg = ®s[insn->dst_reg];
11545 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
11547 if (BPF_SRC(insn->code) == BPF_K) {
11548 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
11549 } else if (src_reg->type == SCALAR_VALUE &&
11550 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
11551 pred = is_branch_taken(dst_reg,
11552 tnum_subreg(src_reg->var_off).value,
11555 } else if (src_reg->type == SCALAR_VALUE &&
11556 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
11557 pred = is_branch_taken(dst_reg,
11558 src_reg->var_off.value,
11561 } else if (reg_is_pkt_pointer_any(dst_reg) &&
11562 reg_is_pkt_pointer_any(src_reg) &&
11564 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
11568 /* If we get here with a dst_reg pointer type it is because
11569 * above is_branch_taken() special cased the 0 comparison.
11571 if (!__is_pointer_value(false, dst_reg))
11572 err = mark_chain_precision(env, insn->dst_reg);
11573 if (BPF_SRC(insn->code) == BPF_X && !err &&
11574 !__is_pointer_value(false, src_reg))
11575 err = mark_chain_precision(env, insn->src_reg);
11581 /* Only follow the goto, ignore fall-through. If needed, push
11582 * the fall-through branch for simulation under speculative
11585 if (!env->bypass_spec_v1 &&
11586 !sanitize_speculative_path(env, insn, *insn_idx + 1,
11589 *insn_idx += insn->off;
11591 } else if (pred == 0) {
11592 /* Only follow the fall-through branch, since that's where the
11593 * program will go. If needed, push the goto branch for
11594 * simulation under speculative execution.
11596 if (!env->bypass_spec_v1 &&
11597 !sanitize_speculative_path(env, insn,
11598 *insn_idx + insn->off + 1,
11604 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
11608 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
11610 /* detect if we are comparing against a constant value so we can adjust
11611 * our min/max values for our dst register.
11612 * this is only legit if both are scalars (or pointers to the same
11613 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
11614 * because otherwise the different base pointers mean the offsets aren't
11617 if (BPF_SRC(insn->code) == BPF_X) {
11618 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
11620 if (dst_reg->type == SCALAR_VALUE &&
11621 src_reg->type == SCALAR_VALUE) {
11622 if (tnum_is_const(src_reg->var_off) ||
11624 tnum_is_const(tnum_subreg(src_reg->var_off))))
11625 reg_set_min_max(&other_branch_regs[insn->dst_reg],
11627 src_reg->var_off.value,
11628 tnum_subreg(src_reg->var_off).value,
11630 else if (tnum_is_const(dst_reg->var_off) ||
11632 tnum_is_const(tnum_subreg(dst_reg->var_off))))
11633 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
11635 dst_reg->var_off.value,
11636 tnum_subreg(dst_reg->var_off).value,
11638 else if (!is_jmp32 &&
11639 (opcode == BPF_JEQ || opcode == BPF_JNE))
11640 /* Comparing for equality, we can combine knowledge */
11641 reg_combine_min_max(&other_branch_regs[insn->src_reg],
11642 &other_branch_regs[insn->dst_reg],
11643 src_reg, dst_reg, opcode);
11645 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
11646 find_equal_scalars(this_branch, src_reg);
11647 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
11651 } else if (dst_reg->type == SCALAR_VALUE) {
11652 reg_set_min_max(&other_branch_regs[insn->dst_reg],
11653 dst_reg, insn->imm, (u32)insn->imm,
11657 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
11658 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
11659 find_equal_scalars(this_branch, dst_reg);
11660 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
11663 /* if one pointer register is compared to another pointer
11664 * register check if PTR_MAYBE_NULL could be lifted.
11665 * E.g. register A - maybe null
11666 * register B - not null
11667 * for JNE A, B, ... - A is not null in the false branch;
11668 * for JEQ A, B, ... - A is not null in the true branch.
11670 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
11671 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
11672 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type)) {
11673 eq_branch_regs = NULL;
11676 eq_branch_regs = other_branch_regs;
11679 eq_branch_regs = regs;
11685 if (eq_branch_regs) {
11686 if (type_may_be_null(src_reg->type))
11687 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
11689 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
11693 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
11694 * NOTE: these optimizations below are related with pointer comparison
11695 * which will never be JMP32.
11697 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
11698 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
11699 type_may_be_null(dst_reg->type)) {
11700 /* Mark all identical registers in each branch as either
11701 * safe or unknown depending R == 0 or R != 0 conditional.
11703 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
11704 opcode == BPF_JNE);
11705 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
11706 opcode == BPF_JEQ);
11707 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
11708 this_branch, other_branch) &&
11709 is_pointer_value(env, insn->dst_reg)) {
11710 verbose(env, "R%d pointer comparison prohibited\n",
11714 if (env->log.level & BPF_LOG_LEVEL)
11715 print_insn_state(env, this_branch->frame[this_branch->curframe]);
11719 /* verify BPF_LD_IMM64 instruction */
11720 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
11722 struct bpf_insn_aux_data *aux = cur_aux(env);
11723 struct bpf_reg_state *regs = cur_regs(env);
11724 struct bpf_reg_state *dst_reg;
11725 struct bpf_map *map;
11728 if (BPF_SIZE(insn->code) != BPF_DW) {
11729 verbose(env, "invalid BPF_LD_IMM insn\n");
11732 if (insn->off != 0) {
11733 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
11737 err = check_reg_arg(env, insn->dst_reg, DST_OP);
11741 dst_reg = ®s[insn->dst_reg];
11742 if (insn->src_reg == 0) {
11743 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
11745 dst_reg->type = SCALAR_VALUE;
11746 __mark_reg_known(®s[insn->dst_reg], imm);
11750 /* All special src_reg cases are listed below. From this point onwards
11751 * we either succeed and assign a corresponding dst_reg->type after
11752 * zeroing the offset, or fail and reject the program.
11754 mark_reg_known_zero(env, regs, insn->dst_reg);
11756 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
11757 dst_reg->type = aux->btf_var.reg_type;
11758 switch (base_type(dst_reg->type)) {
11760 dst_reg->mem_size = aux->btf_var.mem_size;
11762 case PTR_TO_BTF_ID:
11763 dst_reg->btf = aux->btf_var.btf;
11764 dst_reg->btf_id = aux->btf_var.btf_id;
11767 verbose(env, "bpf verifier is misconfigured\n");
11773 if (insn->src_reg == BPF_PSEUDO_FUNC) {
11774 struct bpf_prog_aux *aux = env->prog->aux;
11775 u32 subprogno = find_subprog(env,
11776 env->insn_idx + insn->imm + 1);
11778 if (!aux->func_info) {
11779 verbose(env, "missing btf func_info\n");
11782 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
11783 verbose(env, "callback function not static\n");
11787 dst_reg->type = PTR_TO_FUNC;
11788 dst_reg->subprogno = subprogno;
11792 map = env->used_maps[aux->map_index];
11793 dst_reg->map_ptr = map;
11795 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
11796 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
11797 dst_reg->type = PTR_TO_MAP_VALUE;
11798 dst_reg->off = aux->map_off;
11799 WARN_ON_ONCE(map->max_entries != 1);
11800 /* We want reg->id to be same (0) as map_value is not distinct */
11801 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
11802 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
11803 dst_reg->type = CONST_PTR_TO_MAP;
11805 verbose(env, "bpf verifier is misconfigured\n");
11812 static bool may_access_skb(enum bpf_prog_type type)
11815 case BPF_PROG_TYPE_SOCKET_FILTER:
11816 case BPF_PROG_TYPE_SCHED_CLS:
11817 case BPF_PROG_TYPE_SCHED_ACT:
11824 /* verify safety of LD_ABS|LD_IND instructions:
11825 * - they can only appear in the programs where ctx == skb
11826 * - since they are wrappers of function calls, they scratch R1-R5 registers,
11827 * preserve R6-R9, and store return value into R0
11830 * ctx == skb == R6 == CTX
11833 * SRC == any register
11834 * IMM == 32-bit immediate
11837 * R0 - 8/16/32-bit skb data converted to cpu endianness
11839 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
11841 struct bpf_reg_state *regs = cur_regs(env);
11842 static const int ctx_reg = BPF_REG_6;
11843 u8 mode = BPF_MODE(insn->code);
11846 if (!may_access_skb(resolve_prog_type(env->prog))) {
11847 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
11851 if (!env->ops->gen_ld_abs) {
11852 verbose(env, "bpf verifier is misconfigured\n");
11856 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
11857 BPF_SIZE(insn->code) == BPF_DW ||
11858 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
11859 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
11863 /* check whether implicit source operand (register R6) is readable */
11864 err = check_reg_arg(env, ctx_reg, SRC_OP);
11868 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
11869 * gen_ld_abs() may terminate the program at runtime, leading to
11872 err = check_reference_leak(env);
11874 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
11878 if (env->cur_state->active_lock.ptr) {
11879 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
11883 if (env->cur_state->active_rcu_lock) {
11884 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
11888 if (regs[ctx_reg].type != PTR_TO_CTX) {
11890 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
11894 if (mode == BPF_IND) {
11895 /* check explicit source operand */
11896 err = check_reg_arg(env, insn->src_reg, SRC_OP);
11901 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
11905 /* reset caller saved regs to unreadable */
11906 for (i = 0; i < CALLER_SAVED_REGS; i++) {
11907 mark_reg_not_init(env, regs, caller_saved[i]);
11908 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11911 /* mark destination R0 register as readable, since it contains
11912 * the value fetched from the packet.
11913 * Already marked as written above.
11915 mark_reg_unknown(env, regs, BPF_REG_0);
11916 /* ld_abs load up to 32-bit skb data. */
11917 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
11921 static int check_return_code(struct bpf_verifier_env *env)
11923 struct tnum enforce_attach_type_range = tnum_unknown;
11924 const struct bpf_prog *prog = env->prog;
11925 struct bpf_reg_state *reg;
11926 struct tnum range = tnum_range(0, 1);
11927 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11929 struct bpf_func_state *frame = env->cur_state->frame[0];
11930 const bool is_subprog = frame->subprogno;
11932 /* LSM and struct_ops func-ptr's return type could be "void" */
11934 switch (prog_type) {
11935 case BPF_PROG_TYPE_LSM:
11936 if (prog->expected_attach_type == BPF_LSM_CGROUP)
11937 /* See below, can be 0 or 0-1 depending on hook. */
11940 case BPF_PROG_TYPE_STRUCT_OPS:
11941 if (!prog->aux->attach_func_proto->type)
11949 /* eBPF calling convention is such that R0 is used
11950 * to return the value from eBPF program.
11951 * Make sure that it's readable at this time
11952 * of bpf_exit, which means that program wrote
11953 * something into it earlier
11955 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
11959 if (is_pointer_value(env, BPF_REG_0)) {
11960 verbose(env, "R0 leaks addr as return value\n");
11964 reg = cur_regs(env) + BPF_REG_0;
11966 if (frame->in_async_callback_fn) {
11967 /* enforce return zero from async callbacks like timer */
11968 if (reg->type != SCALAR_VALUE) {
11969 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
11970 reg_type_str(env, reg->type));
11974 if (!tnum_in(tnum_const(0), reg->var_off)) {
11975 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
11982 if (reg->type != SCALAR_VALUE) {
11983 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
11984 reg_type_str(env, reg->type));
11990 switch (prog_type) {
11991 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
11992 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
11993 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
11994 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
11995 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
11996 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
11997 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
11998 range = tnum_range(1, 1);
11999 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
12000 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
12001 range = tnum_range(0, 3);
12003 case BPF_PROG_TYPE_CGROUP_SKB:
12004 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
12005 range = tnum_range(0, 3);
12006 enforce_attach_type_range = tnum_range(2, 3);
12009 case BPF_PROG_TYPE_CGROUP_SOCK:
12010 case BPF_PROG_TYPE_SOCK_OPS:
12011 case BPF_PROG_TYPE_CGROUP_DEVICE:
12012 case BPF_PROG_TYPE_CGROUP_SYSCTL:
12013 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
12015 case BPF_PROG_TYPE_RAW_TRACEPOINT:
12016 if (!env->prog->aux->attach_btf_id)
12018 range = tnum_const(0);
12020 case BPF_PROG_TYPE_TRACING:
12021 switch (env->prog->expected_attach_type) {
12022 case BPF_TRACE_FENTRY:
12023 case BPF_TRACE_FEXIT:
12024 range = tnum_const(0);
12026 case BPF_TRACE_RAW_TP:
12027 case BPF_MODIFY_RETURN:
12029 case BPF_TRACE_ITER:
12035 case BPF_PROG_TYPE_SK_LOOKUP:
12036 range = tnum_range(SK_DROP, SK_PASS);
12039 case BPF_PROG_TYPE_LSM:
12040 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
12041 /* Regular BPF_PROG_TYPE_LSM programs can return
12046 if (!env->prog->aux->attach_func_proto->type) {
12047 /* Make sure programs that attach to void
12048 * hooks don't try to modify return value.
12050 range = tnum_range(1, 1);
12054 case BPF_PROG_TYPE_EXT:
12055 /* freplace program can return anything as its return value
12056 * depends on the to-be-replaced kernel func or bpf program.
12062 if (reg->type != SCALAR_VALUE) {
12063 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
12064 reg_type_str(env, reg->type));
12068 if (!tnum_in(range, reg->var_off)) {
12069 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
12070 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
12071 prog_type == BPF_PROG_TYPE_LSM &&
12072 !prog->aux->attach_func_proto->type)
12073 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
12077 if (!tnum_is_unknown(enforce_attach_type_range) &&
12078 tnum_in(enforce_attach_type_range, reg->var_off))
12079 env->prog->enforce_expected_attach_type = 1;
12083 /* non-recursive DFS pseudo code
12084 * 1 procedure DFS-iterative(G,v):
12085 * 2 label v as discovered
12086 * 3 let S be a stack
12088 * 5 while S is not empty
12090 * 7 if t is what we're looking for:
12092 * 9 for all edges e in G.adjacentEdges(t) do
12093 * 10 if edge e is already labelled
12094 * 11 continue with the next edge
12095 * 12 w <- G.adjacentVertex(t,e)
12096 * 13 if vertex w is not discovered and not explored
12097 * 14 label e as tree-edge
12098 * 15 label w as discovered
12101 * 18 else if vertex w is discovered
12102 * 19 label e as back-edge
12104 * 21 // vertex w is explored
12105 * 22 label e as forward- or cross-edge
12106 * 23 label t as explored
12110 * 0x10 - discovered
12111 * 0x11 - discovered and fall-through edge labelled
12112 * 0x12 - discovered and fall-through and branch edges labelled
12123 static u32 state_htab_size(struct bpf_verifier_env *env)
12125 return env->prog->len;
12128 static struct bpf_verifier_state_list **explored_state(
12129 struct bpf_verifier_env *env,
12132 struct bpf_verifier_state *cur = env->cur_state;
12133 struct bpf_func_state *state = cur->frame[cur->curframe];
12135 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
12138 static void init_explored_state(struct bpf_verifier_env *env, int idx)
12140 env->insn_aux_data[idx].prune_point = true;
12144 DONE_EXPLORING = 0,
12145 KEEP_EXPLORING = 1,
12148 /* t, w, e - match pseudo-code above:
12149 * t - index of current instruction
12150 * w - next instruction
12153 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
12156 int *insn_stack = env->cfg.insn_stack;
12157 int *insn_state = env->cfg.insn_state;
12159 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
12160 return DONE_EXPLORING;
12162 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
12163 return DONE_EXPLORING;
12165 if (w < 0 || w >= env->prog->len) {
12166 verbose_linfo(env, t, "%d: ", t);
12167 verbose(env, "jump out of range from insn %d to %d\n", t, w);
12172 /* mark branch target for state pruning */
12173 init_explored_state(env, w);
12175 if (insn_state[w] == 0) {
12177 insn_state[t] = DISCOVERED | e;
12178 insn_state[w] = DISCOVERED;
12179 if (env->cfg.cur_stack >= env->prog->len)
12181 insn_stack[env->cfg.cur_stack++] = w;
12182 return KEEP_EXPLORING;
12183 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
12184 if (loop_ok && env->bpf_capable)
12185 return DONE_EXPLORING;
12186 verbose_linfo(env, t, "%d: ", t);
12187 verbose_linfo(env, w, "%d: ", w);
12188 verbose(env, "back-edge from insn %d to %d\n", t, w);
12190 } else if (insn_state[w] == EXPLORED) {
12191 /* forward- or cross-edge */
12192 insn_state[t] = DISCOVERED | e;
12194 verbose(env, "insn state internal bug\n");
12197 return DONE_EXPLORING;
12200 static int visit_func_call_insn(int t, int insn_cnt,
12201 struct bpf_insn *insns,
12202 struct bpf_verifier_env *env,
12207 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
12211 if (t + 1 < insn_cnt)
12212 init_explored_state(env, t + 1);
12213 if (visit_callee) {
12214 init_explored_state(env, t);
12215 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
12216 /* It's ok to allow recursion from CFG point of
12217 * view. __check_func_call() will do the actual
12220 bpf_pseudo_func(insns + t));
12225 /* Visits the instruction at index t and returns one of the following:
12226 * < 0 - an error occurred
12227 * DONE_EXPLORING - the instruction was fully explored
12228 * KEEP_EXPLORING - there is still work to be done before it is fully explored
12230 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
12232 struct bpf_insn *insns = env->prog->insnsi;
12235 if (bpf_pseudo_func(insns + t))
12236 return visit_func_call_insn(t, insn_cnt, insns, env, true);
12238 /* All non-branch instructions have a single fall-through edge. */
12239 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
12240 BPF_CLASS(insns[t].code) != BPF_JMP32)
12241 return push_insn(t, t + 1, FALLTHROUGH, env, false);
12243 switch (BPF_OP(insns[t].code)) {
12245 return DONE_EXPLORING;
12248 if (insns[t].imm == BPF_FUNC_timer_set_callback)
12249 /* Mark this call insn to trigger is_state_visited() check
12250 * before call itself is processed by __check_func_call().
12251 * Otherwise new async state will be pushed for further
12254 init_explored_state(env, t);
12255 return visit_func_call_insn(t, insn_cnt, insns, env,
12256 insns[t].src_reg == BPF_PSEUDO_CALL);
12259 if (BPF_SRC(insns[t].code) != BPF_K)
12262 /* unconditional jump with single edge */
12263 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
12268 /* unconditional jmp is not a good pruning point,
12269 * but it's marked, since backtracking needs
12270 * to record jmp history in is_state_visited().
12272 init_explored_state(env, t + insns[t].off + 1);
12273 /* tell verifier to check for equivalent states
12274 * after every call and jump
12276 if (t + 1 < insn_cnt)
12277 init_explored_state(env, t + 1);
12282 /* conditional jump with two edges */
12283 init_explored_state(env, t);
12284 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
12288 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
12292 /* non-recursive depth-first-search to detect loops in BPF program
12293 * loop == back-edge in directed graph
12295 static int check_cfg(struct bpf_verifier_env *env)
12297 int insn_cnt = env->prog->len;
12298 int *insn_stack, *insn_state;
12302 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12306 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12308 kvfree(insn_state);
12312 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
12313 insn_stack[0] = 0; /* 0 is the first instruction */
12314 env->cfg.cur_stack = 1;
12316 while (env->cfg.cur_stack > 0) {
12317 int t = insn_stack[env->cfg.cur_stack - 1];
12319 ret = visit_insn(t, insn_cnt, env);
12321 case DONE_EXPLORING:
12322 insn_state[t] = EXPLORED;
12323 env->cfg.cur_stack--;
12325 case KEEP_EXPLORING:
12329 verbose(env, "visit_insn internal bug\n");
12336 if (env->cfg.cur_stack < 0) {
12337 verbose(env, "pop stack internal bug\n");
12342 for (i = 0; i < insn_cnt; i++) {
12343 if (insn_state[i] != EXPLORED) {
12344 verbose(env, "unreachable insn %d\n", i);
12349 ret = 0; /* cfg looks good */
12352 kvfree(insn_state);
12353 kvfree(insn_stack);
12354 env->cfg.insn_state = env->cfg.insn_stack = NULL;
12358 static int check_abnormal_return(struct bpf_verifier_env *env)
12362 for (i = 1; i < env->subprog_cnt; i++) {
12363 if (env->subprog_info[i].has_ld_abs) {
12364 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
12367 if (env->subprog_info[i].has_tail_call) {
12368 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
12375 /* The minimum supported BTF func info size */
12376 #define MIN_BPF_FUNCINFO_SIZE 8
12377 #define MAX_FUNCINFO_REC_SIZE 252
12379 static int check_btf_func(struct bpf_verifier_env *env,
12380 const union bpf_attr *attr,
12383 const struct btf_type *type, *func_proto, *ret_type;
12384 u32 i, nfuncs, urec_size, min_size;
12385 u32 krec_size = sizeof(struct bpf_func_info);
12386 struct bpf_func_info *krecord;
12387 struct bpf_func_info_aux *info_aux = NULL;
12388 struct bpf_prog *prog;
12389 const struct btf *btf;
12391 u32 prev_offset = 0;
12392 bool scalar_return;
12395 nfuncs = attr->func_info_cnt;
12397 if (check_abnormal_return(env))
12402 if (nfuncs != env->subprog_cnt) {
12403 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
12407 urec_size = attr->func_info_rec_size;
12408 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
12409 urec_size > MAX_FUNCINFO_REC_SIZE ||
12410 urec_size % sizeof(u32)) {
12411 verbose(env, "invalid func info rec size %u\n", urec_size);
12416 btf = prog->aux->btf;
12418 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
12419 min_size = min_t(u32, krec_size, urec_size);
12421 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
12424 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
12428 for (i = 0; i < nfuncs; i++) {
12429 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
12431 if (ret == -E2BIG) {
12432 verbose(env, "nonzero tailing record in func info");
12433 /* set the size kernel expects so loader can zero
12434 * out the rest of the record.
12436 if (copy_to_bpfptr_offset(uattr,
12437 offsetof(union bpf_attr, func_info_rec_size),
12438 &min_size, sizeof(min_size)))
12444 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
12449 /* check insn_off */
12452 if (krecord[i].insn_off) {
12454 "nonzero insn_off %u for the first func info record",
12455 krecord[i].insn_off);
12458 } else if (krecord[i].insn_off <= prev_offset) {
12460 "same or smaller insn offset (%u) than previous func info record (%u)",
12461 krecord[i].insn_off, prev_offset);
12465 if (env->subprog_info[i].start != krecord[i].insn_off) {
12466 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
12470 /* check type_id */
12471 type = btf_type_by_id(btf, krecord[i].type_id);
12472 if (!type || !btf_type_is_func(type)) {
12473 verbose(env, "invalid type id %d in func info",
12474 krecord[i].type_id);
12477 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
12479 func_proto = btf_type_by_id(btf, type->type);
12480 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
12481 /* btf_func_check() already verified it during BTF load */
12483 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
12485 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
12486 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
12487 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
12490 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
12491 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
12495 prev_offset = krecord[i].insn_off;
12496 bpfptr_add(&urecord, urec_size);
12499 prog->aux->func_info = krecord;
12500 prog->aux->func_info_cnt = nfuncs;
12501 prog->aux->func_info_aux = info_aux;
12510 static void adjust_btf_func(struct bpf_verifier_env *env)
12512 struct bpf_prog_aux *aux = env->prog->aux;
12515 if (!aux->func_info)
12518 for (i = 0; i < env->subprog_cnt; i++)
12519 aux->func_info[i].insn_off = env->subprog_info[i].start;
12522 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
12523 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
12525 static int check_btf_line(struct bpf_verifier_env *env,
12526 const union bpf_attr *attr,
12529 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
12530 struct bpf_subprog_info *sub;
12531 struct bpf_line_info *linfo;
12532 struct bpf_prog *prog;
12533 const struct btf *btf;
12537 nr_linfo = attr->line_info_cnt;
12540 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
12543 rec_size = attr->line_info_rec_size;
12544 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
12545 rec_size > MAX_LINEINFO_REC_SIZE ||
12546 rec_size & (sizeof(u32) - 1))
12549 /* Need to zero it in case the userspace may
12550 * pass in a smaller bpf_line_info object.
12552 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
12553 GFP_KERNEL | __GFP_NOWARN);
12558 btf = prog->aux->btf;
12561 sub = env->subprog_info;
12562 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
12563 expected_size = sizeof(struct bpf_line_info);
12564 ncopy = min_t(u32, expected_size, rec_size);
12565 for (i = 0; i < nr_linfo; i++) {
12566 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
12568 if (err == -E2BIG) {
12569 verbose(env, "nonzero tailing record in line_info");
12570 if (copy_to_bpfptr_offset(uattr,
12571 offsetof(union bpf_attr, line_info_rec_size),
12572 &expected_size, sizeof(expected_size)))
12578 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
12584 * Check insn_off to ensure
12585 * 1) strictly increasing AND
12586 * 2) bounded by prog->len
12588 * The linfo[0].insn_off == 0 check logically falls into
12589 * the later "missing bpf_line_info for func..." case
12590 * because the first linfo[0].insn_off must be the
12591 * first sub also and the first sub must have
12592 * subprog_info[0].start == 0.
12594 if ((i && linfo[i].insn_off <= prev_offset) ||
12595 linfo[i].insn_off >= prog->len) {
12596 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
12597 i, linfo[i].insn_off, prev_offset,
12603 if (!prog->insnsi[linfo[i].insn_off].code) {
12605 "Invalid insn code at line_info[%u].insn_off\n",
12611 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
12612 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
12613 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
12618 if (s != env->subprog_cnt) {
12619 if (linfo[i].insn_off == sub[s].start) {
12620 sub[s].linfo_idx = i;
12622 } else if (sub[s].start < linfo[i].insn_off) {
12623 verbose(env, "missing bpf_line_info for func#%u\n", s);
12629 prev_offset = linfo[i].insn_off;
12630 bpfptr_add(&ulinfo, rec_size);
12633 if (s != env->subprog_cnt) {
12634 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
12635 env->subprog_cnt - s, s);
12640 prog->aux->linfo = linfo;
12641 prog->aux->nr_linfo = nr_linfo;
12650 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
12651 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
12653 static int check_core_relo(struct bpf_verifier_env *env,
12654 const union bpf_attr *attr,
12657 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
12658 struct bpf_core_relo core_relo = {};
12659 struct bpf_prog *prog = env->prog;
12660 const struct btf *btf = prog->aux->btf;
12661 struct bpf_core_ctx ctx = {
12665 bpfptr_t u_core_relo;
12668 nr_core_relo = attr->core_relo_cnt;
12671 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
12674 rec_size = attr->core_relo_rec_size;
12675 if (rec_size < MIN_CORE_RELO_SIZE ||
12676 rec_size > MAX_CORE_RELO_SIZE ||
12677 rec_size % sizeof(u32))
12680 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
12681 expected_size = sizeof(struct bpf_core_relo);
12682 ncopy = min_t(u32, expected_size, rec_size);
12684 /* Unlike func_info and line_info, copy and apply each CO-RE
12685 * relocation record one at a time.
12687 for (i = 0; i < nr_core_relo; i++) {
12688 /* future proofing when sizeof(bpf_core_relo) changes */
12689 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
12691 if (err == -E2BIG) {
12692 verbose(env, "nonzero tailing record in core_relo");
12693 if (copy_to_bpfptr_offset(uattr,
12694 offsetof(union bpf_attr, core_relo_rec_size),
12695 &expected_size, sizeof(expected_size)))
12701 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
12706 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
12707 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
12708 i, core_relo.insn_off, prog->len);
12713 err = bpf_core_apply(&ctx, &core_relo, i,
12714 &prog->insnsi[core_relo.insn_off / 8]);
12717 bpfptr_add(&u_core_relo, rec_size);
12722 static int check_btf_info(struct bpf_verifier_env *env,
12723 const union bpf_attr *attr,
12729 if (!attr->func_info_cnt && !attr->line_info_cnt) {
12730 if (check_abnormal_return(env))
12735 btf = btf_get_by_fd(attr->prog_btf_fd);
12737 return PTR_ERR(btf);
12738 if (btf_is_kernel(btf)) {
12742 env->prog->aux->btf = btf;
12744 err = check_btf_func(env, attr, uattr);
12748 err = check_btf_line(env, attr, uattr);
12752 err = check_core_relo(env, attr, uattr);
12759 /* check %cur's range satisfies %old's */
12760 static bool range_within(struct bpf_reg_state *old,
12761 struct bpf_reg_state *cur)
12763 return old->umin_value <= cur->umin_value &&
12764 old->umax_value >= cur->umax_value &&
12765 old->smin_value <= cur->smin_value &&
12766 old->smax_value >= cur->smax_value &&
12767 old->u32_min_value <= cur->u32_min_value &&
12768 old->u32_max_value >= cur->u32_max_value &&
12769 old->s32_min_value <= cur->s32_min_value &&
12770 old->s32_max_value >= cur->s32_max_value;
12773 /* If in the old state two registers had the same id, then they need to have
12774 * the same id in the new state as well. But that id could be different from
12775 * the old state, so we need to track the mapping from old to new ids.
12776 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
12777 * regs with old id 5 must also have new id 9 for the new state to be safe. But
12778 * regs with a different old id could still have new id 9, we don't care about
12780 * So we look through our idmap to see if this old id has been seen before. If
12781 * so, we require the new id to match; otherwise, we add the id pair to the map.
12783 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
12787 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
12788 if (!idmap[i].old) {
12789 /* Reached an empty slot; haven't seen this id before */
12790 idmap[i].old = old_id;
12791 idmap[i].cur = cur_id;
12794 if (idmap[i].old == old_id)
12795 return idmap[i].cur == cur_id;
12797 /* We ran out of idmap slots, which should be impossible */
12802 static void clean_func_state(struct bpf_verifier_env *env,
12803 struct bpf_func_state *st)
12805 enum bpf_reg_liveness live;
12808 for (i = 0; i < BPF_REG_FP; i++) {
12809 live = st->regs[i].live;
12810 /* liveness must not touch this register anymore */
12811 st->regs[i].live |= REG_LIVE_DONE;
12812 if (!(live & REG_LIVE_READ))
12813 /* since the register is unused, clear its state
12814 * to make further comparison simpler
12816 __mark_reg_not_init(env, &st->regs[i]);
12819 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
12820 live = st->stack[i].spilled_ptr.live;
12821 /* liveness must not touch this stack slot anymore */
12822 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
12823 if (!(live & REG_LIVE_READ)) {
12824 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
12825 for (j = 0; j < BPF_REG_SIZE; j++)
12826 st->stack[i].slot_type[j] = STACK_INVALID;
12831 static void clean_verifier_state(struct bpf_verifier_env *env,
12832 struct bpf_verifier_state *st)
12836 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
12837 /* all regs in this state in all frames were already marked */
12840 for (i = 0; i <= st->curframe; i++)
12841 clean_func_state(env, st->frame[i]);
12844 /* the parentage chains form a tree.
12845 * the verifier states are added to state lists at given insn and
12846 * pushed into state stack for future exploration.
12847 * when the verifier reaches bpf_exit insn some of the verifer states
12848 * stored in the state lists have their final liveness state already,
12849 * but a lot of states will get revised from liveness point of view when
12850 * the verifier explores other branches.
12853 * 2: if r1 == 100 goto pc+1
12856 * when the verifier reaches exit insn the register r0 in the state list of
12857 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
12858 * of insn 2 and goes exploring further. At the insn 4 it will walk the
12859 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
12861 * Since the verifier pushes the branch states as it sees them while exploring
12862 * the program the condition of walking the branch instruction for the second
12863 * time means that all states below this branch were already explored and
12864 * their final liveness marks are already propagated.
12865 * Hence when the verifier completes the search of state list in is_state_visited()
12866 * we can call this clean_live_states() function to mark all liveness states
12867 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
12868 * will not be used.
12869 * This function also clears the registers and stack for states that !READ
12870 * to simplify state merging.
12872 * Important note here that walking the same branch instruction in the callee
12873 * doesn't meant that the states are DONE. The verifier has to compare
12876 static void clean_live_states(struct bpf_verifier_env *env, int insn,
12877 struct bpf_verifier_state *cur)
12879 struct bpf_verifier_state_list *sl;
12882 sl = *explored_state(env, insn);
12884 if (sl->state.branches)
12886 if (sl->state.insn_idx != insn ||
12887 sl->state.curframe != cur->curframe)
12889 for (i = 0; i <= cur->curframe; i++)
12890 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
12892 clean_verifier_state(env, &sl->state);
12898 /* Returns true if (rold safe implies rcur safe) */
12899 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
12900 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
12904 if (!(rold->live & REG_LIVE_READ))
12905 /* explored state didn't use this */
12908 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
12910 if (rold->type == PTR_TO_STACK)
12911 /* two stack pointers are equal only if they're pointing to
12912 * the same stack frame, since fp-8 in foo != fp-8 in bar
12914 return equal && rold->frameno == rcur->frameno;
12919 if (rold->type == NOT_INIT)
12920 /* explored state can't have used this */
12922 if (rcur->type == NOT_INIT)
12924 switch (base_type(rold->type)) {
12926 if (env->explore_alu_limits)
12928 if (rcur->type == SCALAR_VALUE) {
12929 if (!rold->precise)
12931 /* new val must satisfy old val knowledge */
12932 return range_within(rold, rcur) &&
12933 tnum_in(rold->var_off, rcur->var_off);
12935 /* We're trying to use a pointer in place of a scalar.
12936 * Even if the scalar was unbounded, this could lead to
12937 * pointer leaks because scalars are allowed to leak
12938 * while pointers are not. We could make this safe in
12939 * special cases if root is calling us, but it's
12940 * probably not worth the hassle.
12944 case PTR_TO_MAP_KEY:
12945 case PTR_TO_MAP_VALUE:
12946 /* a PTR_TO_MAP_VALUE could be safe to use as a
12947 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
12948 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
12949 * checked, doing so could have affected others with the same
12950 * id, and we can't check for that because we lost the id when
12951 * we converted to a PTR_TO_MAP_VALUE.
12953 if (type_may_be_null(rold->type)) {
12954 if (!type_may_be_null(rcur->type))
12956 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
12958 /* Check our ids match any regs they're supposed to */
12959 return check_ids(rold->id, rcur->id, idmap);
12962 /* If the new min/max/var_off satisfy the old ones and
12963 * everything else matches, we are OK.
12964 * 'id' is not compared, since it's only used for maps with
12965 * bpf_spin_lock inside map element and in such cases if
12966 * the rest of the prog is valid for one map element then
12967 * it's valid for all map elements regardless of the key
12968 * used in bpf_map_lookup()
12970 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
12971 range_within(rold, rcur) &&
12972 tnum_in(rold->var_off, rcur->var_off);
12973 case PTR_TO_PACKET_META:
12974 case PTR_TO_PACKET:
12975 if (rcur->type != rold->type)
12977 /* We must have at least as much range as the old ptr
12978 * did, so that any accesses which were safe before are
12979 * still safe. This is true even if old range < old off,
12980 * since someone could have accessed through (ptr - k), or
12981 * even done ptr -= k in a register, to get a safe access.
12983 if (rold->range > rcur->range)
12985 /* If the offsets don't match, we can't trust our alignment;
12986 * nor can we be sure that we won't fall out of range.
12988 if (rold->off != rcur->off)
12990 /* id relations must be preserved */
12991 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
12993 /* new val must satisfy old val knowledge */
12994 return range_within(rold, rcur) &&
12995 tnum_in(rold->var_off, rcur->var_off);
12997 case CONST_PTR_TO_MAP:
12998 case PTR_TO_PACKET_END:
12999 case PTR_TO_FLOW_KEYS:
13000 case PTR_TO_SOCKET:
13001 case PTR_TO_SOCK_COMMON:
13002 case PTR_TO_TCP_SOCK:
13003 case PTR_TO_XDP_SOCK:
13004 /* Only valid matches are exact, which memcmp() above
13005 * would have accepted
13008 /* Don't know what's going on, just say it's not safe */
13012 /* Shouldn't get here; if we do, say it's not safe */
13017 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
13018 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
13022 /* walk slots of the explored stack and ignore any additional
13023 * slots in the current stack, since explored(safe) state
13026 for (i = 0; i < old->allocated_stack; i++) {
13027 spi = i / BPF_REG_SIZE;
13029 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
13030 i += BPF_REG_SIZE - 1;
13031 /* explored state didn't use this */
13035 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
13038 /* explored stack has more populated slots than current stack
13039 * and these slots were used
13041 if (i >= cur->allocated_stack)
13044 /* if old state was safe with misc data in the stack
13045 * it will be safe with zero-initialized stack.
13046 * The opposite is not true
13048 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
13049 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
13051 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
13052 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
13053 /* Ex: old explored (safe) state has STACK_SPILL in
13054 * this stack slot, but current has STACK_MISC ->
13055 * this verifier states are not equivalent,
13056 * return false to continue verification of this path
13059 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
13061 if (!is_spilled_reg(&old->stack[spi]))
13063 if (!regsafe(env, &old->stack[spi].spilled_ptr,
13064 &cur->stack[spi].spilled_ptr, idmap))
13065 /* when explored and current stack slot are both storing
13066 * spilled registers, check that stored pointers types
13067 * are the same as well.
13068 * Ex: explored safe path could have stored
13069 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
13070 * but current path has stored:
13071 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
13072 * such verifier states are not equivalent.
13073 * return false to continue verification of this path
13080 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
13082 if (old->acquired_refs != cur->acquired_refs)
13084 return !memcmp(old->refs, cur->refs,
13085 sizeof(*old->refs) * old->acquired_refs);
13088 /* compare two verifier states
13090 * all states stored in state_list are known to be valid, since
13091 * verifier reached 'bpf_exit' instruction through them
13093 * this function is called when verifier exploring different branches of
13094 * execution popped from the state stack. If it sees an old state that has
13095 * more strict register state and more strict stack state then this execution
13096 * branch doesn't need to be explored further, since verifier already
13097 * concluded that more strict state leads to valid finish.
13099 * Therefore two states are equivalent if register state is more conservative
13100 * and explored stack state is more conservative than the current one.
13103 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
13104 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
13106 * In other words if current stack state (one being explored) has more
13107 * valid slots than old one that already passed validation, it means
13108 * the verifier can stop exploring and conclude that current state is valid too
13110 * Similarly with registers. If explored state has register type as invalid
13111 * whereas register type in current state is meaningful, it means that
13112 * the current state will reach 'bpf_exit' instruction safely
13114 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
13115 struct bpf_func_state *cur)
13119 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
13120 for (i = 0; i < MAX_BPF_REG; i++)
13121 if (!regsafe(env, &old->regs[i], &cur->regs[i],
13122 env->idmap_scratch))
13125 if (!stacksafe(env, old, cur, env->idmap_scratch))
13128 if (!refsafe(old, cur))
13134 static bool states_equal(struct bpf_verifier_env *env,
13135 struct bpf_verifier_state *old,
13136 struct bpf_verifier_state *cur)
13140 if (old->curframe != cur->curframe)
13143 /* Verification state from speculative execution simulation
13144 * must never prune a non-speculative execution one.
13146 if (old->speculative && !cur->speculative)
13149 if (old->active_lock.ptr != cur->active_lock.ptr ||
13150 old->active_lock.id != cur->active_lock.id)
13153 if (old->active_rcu_lock != cur->active_rcu_lock)
13156 /* for states to be equal callsites have to be the same
13157 * and all frame states need to be equivalent
13159 for (i = 0; i <= old->curframe; i++) {
13160 if (old->frame[i]->callsite != cur->frame[i]->callsite)
13162 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
13168 /* Return 0 if no propagation happened. Return negative error code if error
13169 * happened. Otherwise, return the propagated bit.
13171 static int propagate_liveness_reg(struct bpf_verifier_env *env,
13172 struct bpf_reg_state *reg,
13173 struct bpf_reg_state *parent_reg)
13175 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
13176 u8 flag = reg->live & REG_LIVE_READ;
13179 /* When comes here, read flags of PARENT_REG or REG could be any of
13180 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
13181 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
13183 if (parent_flag == REG_LIVE_READ64 ||
13184 /* Or if there is no read flag from REG. */
13186 /* Or if the read flag from REG is the same as PARENT_REG. */
13187 parent_flag == flag)
13190 err = mark_reg_read(env, reg, parent_reg, flag);
13197 /* A write screens off any subsequent reads; but write marks come from the
13198 * straight-line code between a state and its parent. When we arrive at an
13199 * equivalent state (jump target or such) we didn't arrive by the straight-line
13200 * code, so read marks in the state must propagate to the parent regardless
13201 * of the state's write marks. That's what 'parent == state->parent' comparison
13202 * in mark_reg_read() is for.
13204 static int propagate_liveness(struct bpf_verifier_env *env,
13205 const struct bpf_verifier_state *vstate,
13206 struct bpf_verifier_state *vparent)
13208 struct bpf_reg_state *state_reg, *parent_reg;
13209 struct bpf_func_state *state, *parent;
13210 int i, frame, err = 0;
13212 if (vparent->curframe != vstate->curframe) {
13213 WARN(1, "propagate_live: parent frame %d current frame %d\n",
13214 vparent->curframe, vstate->curframe);
13217 /* Propagate read liveness of registers... */
13218 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
13219 for (frame = 0; frame <= vstate->curframe; frame++) {
13220 parent = vparent->frame[frame];
13221 state = vstate->frame[frame];
13222 parent_reg = parent->regs;
13223 state_reg = state->regs;
13224 /* We don't need to worry about FP liveness, it's read-only */
13225 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
13226 err = propagate_liveness_reg(env, &state_reg[i],
13230 if (err == REG_LIVE_READ64)
13231 mark_insn_zext(env, &parent_reg[i]);
13234 /* Propagate stack slots. */
13235 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
13236 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
13237 parent_reg = &parent->stack[i].spilled_ptr;
13238 state_reg = &state->stack[i].spilled_ptr;
13239 err = propagate_liveness_reg(env, state_reg,
13248 /* find precise scalars in the previous equivalent state and
13249 * propagate them into the current state
13251 static int propagate_precision(struct bpf_verifier_env *env,
13252 const struct bpf_verifier_state *old)
13254 struct bpf_reg_state *state_reg;
13255 struct bpf_func_state *state;
13256 int i, err = 0, fr;
13258 for (fr = old->curframe; fr >= 0; fr--) {
13259 state = old->frame[fr];
13260 state_reg = state->regs;
13261 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
13262 if (state_reg->type != SCALAR_VALUE ||
13263 !state_reg->precise)
13265 if (env->log.level & BPF_LOG_LEVEL2)
13266 verbose(env, "frame %d: propagating r%d\n", i, fr);
13267 err = mark_chain_precision_frame(env, fr, i);
13272 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
13273 if (!is_spilled_reg(&state->stack[i]))
13275 state_reg = &state->stack[i].spilled_ptr;
13276 if (state_reg->type != SCALAR_VALUE ||
13277 !state_reg->precise)
13279 if (env->log.level & BPF_LOG_LEVEL2)
13280 verbose(env, "frame %d: propagating fp%d\n",
13281 (-i - 1) * BPF_REG_SIZE, fr);
13282 err = mark_chain_precision_stack_frame(env, fr, i);
13290 static bool states_maybe_looping(struct bpf_verifier_state *old,
13291 struct bpf_verifier_state *cur)
13293 struct bpf_func_state *fold, *fcur;
13294 int i, fr = cur->curframe;
13296 if (old->curframe != fr)
13299 fold = old->frame[fr];
13300 fcur = cur->frame[fr];
13301 for (i = 0; i < MAX_BPF_REG; i++)
13302 if (memcmp(&fold->regs[i], &fcur->regs[i],
13303 offsetof(struct bpf_reg_state, parent)))
13309 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
13311 struct bpf_verifier_state_list *new_sl;
13312 struct bpf_verifier_state_list *sl, **pprev;
13313 struct bpf_verifier_state *cur = env->cur_state, *new;
13314 int i, j, err, states_cnt = 0;
13315 bool add_new_state = env->test_state_freq ? true : false;
13317 cur->last_insn_idx = env->prev_insn_idx;
13318 if (!env->insn_aux_data[insn_idx].prune_point)
13319 /* this 'insn_idx' instruction wasn't marked, so we will not
13320 * be doing state search here
13324 /* bpf progs typically have pruning point every 4 instructions
13325 * http://vger.kernel.org/bpfconf2019.html#session-1
13326 * Do not add new state for future pruning if the verifier hasn't seen
13327 * at least 2 jumps and at least 8 instructions.
13328 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
13329 * In tests that amounts to up to 50% reduction into total verifier
13330 * memory consumption and 20% verifier time speedup.
13332 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
13333 env->insn_processed - env->prev_insn_processed >= 8)
13334 add_new_state = true;
13336 pprev = explored_state(env, insn_idx);
13339 clean_live_states(env, insn_idx, cur);
13343 if (sl->state.insn_idx != insn_idx)
13346 if (sl->state.branches) {
13347 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
13349 if (frame->in_async_callback_fn &&
13350 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
13351 /* Different async_entry_cnt means that the verifier is
13352 * processing another entry into async callback.
13353 * Seeing the same state is not an indication of infinite
13354 * loop or infinite recursion.
13355 * But finding the same state doesn't mean that it's safe
13356 * to stop processing the current state. The previous state
13357 * hasn't yet reached bpf_exit, since state.branches > 0.
13358 * Checking in_async_callback_fn alone is not enough either.
13359 * Since the verifier still needs to catch infinite loops
13360 * inside async callbacks.
13362 } else if (states_maybe_looping(&sl->state, cur) &&
13363 states_equal(env, &sl->state, cur)) {
13364 verbose_linfo(env, insn_idx, "; ");
13365 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
13368 /* if the verifier is processing a loop, avoid adding new state
13369 * too often, since different loop iterations have distinct
13370 * states and may not help future pruning.
13371 * This threshold shouldn't be too low to make sure that
13372 * a loop with large bound will be rejected quickly.
13373 * The most abusive loop will be:
13375 * if r1 < 1000000 goto pc-2
13376 * 1M insn_procssed limit / 100 == 10k peak states.
13377 * This threshold shouldn't be too high either, since states
13378 * at the end of the loop are likely to be useful in pruning.
13380 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
13381 env->insn_processed - env->prev_insn_processed < 100)
13382 add_new_state = false;
13385 if (states_equal(env, &sl->state, cur)) {
13387 /* reached equivalent register/stack state,
13388 * prune the search.
13389 * Registers read by the continuation are read by us.
13390 * If we have any write marks in env->cur_state, they
13391 * will prevent corresponding reads in the continuation
13392 * from reaching our parent (an explored_state). Our
13393 * own state will get the read marks recorded, but
13394 * they'll be immediately forgotten as we're pruning
13395 * this state and will pop a new one.
13397 err = propagate_liveness(env, &sl->state, cur);
13399 /* if previous state reached the exit with precision and
13400 * current state is equivalent to it (except precsion marks)
13401 * the precision needs to be propagated back in
13402 * the current state.
13404 err = err ? : push_jmp_history(env, cur);
13405 err = err ? : propagate_precision(env, &sl->state);
13411 /* when new state is not going to be added do not increase miss count.
13412 * Otherwise several loop iterations will remove the state
13413 * recorded earlier. The goal of these heuristics is to have
13414 * states from some iterations of the loop (some in the beginning
13415 * and some at the end) to help pruning.
13419 /* heuristic to determine whether this state is beneficial
13420 * to keep checking from state equivalence point of view.
13421 * Higher numbers increase max_states_per_insn and verification time,
13422 * but do not meaningfully decrease insn_processed.
13424 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
13425 /* the state is unlikely to be useful. Remove it to
13426 * speed up verification
13429 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
13430 u32 br = sl->state.branches;
13433 "BUG live_done but branches_to_explore %d\n",
13435 free_verifier_state(&sl->state, false);
13437 env->peak_states--;
13439 /* cannot free this state, since parentage chain may
13440 * walk it later. Add it for free_list instead to
13441 * be freed at the end of verification
13443 sl->next = env->free_list;
13444 env->free_list = sl;
13454 if (env->max_states_per_insn < states_cnt)
13455 env->max_states_per_insn = states_cnt;
13457 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
13458 return push_jmp_history(env, cur);
13460 if (!add_new_state)
13461 return push_jmp_history(env, cur);
13463 /* There were no equivalent states, remember the current one.
13464 * Technically the current state is not proven to be safe yet,
13465 * but it will either reach outer most bpf_exit (which means it's safe)
13466 * or it will be rejected. When there are no loops the verifier won't be
13467 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
13468 * again on the way to bpf_exit.
13469 * When looping the sl->state.branches will be > 0 and this state
13470 * will not be considered for equivalence until branches == 0.
13472 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
13475 env->total_states++;
13476 env->peak_states++;
13477 env->prev_jmps_processed = env->jmps_processed;
13478 env->prev_insn_processed = env->insn_processed;
13480 /* forget precise markings we inherited, see __mark_chain_precision */
13481 if (env->bpf_capable)
13482 mark_all_scalars_imprecise(env, cur);
13484 /* add new state to the head of linked list */
13485 new = &new_sl->state;
13486 err = copy_verifier_state(new, cur);
13488 free_verifier_state(new, false);
13492 new->insn_idx = insn_idx;
13493 WARN_ONCE(new->branches != 1,
13494 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
13497 cur->first_insn_idx = insn_idx;
13498 clear_jmp_history(cur);
13499 new_sl->next = *explored_state(env, insn_idx);
13500 *explored_state(env, insn_idx) = new_sl;
13501 /* connect new state to parentage chain. Current frame needs all
13502 * registers connected. Only r6 - r9 of the callers are alive (pushed
13503 * to the stack implicitly by JITs) so in callers' frames connect just
13504 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
13505 * the state of the call instruction (with WRITTEN set), and r0 comes
13506 * from callee with its full parentage chain, anyway.
13508 /* clear write marks in current state: the writes we did are not writes
13509 * our child did, so they don't screen off its reads from us.
13510 * (There are no read marks in current state, because reads always mark
13511 * their parent and current state never has children yet. Only
13512 * explored_states can get read marks.)
13514 for (j = 0; j <= cur->curframe; j++) {
13515 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
13516 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
13517 for (i = 0; i < BPF_REG_FP; i++)
13518 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
13521 /* all stack frames are accessible from callee, clear them all */
13522 for (j = 0; j <= cur->curframe; j++) {
13523 struct bpf_func_state *frame = cur->frame[j];
13524 struct bpf_func_state *newframe = new->frame[j];
13526 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
13527 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
13528 frame->stack[i].spilled_ptr.parent =
13529 &newframe->stack[i].spilled_ptr;
13535 /* Return true if it's OK to have the same insn return a different type. */
13536 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
13538 switch (base_type(type)) {
13540 case PTR_TO_SOCKET:
13541 case PTR_TO_SOCK_COMMON:
13542 case PTR_TO_TCP_SOCK:
13543 case PTR_TO_XDP_SOCK:
13544 case PTR_TO_BTF_ID:
13551 /* If an instruction was previously used with particular pointer types, then we
13552 * need to be careful to avoid cases such as the below, where it may be ok
13553 * for one branch accessing the pointer, but not ok for the other branch:
13558 * R1 = some_other_valid_ptr;
13561 * R2 = *(u32 *)(R1 + 0);
13563 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
13565 return src != prev && (!reg_type_mismatch_ok(src) ||
13566 !reg_type_mismatch_ok(prev));
13569 static int do_check(struct bpf_verifier_env *env)
13571 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13572 struct bpf_verifier_state *state = env->cur_state;
13573 struct bpf_insn *insns = env->prog->insnsi;
13574 struct bpf_reg_state *regs;
13575 int insn_cnt = env->prog->len;
13576 bool do_print_state = false;
13577 int prev_insn_idx = -1;
13580 struct bpf_insn *insn;
13584 env->prev_insn_idx = prev_insn_idx;
13585 if (env->insn_idx >= insn_cnt) {
13586 verbose(env, "invalid insn idx %d insn_cnt %d\n",
13587 env->insn_idx, insn_cnt);
13591 insn = &insns[env->insn_idx];
13592 class = BPF_CLASS(insn->code);
13594 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
13596 "BPF program is too large. Processed %d insn\n",
13597 env->insn_processed);
13601 err = is_state_visited(env, env->insn_idx);
13605 /* found equivalent state, can prune the search */
13606 if (env->log.level & BPF_LOG_LEVEL) {
13607 if (do_print_state)
13608 verbose(env, "\nfrom %d to %d%s: safe\n",
13609 env->prev_insn_idx, env->insn_idx,
13610 env->cur_state->speculative ?
13611 " (speculative execution)" : "");
13613 verbose(env, "%d: safe\n", env->insn_idx);
13615 goto process_bpf_exit;
13618 if (signal_pending(current))
13621 if (need_resched())
13624 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
13625 verbose(env, "\nfrom %d to %d%s:",
13626 env->prev_insn_idx, env->insn_idx,
13627 env->cur_state->speculative ?
13628 " (speculative execution)" : "");
13629 print_verifier_state(env, state->frame[state->curframe], true);
13630 do_print_state = false;
13633 if (env->log.level & BPF_LOG_LEVEL) {
13634 const struct bpf_insn_cbs cbs = {
13635 .cb_call = disasm_kfunc_name,
13636 .cb_print = verbose,
13637 .private_data = env,
13640 if (verifier_state_scratched(env))
13641 print_insn_state(env, state->frame[state->curframe]);
13643 verbose_linfo(env, env->insn_idx, "; ");
13644 env->prev_log_len = env->log.len_used;
13645 verbose(env, "%d: ", env->insn_idx);
13646 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
13647 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
13648 env->prev_log_len = env->log.len_used;
13651 if (bpf_prog_is_dev_bound(env->prog->aux)) {
13652 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
13653 env->prev_insn_idx);
13658 regs = cur_regs(env);
13659 sanitize_mark_insn_seen(env);
13660 prev_insn_idx = env->insn_idx;
13662 if (class == BPF_ALU || class == BPF_ALU64) {
13663 err = check_alu_op(env, insn);
13667 } else if (class == BPF_LDX) {
13668 enum bpf_reg_type *prev_src_type, src_reg_type;
13670 /* check for reserved fields is already done */
13672 /* check src operand */
13673 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13677 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13681 src_reg_type = regs[insn->src_reg].type;
13683 /* check that memory (src_reg + off) is readable,
13684 * the state of dst_reg will be updated by this func
13686 err = check_mem_access(env, env->insn_idx, insn->src_reg,
13687 insn->off, BPF_SIZE(insn->code),
13688 BPF_READ, insn->dst_reg, false);
13692 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13694 if (*prev_src_type == NOT_INIT) {
13695 /* saw a valid insn
13696 * dst_reg = *(u32 *)(src_reg + off)
13697 * save type to validate intersecting paths
13699 *prev_src_type = src_reg_type;
13701 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
13702 /* ABuser program is trying to use the same insn
13703 * dst_reg = *(u32*) (src_reg + off)
13704 * with different pointer types:
13705 * src_reg == ctx in one branch and
13706 * src_reg == stack|map in some other branch.
13709 verbose(env, "same insn cannot be used with different pointers\n");
13713 } else if (class == BPF_STX) {
13714 enum bpf_reg_type *prev_dst_type, dst_reg_type;
13716 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
13717 err = check_atomic(env, env->insn_idx, insn);
13724 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
13725 verbose(env, "BPF_STX uses reserved fields\n");
13729 /* check src1 operand */
13730 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13733 /* check src2 operand */
13734 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13738 dst_reg_type = regs[insn->dst_reg].type;
13740 /* check that memory (dst_reg + off) is writeable */
13741 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13742 insn->off, BPF_SIZE(insn->code),
13743 BPF_WRITE, insn->src_reg, false);
13747 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13749 if (*prev_dst_type == NOT_INIT) {
13750 *prev_dst_type = dst_reg_type;
13751 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
13752 verbose(env, "same insn cannot be used with different pointers\n");
13756 } else if (class == BPF_ST) {
13757 if (BPF_MODE(insn->code) != BPF_MEM ||
13758 insn->src_reg != BPF_REG_0) {
13759 verbose(env, "BPF_ST uses reserved fields\n");
13762 /* check src operand */
13763 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13767 if (is_ctx_reg(env, insn->dst_reg)) {
13768 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
13770 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
13774 /* check that memory (dst_reg + off) is writeable */
13775 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13776 insn->off, BPF_SIZE(insn->code),
13777 BPF_WRITE, -1, false);
13781 } else if (class == BPF_JMP || class == BPF_JMP32) {
13782 u8 opcode = BPF_OP(insn->code);
13784 env->jmps_processed++;
13785 if (opcode == BPF_CALL) {
13786 if (BPF_SRC(insn->code) != BPF_K ||
13787 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
13788 && insn->off != 0) ||
13789 (insn->src_reg != BPF_REG_0 &&
13790 insn->src_reg != BPF_PSEUDO_CALL &&
13791 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
13792 insn->dst_reg != BPF_REG_0 ||
13793 class == BPF_JMP32) {
13794 verbose(env, "BPF_CALL uses reserved fields\n");
13798 if (env->cur_state->active_lock.ptr) {
13799 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
13800 (insn->src_reg == BPF_PSEUDO_CALL) ||
13801 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
13802 (insn->off != 0 || !is_bpf_list_api_kfunc(insn->imm)))) {
13803 verbose(env, "function calls are not allowed while holding a lock\n");
13807 if (insn->src_reg == BPF_PSEUDO_CALL)
13808 err = check_func_call(env, insn, &env->insn_idx);
13809 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
13810 err = check_kfunc_call(env, insn, &env->insn_idx);
13812 err = check_helper_call(env, insn, &env->insn_idx);
13815 } else if (opcode == BPF_JA) {
13816 if (BPF_SRC(insn->code) != BPF_K ||
13818 insn->src_reg != BPF_REG_0 ||
13819 insn->dst_reg != BPF_REG_0 ||
13820 class == BPF_JMP32) {
13821 verbose(env, "BPF_JA uses reserved fields\n");
13825 env->insn_idx += insn->off + 1;
13828 } else if (opcode == BPF_EXIT) {
13829 if (BPF_SRC(insn->code) != BPF_K ||
13831 insn->src_reg != BPF_REG_0 ||
13832 insn->dst_reg != BPF_REG_0 ||
13833 class == BPF_JMP32) {
13834 verbose(env, "BPF_EXIT uses reserved fields\n");
13838 if (env->cur_state->active_lock.ptr) {
13839 verbose(env, "bpf_spin_unlock is missing\n");
13843 if (env->cur_state->active_rcu_lock) {
13844 verbose(env, "bpf_rcu_read_unlock is missing\n");
13848 /* We must do check_reference_leak here before
13849 * prepare_func_exit to handle the case when
13850 * state->curframe > 0, it may be a callback
13851 * function, for which reference_state must
13852 * match caller reference state when it exits.
13854 err = check_reference_leak(env);
13858 if (state->curframe) {
13859 /* exit from nested function */
13860 err = prepare_func_exit(env, &env->insn_idx);
13863 do_print_state = true;
13867 err = check_return_code(env);
13871 mark_verifier_state_scratched(env);
13872 update_branch_counts(env, env->cur_state);
13873 err = pop_stack(env, &prev_insn_idx,
13874 &env->insn_idx, pop_log);
13876 if (err != -ENOENT)
13880 do_print_state = true;
13884 err = check_cond_jmp_op(env, insn, &env->insn_idx);
13888 } else if (class == BPF_LD) {
13889 u8 mode = BPF_MODE(insn->code);
13891 if (mode == BPF_ABS || mode == BPF_IND) {
13892 err = check_ld_abs(env, insn);
13896 } else if (mode == BPF_IMM) {
13897 err = check_ld_imm(env, insn);
13902 sanitize_mark_insn_seen(env);
13904 verbose(env, "invalid BPF_LD mode\n");
13908 verbose(env, "unknown insn class %d\n", class);
13918 static int find_btf_percpu_datasec(struct btf *btf)
13920 const struct btf_type *t;
13925 * Both vmlinux and module each have their own ".data..percpu"
13926 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
13927 * types to look at only module's own BTF types.
13929 n = btf_nr_types(btf);
13930 if (btf_is_module(btf))
13931 i = btf_nr_types(btf_vmlinux);
13935 for(; i < n; i++) {
13936 t = btf_type_by_id(btf, i);
13937 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
13940 tname = btf_name_by_offset(btf, t->name_off);
13941 if (!strcmp(tname, ".data..percpu"))
13948 /* replace pseudo btf_id with kernel symbol address */
13949 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
13950 struct bpf_insn *insn,
13951 struct bpf_insn_aux_data *aux)
13953 const struct btf_var_secinfo *vsi;
13954 const struct btf_type *datasec;
13955 struct btf_mod_pair *btf_mod;
13956 const struct btf_type *t;
13957 const char *sym_name;
13958 bool percpu = false;
13959 u32 type, id = insn->imm;
13963 int i, btf_fd, err;
13965 btf_fd = insn[1].imm;
13967 btf = btf_get_by_fd(btf_fd);
13969 verbose(env, "invalid module BTF object FD specified.\n");
13973 if (!btf_vmlinux) {
13974 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
13981 t = btf_type_by_id(btf, id);
13983 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
13988 if (!btf_type_is_var(t)) {
13989 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
13994 sym_name = btf_name_by_offset(btf, t->name_off);
13995 addr = kallsyms_lookup_name(sym_name);
13997 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
14003 datasec_id = find_btf_percpu_datasec(btf);
14004 if (datasec_id > 0) {
14005 datasec = btf_type_by_id(btf, datasec_id);
14006 for_each_vsi(i, datasec, vsi) {
14007 if (vsi->type == id) {
14014 insn[0].imm = (u32)addr;
14015 insn[1].imm = addr >> 32;
14018 t = btf_type_skip_modifiers(btf, type, NULL);
14020 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
14021 aux->btf_var.btf = btf;
14022 aux->btf_var.btf_id = type;
14023 } else if (!btf_type_is_struct(t)) {
14024 const struct btf_type *ret;
14028 /* resolve the type size of ksym. */
14029 ret = btf_resolve_size(btf, t, &tsize);
14031 tname = btf_name_by_offset(btf, t->name_off);
14032 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
14033 tname, PTR_ERR(ret));
14037 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
14038 aux->btf_var.mem_size = tsize;
14040 aux->btf_var.reg_type = PTR_TO_BTF_ID;
14041 aux->btf_var.btf = btf;
14042 aux->btf_var.btf_id = type;
14045 /* check whether we recorded this BTF (and maybe module) already */
14046 for (i = 0; i < env->used_btf_cnt; i++) {
14047 if (env->used_btfs[i].btf == btf) {
14053 if (env->used_btf_cnt >= MAX_USED_BTFS) {
14058 btf_mod = &env->used_btfs[env->used_btf_cnt];
14059 btf_mod->btf = btf;
14060 btf_mod->module = NULL;
14062 /* if we reference variables from kernel module, bump its refcount */
14063 if (btf_is_module(btf)) {
14064 btf_mod->module = btf_try_get_module(btf);
14065 if (!btf_mod->module) {
14071 env->used_btf_cnt++;
14079 static bool is_tracing_prog_type(enum bpf_prog_type type)
14082 case BPF_PROG_TYPE_KPROBE:
14083 case BPF_PROG_TYPE_TRACEPOINT:
14084 case BPF_PROG_TYPE_PERF_EVENT:
14085 case BPF_PROG_TYPE_RAW_TRACEPOINT:
14086 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
14093 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
14094 struct bpf_map *map,
14095 struct bpf_prog *prog)
14098 enum bpf_prog_type prog_type = resolve_prog_type(prog);
14100 if (btf_record_has_field(map->record, BPF_LIST_HEAD)) {
14101 if (is_tracing_prog_type(prog_type)) {
14102 verbose(env, "tracing progs cannot use bpf_list_head yet\n");
14107 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
14108 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
14109 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
14113 if (is_tracing_prog_type(prog_type)) {
14114 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
14118 if (prog->aux->sleepable) {
14119 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
14124 if (btf_record_has_field(map->record, BPF_TIMER)) {
14125 if (is_tracing_prog_type(prog_type)) {
14126 verbose(env, "tracing progs cannot use bpf_timer yet\n");
14131 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
14132 !bpf_offload_prog_map_match(prog, map)) {
14133 verbose(env, "offload device mismatch between prog and map\n");
14137 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
14138 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
14142 if (prog->aux->sleepable)
14143 switch (map->map_type) {
14144 case BPF_MAP_TYPE_HASH:
14145 case BPF_MAP_TYPE_LRU_HASH:
14146 case BPF_MAP_TYPE_ARRAY:
14147 case BPF_MAP_TYPE_PERCPU_HASH:
14148 case BPF_MAP_TYPE_PERCPU_ARRAY:
14149 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
14150 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
14151 case BPF_MAP_TYPE_HASH_OF_MAPS:
14152 case BPF_MAP_TYPE_RINGBUF:
14153 case BPF_MAP_TYPE_USER_RINGBUF:
14154 case BPF_MAP_TYPE_INODE_STORAGE:
14155 case BPF_MAP_TYPE_SK_STORAGE:
14156 case BPF_MAP_TYPE_TASK_STORAGE:
14157 case BPF_MAP_TYPE_CGRP_STORAGE:
14161 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
14168 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
14170 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
14171 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
14174 /* find and rewrite pseudo imm in ld_imm64 instructions:
14176 * 1. if it accesses map FD, replace it with actual map pointer.
14177 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
14179 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
14181 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
14183 struct bpf_insn *insn = env->prog->insnsi;
14184 int insn_cnt = env->prog->len;
14187 err = bpf_prog_calc_tag(env->prog);
14191 for (i = 0; i < insn_cnt; i++, insn++) {
14192 if (BPF_CLASS(insn->code) == BPF_LDX &&
14193 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
14194 verbose(env, "BPF_LDX uses reserved fields\n");
14198 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
14199 struct bpf_insn_aux_data *aux;
14200 struct bpf_map *map;
14205 if (i == insn_cnt - 1 || insn[1].code != 0 ||
14206 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
14207 insn[1].off != 0) {
14208 verbose(env, "invalid bpf_ld_imm64 insn\n");
14212 if (insn[0].src_reg == 0)
14213 /* valid generic load 64-bit imm */
14216 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
14217 aux = &env->insn_aux_data[i];
14218 err = check_pseudo_btf_id(env, insn, aux);
14224 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
14225 aux = &env->insn_aux_data[i];
14226 aux->ptr_type = PTR_TO_FUNC;
14230 /* In final convert_pseudo_ld_imm64() step, this is
14231 * converted into regular 64-bit imm load insn.
14233 switch (insn[0].src_reg) {
14234 case BPF_PSEUDO_MAP_VALUE:
14235 case BPF_PSEUDO_MAP_IDX_VALUE:
14237 case BPF_PSEUDO_MAP_FD:
14238 case BPF_PSEUDO_MAP_IDX:
14239 if (insn[1].imm == 0)
14243 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
14247 switch (insn[0].src_reg) {
14248 case BPF_PSEUDO_MAP_IDX_VALUE:
14249 case BPF_PSEUDO_MAP_IDX:
14250 if (bpfptr_is_null(env->fd_array)) {
14251 verbose(env, "fd_idx without fd_array is invalid\n");
14254 if (copy_from_bpfptr_offset(&fd, env->fd_array,
14255 insn[0].imm * sizeof(fd),
14265 map = __bpf_map_get(f);
14267 verbose(env, "fd %d is not pointing to valid bpf_map\n",
14269 return PTR_ERR(map);
14272 err = check_map_prog_compatibility(env, map, env->prog);
14278 aux = &env->insn_aux_data[i];
14279 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
14280 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
14281 addr = (unsigned long)map;
14283 u32 off = insn[1].imm;
14285 if (off >= BPF_MAX_VAR_OFF) {
14286 verbose(env, "direct value offset of %u is not allowed\n", off);
14291 if (!map->ops->map_direct_value_addr) {
14292 verbose(env, "no direct value access support for this map type\n");
14297 err = map->ops->map_direct_value_addr(map, &addr, off);
14299 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
14300 map->value_size, off);
14305 aux->map_off = off;
14309 insn[0].imm = (u32)addr;
14310 insn[1].imm = addr >> 32;
14312 /* check whether we recorded this map already */
14313 for (j = 0; j < env->used_map_cnt; j++) {
14314 if (env->used_maps[j] == map) {
14315 aux->map_index = j;
14321 if (env->used_map_cnt >= MAX_USED_MAPS) {
14326 /* hold the map. If the program is rejected by verifier,
14327 * the map will be released by release_maps() or it
14328 * will be used by the valid program until it's unloaded
14329 * and all maps are released in free_used_maps()
14333 aux->map_index = env->used_map_cnt;
14334 env->used_maps[env->used_map_cnt++] = map;
14336 if (bpf_map_is_cgroup_storage(map) &&
14337 bpf_cgroup_storage_assign(env->prog->aux, map)) {
14338 verbose(env, "only one cgroup storage of each type is allowed\n");
14350 /* Basic sanity check before we invest more work here. */
14351 if (!bpf_opcode_in_insntable(insn->code)) {
14352 verbose(env, "unknown opcode %02x\n", insn->code);
14357 /* now all pseudo BPF_LD_IMM64 instructions load valid
14358 * 'struct bpf_map *' into a register instead of user map_fd.
14359 * These pointers will be used later by verifier to validate map access.
14364 /* drop refcnt of maps used by the rejected program */
14365 static void release_maps(struct bpf_verifier_env *env)
14367 __bpf_free_used_maps(env->prog->aux, env->used_maps,
14368 env->used_map_cnt);
14371 /* drop refcnt of maps used by the rejected program */
14372 static void release_btfs(struct bpf_verifier_env *env)
14374 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
14375 env->used_btf_cnt);
14378 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
14379 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
14381 struct bpf_insn *insn = env->prog->insnsi;
14382 int insn_cnt = env->prog->len;
14385 for (i = 0; i < insn_cnt; i++, insn++) {
14386 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
14388 if (insn->src_reg == BPF_PSEUDO_FUNC)
14394 /* single env->prog->insni[off] instruction was replaced with the range
14395 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
14396 * [0, off) and [off, end) to new locations, so the patched range stays zero
14398 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
14399 struct bpf_insn_aux_data *new_data,
14400 struct bpf_prog *new_prog, u32 off, u32 cnt)
14402 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
14403 struct bpf_insn *insn = new_prog->insnsi;
14404 u32 old_seen = old_data[off].seen;
14408 /* aux info at OFF always needs adjustment, no matter fast path
14409 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
14410 * original insn at old prog.
14412 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
14416 prog_len = new_prog->len;
14418 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
14419 memcpy(new_data + off + cnt - 1, old_data + off,
14420 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
14421 for (i = off; i < off + cnt - 1; i++) {
14422 /* Expand insni[off]'s seen count to the patched range. */
14423 new_data[i].seen = old_seen;
14424 new_data[i].zext_dst = insn_has_def32(env, insn + i);
14426 env->insn_aux_data = new_data;
14430 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
14436 /* NOTE: fake 'exit' subprog should be updated as well. */
14437 for (i = 0; i <= env->subprog_cnt; i++) {
14438 if (env->subprog_info[i].start <= off)
14440 env->subprog_info[i].start += len - 1;
14444 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
14446 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
14447 int i, sz = prog->aux->size_poke_tab;
14448 struct bpf_jit_poke_descriptor *desc;
14450 for (i = 0; i < sz; i++) {
14452 if (desc->insn_idx <= off)
14454 desc->insn_idx += len - 1;
14458 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
14459 const struct bpf_insn *patch, u32 len)
14461 struct bpf_prog *new_prog;
14462 struct bpf_insn_aux_data *new_data = NULL;
14465 new_data = vzalloc(array_size(env->prog->len + len - 1,
14466 sizeof(struct bpf_insn_aux_data)));
14471 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
14472 if (IS_ERR(new_prog)) {
14473 if (PTR_ERR(new_prog) == -ERANGE)
14475 "insn %d cannot be patched due to 16-bit range\n",
14476 env->insn_aux_data[off].orig_idx);
14480 adjust_insn_aux_data(env, new_data, new_prog, off, len);
14481 adjust_subprog_starts(env, off, len);
14482 adjust_poke_descs(new_prog, off, len);
14486 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
14491 /* find first prog starting at or after off (first to remove) */
14492 for (i = 0; i < env->subprog_cnt; i++)
14493 if (env->subprog_info[i].start >= off)
14495 /* find first prog starting at or after off + cnt (first to stay) */
14496 for (j = i; j < env->subprog_cnt; j++)
14497 if (env->subprog_info[j].start >= off + cnt)
14499 /* if j doesn't start exactly at off + cnt, we are just removing
14500 * the front of previous prog
14502 if (env->subprog_info[j].start != off + cnt)
14506 struct bpf_prog_aux *aux = env->prog->aux;
14509 /* move fake 'exit' subprog as well */
14510 move = env->subprog_cnt + 1 - j;
14512 memmove(env->subprog_info + i,
14513 env->subprog_info + j,
14514 sizeof(*env->subprog_info) * move);
14515 env->subprog_cnt -= j - i;
14517 /* remove func_info */
14518 if (aux->func_info) {
14519 move = aux->func_info_cnt - j;
14521 memmove(aux->func_info + i,
14522 aux->func_info + j,
14523 sizeof(*aux->func_info) * move);
14524 aux->func_info_cnt -= j - i;
14525 /* func_info->insn_off is set after all code rewrites,
14526 * in adjust_btf_func() - no need to adjust
14530 /* convert i from "first prog to remove" to "first to adjust" */
14531 if (env->subprog_info[i].start == off)
14535 /* update fake 'exit' subprog as well */
14536 for (; i <= env->subprog_cnt; i++)
14537 env->subprog_info[i].start -= cnt;
14542 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
14545 struct bpf_prog *prog = env->prog;
14546 u32 i, l_off, l_cnt, nr_linfo;
14547 struct bpf_line_info *linfo;
14549 nr_linfo = prog->aux->nr_linfo;
14553 linfo = prog->aux->linfo;
14555 /* find first line info to remove, count lines to be removed */
14556 for (i = 0; i < nr_linfo; i++)
14557 if (linfo[i].insn_off >= off)
14562 for (; i < nr_linfo; i++)
14563 if (linfo[i].insn_off < off + cnt)
14568 /* First live insn doesn't match first live linfo, it needs to "inherit"
14569 * last removed linfo. prog is already modified, so prog->len == off
14570 * means no live instructions after (tail of the program was removed).
14572 if (prog->len != off && l_cnt &&
14573 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
14575 linfo[--i].insn_off = off + cnt;
14578 /* remove the line info which refer to the removed instructions */
14580 memmove(linfo + l_off, linfo + i,
14581 sizeof(*linfo) * (nr_linfo - i));
14583 prog->aux->nr_linfo -= l_cnt;
14584 nr_linfo = prog->aux->nr_linfo;
14587 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
14588 for (i = l_off; i < nr_linfo; i++)
14589 linfo[i].insn_off -= cnt;
14591 /* fix up all subprogs (incl. 'exit') which start >= off */
14592 for (i = 0; i <= env->subprog_cnt; i++)
14593 if (env->subprog_info[i].linfo_idx > l_off) {
14594 /* program may have started in the removed region but
14595 * may not be fully removed
14597 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
14598 env->subprog_info[i].linfo_idx -= l_cnt;
14600 env->subprog_info[i].linfo_idx = l_off;
14606 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
14608 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14609 unsigned int orig_prog_len = env->prog->len;
14612 if (bpf_prog_is_dev_bound(env->prog->aux))
14613 bpf_prog_offload_remove_insns(env, off, cnt);
14615 err = bpf_remove_insns(env->prog, off, cnt);
14619 err = adjust_subprog_starts_after_remove(env, off, cnt);
14623 err = bpf_adj_linfo_after_remove(env, off, cnt);
14627 memmove(aux_data + off, aux_data + off + cnt,
14628 sizeof(*aux_data) * (orig_prog_len - off - cnt));
14633 /* The verifier does more data flow analysis than llvm and will not
14634 * explore branches that are dead at run time. Malicious programs can
14635 * have dead code too. Therefore replace all dead at-run-time code
14638 * Just nops are not optimal, e.g. if they would sit at the end of the
14639 * program and through another bug we would manage to jump there, then
14640 * we'd execute beyond program memory otherwise. Returning exception
14641 * code also wouldn't work since we can have subprogs where the dead
14642 * code could be located.
14644 static void sanitize_dead_code(struct bpf_verifier_env *env)
14646 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14647 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
14648 struct bpf_insn *insn = env->prog->insnsi;
14649 const int insn_cnt = env->prog->len;
14652 for (i = 0; i < insn_cnt; i++) {
14653 if (aux_data[i].seen)
14655 memcpy(insn + i, &trap, sizeof(trap));
14656 aux_data[i].zext_dst = false;
14660 static bool insn_is_cond_jump(u8 code)
14664 if (BPF_CLASS(code) == BPF_JMP32)
14667 if (BPF_CLASS(code) != BPF_JMP)
14671 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
14674 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
14676 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14677 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14678 struct bpf_insn *insn = env->prog->insnsi;
14679 const int insn_cnt = env->prog->len;
14682 for (i = 0; i < insn_cnt; i++, insn++) {
14683 if (!insn_is_cond_jump(insn->code))
14686 if (!aux_data[i + 1].seen)
14687 ja.off = insn->off;
14688 else if (!aux_data[i + 1 + insn->off].seen)
14693 if (bpf_prog_is_dev_bound(env->prog->aux))
14694 bpf_prog_offload_replace_insn(env, i, &ja);
14696 memcpy(insn, &ja, sizeof(ja));
14700 static int opt_remove_dead_code(struct bpf_verifier_env *env)
14702 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14703 int insn_cnt = env->prog->len;
14706 for (i = 0; i < insn_cnt; i++) {
14710 while (i + j < insn_cnt && !aux_data[i + j].seen)
14715 err = verifier_remove_insns(env, i, j);
14718 insn_cnt = env->prog->len;
14724 static int opt_remove_nops(struct bpf_verifier_env *env)
14726 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14727 struct bpf_insn *insn = env->prog->insnsi;
14728 int insn_cnt = env->prog->len;
14731 for (i = 0; i < insn_cnt; i++) {
14732 if (memcmp(&insn[i], &ja, sizeof(ja)))
14735 err = verifier_remove_insns(env, i, 1);
14745 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
14746 const union bpf_attr *attr)
14748 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
14749 struct bpf_insn_aux_data *aux = env->insn_aux_data;
14750 int i, patch_len, delta = 0, len = env->prog->len;
14751 struct bpf_insn *insns = env->prog->insnsi;
14752 struct bpf_prog *new_prog;
14755 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
14756 zext_patch[1] = BPF_ZEXT_REG(0);
14757 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
14758 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
14759 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
14760 for (i = 0; i < len; i++) {
14761 int adj_idx = i + delta;
14762 struct bpf_insn insn;
14765 insn = insns[adj_idx];
14766 load_reg = insn_def_regno(&insn);
14767 if (!aux[adj_idx].zext_dst) {
14775 class = BPF_CLASS(code);
14776 if (load_reg == -1)
14779 /* NOTE: arg "reg" (the fourth one) is only used for
14780 * BPF_STX + SRC_OP, so it is safe to pass NULL
14783 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
14784 if (class == BPF_LD &&
14785 BPF_MODE(code) == BPF_IMM)
14790 /* ctx load could be transformed into wider load. */
14791 if (class == BPF_LDX &&
14792 aux[adj_idx].ptr_type == PTR_TO_CTX)
14795 imm_rnd = get_random_u32();
14796 rnd_hi32_patch[0] = insn;
14797 rnd_hi32_patch[1].imm = imm_rnd;
14798 rnd_hi32_patch[3].dst_reg = load_reg;
14799 patch = rnd_hi32_patch;
14801 goto apply_patch_buffer;
14804 /* Add in an zero-extend instruction if a) the JIT has requested
14805 * it or b) it's a CMPXCHG.
14807 * The latter is because: BPF_CMPXCHG always loads a value into
14808 * R0, therefore always zero-extends. However some archs'
14809 * equivalent instruction only does this load when the
14810 * comparison is successful. This detail of CMPXCHG is
14811 * orthogonal to the general zero-extension behaviour of the
14812 * CPU, so it's treated independently of bpf_jit_needs_zext.
14814 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
14817 if (WARN_ON(load_reg == -1)) {
14818 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
14822 zext_patch[0] = insn;
14823 zext_patch[1].dst_reg = load_reg;
14824 zext_patch[1].src_reg = load_reg;
14825 patch = zext_patch;
14827 apply_patch_buffer:
14828 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
14831 env->prog = new_prog;
14832 insns = new_prog->insnsi;
14833 aux = env->insn_aux_data;
14834 delta += patch_len - 1;
14840 /* convert load instructions that access fields of a context type into a
14841 * sequence of instructions that access fields of the underlying structure:
14842 * struct __sk_buff -> struct sk_buff
14843 * struct bpf_sock_ops -> struct sock
14845 static int convert_ctx_accesses(struct bpf_verifier_env *env)
14847 const struct bpf_verifier_ops *ops = env->ops;
14848 int i, cnt, size, ctx_field_size, delta = 0;
14849 const int insn_cnt = env->prog->len;
14850 struct bpf_insn insn_buf[16], *insn;
14851 u32 target_size, size_default, off;
14852 struct bpf_prog *new_prog;
14853 enum bpf_access_type type;
14854 bool is_narrower_load;
14856 if (ops->gen_prologue || env->seen_direct_write) {
14857 if (!ops->gen_prologue) {
14858 verbose(env, "bpf verifier is misconfigured\n");
14861 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
14863 if (cnt >= ARRAY_SIZE(insn_buf)) {
14864 verbose(env, "bpf verifier is misconfigured\n");
14867 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
14871 env->prog = new_prog;
14876 if (bpf_prog_is_dev_bound(env->prog->aux))
14879 insn = env->prog->insnsi + delta;
14881 for (i = 0; i < insn_cnt; i++, insn++) {
14882 bpf_convert_ctx_access_t convert_ctx_access;
14885 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
14886 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
14887 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
14888 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
14891 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
14892 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
14893 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
14894 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
14895 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
14896 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
14897 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
14898 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
14900 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
14905 if (type == BPF_WRITE &&
14906 env->insn_aux_data[i + delta].sanitize_stack_spill) {
14907 struct bpf_insn patch[] = {
14912 cnt = ARRAY_SIZE(patch);
14913 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
14918 env->prog = new_prog;
14919 insn = new_prog->insnsi + i + delta;
14926 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
14928 if (!ops->convert_ctx_access)
14930 convert_ctx_access = ops->convert_ctx_access;
14932 case PTR_TO_SOCKET:
14933 case PTR_TO_SOCK_COMMON:
14934 convert_ctx_access = bpf_sock_convert_ctx_access;
14936 case PTR_TO_TCP_SOCK:
14937 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
14939 case PTR_TO_XDP_SOCK:
14940 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
14942 case PTR_TO_BTF_ID:
14943 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
14944 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
14945 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
14946 * be said once it is marked PTR_UNTRUSTED, hence we must handle
14947 * any faults for loads into such types. BPF_WRITE is disallowed
14950 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
14951 if (type == BPF_READ) {
14952 insn->code = BPF_LDX | BPF_PROBE_MEM |
14953 BPF_SIZE((insn)->code);
14954 env->prog->aux->num_exentries++;
14961 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
14962 size = BPF_LDST_BYTES(insn);
14964 /* If the read access is a narrower load of the field,
14965 * convert to a 4/8-byte load, to minimum program type specific
14966 * convert_ctx_access changes. If conversion is successful,
14967 * we will apply proper mask to the result.
14969 is_narrower_load = size < ctx_field_size;
14970 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
14972 if (is_narrower_load) {
14975 if (type == BPF_WRITE) {
14976 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
14981 if (ctx_field_size == 4)
14983 else if (ctx_field_size == 8)
14984 size_code = BPF_DW;
14986 insn->off = off & ~(size_default - 1);
14987 insn->code = BPF_LDX | BPF_MEM | size_code;
14991 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
14993 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
14994 (ctx_field_size && !target_size)) {
14995 verbose(env, "bpf verifier is misconfigured\n");
14999 if (is_narrower_load && size < target_size) {
15000 u8 shift = bpf_ctx_narrow_access_offset(
15001 off, size, size_default) * 8;
15002 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
15003 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
15006 if (ctx_field_size <= 4) {
15008 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
15011 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
15012 (1 << size * 8) - 1);
15015 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
15018 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
15019 (1ULL << size * 8) - 1);
15023 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15029 /* keep walking new program and skip insns we just inserted */
15030 env->prog = new_prog;
15031 insn = new_prog->insnsi + i + delta;
15037 static int jit_subprogs(struct bpf_verifier_env *env)
15039 struct bpf_prog *prog = env->prog, **func, *tmp;
15040 int i, j, subprog_start, subprog_end = 0, len, subprog;
15041 struct bpf_map *map_ptr;
15042 struct bpf_insn *insn;
15043 void *old_bpf_func;
15044 int err, num_exentries;
15046 if (env->subprog_cnt <= 1)
15049 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15050 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
15053 /* Upon error here we cannot fall back to interpreter but
15054 * need a hard reject of the program. Thus -EFAULT is
15055 * propagated in any case.
15057 subprog = find_subprog(env, i + insn->imm + 1);
15059 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
15060 i + insn->imm + 1);
15063 /* temporarily remember subprog id inside insn instead of
15064 * aux_data, since next loop will split up all insns into funcs
15066 insn->off = subprog;
15067 /* remember original imm in case JIT fails and fallback
15068 * to interpreter will be needed
15070 env->insn_aux_data[i].call_imm = insn->imm;
15071 /* point imm to __bpf_call_base+1 from JITs point of view */
15073 if (bpf_pseudo_func(insn))
15074 /* jit (e.g. x86_64) may emit fewer instructions
15075 * if it learns a u32 imm is the same as a u64 imm.
15076 * Force a non zero here.
15081 err = bpf_prog_alloc_jited_linfo(prog);
15083 goto out_undo_insn;
15086 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
15088 goto out_undo_insn;
15090 for (i = 0; i < env->subprog_cnt; i++) {
15091 subprog_start = subprog_end;
15092 subprog_end = env->subprog_info[i + 1].start;
15094 len = subprog_end - subprog_start;
15095 /* bpf_prog_run() doesn't call subprogs directly,
15096 * hence main prog stats include the runtime of subprogs.
15097 * subprogs don't have IDs and not reachable via prog_get_next_id
15098 * func[i]->stats will never be accessed and stays NULL
15100 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
15103 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
15104 len * sizeof(struct bpf_insn));
15105 func[i]->type = prog->type;
15106 func[i]->len = len;
15107 if (bpf_prog_calc_tag(func[i]))
15109 func[i]->is_func = 1;
15110 func[i]->aux->func_idx = i;
15111 /* Below members will be freed only at prog->aux */
15112 func[i]->aux->btf = prog->aux->btf;
15113 func[i]->aux->func_info = prog->aux->func_info;
15114 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
15115 func[i]->aux->poke_tab = prog->aux->poke_tab;
15116 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
15118 for (j = 0; j < prog->aux->size_poke_tab; j++) {
15119 struct bpf_jit_poke_descriptor *poke;
15121 poke = &prog->aux->poke_tab[j];
15122 if (poke->insn_idx < subprog_end &&
15123 poke->insn_idx >= subprog_start)
15124 poke->aux = func[i]->aux;
15127 func[i]->aux->name[0] = 'F';
15128 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
15129 func[i]->jit_requested = 1;
15130 func[i]->blinding_requested = prog->blinding_requested;
15131 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
15132 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
15133 func[i]->aux->linfo = prog->aux->linfo;
15134 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
15135 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
15136 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
15138 insn = func[i]->insnsi;
15139 for (j = 0; j < func[i]->len; j++, insn++) {
15140 if (BPF_CLASS(insn->code) == BPF_LDX &&
15141 BPF_MODE(insn->code) == BPF_PROBE_MEM)
15144 func[i]->aux->num_exentries = num_exentries;
15145 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
15146 func[i] = bpf_int_jit_compile(func[i]);
15147 if (!func[i]->jited) {
15154 /* at this point all bpf functions were successfully JITed
15155 * now populate all bpf_calls with correct addresses and
15156 * run last pass of JIT
15158 for (i = 0; i < env->subprog_cnt; i++) {
15159 insn = func[i]->insnsi;
15160 for (j = 0; j < func[i]->len; j++, insn++) {
15161 if (bpf_pseudo_func(insn)) {
15162 subprog = insn->off;
15163 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
15164 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
15167 if (!bpf_pseudo_call(insn))
15169 subprog = insn->off;
15170 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
15173 /* we use the aux data to keep a list of the start addresses
15174 * of the JITed images for each function in the program
15176 * for some architectures, such as powerpc64, the imm field
15177 * might not be large enough to hold the offset of the start
15178 * address of the callee's JITed image from __bpf_call_base
15180 * in such cases, we can lookup the start address of a callee
15181 * by using its subprog id, available from the off field of
15182 * the call instruction, as an index for this list
15184 func[i]->aux->func = func;
15185 func[i]->aux->func_cnt = env->subprog_cnt;
15187 for (i = 0; i < env->subprog_cnt; i++) {
15188 old_bpf_func = func[i]->bpf_func;
15189 tmp = bpf_int_jit_compile(func[i]);
15190 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
15191 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
15198 /* finally lock prog and jit images for all functions and
15199 * populate kallsysm
15201 for (i = 0; i < env->subprog_cnt; i++) {
15202 bpf_prog_lock_ro(func[i]);
15203 bpf_prog_kallsyms_add(func[i]);
15206 /* Last step: make now unused interpreter insns from main
15207 * prog consistent for later dump requests, so they can
15208 * later look the same as if they were interpreted only.
15210 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15211 if (bpf_pseudo_func(insn)) {
15212 insn[0].imm = env->insn_aux_data[i].call_imm;
15213 insn[1].imm = insn->off;
15217 if (!bpf_pseudo_call(insn))
15219 insn->off = env->insn_aux_data[i].call_imm;
15220 subprog = find_subprog(env, i + insn->off + 1);
15221 insn->imm = subprog;
15225 prog->bpf_func = func[0]->bpf_func;
15226 prog->jited_len = func[0]->jited_len;
15227 prog->aux->func = func;
15228 prog->aux->func_cnt = env->subprog_cnt;
15229 bpf_prog_jit_attempt_done(prog);
15232 /* We failed JIT'ing, so at this point we need to unregister poke
15233 * descriptors from subprogs, so that kernel is not attempting to
15234 * patch it anymore as we're freeing the subprog JIT memory.
15236 for (i = 0; i < prog->aux->size_poke_tab; i++) {
15237 map_ptr = prog->aux->poke_tab[i].tail_call.map;
15238 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
15240 /* At this point we're guaranteed that poke descriptors are not
15241 * live anymore. We can just unlink its descriptor table as it's
15242 * released with the main prog.
15244 for (i = 0; i < env->subprog_cnt; i++) {
15247 func[i]->aux->poke_tab = NULL;
15248 bpf_jit_free(func[i]);
15252 /* cleanup main prog to be interpreted */
15253 prog->jit_requested = 0;
15254 prog->blinding_requested = 0;
15255 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15256 if (!bpf_pseudo_call(insn))
15259 insn->imm = env->insn_aux_data[i].call_imm;
15261 bpf_prog_jit_attempt_done(prog);
15265 static int fixup_call_args(struct bpf_verifier_env *env)
15267 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15268 struct bpf_prog *prog = env->prog;
15269 struct bpf_insn *insn = prog->insnsi;
15270 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
15275 if (env->prog->jit_requested &&
15276 !bpf_prog_is_dev_bound(env->prog->aux)) {
15277 err = jit_subprogs(env);
15280 if (err == -EFAULT)
15283 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15284 if (has_kfunc_call) {
15285 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
15288 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
15289 /* When JIT fails the progs with bpf2bpf calls and tail_calls
15290 * have to be rejected, since interpreter doesn't support them yet.
15292 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
15295 for (i = 0; i < prog->len; i++, insn++) {
15296 if (bpf_pseudo_func(insn)) {
15297 /* When JIT fails the progs with callback calls
15298 * have to be rejected, since interpreter doesn't support them yet.
15300 verbose(env, "callbacks are not allowed in non-JITed programs\n");
15304 if (!bpf_pseudo_call(insn))
15306 depth = get_callee_stack_depth(env, insn, i);
15309 bpf_patch_call_args(insn, depth);
15316 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
15317 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
15319 const struct bpf_kfunc_desc *desc;
15322 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
15326 /* insn->imm has the btf func_id. Replace it with
15327 * an address (relative to __bpf_base_call).
15329 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
15331 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
15337 insn->imm = desc->imm;
15340 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
15341 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15342 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15343 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
15345 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
15346 insn_buf[1] = addr[0];
15347 insn_buf[2] = addr[1];
15348 insn_buf[3] = *insn;
15350 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
15351 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15352 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15354 insn_buf[0] = addr[0];
15355 insn_buf[1] = addr[1];
15356 insn_buf[2] = *insn;
15358 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
15359 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
15360 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
15366 /* Do various post-verification rewrites in a single program pass.
15367 * These rewrites simplify JIT and interpreter implementations.
15369 static int do_misc_fixups(struct bpf_verifier_env *env)
15371 struct bpf_prog *prog = env->prog;
15372 enum bpf_attach_type eatype = prog->expected_attach_type;
15373 enum bpf_prog_type prog_type = resolve_prog_type(prog);
15374 struct bpf_insn *insn = prog->insnsi;
15375 const struct bpf_func_proto *fn;
15376 const int insn_cnt = prog->len;
15377 const struct bpf_map_ops *ops;
15378 struct bpf_insn_aux_data *aux;
15379 struct bpf_insn insn_buf[16];
15380 struct bpf_prog *new_prog;
15381 struct bpf_map *map_ptr;
15382 int i, ret, cnt, delta = 0;
15384 for (i = 0; i < insn_cnt; i++, insn++) {
15385 /* Make divide-by-zero exceptions impossible. */
15386 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
15387 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
15388 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
15389 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
15390 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
15391 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
15392 struct bpf_insn *patchlet;
15393 struct bpf_insn chk_and_div[] = {
15394 /* [R,W]x div 0 -> 0 */
15395 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15396 BPF_JNE | BPF_K, insn->src_reg,
15398 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
15399 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15402 struct bpf_insn chk_and_mod[] = {
15403 /* [R,W]x mod 0 -> [R,W]x */
15404 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15405 BPF_JEQ | BPF_K, insn->src_reg,
15406 0, 1 + (is64 ? 0 : 1), 0),
15408 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15409 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
15412 patchlet = isdiv ? chk_and_div : chk_and_mod;
15413 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
15414 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
15416 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
15421 env->prog = prog = new_prog;
15422 insn = new_prog->insnsi + i + delta;
15426 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
15427 if (BPF_CLASS(insn->code) == BPF_LD &&
15428 (BPF_MODE(insn->code) == BPF_ABS ||
15429 BPF_MODE(insn->code) == BPF_IND)) {
15430 cnt = env->ops->gen_ld_abs(insn, insn_buf);
15431 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15432 verbose(env, "bpf verifier is misconfigured\n");
15436 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15441 env->prog = prog = new_prog;
15442 insn = new_prog->insnsi + i + delta;
15446 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
15447 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
15448 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
15449 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
15450 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
15451 struct bpf_insn *patch = &insn_buf[0];
15452 bool issrc, isneg, isimm;
15455 aux = &env->insn_aux_data[i + delta];
15456 if (!aux->alu_state ||
15457 aux->alu_state == BPF_ALU_NON_POINTER)
15460 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
15461 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
15462 BPF_ALU_SANITIZE_SRC;
15463 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
15465 off_reg = issrc ? insn->src_reg : insn->dst_reg;
15467 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15470 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15471 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15472 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
15473 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
15474 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
15475 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
15476 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
15479 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
15480 insn->src_reg = BPF_REG_AX;
15482 insn->code = insn->code == code_add ?
15483 code_sub : code_add;
15485 if (issrc && isneg && !isimm)
15486 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15487 cnt = patch - insn_buf;
15489 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15494 env->prog = prog = new_prog;
15495 insn = new_prog->insnsi + i + delta;
15499 if (insn->code != (BPF_JMP | BPF_CALL))
15501 if (insn->src_reg == BPF_PSEUDO_CALL)
15503 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15504 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
15510 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15515 env->prog = prog = new_prog;
15516 insn = new_prog->insnsi + i + delta;
15520 if (insn->imm == BPF_FUNC_get_route_realm)
15521 prog->dst_needed = 1;
15522 if (insn->imm == BPF_FUNC_get_prandom_u32)
15523 bpf_user_rnd_init_once();
15524 if (insn->imm == BPF_FUNC_override_return)
15525 prog->kprobe_override = 1;
15526 if (insn->imm == BPF_FUNC_tail_call) {
15527 /* If we tail call into other programs, we
15528 * cannot make any assumptions since they can
15529 * be replaced dynamically during runtime in
15530 * the program array.
15532 prog->cb_access = 1;
15533 if (!allow_tail_call_in_subprogs(env))
15534 prog->aux->stack_depth = MAX_BPF_STACK;
15535 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
15537 /* mark bpf_tail_call as different opcode to avoid
15538 * conditional branch in the interpreter for every normal
15539 * call and to prevent accidental JITing by JIT compiler
15540 * that doesn't support bpf_tail_call yet
15543 insn->code = BPF_JMP | BPF_TAIL_CALL;
15545 aux = &env->insn_aux_data[i + delta];
15546 if (env->bpf_capable && !prog->blinding_requested &&
15547 prog->jit_requested &&
15548 !bpf_map_key_poisoned(aux) &&
15549 !bpf_map_ptr_poisoned(aux) &&
15550 !bpf_map_ptr_unpriv(aux)) {
15551 struct bpf_jit_poke_descriptor desc = {
15552 .reason = BPF_POKE_REASON_TAIL_CALL,
15553 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
15554 .tail_call.key = bpf_map_key_immediate(aux),
15555 .insn_idx = i + delta,
15558 ret = bpf_jit_add_poke_descriptor(prog, &desc);
15560 verbose(env, "adding tail call poke descriptor failed\n");
15564 insn->imm = ret + 1;
15568 if (!bpf_map_ptr_unpriv(aux))
15571 /* instead of changing every JIT dealing with tail_call
15572 * emit two extra insns:
15573 * if (index >= max_entries) goto out;
15574 * index &= array->index_mask;
15575 * to avoid out-of-bounds cpu speculation
15577 if (bpf_map_ptr_poisoned(aux)) {
15578 verbose(env, "tail_call abusing map_ptr\n");
15582 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15583 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
15584 map_ptr->max_entries, 2);
15585 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
15586 container_of(map_ptr,
15589 insn_buf[2] = *insn;
15591 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15596 env->prog = prog = new_prog;
15597 insn = new_prog->insnsi + i + delta;
15601 if (insn->imm == BPF_FUNC_timer_set_callback) {
15602 /* The verifier will process callback_fn as many times as necessary
15603 * with different maps and the register states prepared by
15604 * set_timer_callback_state will be accurate.
15606 * The following use case is valid:
15607 * map1 is shared by prog1, prog2, prog3.
15608 * prog1 calls bpf_timer_init for some map1 elements
15609 * prog2 calls bpf_timer_set_callback for some map1 elements.
15610 * Those that were not bpf_timer_init-ed will return -EINVAL.
15611 * prog3 calls bpf_timer_start for some map1 elements.
15612 * Those that were not both bpf_timer_init-ed and
15613 * bpf_timer_set_callback-ed will return -EINVAL.
15615 struct bpf_insn ld_addrs[2] = {
15616 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
15619 insn_buf[0] = ld_addrs[0];
15620 insn_buf[1] = ld_addrs[1];
15621 insn_buf[2] = *insn;
15624 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15629 env->prog = prog = new_prog;
15630 insn = new_prog->insnsi + i + delta;
15631 goto patch_call_imm;
15634 if (is_storage_get_function(insn->imm)) {
15635 if (!env->prog->aux->sleepable ||
15636 env->insn_aux_data[i + delta].storage_get_func_atomic)
15637 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
15639 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
15640 insn_buf[1] = *insn;
15643 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15648 env->prog = prog = new_prog;
15649 insn = new_prog->insnsi + i + delta;
15650 goto patch_call_imm;
15653 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
15654 * and other inlining handlers are currently limited to 64 bit
15657 if (prog->jit_requested && BITS_PER_LONG == 64 &&
15658 (insn->imm == BPF_FUNC_map_lookup_elem ||
15659 insn->imm == BPF_FUNC_map_update_elem ||
15660 insn->imm == BPF_FUNC_map_delete_elem ||
15661 insn->imm == BPF_FUNC_map_push_elem ||
15662 insn->imm == BPF_FUNC_map_pop_elem ||
15663 insn->imm == BPF_FUNC_map_peek_elem ||
15664 insn->imm == BPF_FUNC_redirect_map ||
15665 insn->imm == BPF_FUNC_for_each_map_elem ||
15666 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
15667 aux = &env->insn_aux_data[i + delta];
15668 if (bpf_map_ptr_poisoned(aux))
15669 goto patch_call_imm;
15671 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15672 ops = map_ptr->ops;
15673 if (insn->imm == BPF_FUNC_map_lookup_elem &&
15674 ops->map_gen_lookup) {
15675 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
15676 if (cnt == -EOPNOTSUPP)
15677 goto patch_map_ops_generic;
15678 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15679 verbose(env, "bpf verifier is misconfigured\n");
15683 new_prog = bpf_patch_insn_data(env, i + delta,
15689 env->prog = prog = new_prog;
15690 insn = new_prog->insnsi + i + delta;
15694 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
15695 (void *(*)(struct bpf_map *map, void *key))NULL));
15696 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
15697 (int (*)(struct bpf_map *map, void *key))NULL));
15698 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
15699 (int (*)(struct bpf_map *map, void *key, void *value,
15701 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
15702 (int (*)(struct bpf_map *map, void *value,
15704 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
15705 (int (*)(struct bpf_map *map, void *value))NULL));
15706 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
15707 (int (*)(struct bpf_map *map, void *value))NULL));
15708 BUILD_BUG_ON(!__same_type(ops->map_redirect,
15709 (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
15710 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
15711 (int (*)(struct bpf_map *map,
15712 bpf_callback_t callback_fn,
15713 void *callback_ctx,
15715 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
15716 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
15718 patch_map_ops_generic:
15719 switch (insn->imm) {
15720 case BPF_FUNC_map_lookup_elem:
15721 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
15723 case BPF_FUNC_map_update_elem:
15724 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
15726 case BPF_FUNC_map_delete_elem:
15727 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
15729 case BPF_FUNC_map_push_elem:
15730 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
15732 case BPF_FUNC_map_pop_elem:
15733 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
15735 case BPF_FUNC_map_peek_elem:
15736 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
15738 case BPF_FUNC_redirect_map:
15739 insn->imm = BPF_CALL_IMM(ops->map_redirect);
15741 case BPF_FUNC_for_each_map_elem:
15742 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
15744 case BPF_FUNC_map_lookup_percpu_elem:
15745 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
15749 goto patch_call_imm;
15752 /* Implement bpf_jiffies64 inline. */
15753 if (prog->jit_requested && BITS_PER_LONG == 64 &&
15754 insn->imm == BPF_FUNC_jiffies64) {
15755 struct bpf_insn ld_jiffies_addr[2] = {
15756 BPF_LD_IMM64(BPF_REG_0,
15757 (unsigned long)&jiffies),
15760 insn_buf[0] = ld_jiffies_addr[0];
15761 insn_buf[1] = ld_jiffies_addr[1];
15762 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
15766 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
15772 env->prog = prog = new_prog;
15773 insn = new_prog->insnsi + i + delta;
15777 /* Implement bpf_get_func_arg inline. */
15778 if (prog_type == BPF_PROG_TYPE_TRACING &&
15779 insn->imm == BPF_FUNC_get_func_arg) {
15780 /* Load nr_args from ctx - 8 */
15781 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15782 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
15783 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
15784 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
15785 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
15786 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15787 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
15788 insn_buf[7] = BPF_JMP_A(1);
15789 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
15792 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15797 env->prog = prog = new_prog;
15798 insn = new_prog->insnsi + i + delta;
15802 /* Implement bpf_get_func_ret inline. */
15803 if (prog_type == BPF_PROG_TYPE_TRACING &&
15804 insn->imm == BPF_FUNC_get_func_ret) {
15805 if (eatype == BPF_TRACE_FEXIT ||
15806 eatype == BPF_MODIFY_RETURN) {
15807 /* Load nr_args from ctx - 8 */
15808 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15809 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
15810 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
15811 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15812 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
15813 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
15816 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
15820 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15825 env->prog = prog = new_prog;
15826 insn = new_prog->insnsi + i + delta;
15830 /* Implement get_func_arg_cnt inline. */
15831 if (prog_type == BPF_PROG_TYPE_TRACING &&
15832 insn->imm == BPF_FUNC_get_func_arg_cnt) {
15833 /* Load nr_args from ctx - 8 */
15834 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15836 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
15840 env->prog = prog = new_prog;
15841 insn = new_prog->insnsi + i + delta;
15845 /* Implement bpf_get_func_ip inline. */
15846 if (prog_type == BPF_PROG_TYPE_TRACING &&
15847 insn->imm == BPF_FUNC_get_func_ip) {
15848 /* Load IP address from ctx - 16 */
15849 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
15851 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
15855 env->prog = prog = new_prog;
15856 insn = new_prog->insnsi + i + delta;
15861 fn = env->ops->get_func_proto(insn->imm, env->prog);
15862 /* all functions that have prototype and verifier allowed
15863 * programs to call them, must be real in-kernel functions
15867 "kernel subsystem misconfigured func %s#%d\n",
15868 func_id_name(insn->imm), insn->imm);
15871 insn->imm = fn->func - __bpf_call_base;
15874 /* Since poke tab is now finalized, publish aux to tracker. */
15875 for (i = 0; i < prog->aux->size_poke_tab; i++) {
15876 map_ptr = prog->aux->poke_tab[i].tail_call.map;
15877 if (!map_ptr->ops->map_poke_track ||
15878 !map_ptr->ops->map_poke_untrack ||
15879 !map_ptr->ops->map_poke_run) {
15880 verbose(env, "bpf verifier is misconfigured\n");
15884 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
15886 verbose(env, "tracking tail call prog failed\n");
15891 sort_kfunc_descs_by_imm(env->prog);
15896 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
15899 u32 callback_subprogno,
15902 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
15903 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
15904 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
15905 int reg_loop_max = BPF_REG_6;
15906 int reg_loop_cnt = BPF_REG_7;
15907 int reg_loop_ctx = BPF_REG_8;
15909 struct bpf_prog *new_prog;
15910 u32 callback_start;
15911 u32 call_insn_offset;
15912 s32 callback_offset;
15914 /* This represents an inlined version of bpf_iter.c:bpf_loop,
15915 * be careful to modify this code in sync.
15917 struct bpf_insn insn_buf[] = {
15918 /* Return error and jump to the end of the patch if
15919 * expected number of iterations is too big.
15921 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
15922 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
15923 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
15924 /* spill R6, R7, R8 to use these as loop vars */
15925 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
15926 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
15927 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
15928 /* initialize loop vars */
15929 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
15930 BPF_MOV32_IMM(reg_loop_cnt, 0),
15931 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
15933 * if reg_loop_cnt >= reg_loop_max skip the loop body
15935 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
15937 * correct callback offset would be set after patching
15939 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
15940 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
15942 /* increment loop counter */
15943 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
15944 /* jump to loop header if callback returned 0 */
15945 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
15946 /* return value of bpf_loop,
15947 * set R0 to the number of iterations
15949 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
15950 /* restore original values of R6, R7, R8 */
15951 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
15952 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
15953 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
15956 *cnt = ARRAY_SIZE(insn_buf);
15957 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
15961 /* callback start is known only after patching */
15962 callback_start = env->subprog_info[callback_subprogno].start;
15963 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
15964 call_insn_offset = position + 12;
15965 callback_offset = callback_start - call_insn_offset - 1;
15966 new_prog->insnsi[call_insn_offset].imm = callback_offset;
15971 static bool is_bpf_loop_call(struct bpf_insn *insn)
15973 return insn->code == (BPF_JMP | BPF_CALL) &&
15974 insn->src_reg == 0 &&
15975 insn->imm == BPF_FUNC_loop;
15978 /* For all sub-programs in the program (including main) check
15979 * insn_aux_data to see if there are bpf_loop calls that require
15980 * inlining. If such calls are found the calls are replaced with a
15981 * sequence of instructions produced by `inline_bpf_loop` function and
15982 * subprog stack_depth is increased by the size of 3 registers.
15983 * This stack space is used to spill values of the R6, R7, R8. These
15984 * registers are used to store the loop bound, counter and context
15987 static int optimize_bpf_loop(struct bpf_verifier_env *env)
15989 struct bpf_subprog_info *subprogs = env->subprog_info;
15990 int i, cur_subprog = 0, cnt, delta = 0;
15991 struct bpf_insn *insn = env->prog->insnsi;
15992 int insn_cnt = env->prog->len;
15993 u16 stack_depth = subprogs[cur_subprog].stack_depth;
15994 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
15995 u16 stack_depth_extra = 0;
15997 for (i = 0; i < insn_cnt; i++, insn++) {
15998 struct bpf_loop_inline_state *inline_state =
15999 &env->insn_aux_data[i + delta].loop_inline_state;
16001 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
16002 struct bpf_prog *new_prog;
16004 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
16005 new_prog = inline_bpf_loop(env,
16007 -(stack_depth + stack_depth_extra),
16008 inline_state->callback_subprogno,
16014 env->prog = new_prog;
16015 insn = new_prog->insnsi + i + delta;
16018 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
16019 subprogs[cur_subprog].stack_depth += stack_depth_extra;
16021 stack_depth = subprogs[cur_subprog].stack_depth;
16022 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16023 stack_depth_extra = 0;
16027 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16032 static void free_states(struct bpf_verifier_env *env)
16034 struct bpf_verifier_state_list *sl, *sln;
16037 sl = env->free_list;
16040 free_verifier_state(&sl->state, false);
16044 env->free_list = NULL;
16046 if (!env->explored_states)
16049 for (i = 0; i < state_htab_size(env); i++) {
16050 sl = env->explored_states[i];
16054 free_verifier_state(&sl->state, false);
16058 env->explored_states[i] = NULL;
16062 static int do_check_common(struct bpf_verifier_env *env, int subprog)
16064 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16065 struct bpf_verifier_state *state;
16066 struct bpf_reg_state *regs;
16069 env->prev_linfo = NULL;
16072 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
16075 state->curframe = 0;
16076 state->speculative = false;
16077 state->branches = 1;
16078 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
16079 if (!state->frame[0]) {
16083 env->cur_state = state;
16084 init_func_state(env, state->frame[0],
16085 BPF_MAIN_FUNC /* callsite */,
16088 state->first_insn_idx = env->subprog_info[subprog].start;
16089 state->last_insn_idx = -1;
16091 regs = state->frame[state->curframe]->regs;
16092 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
16093 ret = btf_prepare_func_args(env, subprog, regs);
16096 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
16097 if (regs[i].type == PTR_TO_CTX)
16098 mark_reg_known_zero(env, regs, i);
16099 else if (regs[i].type == SCALAR_VALUE)
16100 mark_reg_unknown(env, regs, i);
16101 else if (base_type(regs[i].type) == PTR_TO_MEM) {
16102 const u32 mem_size = regs[i].mem_size;
16104 mark_reg_known_zero(env, regs, i);
16105 regs[i].mem_size = mem_size;
16106 regs[i].id = ++env->id_gen;
16110 /* 1st arg to a function */
16111 regs[BPF_REG_1].type = PTR_TO_CTX;
16112 mark_reg_known_zero(env, regs, BPF_REG_1);
16113 ret = btf_check_subprog_arg_match(env, subprog, regs);
16114 if (ret == -EFAULT)
16115 /* unlikely verifier bug. abort.
16116 * ret == 0 and ret < 0 are sadly acceptable for
16117 * main() function due to backward compatibility.
16118 * Like socket filter program may be written as:
16119 * int bpf_prog(struct pt_regs *ctx)
16120 * and never dereference that ctx in the program.
16121 * 'struct pt_regs' is a type mismatch for socket
16122 * filter that should be using 'struct __sk_buff'.
16127 ret = do_check(env);
16129 /* check for NULL is necessary, since cur_state can be freed inside
16130 * do_check() under memory pressure.
16132 if (env->cur_state) {
16133 free_verifier_state(env->cur_state, true);
16134 env->cur_state = NULL;
16136 while (!pop_stack(env, NULL, NULL, false));
16137 if (!ret && pop_log)
16138 bpf_vlog_reset(&env->log, 0);
16143 /* Verify all global functions in a BPF program one by one based on their BTF.
16144 * All global functions must pass verification. Otherwise the whole program is rejected.
16155 * foo() will be verified first for R1=any_scalar_value. During verification it
16156 * will be assumed that bar() already verified successfully and call to bar()
16157 * from foo() will be checked for type match only. Later bar() will be verified
16158 * independently to check that it's safe for R1=any_scalar_value.
16160 static int do_check_subprogs(struct bpf_verifier_env *env)
16162 struct bpf_prog_aux *aux = env->prog->aux;
16165 if (!aux->func_info)
16168 for (i = 1; i < env->subprog_cnt; i++) {
16169 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
16171 env->insn_idx = env->subprog_info[i].start;
16172 WARN_ON_ONCE(env->insn_idx == 0);
16173 ret = do_check_common(env, i);
16176 } else if (env->log.level & BPF_LOG_LEVEL) {
16178 "Func#%d is safe for any args that match its prototype\n",
16185 static int do_check_main(struct bpf_verifier_env *env)
16190 ret = do_check_common(env, 0);
16192 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16197 static void print_verification_stats(struct bpf_verifier_env *env)
16201 if (env->log.level & BPF_LOG_STATS) {
16202 verbose(env, "verification time %lld usec\n",
16203 div_u64(env->verification_time, 1000));
16204 verbose(env, "stack depth ");
16205 for (i = 0; i < env->subprog_cnt; i++) {
16206 u32 depth = env->subprog_info[i].stack_depth;
16208 verbose(env, "%d", depth);
16209 if (i + 1 < env->subprog_cnt)
16212 verbose(env, "\n");
16214 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
16215 "total_states %d peak_states %d mark_read %d\n",
16216 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
16217 env->max_states_per_insn, env->total_states,
16218 env->peak_states, env->longest_mark_read_walk);
16221 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
16223 const struct btf_type *t, *func_proto;
16224 const struct bpf_struct_ops *st_ops;
16225 const struct btf_member *member;
16226 struct bpf_prog *prog = env->prog;
16227 u32 btf_id, member_idx;
16230 if (!prog->gpl_compatible) {
16231 verbose(env, "struct ops programs must have a GPL compatible license\n");
16235 btf_id = prog->aux->attach_btf_id;
16236 st_ops = bpf_struct_ops_find(btf_id);
16238 verbose(env, "attach_btf_id %u is not a supported struct\n",
16244 member_idx = prog->expected_attach_type;
16245 if (member_idx >= btf_type_vlen(t)) {
16246 verbose(env, "attach to invalid member idx %u of struct %s\n",
16247 member_idx, st_ops->name);
16251 member = &btf_type_member(t)[member_idx];
16252 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
16253 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
16256 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
16257 mname, member_idx, st_ops->name);
16261 if (st_ops->check_member) {
16262 int err = st_ops->check_member(t, member);
16265 verbose(env, "attach to unsupported member %s of struct %s\n",
16266 mname, st_ops->name);
16271 prog->aux->attach_func_proto = func_proto;
16272 prog->aux->attach_func_name = mname;
16273 env->ops = st_ops->verifier_ops;
16277 #define SECURITY_PREFIX "security_"
16279 static int check_attach_modify_return(unsigned long addr, const char *func_name)
16281 if (within_error_injection_list(addr) ||
16282 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
16288 /* list of non-sleepable functions that are otherwise on
16289 * ALLOW_ERROR_INJECTION list
16291 BTF_SET_START(btf_non_sleepable_error_inject)
16292 /* Three functions below can be called from sleepable and non-sleepable context.
16293 * Assume non-sleepable from bpf safety point of view.
16295 BTF_ID(func, __filemap_add_folio)
16296 BTF_ID(func, should_fail_alloc_page)
16297 BTF_ID(func, should_failslab)
16298 BTF_SET_END(btf_non_sleepable_error_inject)
16300 static int check_non_sleepable_error_inject(u32 btf_id)
16302 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
16305 int bpf_check_attach_target(struct bpf_verifier_log *log,
16306 const struct bpf_prog *prog,
16307 const struct bpf_prog *tgt_prog,
16309 struct bpf_attach_target_info *tgt_info)
16311 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
16312 const char prefix[] = "btf_trace_";
16313 int ret = 0, subprog = -1, i;
16314 const struct btf_type *t;
16315 bool conservative = true;
16321 bpf_log(log, "Tracing programs must provide btf_id\n");
16324 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
16327 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
16330 t = btf_type_by_id(btf, btf_id);
16332 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
16335 tname = btf_name_by_offset(btf, t->name_off);
16337 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
16341 struct bpf_prog_aux *aux = tgt_prog->aux;
16343 for (i = 0; i < aux->func_info_cnt; i++)
16344 if (aux->func_info[i].type_id == btf_id) {
16348 if (subprog == -1) {
16349 bpf_log(log, "Subprog %s doesn't exist\n", tname);
16352 conservative = aux->func_info_aux[subprog].unreliable;
16353 if (prog_extension) {
16354 if (conservative) {
16356 "Cannot replace static functions\n");
16359 if (!prog->jit_requested) {
16361 "Extension programs should be JITed\n");
16365 if (!tgt_prog->jited) {
16366 bpf_log(log, "Can attach to only JITed progs\n");
16369 if (tgt_prog->type == prog->type) {
16370 /* Cannot fentry/fexit another fentry/fexit program.
16371 * Cannot attach program extension to another extension.
16372 * It's ok to attach fentry/fexit to extension program.
16374 bpf_log(log, "Cannot recursively attach\n");
16377 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
16379 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
16380 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
16381 /* Program extensions can extend all program types
16382 * except fentry/fexit. The reason is the following.
16383 * The fentry/fexit programs are used for performance
16384 * analysis, stats and can be attached to any program
16385 * type except themselves. When extension program is
16386 * replacing XDP function it is necessary to allow
16387 * performance analysis of all functions. Both original
16388 * XDP program and its program extension. Hence
16389 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
16390 * allowed. If extending of fentry/fexit was allowed it
16391 * would be possible to create long call chain
16392 * fentry->extension->fentry->extension beyond
16393 * reasonable stack size. Hence extending fentry is not
16396 bpf_log(log, "Cannot extend fentry/fexit\n");
16400 if (prog_extension) {
16401 bpf_log(log, "Cannot replace kernel functions\n");
16406 switch (prog->expected_attach_type) {
16407 case BPF_TRACE_RAW_TP:
16410 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
16413 if (!btf_type_is_typedef(t)) {
16414 bpf_log(log, "attach_btf_id %u is not a typedef\n",
16418 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
16419 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
16423 tname += sizeof(prefix) - 1;
16424 t = btf_type_by_id(btf, t->type);
16425 if (!btf_type_is_ptr(t))
16426 /* should never happen in valid vmlinux build */
16428 t = btf_type_by_id(btf, t->type);
16429 if (!btf_type_is_func_proto(t))
16430 /* should never happen in valid vmlinux build */
16434 case BPF_TRACE_ITER:
16435 if (!btf_type_is_func(t)) {
16436 bpf_log(log, "attach_btf_id %u is not a function\n",
16440 t = btf_type_by_id(btf, t->type);
16441 if (!btf_type_is_func_proto(t))
16443 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16448 if (!prog_extension)
16451 case BPF_MODIFY_RETURN:
16453 case BPF_LSM_CGROUP:
16454 case BPF_TRACE_FENTRY:
16455 case BPF_TRACE_FEXIT:
16456 if (!btf_type_is_func(t)) {
16457 bpf_log(log, "attach_btf_id %u is not a function\n",
16461 if (prog_extension &&
16462 btf_check_type_match(log, prog, btf, t))
16464 t = btf_type_by_id(btf, t->type);
16465 if (!btf_type_is_func_proto(t))
16468 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
16469 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
16470 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
16473 if (tgt_prog && conservative)
16476 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16482 addr = (long) tgt_prog->bpf_func;
16484 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
16486 addr = kallsyms_lookup_name(tname);
16489 "The address of function %s cannot be found\n",
16495 if (prog->aux->sleepable) {
16497 switch (prog->type) {
16498 case BPF_PROG_TYPE_TRACING:
16499 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
16500 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
16502 if (!check_non_sleepable_error_inject(btf_id) &&
16503 within_error_injection_list(addr))
16506 case BPF_PROG_TYPE_LSM:
16507 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
16508 * Only some of them are sleepable.
16510 if (bpf_lsm_is_sleepable_hook(btf_id))
16517 bpf_log(log, "%s is not sleepable\n", tname);
16520 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
16522 bpf_log(log, "can't modify return codes of BPF programs\n");
16525 ret = check_attach_modify_return(addr, tname);
16527 bpf_log(log, "%s() is not modifiable\n", tname);
16534 tgt_info->tgt_addr = addr;
16535 tgt_info->tgt_name = tname;
16536 tgt_info->tgt_type = t;
16540 BTF_SET_START(btf_id_deny)
16543 BTF_ID(func, migrate_disable)
16544 BTF_ID(func, migrate_enable)
16546 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
16547 BTF_ID(func, rcu_read_unlock_strict)
16549 BTF_SET_END(btf_id_deny)
16551 static int check_attach_btf_id(struct bpf_verifier_env *env)
16553 struct bpf_prog *prog = env->prog;
16554 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
16555 struct bpf_attach_target_info tgt_info = {};
16556 u32 btf_id = prog->aux->attach_btf_id;
16557 struct bpf_trampoline *tr;
16561 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
16562 if (prog->aux->sleepable)
16563 /* attach_btf_id checked to be zero already */
16565 verbose(env, "Syscall programs can only be sleepable\n");
16569 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
16570 prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
16571 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
16575 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
16576 return check_struct_ops_btf_id(env);
16578 if (prog->type != BPF_PROG_TYPE_TRACING &&
16579 prog->type != BPF_PROG_TYPE_LSM &&
16580 prog->type != BPF_PROG_TYPE_EXT)
16583 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
16587 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
16588 /* to make freplace equivalent to their targets, they need to
16589 * inherit env->ops and expected_attach_type for the rest of the
16592 env->ops = bpf_verifier_ops[tgt_prog->type];
16593 prog->expected_attach_type = tgt_prog->expected_attach_type;
16596 /* store info about the attachment target that will be used later */
16597 prog->aux->attach_func_proto = tgt_info.tgt_type;
16598 prog->aux->attach_func_name = tgt_info.tgt_name;
16601 prog->aux->saved_dst_prog_type = tgt_prog->type;
16602 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
16605 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
16606 prog->aux->attach_btf_trace = true;
16608 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
16609 if (!bpf_iter_prog_supported(prog))
16614 if (prog->type == BPF_PROG_TYPE_LSM) {
16615 ret = bpf_lsm_verify_prog(&env->log, prog);
16618 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
16619 btf_id_set_contains(&btf_id_deny, btf_id)) {
16623 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
16624 tr = bpf_trampoline_get(key, &tgt_info);
16628 prog->aux->dst_trampoline = tr;
16632 struct btf *bpf_get_btf_vmlinux(void)
16634 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
16635 mutex_lock(&bpf_verifier_lock);
16637 btf_vmlinux = btf_parse_vmlinux();
16638 mutex_unlock(&bpf_verifier_lock);
16640 return btf_vmlinux;
16643 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
16645 u64 start_time = ktime_get_ns();
16646 struct bpf_verifier_env *env;
16647 struct bpf_verifier_log *log;
16648 int i, len, ret = -EINVAL;
16651 /* no program is valid */
16652 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
16655 /* 'struct bpf_verifier_env' can be global, but since it's not small,
16656 * allocate/free it every time bpf_check() is called
16658 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
16663 len = (*prog)->len;
16664 env->insn_aux_data =
16665 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
16667 if (!env->insn_aux_data)
16669 for (i = 0; i < len; i++)
16670 env->insn_aux_data[i].orig_idx = i;
16672 env->ops = bpf_verifier_ops[env->prog->type];
16673 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
16674 is_priv = bpf_capable();
16676 bpf_get_btf_vmlinux();
16678 /* grab the mutex to protect few globals used by verifier */
16680 mutex_lock(&bpf_verifier_lock);
16682 if (attr->log_level || attr->log_buf || attr->log_size) {
16683 /* user requested verbose verifier output
16684 * and supplied buffer to store the verification trace
16686 log->level = attr->log_level;
16687 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
16688 log->len_total = attr->log_size;
16690 /* log attributes have to be sane */
16691 if (!bpf_verifier_log_attr_valid(log)) {
16697 mark_verifier_state_clean(env);
16699 if (IS_ERR(btf_vmlinux)) {
16700 /* Either gcc or pahole or kernel are broken. */
16701 verbose(env, "in-kernel BTF is malformed\n");
16702 ret = PTR_ERR(btf_vmlinux);
16703 goto skip_full_check;
16706 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
16707 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
16708 env->strict_alignment = true;
16709 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
16710 env->strict_alignment = false;
16712 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
16713 env->allow_uninit_stack = bpf_allow_uninit_stack();
16714 env->bypass_spec_v1 = bpf_bypass_spec_v1();
16715 env->bypass_spec_v4 = bpf_bypass_spec_v4();
16716 env->bpf_capable = bpf_capable();
16717 env->rcu_tag_supported = btf_vmlinux &&
16718 btf_find_by_name_kind(btf_vmlinux, "rcu", BTF_KIND_TYPE_TAG) > 0;
16721 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
16723 env->explored_states = kvcalloc(state_htab_size(env),
16724 sizeof(struct bpf_verifier_state_list *),
16727 if (!env->explored_states)
16728 goto skip_full_check;
16730 ret = add_subprog_and_kfunc(env);
16732 goto skip_full_check;
16734 ret = check_subprogs(env);
16736 goto skip_full_check;
16738 ret = check_btf_info(env, attr, uattr);
16740 goto skip_full_check;
16742 ret = check_attach_btf_id(env);
16744 goto skip_full_check;
16746 ret = resolve_pseudo_ldimm64(env);
16748 goto skip_full_check;
16750 if (bpf_prog_is_dev_bound(env->prog->aux)) {
16751 ret = bpf_prog_offload_verifier_prep(env->prog);
16753 goto skip_full_check;
16756 ret = check_cfg(env);
16758 goto skip_full_check;
16760 ret = do_check_subprogs(env);
16761 ret = ret ?: do_check_main(env);
16763 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
16764 ret = bpf_prog_offload_finalize(env);
16767 kvfree(env->explored_states);
16770 ret = check_max_stack_depth(env);
16772 /* instruction rewrites happen after this point */
16774 ret = optimize_bpf_loop(env);
16778 opt_hard_wire_dead_code_branches(env);
16780 ret = opt_remove_dead_code(env);
16782 ret = opt_remove_nops(env);
16785 sanitize_dead_code(env);
16789 /* program is valid, convert *(u32*)(ctx + off) accesses */
16790 ret = convert_ctx_accesses(env);
16793 ret = do_misc_fixups(env);
16795 /* do 32-bit optimization after insn patching has done so those patched
16796 * insns could be handled correctly.
16798 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
16799 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
16800 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
16805 ret = fixup_call_args(env);
16807 env->verification_time = ktime_get_ns() - start_time;
16808 print_verification_stats(env);
16809 env->prog->aux->verified_insns = env->insn_processed;
16811 if (log->level && bpf_verifier_log_full(log))
16813 if (log->level && !log->ubuf) {
16815 goto err_release_maps;
16819 goto err_release_maps;
16821 if (env->used_map_cnt) {
16822 /* if program passed verifier, update used_maps in bpf_prog_info */
16823 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
16824 sizeof(env->used_maps[0]),
16827 if (!env->prog->aux->used_maps) {
16829 goto err_release_maps;
16832 memcpy(env->prog->aux->used_maps, env->used_maps,
16833 sizeof(env->used_maps[0]) * env->used_map_cnt);
16834 env->prog->aux->used_map_cnt = env->used_map_cnt;
16836 if (env->used_btf_cnt) {
16837 /* if program passed verifier, update used_btfs in bpf_prog_aux */
16838 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
16839 sizeof(env->used_btfs[0]),
16841 if (!env->prog->aux->used_btfs) {
16843 goto err_release_maps;
16846 memcpy(env->prog->aux->used_btfs, env->used_btfs,
16847 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
16848 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
16850 if (env->used_map_cnt || env->used_btf_cnt) {
16851 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
16852 * bpf_ld_imm64 instructions
16854 convert_pseudo_ld_imm64(env);
16857 adjust_btf_func(env);
16860 if (!env->prog->aux->used_maps)
16861 /* if we didn't copy map pointers into bpf_prog_info, release
16862 * them now. Otherwise free_used_maps() will release them.
16865 if (!env->prog->aux->used_btfs)
16868 /* extension progs temporarily inherit the attach_type of their targets
16869 for verification purposes, so set it back to zero before returning
16871 if (env->prog->type == BPF_PROG_TYPE_EXT)
16872 env->prog->expected_attach_type = 0;
16877 mutex_unlock(&bpf_verifier_lock);
16878 vfree(env->insn_aux_data);