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);
193 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
194 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
195 static int ref_set_non_owning(struct bpf_verifier_env *env,
196 struct bpf_reg_state *reg);
198 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
200 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
203 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
205 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
208 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
209 const struct bpf_map *map, bool unpriv)
211 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
212 unpriv |= bpf_map_ptr_unpriv(aux);
213 aux->map_ptr_state = (unsigned long)map |
214 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
217 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
219 return aux->map_key_state & BPF_MAP_KEY_POISON;
222 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
224 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
227 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
229 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
232 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
234 bool poisoned = bpf_map_key_poisoned(aux);
236 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
237 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
240 static bool bpf_pseudo_call(const struct bpf_insn *insn)
242 return insn->code == (BPF_JMP | BPF_CALL) &&
243 insn->src_reg == BPF_PSEUDO_CALL;
246 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
248 return insn->code == (BPF_JMP | BPF_CALL) &&
249 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
252 struct bpf_call_arg_meta {
253 struct bpf_map *map_ptr;
270 struct btf_field *kptr_field;
273 struct bpf_kfunc_call_arg_meta {
278 const struct btf_type *func_proto;
279 const char *func_name;
296 struct btf_field *field;
299 struct btf_field *field;
302 enum bpf_dynptr_type type;
304 } initialized_dynptr;
308 struct btf *btf_vmlinux;
310 static DEFINE_MUTEX(bpf_verifier_lock);
312 static const struct bpf_line_info *
313 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
315 const struct bpf_line_info *linfo;
316 const struct bpf_prog *prog;
320 nr_linfo = prog->aux->nr_linfo;
322 if (!nr_linfo || insn_off >= prog->len)
325 linfo = prog->aux->linfo;
326 for (i = 1; i < nr_linfo; i++)
327 if (insn_off < linfo[i].insn_off)
330 return &linfo[i - 1];
333 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
338 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
340 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
341 "verifier log line truncated - local buffer too short\n");
343 if (log->level == BPF_LOG_KERNEL) {
344 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
346 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
350 n = min(log->len_total - log->len_used - 1, n);
352 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
358 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
362 if (!bpf_verifier_log_needed(log))
365 log->len_used = new_pos;
366 if (put_user(zero, log->ubuf + new_pos))
370 /* log_level controls verbosity level of eBPF verifier.
371 * bpf_verifier_log_write() is used to dump the verification trace to the log,
372 * so the user can figure out what's wrong with the program
374 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
375 const char *fmt, ...)
379 if (!bpf_verifier_log_needed(&env->log))
383 bpf_verifier_vlog(&env->log, fmt, args);
386 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
388 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
390 struct bpf_verifier_env *env = private_data;
393 if (!bpf_verifier_log_needed(&env->log))
397 bpf_verifier_vlog(&env->log, fmt, args);
401 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
402 const char *fmt, ...)
406 if (!bpf_verifier_log_needed(log))
410 bpf_verifier_vlog(log, fmt, args);
413 EXPORT_SYMBOL_GPL(bpf_log);
415 static const char *ltrim(const char *s)
423 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
425 const char *prefix_fmt, ...)
427 const struct bpf_line_info *linfo;
429 if (!bpf_verifier_log_needed(&env->log))
432 linfo = find_linfo(env, insn_off);
433 if (!linfo || linfo == env->prev_linfo)
439 va_start(args, prefix_fmt);
440 bpf_verifier_vlog(&env->log, prefix_fmt, args);
445 ltrim(btf_name_by_offset(env->prog->aux->btf,
448 env->prev_linfo = linfo;
451 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
452 struct bpf_reg_state *reg,
453 struct tnum *range, const char *ctx,
454 const char *reg_name)
458 verbose(env, "At %s the register %s ", ctx, reg_name);
459 if (!tnum_is_unknown(reg->var_off)) {
460 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
461 verbose(env, "has value %s", tn_buf);
463 verbose(env, "has unknown scalar value");
465 tnum_strn(tn_buf, sizeof(tn_buf), *range);
466 verbose(env, " should have been in %s\n", tn_buf);
469 static bool type_is_pkt_pointer(enum bpf_reg_type type)
471 type = base_type(type);
472 return type == PTR_TO_PACKET ||
473 type == PTR_TO_PACKET_META;
476 static bool type_is_sk_pointer(enum bpf_reg_type type)
478 return type == PTR_TO_SOCKET ||
479 type == PTR_TO_SOCK_COMMON ||
480 type == PTR_TO_TCP_SOCK ||
481 type == PTR_TO_XDP_SOCK;
484 static bool reg_type_not_null(enum bpf_reg_type type)
486 return type == PTR_TO_SOCKET ||
487 type == PTR_TO_TCP_SOCK ||
488 type == PTR_TO_MAP_VALUE ||
489 type == PTR_TO_MAP_KEY ||
490 type == PTR_TO_SOCK_COMMON;
493 static bool type_is_ptr_alloc_obj(u32 type)
495 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
498 static bool type_is_non_owning_ref(u32 type)
500 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
503 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
505 struct btf_record *rec = NULL;
506 struct btf_struct_meta *meta;
508 if (reg->type == PTR_TO_MAP_VALUE) {
509 rec = reg->map_ptr->record;
510 } else if (type_is_ptr_alloc_obj(reg->type)) {
511 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
518 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
520 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
523 static bool type_is_rdonly_mem(u32 type)
525 return type & MEM_RDONLY;
528 static bool type_may_be_null(u32 type)
530 return type & PTR_MAYBE_NULL;
533 static bool is_acquire_function(enum bpf_func_id func_id,
534 const struct bpf_map *map)
536 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
538 if (func_id == BPF_FUNC_sk_lookup_tcp ||
539 func_id == BPF_FUNC_sk_lookup_udp ||
540 func_id == BPF_FUNC_skc_lookup_tcp ||
541 func_id == BPF_FUNC_ringbuf_reserve ||
542 func_id == BPF_FUNC_kptr_xchg)
545 if (func_id == BPF_FUNC_map_lookup_elem &&
546 (map_type == BPF_MAP_TYPE_SOCKMAP ||
547 map_type == BPF_MAP_TYPE_SOCKHASH))
553 static bool is_ptr_cast_function(enum bpf_func_id func_id)
555 return func_id == BPF_FUNC_tcp_sock ||
556 func_id == BPF_FUNC_sk_fullsock ||
557 func_id == BPF_FUNC_skc_to_tcp_sock ||
558 func_id == BPF_FUNC_skc_to_tcp6_sock ||
559 func_id == BPF_FUNC_skc_to_udp6_sock ||
560 func_id == BPF_FUNC_skc_to_mptcp_sock ||
561 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
562 func_id == BPF_FUNC_skc_to_tcp_request_sock;
565 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
567 return func_id == BPF_FUNC_dynptr_data;
570 static bool is_callback_calling_function(enum bpf_func_id func_id)
572 return func_id == BPF_FUNC_for_each_map_elem ||
573 func_id == BPF_FUNC_timer_set_callback ||
574 func_id == BPF_FUNC_find_vma ||
575 func_id == BPF_FUNC_loop ||
576 func_id == BPF_FUNC_user_ringbuf_drain;
579 static bool is_storage_get_function(enum bpf_func_id func_id)
581 return func_id == BPF_FUNC_sk_storage_get ||
582 func_id == BPF_FUNC_inode_storage_get ||
583 func_id == BPF_FUNC_task_storage_get ||
584 func_id == BPF_FUNC_cgrp_storage_get;
587 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
588 const struct bpf_map *map)
590 int ref_obj_uses = 0;
592 if (is_ptr_cast_function(func_id))
594 if (is_acquire_function(func_id, map))
596 if (is_dynptr_ref_function(func_id))
599 return ref_obj_uses > 1;
602 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
604 return BPF_CLASS(insn->code) == BPF_STX &&
605 BPF_MODE(insn->code) == BPF_ATOMIC &&
606 insn->imm == BPF_CMPXCHG;
609 /* string representation of 'enum bpf_reg_type'
611 * Note that reg_type_str() can not appear more than once in a single verbose()
614 static const char *reg_type_str(struct bpf_verifier_env *env,
615 enum bpf_reg_type type)
617 char postfix[16] = {0}, prefix[64] = {0};
618 static const char * const str[] = {
620 [SCALAR_VALUE] = "scalar",
621 [PTR_TO_CTX] = "ctx",
622 [CONST_PTR_TO_MAP] = "map_ptr",
623 [PTR_TO_MAP_VALUE] = "map_value",
624 [PTR_TO_STACK] = "fp",
625 [PTR_TO_PACKET] = "pkt",
626 [PTR_TO_PACKET_META] = "pkt_meta",
627 [PTR_TO_PACKET_END] = "pkt_end",
628 [PTR_TO_FLOW_KEYS] = "flow_keys",
629 [PTR_TO_SOCKET] = "sock",
630 [PTR_TO_SOCK_COMMON] = "sock_common",
631 [PTR_TO_TCP_SOCK] = "tcp_sock",
632 [PTR_TO_TP_BUFFER] = "tp_buffer",
633 [PTR_TO_XDP_SOCK] = "xdp_sock",
634 [PTR_TO_BTF_ID] = "ptr_",
635 [PTR_TO_MEM] = "mem",
636 [PTR_TO_BUF] = "buf",
637 [PTR_TO_FUNC] = "func",
638 [PTR_TO_MAP_KEY] = "map_key",
639 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr",
642 if (type & PTR_MAYBE_NULL) {
643 if (base_type(type) == PTR_TO_BTF_ID)
644 strncpy(postfix, "or_null_", 16);
646 strncpy(postfix, "_or_null", 16);
649 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
650 type & MEM_RDONLY ? "rdonly_" : "",
651 type & MEM_RINGBUF ? "ringbuf_" : "",
652 type & MEM_USER ? "user_" : "",
653 type & MEM_PERCPU ? "percpu_" : "",
654 type & MEM_RCU ? "rcu_" : "",
655 type & PTR_UNTRUSTED ? "untrusted_" : "",
656 type & PTR_TRUSTED ? "trusted_" : ""
659 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
660 prefix, str[base_type(type)], postfix);
661 return env->type_str_buf;
664 static char slot_type_char[] = {
665 [STACK_INVALID] = '?',
669 [STACK_DYNPTR] = 'd',
672 static void print_liveness(struct bpf_verifier_env *env,
673 enum bpf_reg_liveness live)
675 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
677 if (live & REG_LIVE_READ)
679 if (live & REG_LIVE_WRITTEN)
681 if (live & REG_LIVE_DONE)
685 static int __get_spi(s32 off)
687 return (-off - 1) / BPF_REG_SIZE;
690 static struct bpf_func_state *func(struct bpf_verifier_env *env,
691 const struct bpf_reg_state *reg)
693 struct bpf_verifier_state *cur = env->cur_state;
695 return cur->frame[reg->frameno];
698 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
700 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
702 /* We need to check that slots between [spi - nr_slots + 1, spi] are
703 * within [0, allocated_stack).
705 * Please note that the spi grows downwards. For example, a dynptr
706 * takes the size of two stack slots; the first slot will be at
707 * spi and the second slot will be at spi - 1.
709 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
712 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
716 if (!tnum_is_const(reg->var_off)) {
717 verbose(env, "dynptr has to be at a constant offset\n");
721 off = reg->off + reg->var_off.value;
722 if (off % BPF_REG_SIZE) {
723 verbose(env, "cannot pass in dynptr at an offset=%d\n", off);
727 spi = __get_spi(off);
729 verbose(env, "cannot pass in dynptr at an offset=%d\n", off);
733 if (!is_spi_bounds_valid(func(env, reg), spi, BPF_DYNPTR_NR_SLOTS))
738 static const char *kernel_type_name(const struct btf* btf, u32 id)
740 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
743 static const char *dynptr_type_str(enum bpf_dynptr_type type)
746 case BPF_DYNPTR_TYPE_LOCAL:
748 case BPF_DYNPTR_TYPE_RINGBUF:
750 case BPF_DYNPTR_TYPE_SKB:
752 case BPF_DYNPTR_TYPE_XDP:
754 case BPF_DYNPTR_TYPE_INVALID:
757 WARN_ONCE(1, "unknown dynptr type %d\n", type);
762 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
764 env->scratched_regs |= 1U << regno;
767 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
769 env->scratched_stack_slots |= 1ULL << spi;
772 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
774 return (env->scratched_regs >> regno) & 1;
777 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
779 return (env->scratched_stack_slots >> regno) & 1;
782 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
784 return env->scratched_regs || env->scratched_stack_slots;
787 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
789 env->scratched_regs = 0U;
790 env->scratched_stack_slots = 0ULL;
793 /* Used for printing the entire verifier state. */
794 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
796 env->scratched_regs = ~0U;
797 env->scratched_stack_slots = ~0ULL;
800 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
802 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
803 case DYNPTR_TYPE_LOCAL:
804 return BPF_DYNPTR_TYPE_LOCAL;
805 case DYNPTR_TYPE_RINGBUF:
806 return BPF_DYNPTR_TYPE_RINGBUF;
807 case DYNPTR_TYPE_SKB:
808 return BPF_DYNPTR_TYPE_SKB;
809 case DYNPTR_TYPE_XDP:
810 return BPF_DYNPTR_TYPE_XDP;
812 return BPF_DYNPTR_TYPE_INVALID;
816 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
819 case BPF_DYNPTR_TYPE_LOCAL:
820 return DYNPTR_TYPE_LOCAL;
821 case BPF_DYNPTR_TYPE_RINGBUF:
822 return DYNPTR_TYPE_RINGBUF;
823 case BPF_DYNPTR_TYPE_SKB:
824 return DYNPTR_TYPE_SKB;
825 case BPF_DYNPTR_TYPE_XDP:
826 return DYNPTR_TYPE_XDP;
832 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
834 return type == BPF_DYNPTR_TYPE_RINGBUF;
837 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
838 enum bpf_dynptr_type type,
839 bool first_slot, int dynptr_id);
841 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
842 struct bpf_reg_state *reg);
844 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
845 struct bpf_reg_state *sreg1,
846 struct bpf_reg_state *sreg2,
847 enum bpf_dynptr_type type)
849 int id = ++env->id_gen;
851 __mark_dynptr_reg(sreg1, type, true, id);
852 __mark_dynptr_reg(sreg2, type, false, id);
855 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
856 struct bpf_reg_state *reg,
857 enum bpf_dynptr_type type)
859 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
862 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
863 struct bpf_func_state *state, int spi);
865 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
866 enum bpf_arg_type arg_type, int insn_idx)
868 struct bpf_func_state *state = func(env, reg);
869 enum bpf_dynptr_type type;
872 spi = dynptr_get_spi(env, reg);
876 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
877 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
878 * to ensure that for the following example:
881 * So marking spi = 2 should lead to destruction of both d1 and d2. In
882 * case they do belong to same dynptr, second call won't see slot_type
883 * as STACK_DYNPTR and will simply skip destruction.
885 err = destroy_if_dynptr_stack_slot(env, state, spi);
888 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
892 for (i = 0; i < BPF_REG_SIZE; i++) {
893 state->stack[spi].slot_type[i] = STACK_DYNPTR;
894 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
897 type = arg_to_dynptr_type(arg_type);
898 if (type == BPF_DYNPTR_TYPE_INVALID)
901 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
902 &state->stack[spi - 1].spilled_ptr, type);
904 if (dynptr_type_refcounted(type)) {
905 /* The id is used to track proper releasing */
906 id = acquire_reference_state(env, insn_idx);
910 state->stack[spi].spilled_ptr.ref_obj_id = id;
911 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
914 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
915 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
920 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
922 struct bpf_func_state *state = func(env, reg);
925 spi = dynptr_get_spi(env, reg);
929 for (i = 0; i < BPF_REG_SIZE; i++) {
930 state->stack[spi].slot_type[i] = STACK_INVALID;
931 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
934 /* Invalidate any slices associated with this dynptr */
935 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
936 WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
938 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
939 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
941 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
943 * While we don't allow reading STACK_INVALID, it is still possible to
944 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
945 * helpers or insns can do partial read of that part without failing,
946 * but check_stack_range_initialized, check_stack_read_var_off, and
947 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
948 * the slot conservatively. Hence we need to prevent those liveness
951 * This was not a problem before because STACK_INVALID is only set by
952 * default (where the default reg state has its reg->parent as NULL), or
953 * in clean_live_states after REG_LIVE_DONE (at which point
954 * mark_reg_read won't walk reg->parent chain), but not randomly during
955 * verifier state exploration (like we did above). Hence, for our case
956 * parentage chain will still be live (i.e. reg->parent may be
957 * non-NULL), while earlier reg->parent was NULL, so we need
958 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
959 * done later on reads or by mark_dynptr_read as well to unnecessary
960 * mark registers in verifier state.
962 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
963 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
968 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
969 struct bpf_reg_state *reg);
971 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
973 if (!env->allow_ptr_leaks)
974 __mark_reg_not_init(env, reg);
976 __mark_reg_unknown(env, reg);
979 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
980 struct bpf_func_state *state, int spi)
982 struct bpf_func_state *fstate;
983 struct bpf_reg_state *dreg;
986 /* We always ensure that STACK_DYNPTR is never set partially,
987 * hence just checking for slot_type[0] is enough. This is
988 * different for STACK_SPILL, where it may be only set for
989 * 1 byte, so code has to use is_spilled_reg.
991 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
994 /* Reposition spi to first slot */
995 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
998 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
999 verbose(env, "cannot overwrite referenced dynptr\n");
1003 mark_stack_slot_scratched(env, spi);
1004 mark_stack_slot_scratched(env, spi - 1);
1006 /* Writing partially to one dynptr stack slot destroys both. */
1007 for (i = 0; i < BPF_REG_SIZE; i++) {
1008 state->stack[spi].slot_type[i] = STACK_INVALID;
1009 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1012 dynptr_id = state->stack[spi].spilled_ptr.id;
1013 /* Invalidate any slices associated with this dynptr */
1014 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1015 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1016 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1018 if (dreg->dynptr_id == dynptr_id)
1019 mark_reg_invalid(env, dreg);
1022 /* Do not release reference state, we are destroying dynptr on stack,
1023 * not using some helper to release it. Just reset register.
1025 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1026 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1028 /* Same reason as unmark_stack_slots_dynptr above */
1029 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1030 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1035 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1039 if (reg->type == CONST_PTR_TO_DYNPTR)
1042 spi = dynptr_get_spi(env, reg);
1044 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1045 * error because this just means the stack state hasn't been updated yet.
1046 * We will do check_mem_access to check and update stack bounds later.
1048 if (spi < 0 && spi != -ERANGE)
1051 /* We don't need to check if the stack slots are marked by previous
1052 * dynptr initializations because we allow overwriting existing unreferenced
1053 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1054 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1055 * touching are completely destructed before we reinitialize them for a new
1056 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1057 * instead of delaying it until the end where the user will get "Unreleased
1063 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1065 struct bpf_func_state *state = func(env, reg);
1068 /* This already represents first slot of initialized bpf_dynptr.
1070 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1071 * check_func_arg_reg_off's logic, so we don't need to check its
1072 * offset and alignment.
1074 if (reg->type == CONST_PTR_TO_DYNPTR)
1077 spi = dynptr_get_spi(env, reg);
1080 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1083 for (i = 0; i < BPF_REG_SIZE; i++) {
1084 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1085 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1092 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1093 enum bpf_arg_type arg_type)
1095 struct bpf_func_state *state = func(env, reg);
1096 enum bpf_dynptr_type dynptr_type;
1099 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1100 if (arg_type == ARG_PTR_TO_DYNPTR)
1103 dynptr_type = arg_to_dynptr_type(arg_type);
1104 if (reg->type == CONST_PTR_TO_DYNPTR) {
1105 return reg->dynptr.type == dynptr_type;
1107 spi = dynptr_get_spi(env, reg);
1110 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1114 /* The reg state of a pointer or a bounded scalar was saved when
1115 * it was spilled to the stack.
1117 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1119 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1122 static void scrub_spilled_slot(u8 *stype)
1124 if (*stype != STACK_INVALID)
1125 *stype = STACK_MISC;
1128 static void print_verifier_state(struct bpf_verifier_env *env,
1129 const struct bpf_func_state *state,
1132 const struct bpf_reg_state *reg;
1133 enum bpf_reg_type t;
1137 verbose(env, " frame%d:", state->frameno);
1138 for (i = 0; i < MAX_BPF_REG; i++) {
1139 reg = &state->regs[i];
1143 if (!print_all && !reg_scratched(env, i))
1145 verbose(env, " R%d", i);
1146 print_liveness(env, reg->live);
1148 if (t == SCALAR_VALUE && reg->precise)
1150 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1151 tnum_is_const(reg->var_off)) {
1152 /* reg->off should be 0 for SCALAR_VALUE */
1153 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1154 verbose(env, "%lld", reg->var_off.value + reg->off);
1156 const char *sep = "";
1158 verbose(env, "%s", reg_type_str(env, t));
1159 if (base_type(t) == PTR_TO_BTF_ID)
1160 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
1163 * _a stands for append, was shortened to avoid multiline statements below.
1164 * This macro is used to output a comma separated list of attributes.
1166 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1169 verbose_a("id=%d", reg->id);
1170 if (reg->ref_obj_id)
1171 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1172 if (type_is_non_owning_ref(reg->type))
1173 verbose_a("%s", "non_own_ref");
1174 if (t != SCALAR_VALUE)
1175 verbose_a("off=%d", reg->off);
1176 if (type_is_pkt_pointer(t))
1177 verbose_a("r=%d", reg->range);
1178 else if (base_type(t) == CONST_PTR_TO_MAP ||
1179 base_type(t) == PTR_TO_MAP_KEY ||
1180 base_type(t) == PTR_TO_MAP_VALUE)
1181 verbose_a("ks=%d,vs=%d",
1182 reg->map_ptr->key_size,
1183 reg->map_ptr->value_size);
1184 if (tnum_is_const(reg->var_off)) {
1185 /* Typically an immediate SCALAR_VALUE, but
1186 * could be a pointer whose offset is too big
1189 verbose_a("imm=%llx", reg->var_off.value);
1191 if (reg->smin_value != reg->umin_value &&
1192 reg->smin_value != S64_MIN)
1193 verbose_a("smin=%lld", (long long)reg->smin_value);
1194 if (reg->smax_value != reg->umax_value &&
1195 reg->smax_value != S64_MAX)
1196 verbose_a("smax=%lld", (long long)reg->smax_value);
1197 if (reg->umin_value != 0)
1198 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1199 if (reg->umax_value != U64_MAX)
1200 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1201 if (!tnum_is_unknown(reg->var_off)) {
1204 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1205 verbose_a("var_off=%s", tn_buf);
1207 if (reg->s32_min_value != reg->smin_value &&
1208 reg->s32_min_value != S32_MIN)
1209 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1210 if (reg->s32_max_value != reg->smax_value &&
1211 reg->s32_max_value != S32_MAX)
1212 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1213 if (reg->u32_min_value != reg->umin_value &&
1214 reg->u32_min_value != U32_MIN)
1215 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1216 if (reg->u32_max_value != reg->umax_value &&
1217 reg->u32_max_value != U32_MAX)
1218 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1225 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1226 char types_buf[BPF_REG_SIZE + 1];
1230 for (j = 0; j < BPF_REG_SIZE; j++) {
1231 if (state->stack[i].slot_type[j] != STACK_INVALID)
1233 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1235 types_buf[BPF_REG_SIZE] = 0;
1238 if (!print_all && !stack_slot_scratched(env, i))
1240 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1242 reg = &state->stack[i].spilled_ptr;
1245 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1246 print_liveness(env, reg->live);
1247 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1248 if (t == SCALAR_VALUE && reg->precise)
1250 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1251 verbose(env, "%lld", reg->var_off.value + reg->off);
1254 i += BPF_DYNPTR_NR_SLOTS - 1;
1255 reg = &state->stack[i].spilled_ptr;
1257 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1258 print_liveness(env, reg->live);
1259 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1260 if (reg->ref_obj_id)
1261 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1266 reg = &state->stack[i].spilled_ptr;
1268 for (j = 0; j < BPF_REG_SIZE; j++)
1269 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1270 types_buf[BPF_REG_SIZE] = 0;
1272 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1273 print_liveness(env, reg->live);
1274 verbose(env, "=%s", types_buf);
1278 if (state->acquired_refs && state->refs[0].id) {
1279 verbose(env, " refs=%d", state->refs[0].id);
1280 for (i = 1; i < state->acquired_refs; i++)
1281 if (state->refs[i].id)
1282 verbose(env, ",%d", state->refs[i].id);
1284 if (state->in_callback_fn)
1285 verbose(env, " cb");
1286 if (state->in_async_callback_fn)
1287 verbose(env, " async_cb");
1289 mark_verifier_state_clean(env);
1292 static inline u32 vlog_alignment(u32 pos)
1294 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1295 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1298 static void print_insn_state(struct bpf_verifier_env *env,
1299 const struct bpf_func_state *state)
1301 if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
1302 /* remove new line character */
1303 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1304 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1306 verbose(env, "%d:", env->insn_idx);
1308 print_verifier_state(env, state, false);
1311 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1312 * small to hold src. This is different from krealloc since we don't want to preserve
1313 * the contents of dst.
1315 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1318 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1324 if (ZERO_OR_NULL_PTR(src))
1327 if (unlikely(check_mul_overflow(n, size, &bytes)))
1330 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1331 dst = krealloc(orig, alloc_bytes, flags);
1337 memcpy(dst, src, bytes);
1339 return dst ? dst : ZERO_SIZE_PTR;
1342 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1343 * small to hold new_n items. new items are zeroed out if the array grows.
1345 * Contrary to krealloc_array, does not free arr if new_n is zero.
1347 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1352 if (!new_n || old_n == new_n)
1355 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1356 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1364 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1367 return arr ? arr : ZERO_SIZE_PTR;
1370 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1372 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1373 sizeof(struct bpf_reference_state), GFP_KERNEL);
1377 dst->acquired_refs = src->acquired_refs;
1381 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1383 size_t n = src->allocated_stack / BPF_REG_SIZE;
1385 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1390 dst->allocated_stack = src->allocated_stack;
1394 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1396 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1397 sizeof(struct bpf_reference_state));
1401 state->acquired_refs = n;
1405 static int grow_stack_state(struct bpf_func_state *state, int size)
1407 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1412 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1416 state->allocated_stack = size;
1420 /* Acquire a pointer id from the env and update the state->refs to include
1421 * this new pointer reference.
1422 * On success, returns a valid pointer id to associate with the register
1423 * On failure, returns a negative errno.
1425 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1427 struct bpf_func_state *state = cur_func(env);
1428 int new_ofs = state->acquired_refs;
1431 err = resize_reference_state(state, state->acquired_refs + 1);
1435 state->refs[new_ofs].id = id;
1436 state->refs[new_ofs].insn_idx = insn_idx;
1437 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1442 /* release function corresponding to acquire_reference_state(). Idempotent. */
1443 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1447 last_idx = state->acquired_refs - 1;
1448 for (i = 0; i < state->acquired_refs; i++) {
1449 if (state->refs[i].id == ptr_id) {
1450 /* Cannot release caller references in callbacks */
1451 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1453 if (last_idx && i != last_idx)
1454 memcpy(&state->refs[i], &state->refs[last_idx],
1455 sizeof(*state->refs));
1456 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1457 state->acquired_refs--;
1464 static void free_func_state(struct bpf_func_state *state)
1469 kfree(state->stack);
1473 static void clear_jmp_history(struct bpf_verifier_state *state)
1475 kfree(state->jmp_history);
1476 state->jmp_history = NULL;
1477 state->jmp_history_cnt = 0;
1480 static void free_verifier_state(struct bpf_verifier_state *state,
1485 for (i = 0; i <= state->curframe; i++) {
1486 free_func_state(state->frame[i]);
1487 state->frame[i] = NULL;
1489 clear_jmp_history(state);
1494 /* copy verifier state from src to dst growing dst stack space
1495 * when necessary to accommodate larger src stack
1497 static int copy_func_state(struct bpf_func_state *dst,
1498 const struct bpf_func_state *src)
1502 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1503 err = copy_reference_state(dst, src);
1506 return copy_stack_state(dst, src);
1509 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1510 const struct bpf_verifier_state *src)
1512 struct bpf_func_state *dst;
1515 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1516 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1518 if (!dst_state->jmp_history)
1520 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1522 /* if dst has more stack frames then src frame, free them */
1523 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1524 free_func_state(dst_state->frame[i]);
1525 dst_state->frame[i] = NULL;
1527 dst_state->speculative = src->speculative;
1528 dst_state->active_rcu_lock = src->active_rcu_lock;
1529 dst_state->curframe = src->curframe;
1530 dst_state->active_lock.ptr = src->active_lock.ptr;
1531 dst_state->active_lock.id = src->active_lock.id;
1532 dst_state->branches = src->branches;
1533 dst_state->parent = src->parent;
1534 dst_state->first_insn_idx = src->first_insn_idx;
1535 dst_state->last_insn_idx = src->last_insn_idx;
1536 for (i = 0; i <= src->curframe; i++) {
1537 dst = dst_state->frame[i];
1539 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1542 dst_state->frame[i] = dst;
1544 err = copy_func_state(dst, src->frame[i]);
1551 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1554 u32 br = --st->branches;
1556 /* WARN_ON(br > 1) technically makes sense here,
1557 * but see comment in push_stack(), hence:
1559 WARN_ONCE((int)br < 0,
1560 "BUG update_branch_counts:branches_to_explore=%d\n",
1568 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1569 int *insn_idx, bool pop_log)
1571 struct bpf_verifier_state *cur = env->cur_state;
1572 struct bpf_verifier_stack_elem *elem, *head = env->head;
1575 if (env->head == NULL)
1579 err = copy_verifier_state(cur, &head->st);
1584 bpf_vlog_reset(&env->log, head->log_pos);
1586 *insn_idx = head->insn_idx;
1588 *prev_insn_idx = head->prev_insn_idx;
1590 free_verifier_state(&head->st, false);
1597 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1598 int insn_idx, int prev_insn_idx,
1601 struct bpf_verifier_state *cur = env->cur_state;
1602 struct bpf_verifier_stack_elem *elem;
1605 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1609 elem->insn_idx = insn_idx;
1610 elem->prev_insn_idx = prev_insn_idx;
1611 elem->next = env->head;
1612 elem->log_pos = env->log.len_used;
1615 err = copy_verifier_state(&elem->st, cur);
1618 elem->st.speculative |= speculative;
1619 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1620 verbose(env, "The sequence of %d jumps is too complex.\n",
1624 if (elem->st.parent) {
1625 ++elem->st.parent->branches;
1626 /* WARN_ON(branches > 2) technically makes sense here,
1628 * 1. speculative states will bump 'branches' for non-branch
1630 * 2. is_state_visited() heuristics may decide not to create
1631 * a new state for a sequence of branches and all such current
1632 * and cloned states will be pointing to a single parent state
1633 * which might have large 'branches' count.
1638 free_verifier_state(env->cur_state, true);
1639 env->cur_state = NULL;
1640 /* pop all elements and return */
1641 while (!pop_stack(env, NULL, NULL, false));
1645 #define CALLER_SAVED_REGS 6
1646 static const int caller_saved[CALLER_SAVED_REGS] = {
1647 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1650 /* This helper doesn't clear reg->id */
1651 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1653 reg->var_off = tnum_const(imm);
1654 reg->smin_value = (s64)imm;
1655 reg->smax_value = (s64)imm;
1656 reg->umin_value = imm;
1657 reg->umax_value = imm;
1659 reg->s32_min_value = (s32)imm;
1660 reg->s32_max_value = (s32)imm;
1661 reg->u32_min_value = (u32)imm;
1662 reg->u32_max_value = (u32)imm;
1665 /* Mark the unknown part of a register (variable offset or scalar value) as
1666 * known to have the value @imm.
1668 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1670 /* Clear off and union(map_ptr, range) */
1671 memset(((u8 *)reg) + sizeof(reg->type), 0,
1672 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1674 reg->ref_obj_id = 0;
1675 ___mark_reg_known(reg, imm);
1678 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1680 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1681 reg->s32_min_value = (s32)imm;
1682 reg->s32_max_value = (s32)imm;
1683 reg->u32_min_value = (u32)imm;
1684 reg->u32_max_value = (u32)imm;
1687 /* Mark the 'variable offset' part of a register as zero. This should be
1688 * used only on registers holding a pointer type.
1690 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1692 __mark_reg_known(reg, 0);
1695 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1697 __mark_reg_known(reg, 0);
1698 reg->type = SCALAR_VALUE;
1701 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1702 struct bpf_reg_state *regs, u32 regno)
1704 if (WARN_ON(regno >= MAX_BPF_REG)) {
1705 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1706 /* Something bad happened, let's kill all regs */
1707 for (regno = 0; regno < MAX_BPF_REG; regno++)
1708 __mark_reg_not_init(env, regs + regno);
1711 __mark_reg_known_zero(regs + regno);
1714 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1715 bool first_slot, int dynptr_id)
1717 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1718 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1719 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1721 __mark_reg_known_zero(reg);
1722 reg->type = CONST_PTR_TO_DYNPTR;
1723 /* Give each dynptr a unique id to uniquely associate slices to it. */
1724 reg->id = dynptr_id;
1725 reg->dynptr.type = type;
1726 reg->dynptr.first_slot = first_slot;
1729 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1731 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1732 const struct bpf_map *map = reg->map_ptr;
1734 if (map->inner_map_meta) {
1735 reg->type = CONST_PTR_TO_MAP;
1736 reg->map_ptr = map->inner_map_meta;
1737 /* transfer reg's id which is unique for every map_lookup_elem
1738 * as UID of the inner map.
1740 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1741 reg->map_uid = reg->id;
1742 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1743 reg->type = PTR_TO_XDP_SOCK;
1744 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1745 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1746 reg->type = PTR_TO_SOCKET;
1748 reg->type = PTR_TO_MAP_VALUE;
1753 reg->type &= ~PTR_MAYBE_NULL;
1756 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1757 struct btf_field_graph_root *ds_head)
1759 __mark_reg_known_zero(®s[regno]);
1760 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1761 regs[regno].btf = ds_head->btf;
1762 regs[regno].btf_id = ds_head->value_btf_id;
1763 regs[regno].off = ds_head->node_offset;
1766 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1768 return type_is_pkt_pointer(reg->type);
1771 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1773 return reg_is_pkt_pointer(reg) ||
1774 reg->type == PTR_TO_PACKET_END;
1777 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1779 return base_type(reg->type) == PTR_TO_MEM &&
1780 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1783 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1784 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1785 enum bpf_reg_type which)
1787 /* The register can already have a range from prior markings.
1788 * This is fine as long as it hasn't been advanced from its
1791 return reg->type == which &&
1794 tnum_equals_const(reg->var_off, 0);
1797 /* Reset the min/max bounds of a register */
1798 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1800 reg->smin_value = S64_MIN;
1801 reg->smax_value = S64_MAX;
1802 reg->umin_value = 0;
1803 reg->umax_value = U64_MAX;
1805 reg->s32_min_value = S32_MIN;
1806 reg->s32_max_value = S32_MAX;
1807 reg->u32_min_value = 0;
1808 reg->u32_max_value = U32_MAX;
1811 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1813 reg->smin_value = S64_MIN;
1814 reg->smax_value = S64_MAX;
1815 reg->umin_value = 0;
1816 reg->umax_value = U64_MAX;
1819 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1821 reg->s32_min_value = S32_MIN;
1822 reg->s32_max_value = S32_MAX;
1823 reg->u32_min_value = 0;
1824 reg->u32_max_value = U32_MAX;
1827 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1829 struct tnum var32_off = tnum_subreg(reg->var_off);
1831 /* min signed is max(sign bit) | min(other bits) */
1832 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1833 var32_off.value | (var32_off.mask & S32_MIN));
1834 /* max signed is min(sign bit) | max(other bits) */
1835 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1836 var32_off.value | (var32_off.mask & S32_MAX));
1837 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1838 reg->u32_max_value = min(reg->u32_max_value,
1839 (u32)(var32_off.value | var32_off.mask));
1842 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1844 /* min signed is max(sign bit) | min(other bits) */
1845 reg->smin_value = max_t(s64, reg->smin_value,
1846 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1847 /* max signed is min(sign bit) | max(other bits) */
1848 reg->smax_value = min_t(s64, reg->smax_value,
1849 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1850 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1851 reg->umax_value = min(reg->umax_value,
1852 reg->var_off.value | reg->var_off.mask);
1855 static void __update_reg_bounds(struct bpf_reg_state *reg)
1857 __update_reg32_bounds(reg);
1858 __update_reg64_bounds(reg);
1861 /* Uses signed min/max values to inform unsigned, and vice-versa */
1862 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1864 /* Learn sign from signed bounds.
1865 * If we cannot cross the sign boundary, then signed and unsigned bounds
1866 * are the same, so combine. This works even in the negative case, e.g.
1867 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1869 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1870 reg->s32_min_value = reg->u32_min_value =
1871 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1872 reg->s32_max_value = reg->u32_max_value =
1873 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1876 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1877 * boundary, so we must be careful.
1879 if ((s32)reg->u32_max_value >= 0) {
1880 /* Positive. We can't learn anything from the smin, but smax
1881 * is positive, hence safe.
1883 reg->s32_min_value = reg->u32_min_value;
1884 reg->s32_max_value = reg->u32_max_value =
1885 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1886 } else if ((s32)reg->u32_min_value < 0) {
1887 /* Negative. We can't learn anything from the smax, but smin
1888 * is negative, hence safe.
1890 reg->s32_min_value = reg->u32_min_value =
1891 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1892 reg->s32_max_value = reg->u32_max_value;
1896 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1898 /* Learn sign from signed bounds.
1899 * If we cannot cross the sign boundary, then signed and unsigned bounds
1900 * are the same, so combine. This works even in the negative case, e.g.
1901 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1903 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1904 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1906 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1910 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1911 * boundary, so we must be careful.
1913 if ((s64)reg->umax_value >= 0) {
1914 /* Positive. We can't learn anything from the smin, but smax
1915 * is positive, hence safe.
1917 reg->smin_value = reg->umin_value;
1918 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1920 } else if ((s64)reg->umin_value < 0) {
1921 /* Negative. We can't learn anything from the smax, but smin
1922 * is negative, hence safe.
1924 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1926 reg->smax_value = reg->umax_value;
1930 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1932 __reg32_deduce_bounds(reg);
1933 __reg64_deduce_bounds(reg);
1936 /* Attempts to improve var_off based on unsigned min/max information */
1937 static void __reg_bound_offset(struct bpf_reg_state *reg)
1939 struct tnum var64_off = tnum_intersect(reg->var_off,
1940 tnum_range(reg->umin_value,
1942 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1943 tnum_range(reg->u32_min_value,
1944 reg->u32_max_value));
1946 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1949 static void reg_bounds_sync(struct bpf_reg_state *reg)
1951 /* We might have learned new bounds from the var_off. */
1952 __update_reg_bounds(reg);
1953 /* We might have learned something about the sign bit. */
1954 __reg_deduce_bounds(reg);
1955 /* We might have learned some bits from the bounds. */
1956 __reg_bound_offset(reg);
1957 /* Intersecting with the old var_off might have improved our bounds
1958 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1959 * then new var_off is (0; 0x7f...fc) which improves our umax.
1961 __update_reg_bounds(reg);
1964 static bool __reg32_bound_s64(s32 a)
1966 return a >= 0 && a <= S32_MAX;
1969 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1971 reg->umin_value = reg->u32_min_value;
1972 reg->umax_value = reg->u32_max_value;
1974 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1975 * be positive otherwise set to worse case bounds and refine later
1978 if (__reg32_bound_s64(reg->s32_min_value) &&
1979 __reg32_bound_s64(reg->s32_max_value)) {
1980 reg->smin_value = reg->s32_min_value;
1981 reg->smax_value = reg->s32_max_value;
1983 reg->smin_value = 0;
1984 reg->smax_value = U32_MAX;
1988 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1990 /* special case when 64-bit register has upper 32-bit register
1991 * zeroed. Typically happens after zext or <<32, >>32 sequence
1992 * allowing us to use 32-bit bounds directly,
1994 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1995 __reg_assign_32_into_64(reg);
1997 /* Otherwise the best we can do is push lower 32bit known and
1998 * unknown bits into register (var_off set from jmp logic)
1999 * then learn as much as possible from the 64-bit tnum
2000 * known and unknown bits. The previous smin/smax bounds are
2001 * invalid here because of jmp32 compare so mark them unknown
2002 * so they do not impact tnum bounds calculation.
2004 __mark_reg64_unbounded(reg);
2006 reg_bounds_sync(reg);
2009 static bool __reg64_bound_s32(s64 a)
2011 return a >= S32_MIN && a <= S32_MAX;
2014 static bool __reg64_bound_u32(u64 a)
2016 return a >= U32_MIN && a <= U32_MAX;
2019 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2021 __mark_reg32_unbounded(reg);
2022 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2023 reg->s32_min_value = (s32)reg->smin_value;
2024 reg->s32_max_value = (s32)reg->smax_value;
2026 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2027 reg->u32_min_value = (u32)reg->umin_value;
2028 reg->u32_max_value = (u32)reg->umax_value;
2030 reg_bounds_sync(reg);
2033 /* Mark a register as having a completely unknown (scalar) value. */
2034 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2035 struct bpf_reg_state *reg)
2038 * Clear type, off, and union(map_ptr, range) and
2039 * padding between 'type' and union
2041 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2042 reg->type = SCALAR_VALUE;
2044 reg->ref_obj_id = 0;
2045 reg->var_off = tnum_unknown;
2047 reg->precise = !env->bpf_capable;
2048 __mark_reg_unbounded(reg);
2051 static void mark_reg_unknown(struct bpf_verifier_env *env,
2052 struct bpf_reg_state *regs, u32 regno)
2054 if (WARN_ON(regno >= MAX_BPF_REG)) {
2055 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2056 /* Something bad happened, let's kill all regs except FP */
2057 for (regno = 0; regno < BPF_REG_FP; regno++)
2058 __mark_reg_not_init(env, regs + regno);
2061 __mark_reg_unknown(env, regs + regno);
2064 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2065 struct bpf_reg_state *reg)
2067 __mark_reg_unknown(env, reg);
2068 reg->type = NOT_INIT;
2071 static void mark_reg_not_init(struct bpf_verifier_env *env,
2072 struct bpf_reg_state *regs, u32 regno)
2074 if (WARN_ON(regno >= MAX_BPF_REG)) {
2075 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2076 /* Something bad happened, let's kill all regs except FP */
2077 for (regno = 0; regno < BPF_REG_FP; regno++)
2078 __mark_reg_not_init(env, regs + regno);
2081 __mark_reg_not_init(env, regs + regno);
2084 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2085 struct bpf_reg_state *regs, u32 regno,
2086 enum bpf_reg_type reg_type,
2087 struct btf *btf, u32 btf_id,
2088 enum bpf_type_flag flag)
2090 if (reg_type == SCALAR_VALUE) {
2091 mark_reg_unknown(env, regs, regno);
2094 mark_reg_known_zero(env, regs, regno);
2095 regs[regno].type = PTR_TO_BTF_ID | flag;
2096 regs[regno].btf = btf;
2097 regs[regno].btf_id = btf_id;
2100 #define DEF_NOT_SUBREG (0)
2101 static void init_reg_state(struct bpf_verifier_env *env,
2102 struct bpf_func_state *state)
2104 struct bpf_reg_state *regs = state->regs;
2107 for (i = 0; i < MAX_BPF_REG; i++) {
2108 mark_reg_not_init(env, regs, i);
2109 regs[i].live = REG_LIVE_NONE;
2110 regs[i].parent = NULL;
2111 regs[i].subreg_def = DEF_NOT_SUBREG;
2115 regs[BPF_REG_FP].type = PTR_TO_STACK;
2116 mark_reg_known_zero(env, regs, BPF_REG_FP);
2117 regs[BPF_REG_FP].frameno = state->frameno;
2120 #define BPF_MAIN_FUNC (-1)
2121 static void init_func_state(struct bpf_verifier_env *env,
2122 struct bpf_func_state *state,
2123 int callsite, int frameno, int subprogno)
2125 state->callsite = callsite;
2126 state->frameno = frameno;
2127 state->subprogno = subprogno;
2128 state->callback_ret_range = tnum_range(0, 0);
2129 init_reg_state(env, state);
2130 mark_verifier_state_scratched(env);
2133 /* Similar to push_stack(), but for async callbacks */
2134 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2135 int insn_idx, int prev_insn_idx,
2138 struct bpf_verifier_stack_elem *elem;
2139 struct bpf_func_state *frame;
2141 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2145 elem->insn_idx = insn_idx;
2146 elem->prev_insn_idx = prev_insn_idx;
2147 elem->next = env->head;
2148 elem->log_pos = env->log.len_used;
2151 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2153 "The sequence of %d jumps is too complex for async cb.\n",
2157 /* Unlike push_stack() do not copy_verifier_state().
2158 * The caller state doesn't matter.
2159 * This is async callback. It starts in a fresh stack.
2160 * Initialize it similar to do_check_common().
2162 elem->st.branches = 1;
2163 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2166 init_func_state(env, frame,
2167 BPF_MAIN_FUNC /* callsite */,
2168 0 /* frameno within this callchain */,
2169 subprog /* subprog number within this prog */);
2170 elem->st.frame[0] = frame;
2173 free_verifier_state(env->cur_state, true);
2174 env->cur_state = NULL;
2175 /* pop all elements and return */
2176 while (!pop_stack(env, NULL, NULL, false));
2182 SRC_OP, /* register is used as source operand */
2183 DST_OP, /* register is used as destination operand */
2184 DST_OP_NO_MARK /* same as above, check only, don't mark */
2187 static int cmp_subprogs(const void *a, const void *b)
2189 return ((struct bpf_subprog_info *)a)->start -
2190 ((struct bpf_subprog_info *)b)->start;
2193 static int find_subprog(struct bpf_verifier_env *env, int off)
2195 struct bpf_subprog_info *p;
2197 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2198 sizeof(env->subprog_info[0]), cmp_subprogs);
2201 return p - env->subprog_info;
2205 static int add_subprog(struct bpf_verifier_env *env, int off)
2207 int insn_cnt = env->prog->len;
2210 if (off >= insn_cnt || off < 0) {
2211 verbose(env, "call to invalid destination\n");
2214 ret = find_subprog(env, off);
2217 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2218 verbose(env, "too many subprograms\n");
2221 /* determine subprog starts. The end is one before the next starts */
2222 env->subprog_info[env->subprog_cnt++].start = off;
2223 sort(env->subprog_info, env->subprog_cnt,
2224 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2225 return env->subprog_cnt - 1;
2228 #define MAX_KFUNC_DESCS 256
2229 #define MAX_KFUNC_BTFS 256
2231 struct bpf_kfunc_desc {
2232 struct btf_func_model func_model;
2238 struct bpf_kfunc_btf {
2240 struct module *module;
2244 struct bpf_kfunc_desc_tab {
2245 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2249 struct bpf_kfunc_btf_tab {
2250 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2254 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2256 const struct bpf_kfunc_desc *d0 = a;
2257 const struct bpf_kfunc_desc *d1 = b;
2259 /* func_id is not greater than BTF_MAX_TYPE */
2260 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2263 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2265 const struct bpf_kfunc_btf *d0 = a;
2266 const struct bpf_kfunc_btf *d1 = b;
2268 return d0->offset - d1->offset;
2271 static const struct bpf_kfunc_desc *
2272 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2274 struct bpf_kfunc_desc desc = {
2278 struct bpf_kfunc_desc_tab *tab;
2280 tab = prog->aux->kfunc_tab;
2281 return bsearch(&desc, tab->descs, tab->nr_descs,
2282 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2285 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2288 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2289 struct bpf_kfunc_btf_tab *tab;
2290 struct bpf_kfunc_btf *b;
2295 tab = env->prog->aux->kfunc_btf_tab;
2296 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2297 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2299 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2300 verbose(env, "too many different module BTFs\n");
2301 return ERR_PTR(-E2BIG);
2304 if (bpfptr_is_null(env->fd_array)) {
2305 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2306 return ERR_PTR(-EPROTO);
2309 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2310 offset * sizeof(btf_fd),
2312 return ERR_PTR(-EFAULT);
2314 btf = btf_get_by_fd(btf_fd);
2316 verbose(env, "invalid module BTF fd specified\n");
2320 if (!btf_is_module(btf)) {
2321 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2323 return ERR_PTR(-EINVAL);
2326 mod = btf_try_get_module(btf);
2329 return ERR_PTR(-ENXIO);
2332 b = &tab->descs[tab->nr_descs++];
2337 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2338 kfunc_btf_cmp_by_off, NULL);
2343 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2348 while (tab->nr_descs--) {
2349 module_put(tab->descs[tab->nr_descs].module);
2350 btf_put(tab->descs[tab->nr_descs].btf);
2355 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2359 /* In the future, this can be allowed to increase limit
2360 * of fd index into fd_array, interpreted as u16.
2362 verbose(env, "negative offset disallowed for kernel module function call\n");
2363 return ERR_PTR(-EINVAL);
2366 return __find_kfunc_desc_btf(env, offset);
2368 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2371 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2373 const struct btf_type *func, *func_proto;
2374 struct bpf_kfunc_btf_tab *btf_tab;
2375 struct bpf_kfunc_desc_tab *tab;
2376 struct bpf_prog_aux *prog_aux;
2377 struct bpf_kfunc_desc *desc;
2378 const char *func_name;
2379 struct btf *desc_btf;
2380 unsigned long call_imm;
2384 prog_aux = env->prog->aux;
2385 tab = prog_aux->kfunc_tab;
2386 btf_tab = prog_aux->kfunc_btf_tab;
2389 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2393 if (!env->prog->jit_requested) {
2394 verbose(env, "JIT is required for calling kernel function\n");
2398 if (!bpf_jit_supports_kfunc_call()) {
2399 verbose(env, "JIT does not support calling kernel function\n");
2403 if (!env->prog->gpl_compatible) {
2404 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2408 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2411 prog_aux->kfunc_tab = tab;
2414 /* func_id == 0 is always invalid, but instead of returning an error, be
2415 * conservative and wait until the code elimination pass before returning
2416 * error, so that invalid calls that get pruned out can be in BPF programs
2417 * loaded from userspace. It is also required that offset be untouched
2420 if (!func_id && !offset)
2423 if (!btf_tab && offset) {
2424 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2427 prog_aux->kfunc_btf_tab = btf_tab;
2430 desc_btf = find_kfunc_desc_btf(env, offset);
2431 if (IS_ERR(desc_btf)) {
2432 verbose(env, "failed to find BTF for kernel function\n");
2433 return PTR_ERR(desc_btf);
2436 if (find_kfunc_desc(env->prog, func_id, offset))
2439 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2440 verbose(env, "too many different kernel function calls\n");
2444 func = btf_type_by_id(desc_btf, func_id);
2445 if (!func || !btf_type_is_func(func)) {
2446 verbose(env, "kernel btf_id %u is not a function\n",
2450 func_proto = btf_type_by_id(desc_btf, func->type);
2451 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2452 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2457 func_name = btf_name_by_offset(desc_btf, func->name_off);
2458 addr = kallsyms_lookup_name(func_name);
2460 verbose(env, "cannot find address for kernel function %s\n",
2465 call_imm = BPF_CALL_IMM(addr);
2466 /* Check whether or not the relative offset overflows desc->imm */
2467 if ((unsigned long)(s32)call_imm != call_imm) {
2468 verbose(env, "address of kernel function %s is out of range\n",
2473 if (bpf_dev_bound_kfunc_id(func_id)) {
2474 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2479 desc = &tab->descs[tab->nr_descs++];
2480 desc->func_id = func_id;
2481 desc->imm = call_imm;
2482 desc->offset = offset;
2483 err = btf_distill_func_proto(&env->log, desc_btf,
2484 func_proto, func_name,
2487 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2488 kfunc_desc_cmp_by_id_off, NULL);
2492 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2494 const struct bpf_kfunc_desc *d0 = a;
2495 const struct bpf_kfunc_desc *d1 = b;
2497 if (d0->imm > d1->imm)
2499 else if (d0->imm < d1->imm)
2504 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2506 struct bpf_kfunc_desc_tab *tab;
2508 tab = prog->aux->kfunc_tab;
2512 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2513 kfunc_desc_cmp_by_imm, NULL);
2516 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2518 return !!prog->aux->kfunc_tab;
2521 const struct btf_func_model *
2522 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2523 const struct bpf_insn *insn)
2525 const struct bpf_kfunc_desc desc = {
2528 const struct bpf_kfunc_desc *res;
2529 struct bpf_kfunc_desc_tab *tab;
2531 tab = prog->aux->kfunc_tab;
2532 res = bsearch(&desc, tab->descs, tab->nr_descs,
2533 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2535 return res ? &res->func_model : NULL;
2538 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2540 struct bpf_subprog_info *subprog = env->subprog_info;
2541 struct bpf_insn *insn = env->prog->insnsi;
2542 int i, ret, insn_cnt = env->prog->len;
2544 /* Add entry function. */
2545 ret = add_subprog(env, 0);
2549 for (i = 0; i < insn_cnt; i++, insn++) {
2550 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2551 !bpf_pseudo_kfunc_call(insn))
2554 if (!env->bpf_capable) {
2555 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2559 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2560 ret = add_subprog(env, i + insn->imm + 1);
2562 ret = add_kfunc_call(env, insn->imm, insn->off);
2568 /* Add a fake 'exit' subprog which could simplify subprog iteration
2569 * logic. 'subprog_cnt' should not be increased.
2571 subprog[env->subprog_cnt].start = insn_cnt;
2573 if (env->log.level & BPF_LOG_LEVEL2)
2574 for (i = 0; i < env->subprog_cnt; i++)
2575 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2580 static int check_subprogs(struct bpf_verifier_env *env)
2582 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2583 struct bpf_subprog_info *subprog = env->subprog_info;
2584 struct bpf_insn *insn = env->prog->insnsi;
2585 int insn_cnt = env->prog->len;
2587 /* now check that all jumps are within the same subprog */
2588 subprog_start = subprog[cur_subprog].start;
2589 subprog_end = subprog[cur_subprog + 1].start;
2590 for (i = 0; i < insn_cnt; i++) {
2591 u8 code = insn[i].code;
2593 if (code == (BPF_JMP | BPF_CALL) &&
2594 insn[i].src_reg == 0 &&
2595 insn[i].imm == BPF_FUNC_tail_call)
2596 subprog[cur_subprog].has_tail_call = true;
2597 if (BPF_CLASS(code) == BPF_LD &&
2598 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2599 subprog[cur_subprog].has_ld_abs = true;
2600 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2602 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2604 off = i + insn[i].off + 1;
2605 if (off < subprog_start || off >= subprog_end) {
2606 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2610 if (i == subprog_end - 1) {
2611 /* to avoid fall-through from one subprog into another
2612 * the last insn of the subprog should be either exit
2613 * or unconditional jump back
2615 if (code != (BPF_JMP | BPF_EXIT) &&
2616 code != (BPF_JMP | BPF_JA)) {
2617 verbose(env, "last insn is not an exit or jmp\n");
2620 subprog_start = subprog_end;
2622 if (cur_subprog < env->subprog_cnt)
2623 subprog_end = subprog[cur_subprog + 1].start;
2629 /* Parentage chain of this register (or stack slot) should take care of all
2630 * issues like callee-saved registers, stack slot allocation time, etc.
2632 static int mark_reg_read(struct bpf_verifier_env *env,
2633 const struct bpf_reg_state *state,
2634 struct bpf_reg_state *parent, u8 flag)
2636 bool writes = parent == state->parent; /* Observe write marks */
2640 /* if read wasn't screened by an earlier write ... */
2641 if (writes && state->live & REG_LIVE_WRITTEN)
2643 if (parent->live & REG_LIVE_DONE) {
2644 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2645 reg_type_str(env, parent->type),
2646 parent->var_off.value, parent->off);
2649 /* The first condition is more likely to be true than the
2650 * second, checked it first.
2652 if ((parent->live & REG_LIVE_READ) == flag ||
2653 parent->live & REG_LIVE_READ64)
2654 /* The parentage chain never changes and
2655 * this parent was already marked as LIVE_READ.
2656 * There is no need to keep walking the chain again and
2657 * keep re-marking all parents as LIVE_READ.
2658 * This case happens when the same register is read
2659 * multiple times without writes into it in-between.
2660 * Also, if parent has the stronger REG_LIVE_READ64 set,
2661 * then no need to set the weak REG_LIVE_READ32.
2664 /* ... then we depend on parent's value */
2665 parent->live |= flag;
2666 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2667 if (flag == REG_LIVE_READ64)
2668 parent->live &= ~REG_LIVE_READ32;
2670 parent = state->parent;
2675 if (env->longest_mark_read_walk < cnt)
2676 env->longest_mark_read_walk = cnt;
2680 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2682 struct bpf_func_state *state = func(env, reg);
2685 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2686 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2689 if (reg->type == CONST_PTR_TO_DYNPTR)
2691 spi = dynptr_get_spi(env, reg);
2694 /* Caller ensures dynptr is valid and initialized, which means spi is in
2695 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2698 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2699 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2702 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2703 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2706 /* This function is supposed to be used by the following 32-bit optimization
2707 * code only. It returns TRUE if the source or destination register operates
2708 * on 64-bit, otherwise return FALSE.
2710 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2711 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2716 class = BPF_CLASS(code);
2718 if (class == BPF_JMP) {
2719 /* BPF_EXIT for "main" will reach here. Return TRUE
2724 if (op == BPF_CALL) {
2725 /* BPF to BPF call will reach here because of marking
2726 * caller saved clobber with DST_OP_NO_MARK for which we
2727 * don't care the register def because they are anyway
2728 * marked as NOT_INIT already.
2730 if (insn->src_reg == BPF_PSEUDO_CALL)
2732 /* Helper call will reach here because of arg type
2733 * check, conservatively return TRUE.
2742 if (class == BPF_ALU64 || class == BPF_JMP ||
2743 /* BPF_END always use BPF_ALU class. */
2744 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2747 if (class == BPF_ALU || class == BPF_JMP32)
2750 if (class == BPF_LDX) {
2752 return BPF_SIZE(code) == BPF_DW;
2753 /* LDX source must be ptr. */
2757 if (class == BPF_STX) {
2758 /* BPF_STX (including atomic variants) has multiple source
2759 * operands, one of which is a ptr. Check whether the caller is
2762 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2764 return BPF_SIZE(code) == BPF_DW;
2767 if (class == BPF_LD) {
2768 u8 mode = BPF_MODE(code);
2771 if (mode == BPF_IMM)
2774 /* Both LD_IND and LD_ABS return 32-bit data. */
2778 /* Implicit ctx ptr. */
2779 if (regno == BPF_REG_6)
2782 /* Explicit source could be any width. */
2786 if (class == BPF_ST)
2787 /* The only source register for BPF_ST is a ptr. */
2790 /* Conservatively return true at default. */
2794 /* Return the regno defined by the insn, or -1. */
2795 static int insn_def_regno(const struct bpf_insn *insn)
2797 switch (BPF_CLASS(insn->code)) {
2803 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2804 (insn->imm & BPF_FETCH)) {
2805 if (insn->imm == BPF_CMPXCHG)
2808 return insn->src_reg;
2813 return insn->dst_reg;
2817 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2818 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2820 int dst_reg = insn_def_regno(insn);
2825 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2828 static void mark_insn_zext(struct bpf_verifier_env *env,
2829 struct bpf_reg_state *reg)
2831 s32 def_idx = reg->subreg_def;
2833 if (def_idx == DEF_NOT_SUBREG)
2836 env->insn_aux_data[def_idx - 1].zext_dst = true;
2837 /* The dst will be zero extended, so won't be sub-register anymore. */
2838 reg->subreg_def = DEF_NOT_SUBREG;
2841 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2842 enum reg_arg_type t)
2844 struct bpf_verifier_state *vstate = env->cur_state;
2845 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2846 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2847 struct bpf_reg_state *reg, *regs = state->regs;
2850 if (regno >= MAX_BPF_REG) {
2851 verbose(env, "R%d is invalid\n", regno);
2855 mark_reg_scratched(env, regno);
2858 rw64 = is_reg64(env, insn, regno, reg, t);
2860 /* check whether register used as source operand can be read */
2861 if (reg->type == NOT_INIT) {
2862 verbose(env, "R%d !read_ok\n", regno);
2865 /* We don't need to worry about FP liveness because it's read-only */
2866 if (regno == BPF_REG_FP)
2870 mark_insn_zext(env, reg);
2872 return mark_reg_read(env, reg, reg->parent,
2873 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2875 /* check whether register used as dest operand can be written to */
2876 if (regno == BPF_REG_FP) {
2877 verbose(env, "frame pointer is read only\n");
2880 reg->live |= REG_LIVE_WRITTEN;
2881 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2883 mark_reg_unknown(env, regs, regno);
2888 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
2890 env->insn_aux_data[idx].jmp_point = true;
2893 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
2895 return env->insn_aux_data[insn_idx].jmp_point;
2898 /* for any branch, call, exit record the history of jmps in the given state */
2899 static int push_jmp_history(struct bpf_verifier_env *env,
2900 struct bpf_verifier_state *cur)
2902 u32 cnt = cur->jmp_history_cnt;
2903 struct bpf_idx_pair *p;
2906 if (!is_jmp_point(env, env->insn_idx))
2910 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2911 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2914 p[cnt - 1].idx = env->insn_idx;
2915 p[cnt - 1].prev_idx = env->prev_insn_idx;
2916 cur->jmp_history = p;
2917 cur->jmp_history_cnt = cnt;
2921 /* Backtrack one insn at a time. If idx is not at the top of recorded
2922 * history then previous instruction came from straight line execution.
2924 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2929 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2930 i = st->jmp_history[cnt - 1].prev_idx;
2938 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2940 const struct btf_type *func;
2941 struct btf *desc_btf;
2943 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2946 desc_btf = find_kfunc_desc_btf(data, insn->off);
2947 if (IS_ERR(desc_btf))
2950 func = btf_type_by_id(desc_btf, insn->imm);
2951 return btf_name_by_offset(desc_btf, func->name_off);
2954 /* For given verifier state backtrack_insn() is called from the last insn to
2955 * the first insn. Its purpose is to compute a bitmask of registers and
2956 * stack slots that needs precision in the parent verifier state.
2958 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2959 u32 *reg_mask, u64 *stack_mask)
2961 const struct bpf_insn_cbs cbs = {
2962 .cb_call = disasm_kfunc_name,
2963 .cb_print = verbose,
2964 .private_data = env,
2966 struct bpf_insn *insn = env->prog->insnsi + idx;
2967 u8 class = BPF_CLASS(insn->code);
2968 u8 opcode = BPF_OP(insn->code);
2969 u8 mode = BPF_MODE(insn->code);
2970 u32 dreg = 1u << insn->dst_reg;
2971 u32 sreg = 1u << insn->src_reg;
2974 if (insn->code == 0)
2976 if (env->log.level & BPF_LOG_LEVEL2) {
2977 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2978 verbose(env, "%d: ", idx);
2979 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2982 if (class == BPF_ALU || class == BPF_ALU64) {
2983 if (!(*reg_mask & dreg))
2985 if (opcode == BPF_MOV) {
2986 if (BPF_SRC(insn->code) == BPF_X) {
2988 * dreg needs precision after this insn
2989 * sreg needs precision before this insn
2995 * dreg needs precision after this insn.
2996 * Corresponding register is already marked
2997 * as precise=true in this verifier state.
2998 * No further markings in parent are necessary
3003 if (BPF_SRC(insn->code) == BPF_X) {
3005 * both dreg and sreg need precision
3010 * dreg still needs precision before this insn
3013 } else if (class == BPF_LDX) {
3014 if (!(*reg_mask & dreg))
3018 /* scalars can only be spilled into stack w/o losing precision.
3019 * Load from any other memory can be zero extended.
3020 * The desire to keep that precision is already indicated
3021 * by 'precise' mark in corresponding register of this state.
3022 * No further tracking necessary.
3024 if (insn->src_reg != BPF_REG_FP)
3027 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3028 * that [fp - off] slot contains scalar that needs to be
3029 * tracked with precision
3031 spi = (-insn->off - 1) / BPF_REG_SIZE;
3033 verbose(env, "BUG spi %d\n", spi);
3034 WARN_ONCE(1, "verifier backtracking bug");
3037 *stack_mask |= 1ull << spi;
3038 } else if (class == BPF_STX || class == BPF_ST) {
3039 if (*reg_mask & dreg)
3040 /* stx & st shouldn't be using _scalar_ dst_reg
3041 * to access memory. It means backtracking
3042 * encountered a case of pointer subtraction.
3045 /* scalars can only be spilled into stack */
3046 if (insn->dst_reg != BPF_REG_FP)
3048 spi = (-insn->off - 1) / BPF_REG_SIZE;
3050 verbose(env, "BUG spi %d\n", spi);
3051 WARN_ONCE(1, "verifier backtracking bug");
3054 if (!(*stack_mask & (1ull << spi)))
3056 *stack_mask &= ~(1ull << spi);
3057 if (class == BPF_STX)
3059 } else if (class == BPF_JMP || class == BPF_JMP32) {
3060 if (opcode == BPF_CALL) {
3061 if (insn->src_reg == BPF_PSEUDO_CALL)
3063 /* BPF helpers that invoke callback subprogs are
3064 * equivalent to BPF_PSEUDO_CALL above
3066 if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
3068 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3069 * catch this error later. Make backtracking conservative
3072 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3074 /* regular helper call sets R0 */
3076 if (*reg_mask & 0x3f) {
3077 /* if backtracing was looking for registers R1-R5
3078 * they should have been found already.
3080 verbose(env, "BUG regs %x\n", *reg_mask);
3081 WARN_ONCE(1, "verifier backtracking bug");
3084 } else if (opcode == BPF_EXIT) {
3087 } else if (class == BPF_LD) {
3088 if (!(*reg_mask & dreg))
3091 /* It's ld_imm64 or ld_abs or ld_ind.
3092 * For ld_imm64 no further tracking of precision
3093 * into parent is necessary
3095 if (mode == BPF_IND || mode == BPF_ABS)
3096 /* to be analyzed */
3102 /* the scalar precision tracking algorithm:
3103 * . at the start all registers have precise=false.
3104 * . scalar ranges are tracked as normal through alu and jmp insns.
3105 * . once precise value of the scalar register is used in:
3106 * . ptr + scalar alu
3107 * . if (scalar cond K|scalar)
3108 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3109 * backtrack through the verifier states and mark all registers and
3110 * stack slots with spilled constants that these scalar regisers
3111 * should be precise.
3112 * . during state pruning two registers (or spilled stack slots)
3113 * are equivalent if both are not precise.
3115 * Note the verifier cannot simply walk register parentage chain,
3116 * since many different registers and stack slots could have been
3117 * used to compute single precise scalar.
3119 * The approach of starting with precise=true for all registers and then
3120 * backtrack to mark a register as not precise when the verifier detects
3121 * that program doesn't care about specific value (e.g., when helper
3122 * takes register as ARG_ANYTHING parameter) is not safe.
3124 * It's ok to walk single parentage chain of the verifier states.
3125 * It's possible that this backtracking will go all the way till 1st insn.
3126 * All other branches will be explored for needing precision later.
3128 * The backtracking needs to deal with cases like:
3129 * 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)
3132 * if r5 > 0x79f goto pc+7
3133 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3136 * call bpf_perf_event_output#25
3137 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3141 * call foo // uses callee's r6 inside to compute r0
3145 * to track above reg_mask/stack_mask needs to be independent for each frame.
3147 * Also if parent's curframe > frame where backtracking started,
3148 * the verifier need to mark registers in both frames, otherwise callees
3149 * may incorrectly prune callers. This is similar to
3150 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3152 * For now backtracking falls back into conservative marking.
3154 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3155 struct bpf_verifier_state *st)
3157 struct bpf_func_state *func;
3158 struct bpf_reg_state *reg;
3161 /* big hammer: mark all scalars precise in this path.
3162 * pop_stack may still get !precise scalars.
3163 * We also skip current state and go straight to first parent state,
3164 * because precision markings in current non-checkpointed state are
3165 * not needed. See why in the comment in __mark_chain_precision below.
3167 for (st = st->parent; st; st = st->parent) {
3168 for (i = 0; i <= st->curframe; i++) {
3169 func = st->frame[i];
3170 for (j = 0; j < BPF_REG_FP; j++) {
3171 reg = &func->regs[j];
3172 if (reg->type != SCALAR_VALUE)
3174 reg->precise = true;
3176 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3177 if (!is_spilled_reg(&func->stack[j]))
3179 reg = &func->stack[j].spilled_ptr;
3180 if (reg->type != SCALAR_VALUE)
3182 reg->precise = true;
3188 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3190 struct bpf_func_state *func;
3191 struct bpf_reg_state *reg;
3194 for (i = 0; i <= st->curframe; i++) {
3195 func = st->frame[i];
3196 for (j = 0; j < BPF_REG_FP; j++) {
3197 reg = &func->regs[j];
3198 if (reg->type != SCALAR_VALUE)
3200 reg->precise = false;
3202 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3203 if (!is_spilled_reg(&func->stack[j]))
3205 reg = &func->stack[j].spilled_ptr;
3206 if (reg->type != SCALAR_VALUE)
3208 reg->precise = false;
3214 * __mark_chain_precision() backtracks BPF program instruction sequence and
3215 * chain of verifier states making sure that register *regno* (if regno >= 0)
3216 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3217 * SCALARS, as well as any other registers and slots that contribute to
3218 * a tracked state of given registers/stack slots, depending on specific BPF
3219 * assembly instructions (see backtrack_insns() for exact instruction handling
3220 * logic). This backtracking relies on recorded jmp_history and is able to
3221 * traverse entire chain of parent states. This process ends only when all the
3222 * necessary registers/slots and their transitive dependencies are marked as
3225 * One important and subtle aspect is that precise marks *do not matter* in
3226 * the currently verified state (current state). It is important to understand
3227 * why this is the case.
3229 * First, note that current state is the state that is not yet "checkpointed",
3230 * i.e., it is not yet put into env->explored_states, and it has no children
3231 * states as well. It's ephemeral, and can end up either a) being discarded if
3232 * compatible explored state is found at some point or BPF_EXIT instruction is
3233 * reached or b) checkpointed and put into env->explored_states, branching out
3234 * into one or more children states.
3236 * In the former case, precise markings in current state are completely
3237 * ignored by state comparison code (see regsafe() for details). Only
3238 * checkpointed ("old") state precise markings are important, and if old
3239 * state's register/slot is precise, regsafe() assumes current state's
3240 * register/slot as precise and checks value ranges exactly and precisely. If
3241 * states turn out to be compatible, current state's necessary precise
3242 * markings and any required parent states' precise markings are enforced
3243 * after the fact with propagate_precision() logic, after the fact. But it's
3244 * important to realize that in this case, even after marking current state
3245 * registers/slots as precise, we immediately discard current state. So what
3246 * actually matters is any of the precise markings propagated into current
3247 * state's parent states, which are always checkpointed (due to b) case above).
3248 * As such, for scenario a) it doesn't matter if current state has precise
3249 * markings set or not.
3251 * Now, for the scenario b), checkpointing and forking into child(ren)
3252 * state(s). Note that before current state gets to checkpointing step, any
3253 * processed instruction always assumes precise SCALAR register/slot
3254 * knowledge: if precise value or range is useful to prune jump branch, BPF
3255 * verifier takes this opportunity enthusiastically. Similarly, when
3256 * register's value is used to calculate offset or memory address, exact
3257 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3258 * what we mentioned above about state comparison ignoring precise markings
3259 * during state comparison, BPF verifier ignores and also assumes precise
3260 * markings *at will* during instruction verification process. But as verifier
3261 * assumes precision, it also propagates any precision dependencies across
3262 * parent states, which are not yet finalized, so can be further restricted
3263 * based on new knowledge gained from restrictions enforced by their children
3264 * states. This is so that once those parent states are finalized, i.e., when
3265 * they have no more active children state, state comparison logic in
3266 * is_state_visited() would enforce strict and precise SCALAR ranges, if
3267 * required for correctness.
3269 * To build a bit more intuition, note also that once a state is checkpointed,
3270 * the path we took to get to that state is not important. This is crucial
3271 * property for state pruning. When state is checkpointed and finalized at
3272 * some instruction index, it can be correctly and safely used to "short
3273 * circuit" any *compatible* state that reaches exactly the same instruction
3274 * index. I.e., if we jumped to that instruction from a completely different
3275 * code path than original finalized state was derived from, it doesn't
3276 * matter, current state can be discarded because from that instruction
3277 * forward having a compatible state will ensure we will safely reach the
3278 * exit. States describe preconditions for further exploration, but completely
3279 * forget the history of how we got here.
3281 * This also means that even if we needed precise SCALAR range to get to
3282 * finalized state, but from that point forward *that same* SCALAR register is
3283 * never used in a precise context (i.e., it's precise value is not needed for
3284 * correctness), it's correct and safe to mark such register as "imprecise"
3285 * (i.e., precise marking set to false). This is what we rely on when we do
3286 * not set precise marking in current state. If no child state requires
3287 * precision for any given SCALAR register, it's safe to dictate that it can
3288 * be imprecise. If any child state does require this register to be precise,
3289 * we'll mark it precise later retroactively during precise markings
3290 * propagation from child state to parent states.
3292 * Skipping precise marking setting in current state is a mild version of
3293 * relying on the above observation. But we can utilize this property even
3294 * more aggressively by proactively forgetting any precise marking in the
3295 * current state (which we inherited from the parent state), right before we
3296 * checkpoint it and branch off into new child state. This is done by
3297 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3298 * finalized states which help in short circuiting more future states.
3300 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
3303 struct bpf_verifier_state *st = env->cur_state;
3304 int first_idx = st->first_insn_idx;
3305 int last_idx = env->insn_idx;
3306 struct bpf_func_state *func;
3307 struct bpf_reg_state *reg;
3308 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
3309 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
3310 bool skip_first = true;
3311 bool new_marks = false;
3314 if (!env->bpf_capable)
3317 /* Do sanity checks against current state of register and/or stack
3318 * slot, but don't set precise flag in current state, as precision
3319 * tracking in the current state is unnecessary.
3321 func = st->frame[frame];
3323 reg = &func->regs[regno];
3324 if (reg->type != SCALAR_VALUE) {
3325 WARN_ONCE(1, "backtracing misuse");
3332 if (!is_spilled_reg(&func->stack[spi])) {
3336 reg = &func->stack[spi].spilled_ptr;
3337 if (reg->type != SCALAR_VALUE) {
3347 if (!reg_mask && !stack_mask)
3351 DECLARE_BITMAP(mask, 64);
3352 u32 history = st->jmp_history_cnt;
3354 if (env->log.level & BPF_LOG_LEVEL2)
3355 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3358 /* we are at the entry into subprog, which
3359 * is expected for global funcs, but only if
3360 * requested precise registers are R1-R5
3361 * (which are global func's input arguments)
3363 if (st->curframe == 0 &&
3364 st->frame[0]->subprogno > 0 &&
3365 st->frame[0]->callsite == BPF_MAIN_FUNC &&
3366 stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3367 bitmap_from_u64(mask, reg_mask);
3368 for_each_set_bit(i, mask, 32) {
3369 reg = &st->frame[0]->regs[i];
3370 if (reg->type != SCALAR_VALUE) {
3371 reg_mask &= ~(1u << i);
3374 reg->precise = true;
3379 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3380 st->frame[0]->subprogno, reg_mask, stack_mask);
3381 WARN_ONCE(1, "verifier backtracking bug");
3385 for (i = last_idx;;) {
3390 err = backtrack_insn(env, i, ®_mask, &stack_mask);
3392 if (err == -ENOTSUPP) {
3393 mark_all_scalars_precise(env, st);
3398 if (!reg_mask && !stack_mask)
3399 /* Found assignment(s) into tracked register in this state.
3400 * Since this state is already marked, just return.
3401 * Nothing to be tracked further in the parent state.
3406 i = get_prev_insn_idx(st, i, &history);
3407 if (i >= env->prog->len) {
3408 /* This can happen if backtracking reached insn 0
3409 * and there are still reg_mask or stack_mask
3411 * It means the backtracking missed the spot where
3412 * particular register was initialized with a constant.
3414 verbose(env, "BUG backtracking idx %d\n", i);
3415 WARN_ONCE(1, "verifier backtracking bug");
3424 func = st->frame[frame];
3425 bitmap_from_u64(mask, reg_mask);
3426 for_each_set_bit(i, mask, 32) {
3427 reg = &func->regs[i];
3428 if (reg->type != SCALAR_VALUE) {
3429 reg_mask &= ~(1u << i);
3434 reg->precise = true;
3437 bitmap_from_u64(mask, stack_mask);
3438 for_each_set_bit(i, mask, 64) {
3439 if (i >= func->allocated_stack / BPF_REG_SIZE) {
3440 /* the sequence of instructions:
3442 * 3: (7b) *(u64 *)(r3 -8) = r0
3443 * 4: (79) r4 = *(u64 *)(r10 -8)
3444 * doesn't contain jmps. It's backtracked
3445 * as a single block.
3446 * During backtracking insn 3 is not recognized as
3447 * stack access, so at the end of backtracking
3448 * stack slot fp-8 is still marked in stack_mask.
3449 * However the parent state may not have accessed
3450 * fp-8 and it's "unallocated" stack space.
3451 * In such case fallback to conservative.
3453 mark_all_scalars_precise(env, st);
3457 if (!is_spilled_reg(&func->stack[i])) {
3458 stack_mask &= ~(1ull << i);
3461 reg = &func->stack[i].spilled_ptr;
3462 if (reg->type != SCALAR_VALUE) {
3463 stack_mask &= ~(1ull << i);
3468 reg->precise = true;
3470 if (env->log.level & BPF_LOG_LEVEL2) {
3471 verbose(env, "parent %s regs=%x stack=%llx marks:",
3472 new_marks ? "didn't have" : "already had",
3473 reg_mask, stack_mask);
3474 print_verifier_state(env, func, true);
3477 if (!reg_mask && !stack_mask)
3482 last_idx = st->last_insn_idx;
3483 first_idx = st->first_insn_idx;
3488 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3490 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3493 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3495 return __mark_chain_precision(env, frame, regno, -1);
3498 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3500 return __mark_chain_precision(env, frame, -1, spi);
3503 static bool is_spillable_regtype(enum bpf_reg_type type)
3505 switch (base_type(type)) {
3506 case PTR_TO_MAP_VALUE:
3510 case PTR_TO_PACKET_META:
3511 case PTR_TO_PACKET_END:
3512 case PTR_TO_FLOW_KEYS:
3513 case CONST_PTR_TO_MAP:
3515 case PTR_TO_SOCK_COMMON:
3516 case PTR_TO_TCP_SOCK:
3517 case PTR_TO_XDP_SOCK:
3522 case PTR_TO_MAP_KEY:
3529 /* Does this register contain a constant zero? */
3530 static bool register_is_null(struct bpf_reg_state *reg)
3532 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3535 static bool register_is_const(struct bpf_reg_state *reg)
3537 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3540 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3542 return tnum_is_unknown(reg->var_off) &&
3543 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3544 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3545 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3546 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3549 static bool register_is_bounded(struct bpf_reg_state *reg)
3551 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3554 static bool __is_pointer_value(bool allow_ptr_leaks,
3555 const struct bpf_reg_state *reg)
3557 if (allow_ptr_leaks)
3560 return reg->type != SCALAR_VALUE;
3563 /* Copy src state preserving dst->parent and dst->live fields */
3564 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3566 struct bpf_reg_state *parent = dst->parent;
3567 enum bpf_reg_liveness live = dst->live;
3570 dst->parent = parent;
3574 static void save_register_state(struct bpf_func_state *state,
3575 int spi, struct bpf_reg_state *reg,
3580 copy_register_state(&state->stack[spi].spilled_ptr, reg);
3581 if (size == BPF_REG_SIZE)
3582 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3584 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3585 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3587 /* size < 8 bytes spill */
3589 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3592 static bool is_bpf_st_mem(struct bpf_insn *insn)
3594 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3597 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3598 * stack boundary and alignment are checked in check_mem_access()
3600 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3601 /* stack frame we're writing to */
3602 struct bpf_func_state *state,
3603 int off, int size, int value_regno,
3606 struct bpf_func_state *cur; /* state of the current function */
3607 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3608 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3609 struct bpf_reg_state *reg = NULL;
3610 u32 dst_reg = insn->dst_reg;
3612 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3615 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3616 * so it's aligned access and [off, off + size) are within stack limits
3618 if (!env->allow_ptr_leaks &&
3619 state->stack[spi].slot_type[0] == STACK_SPILL &&
3620 size != BPF_REG_SIZE) {
3621 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3625 cur = env->cur_state->frame[env->cur_state->curframe];
3626 if (value_regno >= 0)
3627 reg = &cur->regs[value_regno];
3628 if (!env->bypass_spec_v4) {
3629 bool sanitize = reg && is_spillable_regtype(reg->type);
3631 for (i = 0; i < size; i++) {
3632 u8 type = state->stack[spi].slot_type[i];
3634 if (type != STACK_MISC && type != STACK_ZERO) {
3641 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3644 err = destroy_if_dynptr_stack_slot(env, state, spi);
3648 mark_stack_slot_scratched(env, spi);
3649 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3650 !register_is_null(reg) && env->bpf_capable) {
3651 if (dst_reg != BPF_REG_FP) {
3652 /* The backtracking logic can only recognize explicit
3653 * stack slot address like [fp - 8]. Other spill of
3654 * scalar via different register has to be conservative.
3655 * Backtrack from here and mark all registers as precise
3656 * that contributed into 'reg' being a constant.
3658 err = mark_chain_precision(env, value_regno);
3662 save_register_state(state, spi, reg, size);
3663 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3664 insn->imm != 0 && env->bpf_capable) {
3665 struct bpf_reg_state fake_reg = {};
3667 __mark_reg_known(&fake_reg, (u32)insn->imm);
3668 fake_reg.type = SCALAR_VALUE;
3669 save_register_state(state, spi, &fake_reg, size);
3670 } else if (reg && is_spillable_regtype(reg->type)) {
3671 /* register containing pointer is being spilled into stack */
3672 if (size != BPF_REG_SIZE) {
3673 verbose_linfo(env, insn_idx, "; ");
3674 verbose(env, "invalid size of register spill\n");
3677 if (state != cur && reg->type == PTR_TO_STACK) {
3678 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3681 save_register_state(state, spi, reg, size);
3683 u8 type = STACK_MISC;
3685 /* regular write of data into stack destroys any spilled ptr */
3686 state->stack[spi].spilled_ptr.type = NOT_INIT;
3687 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3688 if (is_spilled_reg(&state->stack[spi]))
3689 for (i = 0; i < BPF_REG_SIZE; i++)
3690 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3692 /* only mark the slot as written if all 8 bytes were written
3693 * otherwise read propagation may incorrectly stop too soon
3694 * when stack slots are partially written.
3695 * This heuristic means that read propagation will be
3696 * conservative, since it will add reg_live_read marks
3697 * to stack slots all the way to first state when programs
3698 * writes+reads less than 8 bytes
3700 if (size == BPF_REG_SIZE)
3701 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3703 /* when we zero initialize stack slots mark them as such */
3704 if ((reg && register_is_null(reg)) ||
3705 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3706 /* backtracking doesn't work for STACK_ZERO yet. */
3707 err = mark_chain_precision(env, value_regno);
3713 /* Mark slots affected by this stack write. */
3714 for (i = 0; i < size; i++)
3715 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3721 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3722 * known to contain a variable offset.
3723 * This function checks whether the write is permitted and conservatively
3724 * tracks the effects of the write, considering that each stack slot in the
3725 * dynamic range is potentially written to.
3727 * 'off' includes 'regno->off'.
3728 * 'value_regno' can be -1, meaning that an unknown value is being written to
3731 * Spilled pointers in range are not marked as written because we don't know
3732 * what's going to be actually written. This means that read propagation for
3733 * future reads cannot be terminated by this write.
3735 * For privileged programs, uninitialized stack slots are considered
3736 * initialized by this write (even though we don't know exactly what offsets
3737 * are going to be written to). The idea is that we don't want the verifier to
3738 * reject future reads that access slots written to through variable offsets.
3740 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3741 /* func where register points to */
3742 struct bpf_func_state *state,
3743 int ptr_regno, int off, int size,
3744 int value_regno, int insn_idx)
3746 struct bpf_func_state *cur; /* state of the current function */
3747 int min_off, max_off;
3749 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3750 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3751 bool writing_zero = false;
3752 /* set if the fact that we're writing a zero is used to let any
3753 * stack slots remain STACK_ZERO
3755 bool zero_used = false;
3757 cur = env->cur_state->frame[env->cur_state->curframe];
3758 ptr_reg = &cur->regs[ptr_regno];
3759 min_off = ptr_reg->smin_value + off;
3760 max_off = ptr_reg->smax_value + off + size;
3761 if (value_regno >= 0)
3762 value_reg = &cur->regs[value_regno];
3763 if ((value_reg && register_is_null(value_reg)) ||
3764 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
3765 writing_zero = true;
3767 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3771 for (i = min_off; i < max_off; i++) {
3775 err = destroy_if_dynptr_stack_slot(env, state, spi);
3780 /* Variable offset writes destroy any spilled pointers in range. */
3781 for (i = min_off; i < max_off; i++) {
3782 u8 new_type, *stype;
3786 spi = slot / BPF_REG_SIZE;
3787 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3788 mark_stack_slot_scratched(env, spi);
3790 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3791 /* Reject the write if range we may write to has not
3792 * been initialized beforehand. If we didn't reject
3793 * here, the ptr status would be erased below (even
3794 * though not all slots are actually overwritten),
3795 * possibly opening the door to leaks.
3797 * We do however catch STACK_INVALID case below, and
3798 * only allow reading possibly uninitialized memory
3799 * later for CAP_PERFMON, as the write may not happen to
3802 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3807 /* Erase all spilled pointers. */
3808 state->stack[spi].spilled_ptr.type = NOT_INIT;
3810 /* Update the slot type. */
3811 new_type = STACK_MISC;
3812 if (writing_zero && *stype == STACK_ZERO) {
3813 new_type = STACK_ZERO;
3816 /* If the slot is STACK_INVALID, we check whether it's OK to
3817 * pretend that it will be initialized by this write. The slot
3818 * might not actually be written to, and so if we mark it as
3819 * initialized future reads might leak uninitialized memory.
3820 * For privileged programs, we will accept such reads to slots
3821 * that may or may not be written because, if we're reject
3822 * them, the error would be too confusing.
3824 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3825 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3832 /* backtracking doesn't work for STACK_ZERO yet. */
3833 err = mark_chain_precision(env, value_regno);
3840 /* When register 'dst_regno' is assigned some values from stack[min_off,
3841 * max_off), we set the register's type according to the types of the
3842 * respective stack slots. If all the stack values are known to be zeros, then
3843 * so is the destination reg. Otherwise, the register is considered to be
3844 * SCALAR. This function does not deal with register filling; the caller must
3845 * ensure that all spilled registers in the stack range have been marked as
3848 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3849 /* func where src register points to */
3850 struct bpf_func_state *ptr_state,
3851 int min_off, int max_off, int dst_regno)
3853 struct bpf_verifier_state *vstate = env->cur_state;
3854 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3859 for (i = min_off; i < max_off; i++) {
3861 spi = slot / BPF_REG_SIZE;
3862 stype = ptr_state->stack[spi].slot_type;
3863 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3867 if (zeros == max_off - min_off) {
3868 /* any access_size read into register is zero extended,
3869 * so the whole register == const_zero
3871 __mark_reg_const_zero(&state->regs[dst_regno]);
3872 /* backtracking doesn't support STACK_ZERO yet,
3873 * so mark it precise here, so that later
3874 * backtracking can stop here.
3875 * Backtracking may not need this if this register
3876 * doesn't participate in pointer adjustment.
3877 * Forward propagation of precise flag is not
3878 * necessary either. This mark is only to stop
3879 * backtracking. Any register that contributed
3880 * to const 0 was marked precise before spill.
3882 state->regs[dst_regno].precise = true;
3884 /* have read misc data from the stack */
3885 mark_reg_unknown(env, state->regs, dst_regno);
3887 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3890 /* Read the stack at 'off' and put the results into the register indicated by
3891 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3894 * 'dst_regno' can be -1, meaning that the read value is not going to a
3897 * The access is assumed to be within the current stack bounds.
3899 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3900 /* func where src register points to */
3901 struct bpf_func_state *reg_state,
3902 int off, int size, int dst_regno)
3904 struct bpf_verifier_state *vstate = env->cur_state;
3905 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3906 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3907 struct bpf_reg_state *reg;
3910 stype = reg_state->stack[spi].slot_type;
3911 reg = ®_state->stack[spi].spilled_ptr;
3913 if (is_spilled_reg(®_state->stack[spi])) {
3916 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3919 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3920 if (reg->type != SCALAR_VALUE) {
3921 verbose_linfo(env, env->insn_idx, "; ");
3922 verbose(env, "invalid size of register fill\n");
3926 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3930 if (!(off % BPF_REG_SIZE) && size == spill_size) {
3931 /* The earlier check_reg_arg() has decided the
3932 * subreg_def for this insn. Save it first.
3934 s32 subreg_def = state->regs[dst_regno].subreg_def;
3936 copy_register_state(&state->regs[dst_regno], reg);
3937 state->regs[dst_regno].subreg_def = subreg_def;
3939 for (i = 0; i < size; i++) {
3940 type = stype[(slot - i) % BPF_REG_SIZE];
3941 if (type == STACK_SPILL)
3943 if (type == STACK_MISC)
3945 if (type == STACK_INVALID && env->allow_uninit_stack)
3947 verbose(env, "invalid read from stack off %d+%d size %d\n",
3951 mark_reg_unknown(env, state->regs, dst_regno);
3953 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3957 if (dst_regno >= 0) {
3958 /* restore register state from stack */
3959 copy_register_state(&state->regs[dst_regno], reg);
3960 /* mark reg as written since spilled pointer state likely
3961 * has its liveness marks cleared by is_state_visited()
3962 * which resets stack/reg liveness for state transitions
3964 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3965 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3966 /* If dst_regno==-1, the caller is asking us whether
3967 * it is acceptable to use this value as a SCALAR_VALUE
3969 * We must not allow unprivileged callers to do that
3970 * with spilled pointers.
3972 verbose(env, "leaking pointer from stack off %d\n",
3976 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3978 for (i = 0; i < size; i++) {
3979 type = stype[(slot - i) % BPF_REG_SIZE];
3980 if (type == STACK_MISC)
3982 if (type == STACK_ZERO)
3984 if (type == STACK_INVALID && env->allow_uninit_stack)
3986 verbose(env, "invalid read from stack off %d+%d size %d\n",
3990 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3992 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3997 enum bpf_access_src {
3998 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
3999 ACCESS_HELPER = 2, /* the access is performed by a helper */
4002 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4003 int regno, int off, int access_size,
4004 bool zero_size_allowed,
4005 enum bpf_access_src type,
4006 struct bpf_call_arg_meta *meta);
4008 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4010 return cur_regs(env) + regno;
4013 /* Read the stack at 'ptr_regno + off' and put the result into the register
4015 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4016 * but not its variable offset.
4017 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4019 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4020 * filling registers (i.e. reads of spilled register cannot be detected when
4021 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4022 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4023 * offset; for a fixed offset check_stack_read_fixed_off should be used
4026 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4027 int ptr_regno, int off, int size, int dst_regno)
4029 /* The state of the source register. */
4030 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4031 struct bpf_func_state *ptr_state = func(env, reg);
4033 int min_off, max_off;
4035 /* Note that we pass a NULL meta, so raw access will not be permitted.
4037 err = check_stack_range_initialized(env, ptr_regno, off, size,
4038 false, ACCESS_DIRECT, NULL);
4042 min_off = reg->smin_value + off;
4043 max_off = reg->smax_value + off;
4044 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4048 /* check_stack_read dispatches to check_stack_read_fixed_off or
4049 * check_stack_read_var_off.
4051 * The caller must ensure that the offset falls within the allocated stack
4054 * 'dst_regno' is a register which will receive the value from the stack. It
4055 * can be -1, meaning that the read value is not going to a register.
4057 static int check_stack_read(struct bpf_verifier_env *env,
4058 int ptr_regno, int off, int size,
4061 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4062 struct bpf_func_state *state = func(env, reg);
4064 /* Some accesses are only permitted with a static offset. */
4065 bool var_off = !tnum_is_const(reg->var_off);
4067 /* The offset is required to be static when reads don't go to a
4068 * register, in order to not leak pointers (see
4069 * check_stack_read_fixed_off).
4071 if (dst_regno < 0 && var_off) {
4074 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4075 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4079 /* Variable offset is prohibited for unprivileged mode for simplicity
4080 * since it requires corresponding support in Spectre masking for stack
4081 * ALU. See also retrieve_ptr_limit().
4083 if (!env->bypass_spec_v1 && var_off) {
4086 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4087 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
4093 off += reg->var_off.value;
4094 err = check_stack_read_fixed_off(env, state, off, size,
4097 /* Variable offset stack reads need more conservative handling
4098 * than fixed offset ones. Note that dst_regno >= 0 on this
4101 err = check_stack_read_var_off(env, ptr_regno, off, size,
4108 /* check_stack_write dispatches to check_stack_write_fixed_off or
4109 * check_stack_write_var_off.
4111 * 'ptr_regno' is the register used as a pointer into the stack.
4112 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4113 * 'value_regno' is the register whose value we're writing to the stack. It can
4114 * be -1, meaning that we're not writing from a register.
4116 * The caller must ensure that the offset falls within the maximum stack size.
4118 static int check_stack_write(struct bpf_verifier_env *env,
4119 int ptr_regno, int off, int size,
4120 int value_regno, int insn_idx)
4122 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4123 struct bpf_func_state *state = func(env, reg);
4126 if (tnum_is_const(reg->var_off)) {
4127 off += reg->var_off.value;
4128 err = check_stack_write_fixed_off(env, state, off, size,
4129 value_regno, insn_idx);
4131 /* Variable offset stack reads need more conservative handling
4132 * than fixed offset ones.
4134 err = check_stack_write_var_off(env, state,
4135 ptr_regno, off, size,
4136 value_regno, insn_idx);
4141 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4142 int off, int size, enum bpf_access_type type)
4144 struct bpf_reg_state *regs = cur_regs(env);
4145 struct bpf_map *map = regs[regno].map_ptr;
4146 u32 cap = bpf_map_flags_to_cap(map);
4148 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4149 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4150 map->value_size, off, size);
4154 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4155 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4156 map->value_size, off, size);
4163 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4164 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4165 int off, int size, u32 mem_size,
4166 bool zero_size_allowed)
4168 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4169 struct bpf_reg_state *reg;
4171 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4174 reg = &cur_regs(env)[regno];
4175 switch (reg->type) {
4176 case PTR_TO_MAP_KEY:
4177 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4178 mem_size, off, size);
4180 case PTR_TO_MAP_VALUE:
4181 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4182 mem_size, off, size);
4185 case PTR_TO_PACKET_META:
4186 case PTR_TO_PACKET_END:
4187 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4188 off, size, regno, reg->id, off, mem_size);
4192 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4193 mem_size, off, size);
4199 /* check read/write into a memory region with possible variable offset */
4200 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4201 int off, int size, u32 mem_size,
4202 bool zero_size_allowed)
4204 struct bpf_verifier_state *vstate = env->cur_state;
4205 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4206 struct bpf_reg_state *reg = &state->regs[regno];
4209 /* We may have adjusted the register pointing to memory region, so we
4210 * need to try adding each of min_value and max_value to off
4211 * to make sure our theoretical access will be safe.
4213 * The minimum value is only important with signed
4214 * comparisons where we can't assume the floor of a
4215 * value is 0. If we are using signed variables for our
4216 * index'es we need to make sure that whatever we use
4217 * will have a set floor within our range.
4219 if (reg->smin_value < 0 &&
4220 (reg->smin_value == S64_MIN ||
4221 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4222 reg->smin_value + off < 0)) {
4223 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4227 err = __check_mem_access(env, regno, reg->smin_value + off, size,
4228 mem_size, zero_size_allowed);
4230 verbose(env, "R%d min value is outside of the allowed memory range\n",
4235 /* If we haven't set a max value then we need to bail since we can't be
4236 * sure we won't do bad things.
4237 * If reg->umax_value + off could overflow, treat that as unbounded too.
4239 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4240 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4244 err = __check_mem_access(env, regno, reg->umax_value + off, size,
4245 mem_size, zero_size_allowed);
4247 verbose(env, "R%d max value is outside of the allowed memory range\n",
4255 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4256 const struct bpf_reg_state *reg, int regno,
4259 /* Access to this pointer-typed register or passing it to a helper
4260 * is only allowed in its original, unmodified form.
4264 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4265 reg_type_str(env, reg->type), regno, reg->off);
4269 if (!fixed_off_ok && reg->off) {
4270 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4271 reg_type_str(env, reg->type), regno, reg->off);
4275 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4278 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4279 verbose(env, "variable %s access var_off=%s disallowed\n",
4280 reg_type_str(env, reg->type), tn_buf);
4287 int check_ptr_off_reg(struct bpf_verifier_env *env,
4288 const struct bpf_reg_state *reg, int regno)
4290 return __check_ptr_off_reg(env, reg, regno, false);
4293 static int map_kptr_match_type(struct bpf_verifier_env *env,
4294 struct btf_field *kptr_field,
4295 struct bpf_reg_state *reg, u32 regno)
4297 const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4298 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4299 const char *reg_name = "";
4301 /* Only unreferenced case accepts untrusted pointers */
4302 if (kptr_field->type == BPF_KPTR_UNREF)
4303 perm_flags |= PTR_UNTRUSTED;
4305 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4308 if (!btf_is_kernel(reg->btf)) {
4309 verbose(env, "R%d must point to kernel BTF\n", regno);
4312 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
4313 reg_name = kernel_type_name(reg->btf, reg->btf_id);
4315 /* For ref_ptr case, release function check should ensure we get one
4316 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4317 * normal store of unreferenced kptr, we must ensure var_off is zero.
4318 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4319 * reg->off and reg->ref_obj_id are not needed here.
4321 if (__check_ptr_off_reg(env, reg, regno, true))
4324 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
4325 * we also need to take into account the reg->off.
4327 * We want to support cases like:
4335 * v = func(); // PTR_TO_BTF_ID
4336 * val->foo = v; // reg->off is zero, btf and btf_id match type
4337 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4338 * // first member type of struct after comparison fails
4339 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4342 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
4343 * is zero. We must also ensure that btf_struct_ids_match does not walk
4344 * the struct to match type against first member of struct, i.e. reject
4345 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4346 * strict mode to true for type match.
4348 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4349 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4350 kptr_field->type == BPF_KPTR_REF))
4354 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4355 reg_type_str(env, reg->type), reg_name);
4356 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4357 if (kptr_field->type == BPF_KPTR_UNREF)
4358 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4365 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4366 * can dereference RCU protected pointers and result is PTR_TRUSTED.
4368 static bool in_rcu_cs(struct bpf_verifier_env *env)
4370 return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
4373 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4374 BTF_SET_START(rcu_protected_types)
4375 BTF_ID(struct, prog_test_ref_kfunc)
4376 BTF_ID(struct, cgroup)
4377 BTF_SET_END(rcu_protected_types)
4379 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4381 if (!btf_is_kernel(btf))
4383 return btf_id_set_contains(&rcu_protected_types, btf_id);
4386 static bool rcu_safe_kptr(const struct btf_field *field)
4388 const struct btf_field_kptr *kptr = &field->kptr;
4390 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
4393 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4394 int value_regno, int insn_idx,
4395 struct btf_field *kptr_field)
4397 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4398 int class = BPF_CLASS(insn->code);
4399 struct bpf_reg_state *val_reg;
4401 /* Things we already checked for in check_map_access and caller:
4402 * - Reject cases where variable offset may touch kptr
4403 * - size of access (must be BPF_DW)
4404 * - tnum_is_const(reg->var_off)
4405 * - kptr_field->offset == off + reg->var_off.value
4407 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4408 if (BPF_MODE(insn->code) != BPF_MEM) {
4409 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4413 /* We only allow loading referenced kptr, since it will be marked as
4414 * untrusted, similar to unreferenced kptr.
4416 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4417 verbose(env, "store to referenced kptr disallowed\n");
4421 if (class == BPF_LDX) {
4422 val_reg = reg_state(env, value_regno);
4423 /* We can simply mark the value_regno receiving the pointer
4424 * value from map as PTR_TO_BTF_ID, with the correct type.
4426 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4427 kptr_field->kptr.btf_id,
4428 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
4429 PTR_MAYBE_NULL | MEM_RCU :
4430 PTR_MAYBE_NULL | PTR_UNTRUSTED);
4431 /* For mark_ptr_or_null_reg */
4432 val_reg->id = ++env->id_gen;
4433 } else if (class == BPF_STX) {
4434 val_reg = reg_state(env, value_regno);
4435 if (!register_is_null(val_reg) &&
4436 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4438 } else if (class == BPF_ST) {
4440 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4441 kptr_field->offset);
4445 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4451 /* check read/write into a map element with possible variable offset */
4452 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4453 int off, int size, bool zero_size_allowed,
4454 enum bpf_access_src src)
4456 struct bpf_verifier_state *vstate = env->cur_state;
4457 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4458 struct bpf_reg_state *reg = &state->regs[regno];
4459 struct bpf_map *map = reg->map_ptr;
4460 struct btf_record *rec;
4463 err = check_mem_region_access(env, regno, off, size, map->value_size,
4468 if (IS_ERR_OR_NULL(map->record))
4471 for (i = 0; i < rec->cnt; i++) {
4472 struct btf_field *field = &rec->fields[i];
4473 u32 p = field->offset;
4475 /* If any part of a field can be touched by load/store, reject
4476 * this program. To check that [x1, x2) overlaps with [y1, y2),
4477 * it is sufficient to check x1 < y2 && y1 < x2.
4479 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4480 p < reg->umax_value + off + size) {
4481 switch (field->type) {
4482 case BPF_KPTR_UNREF:
4484 if (src != ACCESS_DIRECT) {
4485 verbose(env, "kptr cannot be accessed indirectly by helper\n");
4488 if (!tnum_is_const(reg->var_off)) {
4489 verbose(env, "kptr access cannot have variable offset\n");
4492 if (p != off + reg->var_off.value) {
4493 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4494 p, off + reg->var_off.value);
4497 if (size != bpf_size_to_bytes(BPF_DW)) {
4498 verbose(env, "kptr access size must be BPF_DW\n");
4503 verbose(env, "%s cannot be accessed directly by load/store\n",
4504 btf_field_type_name(field->type));
4512 #define MAX_PACKET_OFF 0xffff
4514 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4515 const struct bpf_call_arg_meta *meta,
4516 enum bpf_access_type t)
4518 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4520 switch (prog_type) {
4521 /* Program types only with direct read access go here! */
4522 case BPF_PROG_TYPE_LWT_IN:
4523 case BPF_PROG_TYPE_LWT_OUT:
4524 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4525 case BPF_PROG_TYPE_SK_REUSEPORT:
4526 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4527 case BPF_PROG_TYPE_CGROUP_SKB:
4532 /* Program types with direct read + write access go here! */
4533 case BPF_PROG_TYPE_SCHED_CLS:
4534 case BPF_PROG_TYPE_SCHED_ACT:
4535 case BPF_PROG_TYPE_XDP:
4536 case BPF_PROG_TYPE_LWT_XMIT:
4537 case BPF_PROG_TYPE_SK_SKB:
4538 case BPF_PROG_TYPE_SK_MSG:
4540 return meta->pkt_access;
4542 env->seen_direct_write = true;
4545 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4547 env->seen_direct_write = true;
4556 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4557 int size, bool zero_size_allowed)
4559 struct bpf_reg_state *regs = cur_regs(env);
4560 struct bpf_reg_state *reg = ®s[regno];
4563 /* We may have added a variable offset to the packet pointer; but any
4564 * reg->range we have comes after that. We are only checking the fixed
4568 /* We don't allow negative numbers, because we aren't tracking enough
4569 * detail to prove they're safe.
4571 if (reg->smin_value < 0) {
4572 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4577 err = reg->range < 0 ? -EINVAL :
4578 __check_mem_access(env, regno, off, size, reg->range,
4581 verbose(env, "R%d offset is outside of the packet\n", regno);
4585 /* __check_mem_access has made sure "off + size - 1" is within u16.
4586 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4587 * otherwise find_good_pkt_pointers would have refused to set range info
4588 * that __check_mem_access would have rejected this pkt access.
4589 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4591 env->prog->aux->max_pkt_offset =
4592 max_t(u32, env->prog->aux->max_pkt_offset,
4593 off + reg->umax_value + size - 1);
4598 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
4599 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4600 enum bpf_access_type t, enum bpf_reg_type *reg_type,
4601 struct btf **btf, u32 *btf_id)
4603 struct bpf_insn_access_aux info = {
4604 .reg_type = *reg_type,
4608 if (env->ops->is_valid_access &&
4609 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4610 /* A non zero info.ctx_field_size indicates that this field is a
4611 * candidate for later verifier transformation to load the whole
4612 * field and then apply a mask when accessed with a narrower
4613 * access than actual ctx access size. A zero info.ctx_field_size
4614 * will only allow for whole field access and rejects any other
4615 * type of narrower access.
4617 *reg_type = info.reg_type;
4619 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4621 *btf_id = info.btf_id;
4623 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4625 /* remember the offset of last byte accessed in ctx */
4626 if (env->prog->aux->max_ctx_offset < off + size)
4627 env->prog->aux->max_ctx_offset = off + size;
4631 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4635 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4638 if (size < 0 || off < 0 ||
4639 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4640 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4647 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4648 u32 regno, int off, int size,
4649 enum bpf_access_type t)
4651 struct bpf_reg_state *regs = cur_regs(env);
4652 struct bpf_reg_state *reg = ®s[regno];
4653 struct bpf_insn_access_aux info = {};
4656 if (reg->smin_value < 0) {
4657 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4662 switch (reg->type) {
4663 case PTR_TO_SOCK_COMMON:
4664 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4667 valid = bpf_sock_is_valid_access(off, size, t, &info);
4669 case PTR_TO_TCP_SOCK:
4670 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4672 case PTR_TO_XDP_SOCK:
4673 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4681 env->insn_aux_data[insn_idx].ctx_field_size =
4682 info.ctx_field_size;
4686 verbose(env, "R%d invalid %s access off=%d size=%d\n",
4687 regno, reg_type_str(env, reg->type), off, size);
4692 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4694 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4697 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4699 const struct bpf_reg_state *reg = reg_state(env, regno);
4701 return reg->type == PTR_TO_CTX;
4704 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4706 const struct bpf_reg_state *reg = reg_state(env, regno);
4708 return type_is_sk_pointer(reg->type);
4711 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4713 const struct bpf_reg_state *reg = reg_state(env, regno);
4715 return type_is_pkt_pointer(reg->type);
4718 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4720 const struct bpf_reg_state *reg = reg_state(env, regno);
4722 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4723 return reg->type == PTR_TO_FLOW_KEYS;
4726 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4728 /* A referenced register is always trusted. */
4729 if (reg->ref_obj_id)
4732 /* If a register is not referenced, it is trusted if it has the
4733 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4734 * other type modifiers may be safe, but we elect to take an opt-in
4735 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4738 * Eventually, we should make PTR_TRUSTED the single source of truth
4739 * for whether a register is trusted.
4741 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4742 !bpf_type_has_unsafe_modifiers(reg->type);
4745 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4747 return reg->type & MEM_RCU;
4750 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4751 const struct bpf_reg_state *reg,
4752 int off, int size, bool strict)
4754 struct tnum reg_off;
4757 /* Byte size accesses are always allowed. */
4758 if (!strict || size == 1)
4761 /* For platforms that do not have a Kconfig enabling
4762 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4763 * NET_IP_ALIGN is universally set to '2'. And on platforms
4764 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4765 * to this code only in strict mode where we want to emulate
4766 * the NET_IP_ALIGN==2 checking. Therefore use an
4767 * unconditional IP align value of '2'.
4771 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4772 if (!tnum_is_aligned(reg_off, size)) {
4775 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4777 "misaligned packet access off %d+%s+%d+%d size %d\n",
4778 ip_align, tn_buf, reg->off, off, size);
4785 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4786 const struct bpf_reg_state *reg,
4787 const char *pointer_desc,
4788 int off, int size, bool strict)
4790 struct tnum reg_off;
4792 /* Byte size accesses are always allowed. */
4793 if (!strict || size == 1)
4796 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4797 if (!tnum_is_aligned(reg_off, size)) {
4800 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4801 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4802 pointer_desc, tn_buf, reg->off, off, size);
4809 static int check_ptr_alignment(struct bpf_verifier_env *env,
4810 const struct bpf_reg_state *reg, int off,
4811 int size, bool strict_alignment_once)
4813 bool strict = env->strict_alignment || strict_alignment_once;
4814 const char *pointer_desc = "";
4816 switch (reg->type) {
4818 case PTR_TO_PACKET_META:
4819 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4820 * right in front, treat it the very same way.
4822 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4823 case PTR_TO_FLOW_KEYS:
4824 pointer_desc = "flow keys ";
4826 case PTR_TO_MAP_KEY:
4827 pointer_desc = "key ";
4829 case PTR_TO_MAP_VALUE:
4830 pointer_desc = "value ";
4833 pointer_desc = "context ";
4836 pointer_desc = "stack ";
4837 /* The stack spill tracking logic in check_stack_write_fixed_off()
4838 * and check_stack_read_fixed_off() relies on stack accesses being
4844 pointer_desc = "sock ";
4846 case PTR_TO_SOCK_COMMON:
4847 pointer_desc = "sock_common ";
4849 case PTR_TO_TCP_SOCK:
4850 pointer_desc = "tcp_sock ";
4852 case PTR_TO_XDP_SOCK:
4853 pointer_desc = "xdp_sock ";
4858 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4862 static int update_stack_depth(struct bpf_verifier_env *env,
4863 const struct bpf_func_state *func,
4866 u16 stack = env->subprog_info[func->subprogno].stack_depth;
4871 /* update known max for given subprogram */
4872 env->subprog_info[func->subprogno].stack_depth = -off;
4876 /* starting from main bpf function walk all instructions of the function
4877 * and recursively walk all callees that given function can call.
4878 * Ignore jump and exit insns.
4879 * Since recursion is prevented by check_cfg() this algorithm
4880 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4882 static int check_max_stack_depth(struct bpf_verifier_env *env)
4884 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4885 struct bpf_subprog_info *subprog = env->subprog_info;
4886 struct bpf_insn *insn = env->prog->insnsi;
4887 bool tail_call_reachable = false;
4888 int ret_insn[MAX_CALL_FRAMES];
4889 int ret_prog[MAX_CALL_FRAMES];
4893 /* protect against potential stack overflow that might happen when
4894 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4895 * depth for such case down to 256 so that the worst case scenario
4896 * would result in 8k stack size (32 which is tailcall limit * 256 =
4899 * To get the idea what might happen, see an example:
4900 * func1 -> sub rsp, 128
4901 * subfunc1 -> sub rsp, 256
4902 * tailcall1 -> add rsp, 256
4903 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4904 * subfunc2 -> sub rsp, 64
4905 * subfunc22 -> sub rsp, 128
4906 * tailcall2 -> add rsp, 128
4907 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4909 * tailcall will unwind the current stack frame but it will not get rid
4910 * of caller's stack as shown on the example above.
4912 if (idx && subprog[idx].has_tail_call && depth >= 256) {
4914 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4918 /* round up to 32-bytes, since this is granularity
4919 * of interpreter stack size
4921 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4922 if (depth > MAX_BPF_STACK) {
4923 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4928 subprog_end = subprog[idx + 1].start;
4929 for (; i < subprog_end; i++) {
4932 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4934 /* remember insn and function to return to */
4935 ret_insn[frame] = i + 1;
4936 ret_prog[frame] = idx;
4938 /* find the callee */
4939 next_insn = i + insn[i].imm + 1;
4940 idx = find_subprog(env, next_insn);
4942 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4946 if (subprog[idx].is_async_cb) {
4947 if (subprog[idx].has_tail_call) {
4948 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4951 /* async callbacks don't increase bpf prog stack size */
4956 if (subprog[idx].has_tail_call)
4957 tail_call_reachable = true;
4960 if (frame >= MAX_CALL_FRAMES) {
4961 verbose(env, "the call stack of %d frames is too deep !\n",
4967 /* if tail call got detected across bpf2bpf calls then mark each of the
4968 * currently present subprog frames as tail call reachable subprogs;
4969 * this info will be utilized by JIT so that we will be preserving the
4970 * tail call counter throughout bpf2bpf calls combined with tailcalls
4972 if (tail_call_reachable)
4973 for (j = 0; j < frame; j++)
4974 subprog[ret_prog[j]].tail_call_reachable = true;
4975 if (subprog[0].tail_call_reachable)
4976 env->prog->aux->tail_call_reachable = true;
4978 /* end of for() loop means the last insn of the 'subprog'
4979 * was reached. Doesn't matter whether it was JA or EXIT
4983 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4985 i = ret_insn[frame];
4986 idx = ret_prog[frame];
4990 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4991 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4992 const struct bpf_insn *insn, int idx)
4994 int start = idx + insn->imm + 1, subprog;
4996 subprog = find_subprog(env, start);
4998 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5002 return env->subprog_info[subprog].stack_depth;
5006 static int __check_buffer_access(struct bpf_verifier_env *env,
5007 const char *buf_info,
5008 const struct bpf_reg_state *reg,
5009 int regno, int off, int size)
5013 "R%d invalid %s buffer access: off=%d, size=%d\n",
5014 regno, buf_info, off, size);
5017 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5020 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5022 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5023 regno, off, tn_buf);
5030 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5031 const struct bpf_reg_state *reg,
5032 int regno, int off, int size)
5036 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5040 if (off + size > env->prog->aux->max_tp_access)
5041 env->prog->aux->max_tp_access = off + size;
5046 static int check_buffer_access(struct bpf_verifier_env *env,
5047 const struct bpf_reg_state *reg,
5048 int regno, int off, int size,
5049 bool zero_size_allowed,
5052 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5055 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5059 if (off + size > *max_access)
5060 *max_access = off + size;
5065 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5066 static void zext_32_to_64(struct bpf_reg_state *reg)
5068 reg->var_off = tnum_subreg(reg->var_off);
5069 __reg_assign_32_into_64(reg);
5072 /* truncate register to smaller size (in bytes)
5073 * must be called with size < BPF_REG_SIZE
5075 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5079 /* clear high bits in bit representation */
5080 reg->var_off = tnum_cast(reg->var_off, size);
5082 /* fix arithmetic bounds */
5083 mask = ((u64)1 << (size * 8)) - 1;
5084 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5085 reg->umin_value &= mask;
5086 reg->umax_value &= mask;
5088 reg->umin_value = 0;
5089 reg->umax_value = mask;
5091 reg->smin_value = reg->umin_value;
5092 reg->smax_value = reg->umax_value;
5094 /* If size is smaller than 32bit register the 32bit register
5095 * values are also truncated so we push 64-bit bounds into
5096 * 32-bit bounds. Above were truncated < 32-bits already.
5100 __reg_combine_64_into_32(reg);
5103 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5105 /* A map is considered read-only if the following condition are true:
5107 * 1) BPF program side cannot change any of the map content. The
5108 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5109 * and was set at map creation time.
5110 * 2) The map value(s) have been initialized from user space by a
5111 * loader and then "frozen", such that no new map update/delete
5112 * operations from syscall side are possible for the rest of
5113 * the map's lifetime from that point onwards.
5114 * 3) Any parallel/pending map update/delete operations from syscall
5115 * side have been completed. Only after that point, it's safe to
5116 * assume that map value(s) are immutable.
5118 return (map->map_flags & BPF_F_RDONLY_PROG) &&
5119 READ_ONCE(map->frozen) &&
5120 !bpf_map_write_active(map);
5123 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5129 err = map->ops->map_direct_value_addr(map, &addr, off);
5132 ptr = (void *)(long)addr + off;
5136 *val = (u64)*(u8 *)ptr;
5139 *val = (u64)*(u16 *)ptr;
5142 *val = (u64)*(u32 *)ptr;
5153 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
5154 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
5157 * Allow list few fields as RCU trusted or full trusted.
5158 * This logic doesn't allow mix tagging and will be removed once GCC supports
5162 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5163 BTF_TYPE_SAFE_RCU(struct task_struct) {
5164 const cpumask_t *cpus_ptr;
5165 struct css_set __rcu *cgroups;
5166 struct task_struct __rcu *real_parent;
5167 struct task_struct *group_leader;
5170 BTF_TYPE_SAFE_RCU(struct css_set) {
5171 struct cgroup *dfl_cgrp;
5174 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5175 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5176 __bpf_md_ptr(struct seq_file *, seq);
5179 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5180 __bpf_md_ptr(struct bpf_iter_meta *, meta);
5181 __bpf_md_ptr(struct task_struct *, task);
5184 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5188 BTF_TYPE_SAFE_TRUSTED(struct file) {
5189 struct inode *f_inode;
5192 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5193 /* no negative dentry-s in places where bpf can see it */
5194 struct inode *d_inode;
5197 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5201 static bool type_is_rcu(struct bpf_verifier_env *env,
5202 struct bpf_reg_state *reg,
5205 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5206 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5208 return btf_nested_type_is_trusted(&env->log, reg, off, "__safe_rcu");
5211 static bool type_is_trusted(struct bpf_verifier_env *env,
5212 struct bpf_reg_state *reg,
5215 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5216 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5217 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5218 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5219 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5220 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5222 return btf_nested_type_is_trusted(&env->log, reg, off, "__safe_trusted");
5225 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5226 struct bpf_reg_state *regs,
5227 int regno, int off, int size,
5228 enum bpf_access_type atype,
5231 struct bpf_reg_state *reg = regs + regno;
5232 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5233 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5234 enum bpf_type_flag flag = 0;
5238 if (!env->allow_ptr_leaks) {
5240 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5244 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5246 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5252 "R%d is ptr_%s invalid negative access: off=%d\n",
5256 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5259 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5261 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5262 regno, tname, off, tn_buf);
5266 if (reg->type & MEM_USER) {
5268 "R%d is ptr_%s access user memory: off=%d\n",
5273 if (reg->type & MEM_PERCPU) {
5275 "R%d is ptr_%s access percpu memory: off=%d\n",
5280 if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
5281 if (!btf_is_kernel(reg->btf)) {
5282 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5285 ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5287 /* Writes are permitted with default btf_struct_access for
5288 * program allocated objects (which always have ref_obj_id > 0),
5289 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5291 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
5292 verbose(env, "only read is supported\n");
5296 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5298 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5302 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5308 if (ret != PTR_TO_BTF_ID) {
5311 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
5312 /* If this is an untrusted pointer, all pointers formed by walking it
5313 * also inherit the untrusted flag.
5315 flag = PTR_UNTRUSTED;
5317 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
5318 /* By default any pointer obtained from walking a trusted pointer is no
5319 * longer trusted, unless the field being accessed has explicitly been
5320 * marked as inheriting its parent's state of trust (either full or RCU).
5322 * 'cgroups' pointer is untrusted if task->cgroups dereference
5323 * happened in a sleepable program outside of bpf_rcu_read_lock()
5324 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
5325 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
5327 * A regular RCU-protected pointer with __rcu tag can also be deemed
5328 * trusted if we are in an RCU CS. Such pointer can be NULL.
5330 if (type_is_trusted(env, reg, off)) {
5331 flag |= PTR_TRUSTED;
5332 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
5333 if (type_is_rcu(env, reg, off)) {
5334 /* ignore __rcu tag and mark it MEM_RCU */
5336 } else if (flag & MEM_RCU) {
5337 /* __rcu tagged pointers can be NULL */
5338 flag |= PTR_MAYBE_NULL;
5339 } else if (flag & (MEM_PERCPU | MEM_USER)) {
5342 /* walking unknown pointers yields untrusted pointer */
5343 flag = PTR_UNTRUSTED;
5347 * If not in RCU CS or MEM_RCU pointer can be NULL then
5348 * aggressively mark as untrusted otherwise such
5349 * pointers will be plain PTR_TO_BTF_ID without flags
5350 * and will be allowed to be passed into helpers for
5353 flag = PTR_UNTRUSTED;
5356 /* Old compat. Deprecated */
5357 flag &= ~PTR_TRUSTED;
5360 if (atype == BPF_READ && value_regno >= 0)
5361 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5366 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5367 struct bpf_reg_state *regs,
5368 int regno, int off, int size,
5369 enum bpf_access_type atype,
5372 struct bpf_reg_state *reg = regs + regno;
5373 struct bpf_map *map = reg->map_ptr;
5374 struct bpf_reg_state map_reg;
5375 enum bpf_type_flag flag = 0;
5376 const struct btf_type *t;
5382 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5386 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5387 verbose(env, "map_ptr access not supported for map type %d\n",
5392 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5393 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5395 if (!env->allow_ptr_leaks) {
5397 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5403 verbose(env, "R%d is %s invalid negative access: off=%d\n",
5408 if (atype != BPF_READ) {
5409 verbose(env, "only read from %s is supported\n", tname);
5413 /* Simulate access to a PTR_TO_BTF_ID */
5414 memset(&map_reg, 0, sizeof(map_reg));
5415 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
5416 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
5420 if (value_regno >= 0)
5421 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
5426 /* Check that the stack access at the given offset is within bounds. The
5427 * maximum valid offset is -1.
5429 * The minimum valid offset is -MAX_BPF_STACK for writes, and
5430 * -state->allocated_stack for reads.
5432 static int check_stack_slot_within_bounds(int off,
5433 struct bpf_func_state *state,
5434 enum bpf_access_type t)
5439 min_valid_off = -MAX_BPF_STACK;
5441 min_valid_off = -state->allocated_stack;
5443 if (off < min_valid_off || off > -1)
5448 /* Check that the stack access at 'regno + off' falls within the maximum stack
5451 * 'off' includes `regno->offset`, but not its dynamic part (if any).
5453 static int check_stack_access_within_bounds(
5454 struct bpf_verifier_env *env,
5455 int regno, int off, int access_size,
5456 enum bpf_access_src src, enum bpf_access_type type)
5458 struct bpf_reg_state *regs = cur_regs(env);
5459 struct bpf_reg_state *reg = regs + regno;
5460 struct bpf_func_state *state = func(env, reg);
5461 int min_off, max_off;
5465 if (src == ACCESS_HELPER)
5466 /* We don't know if helpers are reading or writing (or both). */
5467 err_extra = " indirect access to";
5468 else if (type == BPF_READ)
5469 err_extra = " read from";
5471 err_extra = " write to";
5473 if (tnum_is_const(reg->var_off)) {
5474 min_off = reg->var_off.value + off;
5475 if (access_size > 0)
5476 max_off = min_off + access_size - 1;
5480 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
5481 reg->smin_value <= -BPF_MAX_VAR_OFF) {
5482 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
5486 min_off = reg->smin_value + off;
5487 if (access_size > 0)
5488 max_off = reg->smax_value + off + access_size - 1;
5493 err = check_stack_slot_within_bounds(min_off, state, type);
5495 err = check_stack_slot_within_bounds(max_off, state, type);
5498 if (tnum_is_const(reg->var_off)) {
5499 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5500 err_extra, regno, off, access_size);
5504 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5505 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5506 err_extra, regno, tn_buf, access_size);
5512 /* check whether memory at (regno + off) is accessible for t = (read | write)
5513 * if t==write, value_regno is a register which value is stored into memory
5514 * if t==read, value_regno is a register which will receive the value from memory
5515 * if t==write && value_regno==-1, some unknown value is stored into memory
5516 * if t==read && value_regno==-1, don't care what we read from memory
5518 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5519 int off, int bpf_size, enum bpf_access_type t,
5520 int value_regno, bool strict_alignment_once)
5522 struct bpf_reg_state *regs = cur_regs(env);
5523 struct bpf_reg_state *reg = regs + regno;
5524 struct bpf_func_state *state;
5527 size = bpf_size_to_bytes(bpf_size);
5531 /* alignment checks will add in reg->off themselves */
5532 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5536 /* for access checks, reg->off is just part of off */
5539 if (reg->type == PTR_TO_MAP_KEY) {
5540 if (t == BPF_WRITE) {
5541 verbose(env, "write to change key R%d not allowed\n", regno);
5545 err = check_mem_region_access(env, regno, off, size,
5546 reg->map_ptr->key_size, false);
5549 if (value_regno >= 0)
5550 mark_reg_unknown(env, regs, value_regno);
5551 } else if (reg->type == PTR_TO_MAP_VALUE) {
5552 struct btf_field *kptr_field = NULL;
5554 if (t == BPF_WRITE && value_regno >= 0 &&
5555 is_pointer_value(env, value_regno)) {
5556 verbose(env, "R%d leaks addr into map\n", value_regno);
5559 err = check_map_access_type(env, regno, off, size, t);
5562 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5565 if (tnum_is_const(reg->var_off))
5566 kptr_field = btf_record_find(reg->map_ptr->record,
5567 off + reg->var_off.value, BPF_KPTR);
5569 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5570 } else if (t == BPF_READ && value_regno >= 0) {
5571 struct bpf_map *map = reg->map_ptr;
5573 /* if map is read-only, track its contents as scalars */
5574 if (tnum_is_const(reg->var_off) &&
5575 bpf_map_is_rdonly(map) &&
5576 map->ops->map_direct_value_addr) {
5577 int map_off = off + reg->var_off.value;
5580 err = bpf_map_direct_read(map, map_off, size,
5585 regs[value_regno].type = SCALAR_VALUE;
5586 __mark_reg_known(®s[value_regno], val);
5588 mark_reg_unknown(env, regs, value_regno);
5591 } else if (base_type(reg->type) == PTR_TO_MEM) {
5592 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5594 if (type_may_be_null(reg->type)) {
5595 verbose(env, "R%d invalid mem access '%s'\n", regno,
5596 reg_type_str(env, reg->type));
5600 if (t == BPF_WRITE && rdonly_mem) {
5601 verbose(env, "R%d cannot write into %s\n",
5602 regno, reg_type_str(env, reg->type));
5606 if (t == BPF_WRITE && value_regno >= 0 &&
5607 is_pointer_value(env, value_regno)) {
5608 verbose(env, "R%d leaks addr into mem\n", value_regno);
5612 err = check_mem_region_access(env, regno, off, size,
5613 reg->mem_size, false);
5614 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5615 mark_reg_unknown(env, regs, value_regno);
5616 } else if (reg->type == PTR_TO_CTX) {
5617 enum bpf_reg_type reg_type = SCALAR_VALUE;
5618 struct btf *btf = NULL;
5621 if (t == BPF_WRITE && value_regno >= 0 &&
5622 is_pointer_value(env, value_regno)) {
5623 verbose(env, "R%d leaks addr into ctx\n", value_regno);
5627 err = check_ptr_off_reg(env, reg, regno);
5631 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
5634 verbose_linfo(env, insn_idx, "; ");
5635 if (!err && t == BPF_READ && value_regno >= 0) {
5636 /* ctx access returns either a scalar, or a
5637 * PTR_TO_PACKET[_META,_END]. In the latter
5638 * case, we know the offset is zero.
5640 if (reg_type == SCALAR_VALUE) {
5641 mark_reg_unknown(env, regs, value_regno);
5643 mark_reg_known_zero(env, regs,
5645 if (type_may_be_null(reg_type))
5646 regs[value_regno].id = ++env->id_gen;
5647 /* A load of ctx field could have different
5648 * actual load size with the one encoded in the
5649 * insn. When the dst is PTR, it is for sure not
5652 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5653 if (base_type(reg_type) == PTR_TO_BTF_ID) {
5654 regs[value_regno].btf = btf;
5655 regs[value_regno].btf_id = btf_id;
5658 regs[value_regno].type = reg_type;
5661 } else if (reg->type == PTR_TO_STACK) {
5662 /* Basic bounds checks. */
5663 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5667 state = func(env, reg);
5668 err = update_stack_depth(env, state, off);
5673 err = check_stack_read(env, regno, off, size,
5676 err = check_stack_write(env, regno, off, size,
5677 value_regno, insn_idx);
5678 } else if (reg_is_pkt_pointer(reg)) {
5679 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5680 verbose(env, "cannot write into packet\n");
5683 if (t == BPF_WRITE && value_regno >= 0 &&
5684 is_pointer_value(env, value_regno)) {
5685 verbose(env, "R%d leaks addr into packet\n",
5689 err = check_packet_access(env, regno, off, size, false);
5690 if (!err && t == BPF_READ && value_regno >= 0)
5691 mark_reg_unknown(env, regs, value_regno);
5692 } else if (reg->type == PTR_TO_FLOW_KEYS) {
5693 if (t == BPF_WRITE && value_regno >= 0 &&
5694 is_pointer_value(env, value_regno)) {
5695 verbose(env, "R%d leaks addr into flow keys\n",
5700 err = check_flow_keys_access(env, off, size);
5701 if (!err && t == BPF_READ && value_regno >= 0)
5702 mark_reg_unknown(env, regs, value_regno);
5703 } else if (type_is_sk_pointer(reg->type)) {
5704 if (t == BPF_WRITE) {
5705 verbose(env, "R%d cannot write into %s\n",
5706 regno, reg_type_str(env, reg->type));
5709 err = check_sock_access(env, insn_idx, regno, off, size, t);
5710 if (!err && value_regno >= 0)
5711 mark_reg_unknown(env, regs, value_regno);
5712 } else if (reg->type == PTR_TO_TP_BUFFER) {
5713 err = check_tp_buffer_access(env, reg, regno, off, size);
5714 if (!err && t == BPF_READ && value_regno >= 0)
5715 mark_reg_unknown(env, regs, value_regno);
5716 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5717 !type_may_be_null(reg->type)) {
5718 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5720 } else if (reg->type == CONST_PTR_TO_MAP) {
5721 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5723 } else if (base_type(reg->type) == PTR_TO_BUF) {
5724 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5728 if (t == BPF_WRITE) {
5729 verbose(env, "R%d cannot write into %s\n",
5730 regno, reg_type_str(env, reg->type));
5733 max_access = &env->prog->aux->max_rdonly_access;
5735 max_access = &env->prog->aux->max_rdwr_access;
5738 err = check_buffer_access(env, reg, regno, off, size, false,
5741 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5742 mark_reg_unknown(env, regs, value_regno);
5744 verbose(env, "R%d invalid mem access '%s'\n", regno,
5745 reg_type_str(env, reg->type));
5749 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5750 regs[value_regno].type == SCALAR_VALUE) {
5751 /* b/h/w load zero-extends, mark upper bits as known 0 */
5752 coerce_reg_to_size(®s[value_regno], size);
5757 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5762 switch (insn->imm) {
5764 case BPF_ADD | BPF_FETCH:
5766 case BPF_AND | BPF_FETCH:
5768 case BPF_OR | BPF_FETCH:
5770 case BPF_XOR | BPF_FETCH:
5775 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5779 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5780 verbose(env, "invalid atomic operand size\n");
5784 /* check src1 operand */
5785 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5789 /* check src2 operand */
5790 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5794 if (insn->imm == BPF_CMPXCHG) {
5795 /* Check comparison of R0 with memory location */
5796 const u32 aux_reg = BPF_REG_0;
5798 err = check_reg_arg(env, aux_reg, SRC_OP);
5802 if (is_pointer_value(env, aux_reg)) {
5803 verbose(env, "R%d leaks addr into mem\n", aux_reg);
5808 if (is_pointer_value(env, insn->src_reg)) {
5809 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5813 if (is_ctx_reg(env, insn->dst_reg) ||
5814 is_pkt_reg(env, insn->dst_reg) ||
5815 is_flow_key_reg(env, insn->dst_reg) ||
5816 is_sk_reg(env, insn->dst_reg)) {
5817 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5819 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5823 if (insn->imm & BPF_FETCH) {
5824 if (insn->imm == BPF_CMPXCHG)
5825 load_reg = BPF_REG_0;
5827 load_reg = insn->src_reg;
5829 /* check and record load of old value */
5830 err = check_reg_arg(env, load_reg, DST_OP);
5834 /* This instruction accesses a memory location but doesn't
5835 * actually load it into a register.
5840 /* Check whether we can read the memory, with second call for fetch
5841 * case to simulate the register fill.
5843 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5844 BPF_SIZE(insn->code), BPF_READ, -1, true);
5845 if (!err && load_reg >= 0)
5846 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5847 BPF_SIZE(insn->code), BPF_READ, load_reg,
5852 /* Check whether we can write into the same memory. */
5853 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5854 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5861 /* When register 'regno' is used to read the stack (either directly or through
5862 * a helper function) make sure that it's within stack boundary and, depending
5863 * on the access type, that all elements of the stack are initialized.
5865 * 'off' includes 'regno->off', but not its dynamic part (if any).
5867 * All registers that have been spilled on the stack in the slots within the
5868 * read offsets are marked as read.
5870 static int check_stack_range_initialized(
5871 struct bpf_verifier_env *env, int regno, int off,
5872 int access_size, bool zero_size_allowed,
5873 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5875 struct bpf_reg_state *reg = reg_state(env, regno);
5876 struct bpf_func_state *state = func(env, reg);
5877 int err, min_off, max_off, i, j, slot, spi;
5878 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5879 enum bpf_access_type bounds_check_type;
5880 /* Some accesses can write anything into the stack, others are
5883 bool clobber = false;
5885 if (access_size == 0 && !zero_size_allowed) {
5886 verbose(env, "invalid zero-sized read\n");
5890 if (type == ACCESS_HELPER) {
5891 /* The bounds checks for writes are more permissive than for
5892 * reads. However, if raw_mode is not set, we'll do extra
5895 bounds_check_type = BPF_WRITE;
5898 bounds_check_type = BPF_READ;
5900 err = check_stack_access_within_bounds(env, regno, off, access_size,
5901 type, bounds_check_type);
5906 if (tnum_is_const(reg->var_off)) {
5907 min_off = max_off = reg->var_off.value + off;
5909 /* Variable offset is prohibited for unprivileged mode for
5910 * simplicity since it requires corresponding support in
5911 * Spectre masking for stack ALU.
5912 * See also retrieve_ptr_limit().
5914 if (!env->bypass_spec_v1) {
5917 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5918 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5919 regno, err_extra, tn_buf);
5922 /* Only initialized buffer on stack is allowed to be accessed
5923 * with variable offset. With uninitialized buffer it's hard to
5924 * guarantee that whole memory is marked as initialized on
5925 * helper return since specific bounds are unknown what may
5926 * cause uninitialized stack leaking.
5928 if (meta && meta->raw_mode)
5931 min_off = reg->smin_value + off;
5932 max_off = reg->smax_value + off;
5935 if (meta && meta->raw_mode) {
5936 /* Ensure we won't be overwriting dynptrs when simulating byte
5937 * by byte access in check_helper_call using meta.access_size.
5938 * This would be a problem if we have a helper in the future
5941 * helper(uninit_mem, len, dynptr)
5943 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
5944 * may end up writing to dynptr itself when touching memory from
5945 * arg 1. This can be relaxed on a case by case basis for known
5946 * safe cases, but reject due to the possibilitiy of aliasing by
5949 for (i = min_off; i < max_off + access_size; i++) {
5950 int stack_off = -i - 1;
5953 /* raw_mode may write past allocated_stack */
5954 if (state->allocated_stack <= stack_off)
5956 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
5957 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
5961 meta->access_size = access_size;
5962 meta->regno = regno;
5966 for (i = min_off; i < max_off + access_size; i++) {
5970 spi = slot / BPF_REG_SIZE;
5971 if (state->allocated_stack <= slot)
5973 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5974 if (*stype == STACK_MISC)
5976 if ((*stype == STACK_ZERO) ||
5977 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
5979 /* helper can write anything into the stack */
5980 *stype = STACK_MISC;
5985 if (is_spilled_reg(&state->stack[spi]) &&
5986 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5987 env->allow_ptr_leaks)) {
5989 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5990 for (j = 0; j < BPF_REG_SIZE; j++)
5991 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5997 if (tnum_is_const(reg->var_off)) {
5998 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5999 err_extra, regno, min_off, i - min_off, access_size);
6003 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6004 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6005 err_extra, regno, tn_buf, i - min_off, access_size);
6009 /* reading any byte out of 8-byte 'spill_slot' will cause
6010 * the whole slot to be marked as 'read'
6012 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6013 state->stack[spi].spilled_ptr.parent,
6015 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6016 * be sure that whether stack slot is written to or not. Hence,
6017 * we must still conservatively propagate reads upwards even if
6018 * helper may write to the entire memory range.
6021 return update_stack_depth(env, state, min_off);
6024 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6025 int access_size, bool zero_size_allowed,
6026 struct bpf_call_arg_meta *meta)
6028 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6031 switch (base_type(reg->type)) {
6033 case PTR_TO_PACKET_META:
6034 return check_packet_access(env, regno, reg->off, access_size,
6036 case PTR_TO_MAP_KEY:
6037 if (meta && meta->raw_mode) {
6038 verbose(env, "R%d cannot write into %s\n", regno,
6039 reg_type_str(env, reg->type));
6042 return check_mem_region_access(env, regno, reg->off, access_size,
6043 reg->map_ptr->key_size, false);
6044 case PTR_TO_MAP_VALUE:
6045 if (check_map_access_type(env, regno, reg->off, access_size,
6046 meta && meta->raw_mode ? BPF_WRITE :
6049 return check_map_access(env, regno, reg->off, access_size,
6050 zero_size_allowed, ACCESS_HELPER);
6052 if (type_is_rdonly_mem(reg->type)) {
6053 if (meta && meta->raw_mode) {
6054 verbose(env, "R%d cannot write into %s\n", regno,
6055 reg_type_str(env, reg->type));
6059 return check_mem_region_access(env, regno, reg->off,
6060 access_size, reg->mem_size,
6063 if (type_is_rdonly_mem(reg->type)) {
6064 if (meta && meta->raw_mode) {
6065 verbose(env, "R%d cannot write into %s\n", regno,
6066 reg_type_str(env, reg->type));
6070 max_access = &env->prog->aux->max_rdonly_access;
6072 max_access = &env->prog->aux->max_rdwr_access;
6074 return check_buffer_access(env, reg, regno, reg->off,
6075 access_size, zero_size_allowed,
6078 return check_stack_range_initialized(
6080 regno, reg->off, access_size,
6081 zero_size_allowed, ACCESS_HELPER, meta);
6083 /* in case the function doesn't know how to access the context,
6084 * (because we are in a program of type SYSCALL for example), we
6085 * can not statically check its size.
6086 * Dynamically check it now.
6088 if (!env->ops->convert_ctx_access) {
6089 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6090 int offset = access_size - 1;
6092 /* Allow zero-byte read from PTR_TO_CTX */
6093 if (access_size == 0)
6094 return zero_size_allowed ? 0 : -EACCES;
6096 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6101 default: /* scalar_value or invalid ptr */
6102 /* Allow zero-byte read from NULL, regardless of pointer type */
6103 if (zero_size_allowed && access_size == 0 &&
6104 register_is_null(reg))
6107 verbose(env, "R%d type=%s ", regno,
6108 reg_type_str(env, reg->type));
6109 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6114 static int check_mem_size_reg(struct bpf_verifier_env *env,
6115 struct bpf_reg_state *reg, u32 regno,
6116 bool zero_size_allowed,
6117 struct bpf_call_arg_meta *meta)
6121 /* This is used to refine r0 return value bounds for helpers
6122 * that enforce this value as an upper bound on return values.
6123 * See do_refine_retval_range() for helpers that can refine
6124 * the return value. C type of helper is u32 so we pull register
6125 * bound from umax_value however, if negative verifier errors
6126 * out. Only upper bounds can be learned because retval is an
6127 * int type and negative retvals are allowed.
6129 meta->msize_max_value = reg->umax_value;
6131 /* The register is SCALAR_VALUE; the access check
6132 * happens using its boundaries.
6134 if (!tnum_is_const(reg->var_off))
6135 /* For unprivileged variable accesses, disable raw
6136 * mode so that the program is required to
6137 * initialize all the memory that the helper could
6138 * just partially fill up.
6142 if (reg->smin_value < 0) {
6143 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6148 if (reg->umin_value == 0) {
6149 err = check_helper_mem_access(env, regno - 1, 0,
6156 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6157 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6161 err = check_helper_mem_access(env, regno - 1,
6163 zero_size_allowed, meta);
6165 err = mark_chain_precision(env, regno);
6169 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6170 u32 regno, u32 mem_size)
6172 bool may_be_null = type_may_be_null(reg->type);
6173 struct bpf_reg_state saved_reg;
6174 struct bpf_call_arg_meta meta;
6177 if (register_is_null(reg))
6180 memset(&meta, 0, sizeof(meta));
6181 /* Assuming that the register contains a value check if the memory
6182 * access is safe. Temporarily save and restore the register's state as
6183 * the conversion shouldn't be visible to a caller.
6187 mark_ptr_not_null_reg(reg);
6190 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6191 /* Check access for BPF_WRITE */
6192 meta.raw_mode = true;
6193 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6201 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6204 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6205 bool may_be_null = type_may_be_null(mem_reg->type);
6206 struct bpf_reg_state saved_reg;
6207 struct bpf_call_arg_meta meta;
6210 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6212 memset(&meta, 0, sizeof(meta));
6215 saved_reg = *mem_reg;
6216 mark_ptr_not_null_reg(mem_reg);
6219 err = check_mem_size_reg(env, reg, regno, true, &meta);
6220 /* Check access for BPF_WRITE */
6221 meta.raw_mode = true;
6222 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6225 *mem_reg = saved_reg;
6229 /* Implementation details:
6230 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6231 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6232 * Two bpf_map_lookups (even with the same key) will have different reg->id.
6233 * Two separate bpf_obj_new will also have different reg->id.
6234 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6235 * clears reg->id after value_or_null->value transition, since the verifier only
6236 * cares about the range of access to valid map value pointer and doesn't care
6237 * about actual address of the map element.
6238 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6239 * reg->id > 0 after value_or_null->value transition. By doing so
6240 * two bpf_map_lookups will be considered two different pointers that
6241 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6242 * returned from bpf_obj_new.
6243 * The verifier allows taking only one bpf_spin_lock at a time to avoid
6245 * Since only one bpf_spin_lock is allowed the checks are simpler than
6246 * reg_is_refcounted() logic. The verifier needs to remember only
6247 * one spin_lock instead of array of acquired_refs.
6248 * cur_state->active_lock remembers which map value element or allocated
6249 * object got locked and clears it after bpf_spin_unlock.
6251 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6254 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6255 struct bpf_verifier_state *cur = env->cur_state;
6256 bool is_const = tnum_is_const(reg->var_off);
6257 u64 val = reg->var_off.value;
6258 struct bpf_map *map = NULL;
6259 struct btf *btf = NULL;
6260 struct btf_record *rec;
6264 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6268 if (reg->type == PTR_TO_MAP_VALUE) {
6272 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
6280 rec = reg_btf_record(reg);
6281 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6282 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6283 map ? map->name : "kptr");
6286 if (rec->spin_lock_off != val + reg->off) {
6287 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
6288 val + reg->off, rec->spin_lock_off);
6292 if (cur->active_lock.ptr) {
6294 "Locking two bpf_spin_locks are not allowed\n");
6298 cur->active_lock.ptr = map;
6300 cur->active_lock.ptr = btf;
6301 cur->active_lock.id = reg->id;
6310 if (!cur->active_lock.ptr) {
6311 verbose(env, "bpf_spin_unlock without taking a lock\n");
6314 if (cur->active_lock.ptr != ptr ||
6315 cur->active_lock.id != reg->id) {
6316 verbose(env, "bpf_spin_unlock of different lock\n");
6320 invalidate_non_owning_refs(env);
6322 cur->active_lock.ptr = NULL;
6323 cur->active_lock.id = 0;
6328 static int process_timer_func(struct bpf_verifier_env *env, int regno,
6329 struct bpf_call_arg_meta *meta)
6331 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6332 bool is_const = tnum_is_const(reg->var_off);
6333 struct bpf_map *map = reg->map_ptr;
6334 u64 val = reg->var_off.value;
6338 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6343 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6347 if (!btf_record_has_field(map->record, BPF_TIMER)) {
6348 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
6351 if (map->record->timer_off != val + reg->off) {
6352 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
6353 val + reg->off, map->record->timer_off);
6356 if (meta->map_ptr) {
6357 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6360 meta->map_uid = reg->map_uid;
6361 meta->map_ptr = map;
6365 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6366 struct bpf_call_arg_meta *meta)
6368 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6369 struct bpf_map *map_ptr = reg->map_ptr;
6370 struct btf_field *kptr_field;
6373 if (!tnum_is_const(reg->var_off)) {
6375 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6379 if (!map_ptr->btf) {
6380 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6384 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6385 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
6389 meta->map_ptr = map_ptr;
6390 kptr_off = reg->off + reg->var_off.value;
6391 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
6393 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
6396 if (kptr_field->type != BPF_KPTR_REF) {
6397 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
6400 meta->kptr_field = kptr_field;
6404 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6405 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6407 * In both cases we deal with the first 8 bytes, but need to mark the next 8
6408 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6409 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6411 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6412 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6413 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6414 * mutate the view of the dynptr and also possibly destroy it. In the latter
6415 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6416 * memory that dynptr points to.
6418 * The verifier will keep track both levels of mutation (bpf_dynptr's in
6419 * reg->type and the memory's in reg->dynptr.type), but there is no support for
6420 * readonly dynptr view yet, hence only the first case is tracked and checked.
6422 * This is consistent with how C applies the const modifier to a struct object,
6423 * where the pointer itself inside bpf_dynptr becomes const but not what it
6426 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6427 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6429 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
6430 enum bpf_arg_type arg_type)
6432 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6435 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6436 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6438 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6439 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6443 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
6444 * constructing a mutable bpf_dynptr object.
6446 * Currently, this is only possible with PTR_TO_STACK
6447 * pointing to a region of at least 16 bytes which doesn't
6448 * contain an existing bpf_dynptr.
6450 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6451 * mutated or destroyed. However, the memory it points to
6454 * None - Points to a initialized dynptr that can be mutated and
6455 * destroyed, including mutation of the memory it points
6458 if (arg_type & MEM_UNINIT) {
6461 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6462 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6466 /* we write BPF_DW bits (8 bytes) at a time */
6467 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
6468 err = check_mem_access(env, insn_idx, regno,
6469 i, BPF_DW, BPF_WRITE, -1, false);
6474 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx);
6475 } else /* MEM_RDONLY and None case from above */ {
6476 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6477 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6478 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6482 if (!is_dynptr_reg_valid_init(env, reg)) {
6484 "Expected an initialized dynptr as arg #%d\n",
6489 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6490 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6492 "Expected a dynptr of type %s as arg #%d\n",
6493 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
6497 err = mark_dynptr_read(env, reg);
6502 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6504 return type == ARG_CONST_SIZE ||
6505 type == ARG_CONST_SIZE_OR_ZERO;
6508 static bool arg_type_is_release(enum bpf_arg_type type)
6510 return type & OBJ_RELEASE;
6513 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6515 return base_type(type) == ARG_PTR_TO_DYNPTR;
6518 static int int_ptr_type_to_size(enum bpf_arg_type type)
6520 if (type == ARG_PTR_TO_INT)
6522 else if (type == ARG_PTR_TO_LONG)
6528 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6529 const struct bpf_call_arg_meta *meta,
6530 enum bpf_arg_type *arg_type)
6532 if (!meta->map_ptr) {
6533 /* kernel subsystem misconfigured verifier */
6534 verbose(env, "invalid map_ptr to access map->type\n");
6538 switch (meta->map_ptr->map_type) {
6539 case BPF_MAP_TYPE_SOCKMAP:
6540 case BPF_MAP_TYPE_SOCKHASH:
6541 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6542 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6544 verbose(env, "invalid arg_type for sockmap/sockhash\n");
6548 case BPF_MAP_TYPE_BLOOM_FILTER:
6549 if (meta->func_id == BPF_FUNC_map_peek_elem)
6550 *arg_type = ARG_PTR_TO_MAP_VALUE;
6558 struct bpf_reg_types {
6559 const enum bpf_reg_type types[10];
6563 static const struct bpf_reg_types sock_types = {
6573 static const struct bpf_reg_types btf_id_sock_common_types = {
6580 PTR_TO_BTF_ID | PTR_TRUSTED,
6582 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6586 static const struct bpf_reg_types mem_types = {
6594 PTR_TO_MEM | MEM_RINGBUF,
6599 static const struct bpf_reg_types int_ptr_types = {
6609 static const struct bpf_reg_types spin_lock_types = {
6612 PTR_TO_BTF_ID | MEM_ALLOC,
6616 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
6617 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
6618 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
6619 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
6620 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
6621 static const struct bpf_reg_types btf_ptr_types = {
6624 PTR_TO_BTF_ID | PTR_TRUSTED,
6625 PTR_TO_BTF_ID | MEM_RCU,
6628 static const struct bpf_reg_types percpu_btf_ptr_types = {
6630 PTR_TO_BTF_ID | MEM_PERCPU,
6631 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
6634 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
6635 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
6636 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
6637 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
6638 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
6639 static const struct bpf_reg_types dynptr_types = {
6642 CONST_PTR_TO_DYNPTR,
6646 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
6647 [ARG_PTR_TO_MAP_KEY] = &mem_types,
6648 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
6649 [ARG_CONST_SIZE] = &scalar_types,
6650 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
6651 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
6652 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
6653 [ARG_PTR_TO_CTX] = &context_types,
6654 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
6656 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
6658 [ARG_PTR_TO_SOCKET] = &fullsock_types,
6659 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
6660 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
6661 [ARG_PTR_TO_MEM] = &mem_types,
6662 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
6663 [ARG_PTR_TO_INT] = &int_ptr_types,
6664 [ARG_PTR_TO_LONG] = &int_ptr_types,
6665 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
6666 [ARG_PTR_TO_FUNC] = &func_ptr_types,
6667 [ARG_PTR_TO_STACK] = &stack_ptr_types,
6668 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
6669 [ARG_PTR_TO_TIMER] = &timer_types,
6670 [ARG_PTR_TO_KPTR] = &kptr_types,
6671 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
6674 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
6675 enum bpf_arg_type arg_type,
6676 const u32 *arg_btf_id,
6677 struct bpf_call_arg_meta *meta)
6679 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6680 enum bpf_reg_type expected, type = reg->type;
6681 const struct bpf_reg_types *compatible;
6684 compatible = compatible_reg_types[base_type(arg_type)];
6686 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
6690 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
6691 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
6693 * Same for MAYBE_NULL:
6695 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
6696 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
6698 * Therefore we fold these flags depending on the arg_type before comparison.
6700 if (arg_type & MEM_RDONLY)
6701 type &= ~MEM_RDONLY;
6702 if (arg_type & PTR_MAYBE_NULL)
6703 type &= ~PTR_MAYBE_NULL;
6705 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
6706 expected = compatible->types[i];
6707 if (expected == NOT_INIT)
6710 if (type == expected)
6714 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
6715 for (j = 0; j + 1 < i; j++)
6716 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
6717 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
6721 if (base_type(reg->type) != PTR_TO_BTF_ID)
6724 switch ((int)reg->type) {
6726 case PTR_TO_BTF_ID | PTR_TRUSTED:
6727 case PTR_TO_BTF_ID | MEM_RCU:
6729 /* For bpf_sk_release, it needs to match against first member
6730 * 'struct sock_common', hence make an exception for it. This
6731 * allows bpf_sk_release to work for multiple socket types.
6733 bool strict_type_match = arg_type_is_release(arg_type) &&
6734 meta->func_id != BPF_FUNC_sk_release;
6737 if (!compatible->btf_id) {
6738 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6741 arg_btf_id = compatible->btf_id;
6744 if (meta->func_id == BPF_FUNC_kptr_xchg) {
6745 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6748 if (arg_btf_id == BPF_PTR_POISON) {
6749 verbose(env, "verifier internal error:");
6750 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6755 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6756 btf_vmlinux, *arg_btf_id,
6757 strict_type_match)) {
6758 verbose(env, "R%d is of type %s but %s is expected\n",
6759 regno, kernel_type_name(reg->btf, reg->btf_id),
6760 kernel_type_name(btf_vmlinux, *arg_btf_id));
6766 case PTR_TO_BTF_ID | MEM_ALLOC:
6767 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6768 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6771 /* Handled by helper specific checks */
6773 case PTR_TO_BTF_ID | MEM_PERCPU:
6774 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
6775 /* Handled by helper specific checks */
6778 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
6784 static struct btf_field *
6785 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
6787 struct btf_field *field;
6788 struct btf_record *rec;
6790 rec = reg_btf_record(reg);
6794 field = btf_record_find(rec, off, fields);
6801 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6802 const struct bpf_reg_state *reg, int regno,
6803 enum bpf_arg_type arg_type)
6805 u32 type = reg->type;
6807 /* When referenced register is passed to release function, its fixed
6810 * We will check arg_type_is_release reg has ref_obj_id when storing
6811 * meta->release_regno.
6813 if (arg_type_is_release(arg_type)) {
6814 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
6815 * may not directly point to the object being released, but to
6816 * dynptr pointing to such object, which might be at some offset
6817 * on the stack. In that case, we simply to fallback to the
6820 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
6823 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
6824 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
6825 return __check_ptr_off_reg(env, reg, regno, true);
6827 verbose(env, "R%d must have zero offset when passed to release func\n",
6829 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
6830 kernel_type_name(reg->btf, reg->btf_id), reg->off);
6834 /* Doing check_ptr_off_reg check for the offset will catch this
6835 * because fixed_off_ok is false, but checking here allows us
6836 * to give the user a better error message.
6839 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
6843 return __check_ptr_off_reg(env, reg, regno, false);
6847 /* Pointer types where both fixed and variable offset is explicitly allowed: */
6850 case PTR_TO_PACKET_META:
6851 case PTR_TO_MAP_KEY:
6852 case PTR_TO_MAP_VALUE:
6854 case PTR_TO_MEM | MEM_RDONLY:
6855 case PTR_TO_MEM | MEM_RINGBUF:
6857 case PTR_TO_BUF | MEM_RDONLY:
6860 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6864 case PTR_TO_BTF_ID | MEM_ALLOC:
6865 case PTR_TO_BTF_ID | PTR_TRUSTED:
6866 case PTR_TO_BTF_ID | MEM_RCU:
6867 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
6868 /* When referenced PTR_TO_BTF_ID is passed to release function,
6869 * its fixed offset must be 0. In the other cases, fixed offset
6870 * can be non-zero. This was already checked above. So pass
6871 * fixed_off_ok as true to allow fixed offset for all other
6872 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
6873 * still need to do checks instead of returning.
6875 return __check_ptr_off_reg(env, reg, regno, true);
6877 return __check_ptr_off_reg(env, reg, regno, false);
6881 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
6882 const struct bpf_func_proto *fn,
6883 struct bpf_reg_state *regs)
6885 struct bpf_reg_state *state = NULL;
6888 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
6889 if (arg_type_is_dynptr(fn->arg_type[i])) {
6891 verbose(env, "verifier internal error: multiple dynptr args\n");
6894 state = ®s[BPF_REG_1 + i];
6898 verbose(env, "verifier internal error: no dynptr arg found\n");
6903 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6905 struct bpf_func_state *state = func(env, reg);
6908 if (reg->type == CONST_PTR_TO_DYNPTR)
6910 spi = dynptr_get_spi(env, reg);
6913 return state->stack[spi].spilled_ptr.id;
6916 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6918 struct bpf_func_state *state = func(env, reg);
6921 if (reg->type == CONST_PTR_TO_DYNPTR)
6922 return reg->ref_obj_id;
6923 spi = dynptr_get_spi(env, reg);
6926 return state->stack[spi].spilled_ptr.ref_obj_id;
6929 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
6930 struct bpf_reg_state *reg)
6932 struct bpf_func_state *state = func(env, reg);
6935 if (reg->type == CONST_PTR_TO_DYNPTR)
6936 return reg->dynptr.type;
6938 spi = __get_spi(reg->off);
6940 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
6941 return BPF_DYNPTR_TYPE_INVALID;
6944 return state->stack[spi].spilled_ptr.dynptr.type;
6947 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6948 struct bpf_call_arg_meta *meta,
6949 const struct bpf_func_proto *fn,
6952 u32 regno = BPF_REG_1 + arg;
6953 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6954 enum bpf_arg_type arg_type = fn->arg_type[arg];
6955 enum bpf_reg_type type = reg->type;
6956 u32 *arg_btf_id = NULL;
6959 if (arg_type == ARG_DONTCARE)
6962 err = check_reg_arg(env, regno, SRC_OP);
6966 if (arg_type == ARG_ANYTHING) {
6967 if (is_pointer_value(env, regno)) {
6968 verbose(env, "R%d leaks addr into helper function\n",
6975 if (type_is_pkt_pointer(type) &&
6976 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6977 verbose(env, "helper access to the packet is not allowed\n");
6981 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6982 err = resolve_map_arg_type(env, meta, &arg_type);
6987 if (register_is_null(reg) && type_may_be_null(arg_type))
6988 /* A NULL register has a SCALAR_VALUE type, so skip
6991 goto skip_type_check;
6993 /* arg_btf_id and arg_size are in a union. */
6994 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6995 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6996 arg_btf_id = fn->arg_btf_id[arg];
6998 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7002 err = check_func_arg_reg_off(env, reg, regno, arg_type);
7007 if (arg_type_is_release(arg_type)) {
7008 if (arg_type_is_dynptr(arg_type)) {
7009 struct bpf_func_state *state = func(env, reg);
7012 /* Only dynptr created on stack can be released, thus
7013 * the get_spi and stack state checks for spilled_ptr
7014 * should only be done before process_dynptr_func for
7017 if (reg->type == PTR_TO_STACK) {
7018 spi = dynptr_get_spi(env, reg);
7019 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7020 verbose(env, "arg %d is an unacquired reference\n", regno);
7024 verbose(env, "cannot release unowned const bpf_dynptr\n");
7027 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
7028 verbose(env, "R%d must be referenced when passed to release function\n",
7032 if (meta->release_regno) {
7033 verbose(env, "verifier internal error: more than one release argument\n");
7036 meta->release_regno = regno;
7039 if (reg->ref_obj_id) {
7040 if (meta->ref_obj_id) {
7041 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
7042 regno, reg->ref_obj_id,
7046 meta->ref_obj_id = reg->ref_obj_id;
7049 switch (base_type(arg_type)) {
7050 case ARG_CONST_MAP_PTR:
7051 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
7052 if (meta->map_ptr) {
7053 /* Use map_uid (which is unique id of inner map) to reject:
7054 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
7055 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
7056 * if (inner_map1 && inner_map2) {
7057 * timer = bpf_map_lookup_elem(inner_map1);
7059 * // mismatch would have been allowed
7060 * bpf_timer_init(timer, inner_map2);
7063 * Comparing map_ptr is enough to distinguish normal and outer maps.
7065 if (meta->map_ptr != reg->map_ptr ||
7066 meta->map_uid != reg->map_uid) {
7068 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
7069 meta->map_uid, reg->map_uid);
7073 meta->map_ptr = reg->map_ptr;
7074 meta->map_uid = reg->map_uid;
7076 case ARG_PTR_TO_MAP_KEY:
7077 /* bpf_map_xxx(..., map_ptr, ..., key) call:
7078 * check that [key, key + map->key_size) are within
7079 * stack limits and initialized
7081 if (!meta->map_ptr) {
7082 /* in function declaration map_ptr must come before
7083 * map_key, so that it's verified and known before
7084 * we have to check map_key here. Otherwise it means
7085 * that kernel subsystem misconfigured verifier
7087 verbose(env, "invalid map_ptr to access map->key\n");
7090 err = check_helper_mem_access(env, regno,
7091 meta->map_ptr->key_size, false,
7094 case ARG_PTR_TO_MAP_VALUE:
7095 if (type_may_be_null(arg_type) && register_is_null(reg))
7098 /* bpf_map_xxx(..., map_ptr, ..., value) call:
7099 * check [value, value + map->value_size) validity
7101 if (!meta->map_ptr) {
7102 /* kernel subsystem misconfigured verifier */
7103 verbose(env, "invalid map_ptr to access map->value\n");
7106 meta->raw_mode = arg_type & MEM_UNINIT;
7107 err = check_helper_mem_access(env, regno,
7108 meta->map_ptr->value_size, false,
7111 case ARG_PTR_TO_PERCPU_BTF_ID:
7113 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
7116 meta->ret_btf = reg->btf;
7117 meta->ret_btf_id = reg->btf_id;
7119 case ARG_PTR_TO_SPIN_LOCK:
7120 if (in_rbtree_lock_required_cb(env)) {
7121 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
7124 if (meta->func_id == BPF_FUNC_spin_lock) {
7125 err = process_spin_lock(env, regno, true);
7128 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
7129 err = process_spin_lock(env, regno, false);
7133 verbose(env, "verifier internal error\n");
7137 case ARG_PTR_TO_TIMER:
7138 err = process_timer_func(env, regno, meta);
7142 case ARG_PTR_TO_FUNC:
7143 meta->subprogno = reg->subprogno;
7145 case ARG_PTR_TO_MEM:
7146 /* The access to this pointer is only checked when we hit the
7147 * next is_mem_size argument below.
7149 meta->raw_mode = arg_type & MEM_UNINIT;
7150 if (arg_type & MEM_FIXED_SIZE) {
7151 err = check_helper_mem_access(env, regno,
7152 fn->arg_size[arg], false,
7156 case ARG_CONST_SIZE:
7157 err = check_mem_size_reg(env, reg, regno, false, meta);
7159 case ARG_CONST_SIZE_OR_ZERO:
7160 err = check_mem_size_reg(env, reg, regno, true, meta);
7162 case ARG_PTR_TO_DYNPTR:
7163 err = process_dynptr_func(env, regno, insn_idx, arg_type);
7167 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
7168 if (!tnum_is_const(reg->var_off)) {
7169 verbose(env, "R%d is not a known constant'\n",
7173 meta->mem_size = reg->var_off.value;
7174 err = mark_chain_precision(env, regno);
7178 case ARG_PTR_TO_INT:
7179 case ARG_PTR_TO_LONG:
7181 int size = int_ptr_type_to_size(arg_type);
7183 err = check_helper_mem_access(env, regno, size, false, meta);
7186 err = check_ptr_alignment(env, reg, 0, size, true);
7189 case ARG_PTR_TO_CONST_STR:
7191 struct bpf_map *map = reg->map_ptr;
7196 if (!bpf_map_is_rdonly(map)) {
7197 verbose(env, "R%d does not point to a readonly map'\n", regno);
7201 if (!tnum_is_const(reg->var_off)) {
7202 verbose(env, "R%d is not a constant address'\n", regno);
7206 if (!map->ops->map_direct_value_addr) {
7207 verbose(env, "no direct value access support for this map type\n");
7211 err = check_map_access(env, regno, reg->off,
7212 map->value_size - reg->off, false,
7217 map_off = reg->off + reg->var_off.value;
7218 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
7220 verbose(env, "direct value access on string failed\n");
7224 str_ptr = (char *)(long)(map_addr);
7225 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
7226 verbose(env, "string is not zero-terminated\n");
7231 case ARG_PTR_TO_KPTR:
7232 err = process_kptr_func(env, regno, meta);
7241 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
7243 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7244 enum bpf_prog_type type = resolve_prog_type(env->prog);
7246 if (func_id != BPF_FUNC_map_update_elem)
7249 /* It's not possible to get access to a locked struct sock in these
7250 * contexts, so updating is safe.
7253 case BPF_PROG_TYPE_TRACING:
7254 if (eatype == BPF_TRACE_ITER)
7257 case BPF_PROG_TYPE_SOCKET_FILTER:
7258 case BPF_PROG_TYPE_SCHED_CLS:
7259 case BPF_PROG_TYPE_SCHED_ACT:
7260 case BPF_PROG_TYPE_XDP:
7261 case BPF_PROG_TYPE_SK_REUSEPORT:
7262 case BPF_PROG_TYPE_FLOW_DISSECTOR:
7263 case BPF_PROG_TYPE_SK_LOOKUP:
7269 verbose(env, "cannot update sockmap in this context\n");
7273 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
7275 return env->prog->jit_requested &&
7276 bpf_jit_supports_subprog_tailcalls();
7279 static int check_map_func_compatibility(struct bpf_verifier_env *env,
7280 struct bpf_map *map, int func_id)
7285 /* We need a two way check, first is from map perspective ... */
7286 switch (map->map_type) {
7287 case BPF_MAP_TYPE_PROG_ARRAY:
7288 if (func_id != BPF_FUNC_tail_call)
7291 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
7292 if (func_id != BPF_FUNC_perf_event_read &&
7293 func_id != BPF_FUNC_perf_event_output &&
7294 func_id != BPF_FUNC_skb_output &&
7295 func_id != BPF_FUNC_perf_event_read_value &&
7296 func_id != BPF_FUNC_xdp_output)
7299 case BPF_MAP_TYPE_RINGBUF:
7300 if (func_id != BPF_FUNC_ringbuf_output &&
7301 func_id != BPF_FUNC_ringbuf_reserve &&
7302 func_id != BPF_FUNC_ringbuf_query &&
7303 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
7304 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
7305 func_id != BPF_FUNC_ringbuf_discard_dynptr)
7308 case BPF_MAP_TYPE_USER_RINGBUF:
7309 if (func_id != BPF_FUNC_user_ringbuf_drain)
7312 case BPF_MAP_TYPE_STACK_TRACE:
7313 if (func_id != BPF_FUNC_get_stackid)
7316 case BPF_MAP_TYPE_CGROUP_ARRAY:
7317 if (func_id != BPF_FUNC_skb_under_cgroup &&
7318 func_id != BPF_FUNC_current_task_under_cgroup)
7321 case BPF_MAP_TYPE_CGROUP_STORAGE:
7322 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
7323 if (func_id != BPF_FUNC_get_local_storage)
7326 case BPF_MAP_TYPE_DEVMAP:
7327 case BPF_MAP_TYPE_DEVMAP_HASH:
7328 if (func_id != BPF_FUNC_redirect_map &&
7329 func_id != BPF_FUNC_map_lookup_elem)
7332 /* Restrict bpf side of cpumap and xskmap, open when use-cases
7335 case BPF_MAP_TYPE_CPUMAP:
7336 if (func_id != BPF_FUNC_redirect_map)
7339 case BPF_MAP_TYPE_XSKMAP:
7340 if (func_id != BPF_FUNC_redirect_map &&
7341 func_id != BPF_FUNC_map_lookup_elem)
7344 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
7345 case BPF_MAP_TYPE_HASH_OF_MAPS:
7346 if (func_id != BPF_FUNC_map_lookup_elem)
7349 case BPF_MAP_TYPE_SOCKMAP:
7350 if (func_id != BPF_FUNC_sk_redirect_map &&
7351 func_id != BPF_FUNC_sock_map_update &&
7352 func_id != BPF_FUNC_map_delete_elem &&
7353 func_id != BPF_FUNC_msg_redirect_map &&
7354 func_id != BPF_FUNC_sk_select_reuseport &&
7355 func_id != BPF_FUNC_map_lookup_elem &&
7356 !may_update_sockmap(env, func_id))
7359 case BPF_MAP_TYPE_SOCKHASH:
7360 if (func_id != BPF_FUNC_sk_redirect_hash &&
7361 func_id != BPF_FUNC_sock_hash_update &&
7362 func_id != BPF_FUNC_map_delete_elem &&
7363 func_id != BPF_FUNC_msg_redirect_hash &&
7364 func_id != BPF_FUNC_sk_select_reuseport &&
7365 func_id != BPF_FUNC_map_lookup_elem &&
7366 !may_update_sockmap(env, func_id))
7369 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
7370 if (func_id != BPF_FUNC_sk_select_reuseport)
7373 case BPF_MAP_TYPE_QUEUE:
7374 case BPF_MAP_TYPE_STACK:
7375 if (func_id != BPF_FUNC_map_peek_elem &&
7376 func_id != BPF_FUNC_map_pop_elem &&
7377 func_id != BPF_FUNC_map_push_elem)
7380 case BPF_MAP_TYPE_SK_STORAGE:
7381 if (func_id != BPF_FUNC_sk_storage_get &&
7382 func_id != BPF_FUNC_sk_storage_delete &&
7383 func_id != BPF_FUNC_kptr_xchg)
7386 case BPF_MAP_TYPE_INODE_STORAGE:
7387 if (func_id != BPF_FUNC_inode_storage_get &&
7388 func_id != BPF_FUNC_inode_storage_delete &&
7389 func_id != BPF_FUNC_kptr_xchg)
7392 case BPF_MAP_TYPE_TASK_STORAGE:
7393 if (func_id != BPF_FUNC_task_storage_get &&
7394 func_id != BPF_FUNC_task_storage_delete &&
7395 func_id != BPF_FUNC_kptr_xchg)
7398 case BPF_MAP_TYPE_CGRP_STORAGE:
7399 if (func_id != BPF_FUNC_cgrp_storage_get &&
7400 func_id != BPF_FUNC_cgrp_storage_delete &&
7401 func_id != BPF_FUNC_kptr_xchg)
7404 case BPF_MAP_TYPE_BLOOM_FILTER:
7405 if (func_id != BPF_FUNC_map_peek_elem &&
7406 func_id != BPF_FUNC_map_push_elem)
7413 /* ... and second from the function itself. */
7415 case BPF_FUNC_tail_call:
7416 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
7418 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
7419 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
7423 case BPF_FUNC_perf_event_read:
7424 case BPF_FUNC_perf_event_output:
7425 case BPF_FUNC_perf_event_read_value:
7426 case BPF_FUNC_skb_output:
7427 case BPF_FUNC_xdp_output:
7428 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
7431 case BPF_FUNC_ringbuf_output:
7432 case BPF_FUNC_ringbuf_reserve:
7433 case BPF_FUNC_ringbuf_query:
7434 case BPF_FUNC_ringbuf_reserve_dynptr:
7435 case BPF_FUNC_ringbuf_submit_dynptr:
7436 case BPF_FUNC_ringbuf_discard_dynptr:
7437 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
7440 case BPF_FUNC_user_ringbuf_drain:
7441 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
7444 case BPF_FUNC_get_stackid:
7445 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
7448 case BPF_FUNC_current_task_under_cgroup:
7449 case BPF_FUNC_skb_under_cgroup:
7450 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
7453 case BPF_FUNC_redirect_map:
7454 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
7455 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
7456 map->map_type != BPF_MAP_TYPE_CPUMAP &&
7457 map->map_type != BPF_MAP_TYPE_XSKMAP)
7460 case BPF_FUNC_sk_redirect_map:
7461 case BPF_FUNC_msg_redirect_map:
7462 case BPF_FUNC_sock_map_update:
7463 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
7466 case BPF_FUNC_sk_redirect_hash:
7467 case BPF_FUNC_msg_redirect_hash:
7468 case BPF_FUNC_sock_hash_update:
7469 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
7472 case BPF_FUNC_get_local_storage:
7473 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
7474 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
7477 case BPF_FUNC_sk_select_reuseport:
7478 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
7479 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
7480 map->map_type != BPF_MAP_TYPE_SOCKHASH)
7483 case BPF_FUNC_map_pop_elem:
7484 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7485 map->map_type != BPF_MAP_TYPE_STACK)
7488 case BPF_FUNC_map_peek_elem:
7489 case BPF_FUNC_map_push_elem:
7490 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7491 map->map_type != BPF_MAP_TYPE_STACK &&
7492 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
7495 case BPF_FUNC_map_lookup_percpu_elem:
7496 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
7497 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7498 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
7501 case BPF_FUNC_sk_storage_get:
7502 case BPF_FUNC_sk_storage_delete:
7503 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
7506 case BPF_FUNC_inode_storage_get:
7507 case BPF_FUNC_inode_storage_delete:
7508 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
7511 case BPF_FUNC_task_storage_get:
7512 case BPF_FUNC_task_storage_delete:
7513 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
7516 case BPF_FUNC_cgrp_storage_get:
7517 case BPF_FUNC_cgrp_storage_delete:
7518 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
7527 verbose(env, "cannot pass map_type %d into func %s#%d\n",
7528 map->map_type, func_id_name(func_id), func_id);
7532 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
7536 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
7538 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
7540 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
7542 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
7544 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
7547 /* We only support one arg being in raw mode at the moment,
7548 * which is sufficient for the helper functions we have
7554 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
7556 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
7557 bool has_size = fn->arg_size[arg] != 0;
7558 bool is_next_size = false;
7560 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
7561 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
7563 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
7564 return is_next_size;
7566 return has_size == is_next_size || is_next_size == is_fixed;
7569 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
7571 /* bpf_xxx(..., buf, len) call will access 'len'
7572 * bytes from memory 'buf'. Both arg types need
7573 * to be paired, so make sure there's no buggy
7574 * helper function specification.
7576 if (arg_type_is_mem_size(fn->arg1_type) ||
7577 check_args_pair_invalid(fn, 0) ||
7578 check_args_pair_invalid(fn, 1) ||
7579 check_args_pair_invalid(fn, 2) ||
7580 check_args_pair_invalid(fn, 3) ||
7581 check_args_pair_invalid(fn, 4))
7587 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
7591 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
7592 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
7593 return !!fn->arg_btf_id[i];
7594 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
7595 return fn->arg_btf_id[i] == BPF_PTR_POISON;
7596 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
7597 /* arg_btf_id and arg_size are in a union. */
7598 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
7599 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
7606 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
7608 return check_raw_mode_ok(fn) &&
7609 check_arg_pair_ok(fn) &&
7610 check_btf_id_ok(fn) ? 0 : -EINVAL;
7613 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
7614 * are now invalid, so turn them into unknown SCALAR_VALUE.
7616 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
7617 * since these slices point to packet data.
7619 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
7621 struct bpf_func_state *state;
7622 struct bpf_reg_state *reg;
7624 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7625 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
7626 mark_reg_invalid(env, reg);
7632 BEYOND_PKT_END = -2,
7635 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
7637 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7638 struct bpf_reg_state *reg = &state->regs[regn];
7640 if (reg->type != PTR_TO_PACKET)
7641 /* PTR_TO_PACKET_META is not supported yet */
7644 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
7645 * How far beyond pkt_end it goes is unknown.
7646 * if (!range_open) it's the case of pkt >= pkt_end
7647 * if (range_open) it's the case of pkt > pkt_end
7648 * hence this pointer is at least 1 byte bigger than pkt_end
7651 reg->range = BEYOND_PKT_END;
7653 reg->range = AT_PKT_END;
7656 /* The pointer with the specified id has released its reference to kernel
7657 * resources. Identify all copies of the same pointer and clear the reference.
7659 static int release_reference(struct bpf_verifier_env *env,
7662 struct bpf_func_state *state;
7663 struct bpf_reg_state *reg;
7666 err = release_reference_state(cur_func(env), ref_obj_id);
7670 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7671 if (reg->ref_obj_id == ref_obj_id)
7672 mark_reg_invalid(env, reg);
7678 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
7680 struct bpf_func_state *unused;
7681 struct bpf_reg_state *reg;
7683 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
7684 if (type_is_non_owning_ref(reg->type))
7685 mark_reg_invalid(env, reg);
7689 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
7690 struct bpf_reg_state *regs)
7694 /* after the call registers r0 - r5 were scratched */
7695 for (i = 0; i < CALLER_SAVED_REGS; i++) {
7696 mark_reg_not_init(env, regs, caller_saved[i]);
7697 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7701 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
7702 struct bpf_func_state *caller,
7703 struct bpf_func_state *callee,
7706 static int set_callee_state(struct bpf_verifier_env *env,
7707 struct bpf_func_state *caller,
7708 struct bpf_func_state *callee, int insn_idx);
7710 static bool is_callback_calling_kfunc(u32 btf_id);
7712 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7713 int *insn_idx, int subprog,
7714 set_callee_state_fn set_callee_state_cb)
7716 struct bpf_verifier_state *state = env->cur_state;
7717 struct bpf_func_info_aux *func_info_aux;
7718 struct bpf_func_state *caller, *callee;
7720 bool is_global = false;
7722 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
7723 verbose(env, "the call stack of %d frames is too deep\n",
7724 state->curframe + 2);
7728 caller = state->frame[state->curframe];
7729 if (state->frame[state->curframe + 1]) {
7730 verbose(env, "verifier bug. Frame %d already allocated\n",
7731 state->curframe + 1);
7735 func_info_aux = env->prog->aux->func_info_aux;
7737 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
7738 err = btf_check_subprog_call(env, subprog, caller->regs);
7743 verbose(env, "Caller passes invalid args into func#%d\n",
7747 if (env->log.level & BPF_LOG_LEVEL)
7749 "Func#%d is global and valid. Skipping.\n",
7751 clear_caller_saved_regs(env, caller->regs);
7753 /* All global functions return a 64-bit SCALAR_VALUE */
7754 mark_reg_unknown(env, caller->regs, BPF_REG_0);
7755 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7757 /* continue with next insn after call */
7762 /* set_callee_state is used for direct subprog calls, but we are
7763 * interested in validating only BPF helpers that can call subprogs as
7766 if (set_callee_state_cb != set_callee_state) {
7767 if (bpf_pseudo_kfunc_call(insn) &&
7768 !is_callback_calling_kfunc(insn->imm)) {
7769 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
7770 func_id_name(insn->imm), insn->imm);
7772 } else if (!bpf_pseudo_kfunc_call(insn) &&
7773 !is_callback_calling_function(insn->imm)) { /* helper */
7774 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
7775 func_id_name(insn->imm), insn->imm);
7780 if (insn->code == (BPF_JMP | BPF_CALL) &&
7781 insn->src_reg == 0 &&
7782 insn->imm == BPF_FUNC_timer_set_callback) {
7783 struct bpf_verifier_state *async_cb;
7785 /* there is no real recursion here. timer callbacks are async */
7786 env->subprog_info[subprog].is_async_cb = true;
7787 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
7788 *insn_idx, subprog);
7791 callee = async_cb->frame[0];
7792 callee->async_entry_cnt = caller->async_entry_cnt + 1;
7794 /* Convert bpf_timer_set_callback() args into timer callback args */
7795 err = set_callee_state_cb(env, caller, callee, *insn_idx);
7799 clear_caller_saved_regs(env, caller->regs);
7800 mark_reg_unknown(env, caller->regs, BPF_REG_0);
7801 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7802 /* continue with next insn after call */
7806 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
7809 state->frame[state->curframe + 1] = callee;
7811 /* callee cannot access r0, r6 - r9 for reading and has to write
7812 * into its own stack before reading from it.
7813 * callee can read/write into caller's stack
7815 init_func_state(env, callee,
7816 /* remember the callsite, it will be used by bpf_exit */
7817 *insn_idx /* callsite */,
7818 state->curframe + 1 /* frameno within this callchain */,
7819 subprog /* subprog number within this prog */);
7821 /* Transfer references to the callee */
7822 err = copy_reference_state(callee, caller);
7826 err = set_callee_state_cb(env, caller, callee, *insn_idx);
7830 clear_caller_saved_regs(env, caller->regs);
7832 /* only increment it after check_reg_arg() finished */
7835 /* and go analyze first insn of the callee */
7836 *insn_idx = env->subprog_info[subprog].start - 1;
7838 if (env->log.level & BPF_LOG_LEVEL) {
7839 verbose(env, "caller:\n");
7840 print_verifier_state(env, caller, true);
7841 verbose(env, "callee:\n");
7842 print_verifier_state(env, callee, true);
7847 free_func_state(callee);
7848 state->frame[state->curframe + 1] = NULL;
7852 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7853 struct bpf_func_state *caller,
7854 struct bpf_func_state *callee)
7856 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7857 * void *callback_ctx, u64 flags);
7858 * callback_fn(struct bpf_map *map, void *key, void *value,
7859 * void *callback_ctx);
7861 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7863 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7864 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7865 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7867 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7868 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7869 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7871 /* pointer to stack or null */
7872 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7875 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7879 static int set_callee_state(struct bpf_verifier_env *env,
7880 struct bpf_func_state *caller,
7881 struct bpf_func_state *callee, int insn_idx)
7885 /* copy r1 - r5 args that callee can access. The copy includes parent
7886 * pointers, which connects us up to the liveness chain
7888 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7889 callee->regs[i] = caller->regs[i];
7893 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7896 int subprog, target_insn;
7898 target_insn = *insn_idx + insn->imm + 1;
7899 subprog = find_subprog(env, target_insn);
7901 verbose(env, "verifier bug. No program starts at insn %d\n",
7906 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7909 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7910 struct bpf_func_state *caller,
7911 struct bpf_func_state *callee,
7914 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7915 struct bpf_map *map;
7918 if (bpf_map_ptr_poisoned(insn_aux)) {
7919 verbose(env, "tail_call abusing map_ptr\n");
7923 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7924 if (!map->ops->map_set_for_each_callback_args ||
7925 !map->ops->map_for_each_callback) {
7926 verbose(env, "callback function not allowed for map\n");
7930 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7934 callee->in_callback_fn = true;
7935 callee->callback_ret_range = tnum_range(0, 1);
7939 static int set_loop_callback_state(struct bpf_verifier_env *env,
7940 struct bpf_func_state *caller,
7941 struct bpf_func_state *callee,
7944 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7946 * callback_fn(u32 index, void *callback_ctx);
7948 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7949 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7952 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7953 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7954 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7956 callee->in_callback_fn = true;
7957 callee->callback_ret_range = tnum_range(0, 1);
7961 static int set_timer_callback_state(struct bpf_verifier_env *env,
7962 struct bpf_func_state *caller,
7963 struct bpf_func_state *callee,
7966 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7968 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7969 * callback_fn(struct bpf_map *map, void *key, void *value);
7971 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7972 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7973 callee->regs[BPF_REG_1].map_ptr = map_ptr;
7975 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7976 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7977 callee->regs[BPF_REG_2].map_ptr = map_ptr;
7979 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7980 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7981 callee->regs[BPF_REG_3].map_ptr = map_ptr;
7984 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7985 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7986 callee->in_async_callback_fn = true;
7987 callee->callback_ret_range = tnum_range(0, 1);
7991 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7992 struct bpf_func_state *caller,
7993 struct bpf_func_state *callee,
7996 /* bpf_find_vma(struct task_struct *task, u64 addr,
7997 * void *callback_fn, void *callback_ctx, u64 flags)
7998 * (callback_fn)(struct task_struct *task,
7999 * struct vm_area_struct *vma, void *callback_ctx);
8001 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8003 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8004 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8005 callee->regs[BPF_REG_2].btf = btf_vmlinux;
8006 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8008 /* pointer to stack or null */
8009 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8012 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8013 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8014 callee->in_callback_fn = true;
8015 callee->callback_ret_range = tnum_range(0, 1);
8019 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8020 struct bpf_func_state *caller,
8021 struct bpf_func_state *callee,
8024 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8025 * callback_ctx, u64 flags);
8026 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8028 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
8029 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
8030 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8033 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8034 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8035 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8037 callee->in_callback_fn = true;
8038 callee->callback_ret_range = tnum_range(0, 1);
8042 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
8043 struct bpf_func_state *caller,
8044 struct bpf_func_state *callee,
8047 /* void bpf_rbtree_add(struct bpf_rb_root *root, struct bpf_rb_node *node,
8048 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
8050 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add is the same PTR_TO_BTF_ID w/ offset
8051 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
8052 * by this point, so look at 'root'
8054 struct btf_field *field;
8056 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
8058 if (!field || !field->graph_root.value_btf_id)
8061 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
8062 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
8063 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
8064 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
8066 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8067 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8068 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8069 callee->in_callback_fn = true;
8070 callee->callback_ret_range = tnum_range(0, 1);
8074 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
8076 /* Are we currently verifying the callback for a rbtree helper that must
8077 * be called with lock held? If so, no need to complain about unreleased
8080 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
8082 struct bpf_verifier_state *state = env->cur_state;
8083 struct bpf_insn *insn = env->prog->insnsi;
8084 struct bpf_func_state *callee;
8087 if (!state->curframe)
8090 callee = state->frame[state->curframe];
8092 if (!callee->in_callback_fn)
8095 kfunc_btf_id = insn[callee->callsite].imm;
8096 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
8099 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
8101 struct bpf_verifier_state *state = env->cur_state;
8102 struct bpf_func_state *caller, *callee;
8103 struct bpf_reg_state *r0;
8106 callee = state->frame[state->curframe];
8107 r0 = &callee->regs[BPF_REG_0];
8108 if (r0->type == PTR_TO_STACK) {
8109 /* technically it's ok to return caller's stack pointer
8110 * (or caller's caller's pointer) back to the caller,
8111 * since these pointers are valid. Only current stack
8112 * pointer will be invalid as soon as function exits,
8113 * but let's be conservative
8115 verbose(env, "cannot return stack pointer to the caller\n");
8119 caller = state->frame[state->curframe - 1];
8120 if (callee->in_callback_fn) {
8121 /* enforce R0 return value range [0, 1]. */
8122 struct tnum range = callee->callback_ret_range;
8124 if (r0->type != SCALAR_VALUE) {
8125 verbose(env, "R0 not a scalar value\n");
8128 if (!tnum_in(range, r0->var_off)) {
8129 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
8133 /* return to the caller whatever r0 had in the callee */
8134 caller->regs[BPF_REG_0] = *r0;
8137 /* callback_fn frame should have released its own additions to parent's
8138 * reference state at this point, or check_reference_leak would
8139 * complain, hence it must be the same as the caller. There is no need
8142 if (!callee->in_callback_fn) {
8143 /* Transfer references to the caller */
8144 err = copy_reference_state(caller, callee);
8149 *insn_idx = callee->callsite + 1;
8150 if (env->log.level & BPF_LOG_LEVEL) {
8151 verbose(env, "returning from callee:\n");
8152 print_verifier_state(env, callee, true);
8153 verbose(env, "to caller at %d:\n", *insn_idx);
8154 print_verifier_state(env, caller, true);
8156 /* clear everything in the callee */
8157 free_func_state(callee);
8158 state->frame[state->curframe--] = NULL;
8162 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
8164 struct bpf_call_arg_meta *meta)
8166 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
8168 if (ret_type != RET_INTEGER ||
8169 (func_id != BPF_FUNC_get_stack &&
8170 func_id != BPF_FUNC_get_task_stack &&
8171 func_id != BPF_FUNC_probe_read_str &&
8172 func_id != BPF_FUNC_probe_read_kernel_str &&
8173 func_id != BPF_FUNC_probe_read_user_str))
8176 ret_reg->smax_value = meta->msize_max_value;
8177 ret_reg->s32_max_value = meta->msize_max_value;
8178 ret_reg->smin_value = -MAX_ERRNO;
8179 ret_reg->s32_min_value = -MAX_ERRNO;
8180 reg_bounds_sync(ret_reg);
8184 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8185 int func_id, int insn_idx)
8187 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8188 struct bpf_map *map = meta->map_ptr;
8190 if (func_id != BPF_FUNC_tail_call &&
8191 func_id != BPF_FUNC_map_lookup_elem &&
8192 func_id != BPF_FUNC_map_update_elem &&
8193 func_id != BPF_FUNC_map_delete_elem &&
8194 func_id != BPF_FUNC_map_push_elem &&
8195 func_id != BPF_FUNC_map_pop_elem &&
8196 func_id != BPF_FUNC_map_peek_elem &&
8197 func_id != BPF_FUNC_for_each_map_elem &&
8198 func_id != BPF_FUNC_redirect_map &&
8199 func_id != BPF_FUNC_map_lookup_percpu_elem)
8203 verbose(env, "kernel subsystem misconfigured verifier\n");
8207 /* In case of read-only, some additional restrictions
8208 * need to be applied in order to prevent altering the
8209 * state of the map from program side.
8211 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
8212 (func_id == BPF_FUNC_map_delete_elem ||
8213 func_id == BPF_FUNC_map_update_elem ||
8214 func_id == BPF_FUNC_map_push_elem ||
8215 func_id == BPF_FUNC_map_pop_elem)) {
8216 verbose(env, "write into map forbidden\n");
8220 if (!BPF_MAP_PTR(aux->map_ptr_state))
8221 bpf_map_ptr_store(aux, meta->map_ptr,
8222 !meta->map_ptr->bypass_spec_v1);
8223 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
8224 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
8225 !meta->map_ptr->bypass_spec_v1);
8230 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8231 int func_id, int insn_idx)
8233 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8234 struct bpf_reg_state *regs = cur_regs(env), *reg;
8235 struct bpf_map *map = meta->map_ptr;
8239 if (func_id != BPF_FUNC_tail_call)
8241 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
8242 verbose(env, "kernel subsystem misconfigured verifier\n");
8246 reg = ®s[BPF_REG_3];
8247 val = reg->var_off.value;
8248 max = map->max_entries;
8250 if (!(register_is_const(reg) && val < max)) {
8251 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8255 err = mark_chain_precision(env, BPF_REG_3);
8258 if (bpf_map_key_unseen(aux))
8259 bpf_map_key_store(aux, val);
8260 else if (!bpf_map_key_poisoned(aux) &&
8261 bpf_map_key_immediate(aux) != val)
8262 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8266 static int check_reference_leak(struct bpf_verifier_env *env)
8268 struct bpf_func_state *state = cur_func(env);
8269 bool refs_lingering = false;
8272 if (state->frameno && !state->in_callback_fn)
8275 for (i = 0; i < state->acquired_refs; i++) {
8276 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
8278 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
8279 state->refs[i].id, state->refs[i].insn_idx);
8280 refs_lingering = true;
8282 return refs_lingering ? -EINVAL : 0;
8285 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
8286 struct bpf_reg_state *regs)
8288 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
8289 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
8290 struct bpf_map *fmt_map = fmt_reg->map_ptr;
8291 struct bpf_bprintf_data data = {};
8292 int err, fmt_map_off, num_args;
8296 /* data must be an array of u64 */
8297 if (data_len_reg->var_off.value % 8)
8299 num_args = data_len_reg->var_off.value / 8;
8301 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
8302 * and map_direct_value_addr is set.
8304 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
8305 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
8308 verbose(env, "verifier bug\n");
8311 fmt = (char *)(long)fmt_addr + fmt_map_off;
8313 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
8314 * can focus on validating the format specifiers.
8316 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
8318 verbose(env, "Invalid format string\n");
8323 static int check_get_func_ip(struct bpf_verifier_env *env)
8325 enum bpf_prog_type type = resolve_prog_type(env->prog);
8326 int func_id = BPF_FUNC_get_func_ip;
8328 if (type == BPF_PROG_TYPE_TRACING) {
8329 if (!bpf_prog_has_trampoline(env->prog)) {
8330 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
8331 func_id_name(func_id), func_id);
8335 } else if (type == BPF_PROG_TYPE_KPROBE) {
8339 verbose(env, "func %s#%d not supported for program type %d\n",
8340 func_id_name(func_id), func_id, type);
8344 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
8346 return &env->insn_aux_data[env->insn_idx];
8349 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
8351 struct bpf_reg_state *regs = cur_regs(env);
8352 struct bpf_reg_state *reg = ®s[BPF_REG_4];
8353 bool reg_is_null = register_is_null(reg);
8356 mark_chain_precision(env, BPF_REG_4);
8361 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
8363 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
8365 if (!state->initialized) {
8366 state->initialized = 1;
8367 state->fit_for_inline = loop_flag_is_zero(env);
8368 state->callback_subprogno = subprogno;
8372 if (!state->fit_for_inline)
8375 state->fit_for_inline = (loop_flag_is_zero(env) &&
8376 state->callback_subprogno == subprogno);
8379 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8382 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8383 const struct bpf_func_proto *fn = NULL;
8384 enum bpf_return_type ret_type;
8385 enum bpf_type_flag ret_flag;
8386 struct bpf_reg_state *regs;
8387 struct bpf_call_arg_meta meta;
8388 int insn_idx = *insn_idx_p;
8390 int i, err, func_id;
8392 /* find function prototype */
8393 func_id = insn->imm;
8394 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
8395 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
8400 if (env->ops->get_func_proto)
8401 fn = env->ops->get_func_proto(func_id, env->prog);
8403 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
8408 /* eBPF programs must be GPL compatible to use GPL-ed functions */
8409 if (!env->prog->gpl_compatible && fn->gpl_only) {
8410 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
8414 if (fn->allowed && !fn->allowed(env->prog)) {
8415 verbose(env, "helper call is not allowed in probe\n");
8419 if (!env->prog->aux->sleepable && fn->might_sleep) {
8420 verbose(env, "helper call might sleep in a non-sleepable prog\n");
8424 /* With LD_ABS/IND some JITs save/restore skb from r1. */
8425 changes_data = bpf_helper_changes_pkt_data(fn->func);
8426 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
8427 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
8428 func_id_name(func_id), func_id);
8432 memset(&meta, 0, sizeof(meta));
8433 meta.pkt_access = fn->pkt_access;
8435 err = check_func_proto(fn, func_id);
8437 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
8438 func_id_name(func_id), func_id);
8442 if (env->cur_state->active_rcu_lock) {
8443 if (fn->might_sleep) {
8444 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
8445 func_id_name(func_id), func_id);
8449 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
8450 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
8453 meta.func_id = func_id;
8455 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8456 err = check_func_arg(env, i, &meta, fn, insn_idx);
8461 err = record_func_map(env, &meta, func_id, insn_idx);
8465 err = record_func_key(env, &meta, func_id, insn_idx);
8469 /* Mark slots with STACK_MISC in case of raw mode, stack offset
8470 * is inferred from register state.
8472 for (i = 0; i < meta.access_size; i++) {
8473 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
8474 BPF_WRITE, -1, false);
8479 regs = cur_regs(env);
8481 if (meta.release_regno) {
8483 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8484 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
8485 * is safe to do directly.
8487 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
8488 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
8489 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
8492 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
8493 } else if (meta.ref_obj_id) {
8494 err = release_reference(env, meta.ref_obj_id);
8495 } else if (register_is_null(®s[meta.release_regno])) {
8496 /* meta.ref_obj_id can only be 0 if register that is meant to be
8497 * released is NULL, which must be > R0.
8502 verbose(env, "func %s#%d reference has not been acquired before\n",
8503 func_id_name(func_id), func_id);
8509 case BPF_FUNC_tail_call:
8510 err = check_reference_leak(env);
8512 verbose(env, "tail_call would lead to reference leak\n");
8516 case BPF_FUNC_get_local_storage:
8517 /* check that flags argument in get_local_storage(map, flags) is 0,
8518 * this is required because get_local_storage() can't return an error.
8520 if (!register_is_null(®s[BPF_REG_2])) {
8521 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
8525 case BPF_FUNC_for_each_map_elem:
8526 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8527 set_map_elem_callback_state);
8529 case BPF_FUNC_timer_set_callback:
8530 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8531 set_timer_callback_state);
8533 case BPF_FUNC_find_vma:
8534 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8535 set_find_vma_callback_state);
8537 case BPF_FUNC_snprintf:
8538 err = check_bpf_snprintf_call(env, regs);
8541 update_loop_inline_state(env, meta.subprogno);
8542 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8543 set_loop_callback_state);
8545 case BPF_FUNC_dynptr_from_mem:
8546 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
8547 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
8548 reg_type_str(env, regs[BPF_REG_1].type));
8552 case BPF_FUNC_set_retval:
8553 if (prog_type == BPF_PROG_TYPE_LSM &&
8554 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
8555 if (!env->prog->aux->attach_func_proto->type) {
8556 /* Make sure programs that attach to void
8557 * hooks don't try to modify return value.
8559 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
8564 case BPF_FUNC_dynptr_data:
8566 struct bpf_reg_state *reg;
8569 reg = get_dynptr_arg_reg(env, fn, regs);
8574 if (meta.dynptr_id) {
8575 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
8578 if (meta.ref_obj_id) {
8579 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
8583 id = dynptr_id(env, reg);
8585 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
8589 ref_obj_id = dynptr_ref_obj_id(env, reg);
8590 if (ref_obj_id < 0) {
8591 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
8595 meta.dynptr_id = id;
8596 meta.ref_obj_id = ref_obj_id;
8600 case BPF_FUNC_dynptr_write:
8602 enum bpf_dynptr_type dynptr_type;
8603 struct bpf_reg_state *reg;
8605 reg = get_dynptr_arg_reg(env, fn, regs);
8609 dynptr_type = dynptr_get_type(env, reg);
8610 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
8613 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
8614 /* this will trigger clear_all_pkt_pointers(), which will
8615 * invalidate all dynptr slices associated with the skb
8617 changes_data = true;
8621 case BPF_FUNC_user_ringbuf_drain:
8622 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8623 set_user_ringbuf_callback_state);
8630 /* reset caller saved regs */
8631 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8632 mark_reg_not_init(env, regs, caller_saved[i]);
8633 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8636 /* helper call returns 64-bit value. */
8637 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8639 /* update return register (already marked as written above) */
8640 ret_type = fn->ret_type;
8641 ret_flag = type_flag(ret_type);
8643 switch (base_type(ret_type)) {
8645 /* sets type to SCALAR_VALUE */
8646 mark_reg_unknown(env, regs, BPF_REG_0);
8649 regs[BPF_REG_0].type = NOT_INIT;
8651 case RET_PTR_TO_MAP_VALUE:
8652 /* There is no offset yet applied, variable or fixed */
8653 mark_reg_known_zero(env, regs, BPF_REG_0);
8654 /* remember map_ptr, so that check_map_access()
8655 * can check 'value_size' boundary of memory access
8656 * to map element returned from bpf_map_lookup_elem()
8658 if (meta.map_ptr == NULL) {
8660 "kernel subsystem misconfigured verifier\n");
8663 regs[BPF_REG_0].map_ptr = meta.map_ptr;
8664 regs[BPF_REG_0].map_uid = meta.map_uid;
8665 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
8666 if (!type_may_be_null(ret_type) &&
8667 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
8668 regs[BPF_REG_0].id = ++env->id_gen;
8671 case RET_PTR_TO_SOCKET:
8672 mark_reg_known_zero(env, regs, BPF_REG_0);
8673 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
8675 case RET_PTR_TO_SOCK_COMMON:
8676 mark_reg_known_zero(env, regs, BPF_REG_0);
8677 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
8679 case RET_PTR_TO_TCP_SOCK:
8680 mark_reg_known_zero(env, regs, BPF_REG_0);
8681 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
8683 case RET_PTR_TO_MEM:
8684 mark_reg_known_zero(env, regs, BPF_REG_0);
8685 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8686 regs[BPF_REG_0].mem_size = meta.mem_size;
8688 case RET_PTR_TO_MEM_OR_BTF_ID:
8690 const struct btf_type *t;
8692 mark_reg_known_zero(env, regs, BPF_REG_0);
8693 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
8694 if (!btf_type_is_struct(t)) {
8696 const struct btf_type *ret;
8699 /* resolve the type size of ksym. */
8700 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
8702 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
8703 verbose(env, "unable to resolve the size of type '%s': %ld\n",
8704 tname, PTR_ERR(ret));
8707 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8708 regs[BPF_REG_0].mem_size = tsize;
8710 /* MEM_RDONLY may be carried from ret_flag, but it
8711 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
8712 * it will confuse the check of PTR_TO_BTF_ID in
8713 * check_mem_access().
8715 ret_flag &= ~MEM_RDONLY;
8717 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8718 regs[BPF_REG_0].btf = meta.ret_btf;
8719 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8723 case RET_PTR_TO_BTF_ID:
8725 struct btf *ret_btf;
8728 mark_reg_known_zero(env, regs, BPF_REG_0);
8729 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8730 if (func_id == BPF_FUNC_kptr_xchg) {
8731 ret_btf = meta.kptr_field->kptr.btf;
8732 ret_btf_id = meta.kptr_field->kptr.btf_id;
8734 if (fn->ret_btf_id == BPF_PTR_POISON) {
8735 verbose(env, "verifier internal error:");
8736 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
8737 func_id_name(func_id));
8740 ret_btf = btf_vmlinux;
8741 ret_btf_id = *fn->ret_btf_id;
8743 if (ret_btf_id == 0) {
8744 verbose(env, "invalid return type %u of func %s#%d\n",
8745 base_type(ret_type), func_id_name(func_id),
8749 regs[BPF_REG_0].btf = ret_btf;
8750 regs[BPF_REG_0].btf_id = ret_btf_id;
8754 verbose(env, "unknown return type %u of func %s#%d\n",
8755 base_type(ret_type), func_id_name(func_id), func_id);
8759 if (type_may_be_null(regs[BPF_REG_0].type))
8760 regs[BPF_REG_0].id = ++env->id_gen;
8762 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
8763 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
8764 func_id_name(func_id), func_id);
8768 if (is_dynptr_ref_function(func_id))
8769 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
8771 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
8772 /* For release_reference() */
8773 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8774 } else if (is_acquire_function(func_id, meta.map_ptr)) {
8775 int id = acquire_reference_state(env, insn_idx);
8779 /* For mark_ptr_or_null_reg() */
8780 regs[BPF_REG_0].id = id;
8781 /* For release_reference() */
8782 regs[BPF_REG_0].ref_obj_id = id;
8785 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
8787 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
8791 if ((func_id == BPF_FUNC_get_stack ||
8792 func_id == BPF_FUNC_get_task_stack) &&
8793 !env->prog->has_callchain_buf) {
8794 const char *err_str;
8796 #ifdef CONFIG_PERF_EVENTS
8797 err = get_callchain_buffers(sysctl_perf_event_max_stack);
8798 err_str = "cannot get callchain buffer for func %s#%d\n";
8801 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
8804 verbose(env, err_str, func_id_name(func_id), func_id);
8808 env->prog->has_callchain_buf = true;
8811 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
8812 env->prog->call_get_stack = true;
8814 if (func_id == BPF_FUNC_get_func_ip) {
8815 if (check_get_func_ip(env))
8817 env->prog->call_get_func_ip = true;
8821 clear_all_pkt_pointers(env);
8825 /* mark_btf_func_reg_size() is used when the reg size is determined by
8826 * the BTF func_proto's return value size and argument.
8828 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
8831 struct bpf_reg_state *reg = &cur_regs(env)[regno];
8833 if (regno == BPF_REG_0) {
8834 /* Function return value */
8835 reg->live |= REG_LIVE_WRITTEN;
8836 reg->subreg_def = reg_size == sizeof(u64) ?
8837 DEF_NOT_SUBREG : env->insn_idx + 1;
8839 /* Function argument */
8840 if (reg_size == sizeof(u64)) {
8841 mark_insn_zext(env, reg);
8842 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
8844 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
8849 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
8851 return meta->kfunc_flags & KF_ACQUIRE;
8854 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
8856 return meta->kfunc_flags & KF_RET_NULL;
8859 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
8861 return meta->kfunc_flags & KF_RELEASE;
8864 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
8866 return meta->kfunc_flags & KF_TRUSTED_ARGS;
8869 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
8871 return meta->kfunc_flags & KF_SLEEPABLE;
8874 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
8876 return meta->kfunc_flags & KF_DESTRUCTIVE;
8879 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
8881 return meta->kfunc_flags & KF_RCU;
8884 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
8886 return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
8889 static bool __kfunc_param_match_suffix(const struct btf *btf,
8890 const struct btf_param *arg,
8893 int suffix_len = strlen(suffix), len;
8894 const char *param_name;
8896 /* In the future, this can be ported to use BTF tagging */
8897 param_name = btf_name_by_offset(btf, arg->name_off);
8898 if (str_is_empty(param_name))
8900 len = strlen(param_name);
8901 if (len < suffix_len)
8903 param_name += len - suffix_len;
8904 return !strncmp(param_name, suffix, suffix_len);
8907 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8908 const struct btf_param *arg,
8909 const struct bpf_reg_state *reg)
8911 const struct btf_type *t;
8913 t = btf_type_skip_modifiers(btf, arg->type, NULL);
8914 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8917 return __kfunc_param_match_suffix(btf, arg, "__sz");
8920 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
8921 const struct btf_param *arg,
8922 const struct bpf_reg_state *reg)
8924 const struct btf_type *t;
8926 t = btf_type_skip_modifiers(btf, arg->type, NULL);
8927 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8930 return __kfunc_param_match_suffix(btf, arg, "__szk");
8933 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8935 return __kfunc_param_match_suffix(btf, arg, "__k");
8938 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8940 return __kfunc_param_match_suffix(btf, arg, "__ign");
8943 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8945 return __kfunc_param_match_suffix(btf, arg, "__alloc");
8948 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
8950 return __kfunc_param_match_suffix(btf, arg, "__uninit");
8953 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8954 const struct btf_param *arg,
8957 int len, target_len = strlen(name);
8958 const char *param_name;
8960 param_name = btf_name_by_offset(btf, arg->name_off);
8961 if (str_is_empty(param_name))
8963 len = strlen(param_name);
8964 if (len != target_len)
8966 if (strcmp(param_name, name))
8974 KF_ARG_LIST_HEAD_ID,
8975 KF_ARG_LIST_NODE_ID,
8980 BTF_ID_LIST(kf_arg_btf_ids)
8981 BTF_ID(struct, bpf_dynptr_kern)
8982 BTF_ID(struct, bpf_list_head)
8983 BTF_ID(struct, bpf_list_node)
8984 BTF_ID(struct, bpf_rb_root)
8985 BTF_ID(struct, bpf_rb_node)
8987 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8988 const struct btf_param *arg, int type)
8990 const struct btf_type *t;
8993 t = btf_type_skip_modifiers(btf, arg->type, NULL);
8996 if (!btf_type_is_ptr(t))
8998 t = btf_type_skip_modifiers(btf, t->type, &res_id);
9001 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9004 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9006 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9009 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9011 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9014 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
9016 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
9019 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9021 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9024 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
9026 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
9029 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
9030 const struct btf_param *arg)
9032 const struct btf_type *t;
9034 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
9041 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
9042 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
9043 const struct btf *btf,
9044 const struct btf_type *t, int rec)
9046 const struct btf_type *member_type;
9047 const struct btf_member *member;
9050 if (!btf_type_is_struct(t))
9053 for_each_member(i, t, member) {
9054 const struct btf_array *array;
9056 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
9057 if (btf_type_is_struct(member_type)) {
9059 verbose(env, "max struct nesting depth exceeded\n");
9062 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
9066 if (btf_type_is_array(member_type)) {
9067 array = btf_array(member_type);
9070 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
9071 if (!btf_type_is_scalar(member_type))
9075 if (!btf_type_is_scalar(member_type))
9082 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
9084 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
9085 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9086 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
9090 enum kfunc_ptr_arg_type {
9092 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
9093 KF_ARG_PTR_TO_KPTR, /* PTR_TO_KPTR but type specific */
9094 KF_ARG_PTR_TO_DYNPTR,
9095 KF_ARG_PTR_TO_LIST_HEAD,
9096 KF_ARG_PTR_TO_LIST_NODE,
9097 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
9099 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
9100 KF_ARG_PTR_TO_CALLBACK,
9101 KF_ARG_PTR_TO_RB_ROOT,
9102 KF_ARG_PTR_TO_RB_NODE,
9105 enum special_kfunc_type {
9106 KF_bpf_obj_new_impl,
9107 KF_bpf_obj_drop_impl,
9108 KF_bpf_list_push_front,
9109 KF_bpf_list_push_back,
9110 KF_bpf_list_pop_front,
9111 KF_bpf_list_pop_back,
9112 KF_bpf_cast_to_kern_ctx,
9114 KF_bpf_rcu_read_lock,
9115 KF_bpf_rcu_read_unlock,
9116 KF_bpf_rbtree_remove,
9118 KF_bpf_rbtree_first,
9119 KF_bpf_dynptr_from_skb,
9120 KF_bpf_dynptr_from_xdp,
9121 KF_bpf_dynptr_slice,
9122 KF_bpf_dynptr_slice_rdwr,
9125 BTF_SET_START(special_kfunc_set)
9126 BTF_ID(func, bpf_obj_new_impl)
9127 BTF_ID(func, bpf_obj_drop_impl)
9128 BTF_ID(func, bpf_list_push_front)
9129 BTF_ID(func, bpf_list_push_back)
9130 BTF_ID(func, bpf_list_pop_front)
9131 BTF_ID(func, bpf_list_pop_back)
9132 BTF_ID(func, bpf_cast_to_kern_ctx)
9133 BTF_ID(func, bpf_rdonly_cast)
9134 BTF_ID(func, bpf_rbtree_remove)
9135 BTF_ID(func, bpf_rbtree_add)
9136 BTF_ID(func, bpf_rbtree_first)
9137 BTF_ID(func, bpf_dynptr_from_skb)
9138 BTF_ID(func, bpf_dynptr_from_xdp)
9139 BTF_ID(func, bpf_dynptr_slice)
9140 BTF_ID(func, bpf_dynptr_slice_rdwr)
9141 BTF_SET_END(special_kfunc_set)
9143 BTF_ID_LIST(special_kfunc_list)
9144 BTF_ID(func, bpf_obj_new_impl)
9145 BTF_ID(func, bpf_obj_drop_impl)
9146 BTF_ID(func, bpf_list_push_front)
9147 BTF_ID(func, bpf_list_push_back)
9148 BTF_ID(func, bpf_list_pop_front)
9149 BTF_ID(func, bpf_list_pop_back)
9150 BTF_ID(func, bpf_cast_to_kern_ctx)
9151 BTF_ID(func, bpf_rdonly_cast)
9152 BTF_ID(func, bpf_rcu_read_lock)
9153 BTF_ID(func, bpf_rcu_read_unlock)
9154 BTF_ID(func, bpf_rbtree_remove)
9155 BTF_ID(func, bpf_rbtree_add)
9156 BTF_ID(func, bpf_rbtree_first)
9157 BTF_ID(func, bpf_dynptr_from_skb)
9158 BTF_ID(func, bpf_dynptr_from_xdp)
9159 BTF_ID(func, bpf_dynptr_slice)
9160 BTF_ID(func, bpf_dynptr_slice_rdwr)
9162 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
9164 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
9167 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
9169 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
9172 static enum kfunc_ptr_arg_type
9173 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
9174 struct bpf_kfunc_call_arg_meta *meta,
9175 const struct btf_type *t, const struct btf_type *ref_t,
9176 const char *ref_tname, const struct btf_param *args,
9177 int argno, int nargs)
9179 u32 regno = argno + 1;
9180 struct bpf_reg_state *regs = cur_regs(env);
9181 struct bpf_reg_state *reg = ®s[regno];
9182 bool arg_mem_size = false;
9184 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
9185 return KF_ARG_PTR_TO_CTX;
9187 /* In this function, we verify the kfunc's BTF as per the argument type,
9188 * leaving the rest of the verification with respect to the register
9189 * type to our caller. When a set of conditions hold in the BTF type of
9190 * arguments, we resolve it to a known kfunc_ptr_arg_type.
9192 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
9193 return KF_ARG_PTR_TO_CTX;
9195 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
9196 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
9198 if (is_kfunc_arg_kptr_get(meta, argno)) {
9199 if (!btf_type_is_ptr(ref_t)) {
9200 verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
9203 ref_t = btf_type_by_id(meta->btf, ref_t->type);
9204 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
9205 if (!btf_type_is_struct(ref_t)) {
9206 verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
9207 meta->func_name, btf_type_str(ref_t), ref_tname);
9210 return KF_ARG_PTR_TO_KPTR;
9213 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
9214 return KF_ARG_PTR_TO_DYNPTR;
9216 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
9217 return KF_ARG_PTR_TO_LIST_HEAD;
9219 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
9220 return KF_ARG_PTR_TO_LIST_NODE;
9222 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
9223 return KF_ARG_PTR_TO_RB_ROOT;
9225 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
9226 return KF_ARG_PTR_TO_RB_NODE;
9228 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
9229 if (!btf_type_is_struct(ref_t)) {
9230 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
9231 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9234 return KF_ARG_PTR_TO_BTF_ID;
9237 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
9238 return KF_ARG_PTR_TO_CALLBACK;
9241 if (argno + 1 < nargs &&
9242 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
9243 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
9244 arg_mem_size = true;
9246 /* This is the catch all argument type of register types supported by
9247 * check_helper_mem_access. However, we only allow when argument type is
9248 * pointer to scalar, or struct composed (recursively) of scalars. When
9249 * arg_mem_size is true, the pointer can be void *.
9251 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
9252 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
9253 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
9254 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
9257 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
9260 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
9261 struct bpf_reg_state *reg,
9262 const struct btf_type *ref_t,
9263 const char *ref_tname, u32 ref_id,
9264 struct bpf_kfunc_call_arg_meta *meta,
9267 const struct btf_type *reg_ref_t;
9268 bool strict_type_match = false;
9269 const struct btf *reg_btf;
9270 const char *reg_ref_tname;
9273 if (base_type(reg->type) == PTR_TO_BTF_ID) {
9275 reg_ref_id = reg->btf_id;
9277 reg_btf = btf_vmlinux;
9278 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
9281 /* Enforce strict type matching for calls to kfuncs that are acquiring
9282 * or releasing a reference, or are no-cast aliases. We do _not_
9283 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
9284 * as we want to enable BPF programs to pass types that are bitwise
9285 * equivalent without forcing them to explicitly cast with something
9286 * like bpf_cast_to_kern_ctx().
9288 * For example, say we had a type like the following:
9290 * struct bpf_cpumask {
9291 * cpumask_t cpumask;
9295 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
9296 * to a struct cpumask, so it would be safe to pass a struct
9297 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
9299 * The philosophy here is similar to how we allow scalars of different
9300 * types to be passed to kfuncs as long as the size is the same. The
9301 * only difference here is that we're simply allowing
9302 * btf_struct_ids_match() to walk the struct at the 0th offset, and
9305 if (is_kfunc_acquire(meta) ||
9306 (is_kfunc_release(meta) && reg->ref_obj_id) ||
9307 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
9308 strict_type_match = true;
9310 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
9312 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
9313 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
9314 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
9315 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
9316 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
9317 btf_type_str(reg_ref_t), reg_ref_tname);
9323 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
9324 struct bpf_reg_state *reg,
9325 const struct btf_type *ref_t,
9326 const char *ref_tname,
9327 struct bpf_kfunc_call_arg_meta *meta,
9330 struct btf_field *kptr_field;
9332 /* check_func_arg_reg_off allows var_off for
9333 * PTR_TO_MAP_VALUE, but we need fixed offset to find
9336 if (!tnum_is_const(reg->var_off)) {
9337 verbose(env, "arg#0 must have constant offset\n");
9341 kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
9342 if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
9343 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
9344 reg->off + reg->var_off.value);
9348 if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
9349 kptr_field->kptr.btf_id, true)) {
9350 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
9351 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9357 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9359 struct bpf_verifier_state *state = env->cur_state;
9361 if (!state->active_lock.ptr) {
9362 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
9366 if (type_flag(reg->type) & NON_OWN_REF) {
9367 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
9371 reg->type |= NON_OWN_REF;
9375 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
9377 struct bpf_func_state *state, *unused;
9378 struct bpf_reg_state *reg;
9381 state = cur_func(env);
9384 verbose(env, "verifier internal error: ref_obj_id is zero for "
9385 "owning -> non-owning conversion\n");
9389 for (i = 0; i < state->acquired_refs; i++) {
9390 if (state->refs[i].id != ref_obj_id)
9393 /* Clear ref_obj_id here so release_reference doesn't clobber
9396 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9397 if (reg->ref_obj_id == ref_obj_id) {
9398 reg->ref_obj_id = 0;
9399 ref_set_non_owning(env, reg);
9405 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
9409 /* Implementation details:
9411 * Each register points to some region of memory, which we define as an
9412 * allocation. Each allocation may embed a bpf_spin_lock which protects any
9413 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
9414 * allocation. The lock and the data it protects are colocated in the same
9417 * Hence, everytime a register holds a pointer value pointing to such
9418 * allocation, the verifier preserves a unique reg->id for it.
9420 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
9421 * bpf_spin_lock is called.
9423 * To enable this, lock state in the verifier captures two values:
9424 * active_lock.ptr = Register's type specific pointer
9425 * active_lock.id = A unique ID for each register pointer value
9427 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
9428 * supported register types.
9430 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
9431 * allocated objects is the reg->btf pointer.
9433 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
9434 * can establish the provenance of the map value statically for each distinct
9435 * lookup into such maps. They always contain a single map value hence unique
9436 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
9438 * So, in case of global variables, they use array maps with max_entries = 1,
9439 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
9440 * into the same map value as max_entries is 1, as described above).
9442 * In case of inner map lookups, the inner map pointer has same map_ptr as the
9443 * outer map pointer (in verifier context), but each lookup into an inner map
9444 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
9445 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
9446 * will get different reg->id assigned to each lookup, hence different
9449 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
9450 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
9451 * returned from bpf_obj_new. Each allocation receives a new reg->id.
9453 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9458 switch ((int)reg->type) {
9459 case PTR_TO_MAP_VALUE:
9462 case PTR_TO_BTF_ID | MEM_ALLOC:
9466 verbose(env, "verifier internal error: unknown reg type for lock check\n");
9471 if (!env->cur_state->active_lock.ptr)
9473 if (env->cur_state->active_lock.ptr != ptr ||
9474 env->cur_state->active_lock.id != id) {
9475 verbose(env, "held lock and object are not in the same allocation\n");
9481 static bool is_bpf_list_api_kfunc(u32 btf_id)
9483 return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9484 btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
9485 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9486 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
9489 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
9491 return btf_id == special_kfunc_list[KF_bpf_rbtree_add] ||
9492 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9493 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
9496 static bool is_bpf_graph_api_kfunc(u32 btf_id)
9498 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id);
9501 static bool is_callback_calling_kfunc(u32 btf_id)
9503 return btf_id == special_kfunc_list[KF_bpf_rbtree_add];
9506 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
9508 return is_bpf_rbtree_api_kfunc(btf_id);
9511 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
9512 enum btf_field_type head_field_type,
9517 switch (head_field_type) {
9519 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
9522 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
9525 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
9526 btf_field_type_name(head_field_type));
9531 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
9532 btf_field_type_name(head_field_type));
9536 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
9537 enum btf_field_type node_field_type,
9542 switch (node_field_type) {
9544 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9545 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back]);
9548 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9549 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add]);
9552 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
9553 btf_field_type_name(node_field_type));
9558 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
9559 btf_field_type_name(node_field_type));
9564 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
9565 struct bpf_reg_state *reg, u32 regno,
9566 struct bpf_kfunc_call_arg_meta *meta,
9567 enum btf_field_type head_field_type,
9568 struct btf_field **head_field)
9570 const char *head_type_name;
9571 struct btf_field *field;
9572 struct btf_record *rec;
9575 if (meta->btf != btf_vmlinux) {
9576 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
9580 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
9583 head_type_name = btf_field_type_name(head_field_type);
9584 if (!tnum_is_const(reg->var_off)) {
9586 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
9587 regno, head_type_name);
9591 rec = reg_btf_record(reg);
9592 head_off = reg->off + reg->var_off.value;
9593 field = btf_record_find(rec, head_off, head_field_type);
9595 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
9599 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
9600 if (check_reg_allocation_locked(env, reg)) {
9601 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
9602 rec->spin_lock_off, head_type_name);
9607 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
9610 *head_field = field;
9614 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
9615 struct bpf_reg_state *reg, u32 regno,
9616 struct bpf_kfunc_call_arg_meta *meta)
9618 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
9619 &meta->arg_list_head.field);
9622 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
9623 struct bpf_reg_state *reg, u32 regno,
9624 struct bpf_kfunc_call_arg_meta *meta)
9626 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
9627 &meta->arg_rbtree_root.field);
9631 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
9632 struct bpf_reg_state *reg, u32 regno,
9633 struct bpf_kfunc_call_arg_meta *meta,
9634 enum btf_field_type head_field_type,
9635 enum btf_field_type node_field_type,
9636 struct btf_field **node_field)
9638 const char *node_type_name;
9639 const struct btf_type *et, *t;
9640 struct btf_field *field;
9643 if (meta->btf != btf_vmlinux) {
9644 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
9648 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
9651 node_type_name = btf_field_type_name(node_field_type);
9652 if (!tnum_is_const(reg->var_off)) {
9654 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
9655 regno, node_type_name);
9659 node_off = reg->off + reg->var_off.value;
9660 field = reg_find_field_offset(reg, node_off, node_field_type);
9661 if (!field || field->offset != node_off) {
9662 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
9666 field = *node_field;
9668 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
9669 t = btf_type_by_id(reg->btf, reg->btf_id);
9670 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
9671 field->graph_root.value_btf_id, true)) {
9672 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
9673 "in struct %s, but arg is at offset=%d in struct %s\n",
9674 btf_field_type_name(head_field_type),
9675 btf_field_type_name(node_field_type),
9676 field->graph_root.node_offset,
9677 btf_name_by_offset(field->graph_root.btf, et->name_off),
9678 node_off, btf_name_by_offset(reg->btf, t->name_off));
9682 if (node_off != field->graph_root.node_offset) {
9683 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
9684 node_off, btf_field_type_name(node_field_type),
9685 field->graph_root.node_offset,
9686 btf_name_by_offset(field->graph_root.btf, et->name_off));
9693 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
9694 struct bpf_reg_state *reg, u32 regno,
9695 struct bpf_kfunc_call_arg_meta *meta)
9697 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
9698 BPF_LIST_HEAD, BPF_LIST_NODE,
9699 &meta->arg_list_head.field);
9702 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
9703 struct bpf_reg_state *reg, u32 regno,
9704 struct bpf_kfunc_call_arg_meta *meta)
9706 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
9707 BPF_RB_ROOT, BPF_RB_NODE,
9708 &meta->arg_rbtree_root.field);
9711 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
9714 const char *func_name = meta->func_name, *ref_tname;
9715 const struct btf *btf = meta->btf;
9716 const struct btf_param *args;
9720 args = (const struct btf_param *)(meta->func_proto + 1);
9721 nargs = btf_type_vlen(meta->func_proto);
9722 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
9723 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
9724 MAX_BPF_FUNC_REG_ARGS);
9728 /* Check that BTF function arguments match actual types that the
9731 for (i = 0; i < nargs; i++) {
9732 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
9733 const struct btf_type *t, *ref_t, *resolve_ret;
9734 enum bpf_arg_type arg_type = ARG_DONTCARE;
9735 u32 regno = i + 1, ref_id, type_size;
9736 bool is_ret_buf_sz = false;
9739 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
9741 if (is_kfunc_arg_ignore(btf, &args[i]))
9744 if (btf_type_is_scalar(t)) {
9745 if (reg->type != SCALAR_VALUE) {
9746 verbose(env, "R%d is not a scalar\n", regno);
9750 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
9751 if (meta->arg_constant.found) {
9752 verbose(env, "verifier internal error: only one constant argument permitted\n");
9755 if (!tnum_is_const(reg->var_off)) {
9756 verbose(env, "R%d must be a known constant\n", regno);
9759 ret = mark_chain_precision(env, regno);
9762 meta->arg_constant.found = true;
9763 meta->arg_constant.value = reg->var_off.value;
9764 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
9765 meta->r0_rdonly = true;
9766 is_ret_buf_sz = true;
9767 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
9768 is_ret_buf_sz = true;
9771 if (is_ret_buf_sz) {
9772 if (meta->r0_size) {
9773 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
9777 if (!tnum_is_const(reg->var_off)) {
9778 verbose(env, "R%d is not a const\n", regno);
9782 meta->r0_size = reg->var_off.value;
9783 ret = mark_chain_precision(env, regno);
9790 if (!btf_type_is_ptr(t)) {
9791 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
9795 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
9796 (register_is_null(reg) || type_may_be_null(reg->type))) {
9797 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
9801 if (reg->ref_obj_id) {
9802 if (is_kfunc_release(meta) && meta->ref_obj_id) {
9803 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
9804 regno, reg->ref_obj_id,
9808 meta->ref_obj_id = reg->ref_obj_id;
9809 if (is_kfunc_release(meta))
9810 meta->release_regno = regno;
9813 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
9814 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
9816 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
9817 if (kf_arg_type < 0)
9820 switch (kf_arg_type) {
9821 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9822 case KF_ARG_PTR_TO_BTF_ID:
9823 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
9826 if (!is_trusted_reg(reg)) {
9827 if (!is_kfunc_rcu(meta)) {
9828 verbose(env, "R%d must be referenced or trusted\n", regno);
9831 if (!is_rcu_reg(reg)) {
9832 verbose(env, "R%d must be a rcu pointer\n", regno);
9838 case KF_ARG_PTR_TO_CTX:
9839 /* Trusted arguments have the same offset checks as release arguments */
9840 arg_type |= OBJ_RELEASE;
9842 case KF_ARG_PTR_TO_KPTR:
9843 case KF_ARG_PTR_TO_DYNPTR:
9844 case KF_ARG_PTR_TO_LIST_HEAD:
9845 case KF_ARG_PTR_TO_LIST_NODE:
9846 case KF_ARG_PTR_TO_RB_ROOT:
9847 case KF_ARG_PTR_TO_RB_NODE:
9848 case KF_ARG_PTR_TO_MEM:
9849 case KF_ARG_PTR_TO_MEM_SIZE:
9850 case KF_ARG_PTR_TO_CALLBACK:
9851 /* Trusted by default */
9858 if (is_kfunc_release(meta) && reg->ref_obj_id)
9859 arg_type |= OBJ_RELEASE;
9860 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
9864 switch (kf_arg_type) {
9865 case KF_ARG_PTR_TO_CTX:
9866 if (reg->type != PTR_TO_CTX) {
9867 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
9871 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9872 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
9875 meta->ret_btf_id = ret;
9878 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9879 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9880 verbose(env, "arg#%d expected pointer to allocated object\n", i);
9883 if (!reg->ref_obj_id) {
9884 verbose(env, "allocated object must be referenced\n");
9887 if (meta->btf == btf_vmlinux &&
9888 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9889 meta->arg_obj_drop.btf = reg->btf;
9890 meta->arg_obj_drop.btf_id = reg->btf_id;
9893 case KF_ARG_PTR_TO_KPTR:
9894 if (reg->type != PTR_TO_MAP_VALUE) {
9895 verbose(env, "arg#0 expected pointer to map value\n");
9898 ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
9902 case KF_ARG_PTR_TO_DYNPTR:
9904 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
9906 if (reg->type != PTR_TO_STACK &&
9907 reg->type != CONST_PTR_TO_DYNPTR) {
9908 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
9912 if (reg->type == CONST_PTR_TO_DYNPTR)
9913 dynptr_arg_type |= MEM_RDONLY;
9915 if (is_kfunc_arg_uninit(btf, &args[i]))
9916 dynptr_arg_type |= MEM_UNINIT;
9918 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb])
9919 dynptr_arg_type |= DYNPTR_TYPE_SKB;
9920 else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp])
9921 dynptr_arg_type |= DYNPTR_TYPE_XDP;
9923 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type);
9927 if (!(dynptr_arg_type & MEM_UNINIT)) {
9928 int id = dynptr_id(env, reg);
9931 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9934 meta->initialized_dynptr.id = id;
9935 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
9940 case KF_ARG_PTR_TO_LIST_HEAD:
9941 if (reg->type != PTR_TO_MAP_VALUE &&
9942 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9943 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9946 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9947 verbose(env, "allocated object must be referenced\n");
9950 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
9954 case KF_ARG_PTR_TO_RB_ROOT:
9955 if (reg->type != PTR_TO_MAP_VALUE &&
9956 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9957 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9960 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9961 verbose(env, "allocated object must be referenced\n");
9964 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
9968 case KF_ARG_PTR_TO_LIST_NODE:
9969 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9970 verbose(env, "arg#%d expected pointer to allocated object\n", i);
9973 if (!reg->ref_obj_id) {
9974 verbose(env, "allocated object must be referenced\n");
9977 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
9981 case KF_ARG_PTR_TO_RB_NODE:
9982 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
9983 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
9984 verbose(env, "rbtree_remove node input must be non-owning ref\n");
9987 if (in_rbtree_lock_required_cb(env)) {
9988 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
9992 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9993 verbose(env, "arg#%d expected pointer to allocated object\n", i);
9996 if (!reg->ref_obj_id) {
9997 verbose(env, "allocated object must be referenced\n");
10002 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10006 case KF_ARG_PTR_TO_BTF_ID:
10007 /* Only base_type is checked, further checks are done here */
10008 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10009 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10010 !reg2btf_ids[base_type(reg->type)]) {
10011 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10012 verbose(env, "expected %s or socket\n",
10013 reg_type_str(env, base_type(reg->type) |
10014 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10017 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10021 case KF_ARG_PTR_TO_MEM:
10022 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10023 if (IS_ERR(resolve_ret)) {
10024 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10025 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10028 ret = check_mem_reg(env, reg, regno, type_size);
10032 case KF_ARG_PTR_TO_MEM_SIZE:
10034 struct bpf_reg_state *size_reg = ®s[regno + 1];
10035 const struct btf_param *size_arg = &args[i + 1];
10037 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
10039 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
10043 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
10044 if (meta->arg_constant.found) {
10045 verbose(env, "verifier internal error: only one constant argument permitted\n");
10048 if (!tnum_is_const(size_reg->var_off)) {
10049 verbose(env, "R%d must be a known constant\n", regno + 1);
10052 meta->arg_constant.found = true;
10053 meta->arg_constant.value = size_reg->var_off.value;
10056 /* Skip next '__sz' or '__szk' argument */
10060 case KF_ARG_PTR_TO_CALLBACK:
10061 meta->subprogno = reg->subprogno;
10066 if (is_kfunc_release(meta) && !meta->release_regno) {
10067 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
10075 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10078 const struct btf_type *t, *func, *func_proto, *ptr_type;
10079 u32 i, nargs, func_id, ptr_type_id, release_ref_obj_id;
10080 struct bpf_reg_state *regs = cur_regs(env);
10081 const char *func_name, *ptr_type_name;
10082 bool sleepable, rcu_lock, rcu_unlock;
10083 struct bpf_kfunc_call_arg_meta meta;
10084 int err, insn_idx = *insn_idx_p;
10085 const struct btf_param *args;
10086 const struct btf_type *ret_t;
10087 struct btf *desc_btf;
10090 /* skip for now, but return error when we find this in fixup_kfunc_call */
10094 desc_btf = find_kfunc_desc_btf(env, insn->off);
10095 if (IS_ERR(desc_btf))
10096 return PTR_ERR(desc_btf);
10098 func_id = insn->imm;
10099 func = btf_type_by_id(desc_btf, func_id);
10100 func_name = btf_name_by_offset(desc_btf, func->name_off);
10101 func_proto = btf_type_by_id(desc_btf, func->type);
10103 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
10104 if (!kfunc_flags) {
10105 verbose(env, "calling kernel function %s is not allowed\n",
10110 /* Prepare kfunc call metadata */
10111 memset(&meta, 0, sizeof(meta));
10112 meta.btf = desc_btf;
10113 meta.func_id = func_id;
10114 meta.kfunc_flags = *kfunc_flags;
10115 meta.func_proto = func_proto;
10116 meta.func_name = func_name;
10118 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
10119 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
10123 sleepable = is_kfunc_sleepable(&meta);
10124 if (sleepable && !env->prog->aux->sleepable) {
10125 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
10129 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
10130 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
10132 if (env->cur_state->active_rcu_lock) {
10133 struct bpf_func_state *state;
10134 struct bpf_reg_state *reg;
10137 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
10139 } else if (rcu_unlock) {
10140 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10141 if (reg->type & MEM_RCU) {
10142 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
10143 reg->type |= PTR_UNTRUSTED;
10146 env->cur_state->active_rcu_lock = false;
10147 } else if (sleepable) {
10148 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
10151 } else if (rcu_lock) {
10152 env->cur_state->active_rcu_lock = true;
10153 } else if (rcu_unlock) {
10154 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
10158 /* Check the arguments */
10159 err = check_kfunc_args(env, &meta, insn_idx);
10162 /* In case of release function, we get register number of refcounted
10163 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
10165 if (meta.release_regno) {
10166 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
10168 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10169 func_name, func_id);
10174 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front] ||
10175 meta.func_id == special_kfunc_list[KF_bpf_list_push_back] ||
10176 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
10177 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
10178 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
10180 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
10181 func_name, func_id);
10185 err = release_reference(env, release_ref_obj_id);
10187 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10188 func_name, func_id);
10193 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
10194 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10195 set_rbtree_add_callback_state);
10197 verbose(env, "kfunc %s#%d failed callback verification\n",
10198 func_name, func_id);
10203 for (i = 0; i < CALLER_SAVED_REGS; i++)
10204 mark_reg_not_init(env, regs, caller_saved[i]);
10206 /* Check return type */
10207 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
10209 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
10210 /* Only exception is bpf_obj_new_impl */
10211 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
10212 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
10217 if (btf_type_is_scalar(t)) {
10218 mark_reg_unknown(env, regs, BPF_REG_0);
10219 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
10220 } else if (btf_type_is_ptr(t)) {
10221 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
10223 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
10224 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
10225 struct btf *ret_btf;
10228 if (unlikely(!bpf_global_ma_set))
10231 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
10232 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
10236 ret_btf = env->prog->aux->btf;
10237 ret_btf_id = meta.arg_constant.value;
10239 /* This may be NULL due to user not supplying a BTF */
10241 verbose(env, "bpf_obj_new requires prog BTF\n");
10245 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
10246 if (!ret_t || !__btf_type_is_struct(ret_t)) {
10247 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
10251 mark_reg_known_zero(env, regs, BPF_REG_0);
10252 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
10253 regs[BPF_REG_0].btf = ret_btf;
10254 regs[BPF_REG_0].btf_id = ret_btf_id;
10256 env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
10257 env->insn_aux_data[insn_idx].kptr_struct_meta =
10258 btf_find_struct_meta(ret_btf, ret_btf_id);
10259 } else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10260 env->insn_aux_data[insn_idx].kptr_struct_meta =
10261 btf_find_struct_meta(meta.arg_obj_drop.btf,
10262 meta.arg_obj_drop.btf_id);
10263 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10264 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
10265 struct btf_field *field = meta.arg_list_head.field;
10267 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10268 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10269 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10270 struct btf_field *field = meta.arg_rbtree_root.field;
10272 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10273 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10274 mark_reg_known_zero(env, regs, BPF_REG_0);
10275 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
10276 regs[BPF_REG_0].btf = desc_btf;
10277 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10278 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
10279 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
10280 if (!ret_t || !btf_type_is_struct(ret_t)) {
10282 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
10286 mark_reg_known_zero(env, regs, BPF_REG_0);
10287 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
10288 regs[BPF_REG_0].btf = desc_btf;
10289 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
10290 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
10291 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
10292 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
10294 mark_reg_known_zero(env, regs, BPF_REG_0);
10296 if (!meta.arg_constant.found) {
10297 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
10301 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
10303 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
10304 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
10306 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
10307 regs[BPF_REG_0].type |= MEM_RDONLY;
10309 /* this will set env->seen_direct_write to true */
10310 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
10311 verbose(env, "the prog does not allow writes to packet data\n");
10316 if (!meta.initialized_dynptr.id) {
10317 verbose(env, "verifier internal error: no dynptr id\n");
10320 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
10322 /* we don't need to set BPF_REG_0's ref obj id
10323 * because packet slices are not refcounted (see
10324 * dynptr_type_refcounted)
10327 verbose(env, "kernel function %s unhandled dynamic return type\n",
10331 } else if (!__btf_type_is_struct(ptr_type)) {
10332 if (!meta.r0_size) {
10333 ptr_type_name = btf_name_by_offset(desc_btf,
10334 ptr_type->name_off);
10336 "kernel function %s returns pointer type %s %s is not supported\n",
10338 btf_type_str(ptr_type),
10343 mark_reg_known_zero(env, regs, BPF_REG_0);
10344 regs[BPF_REG_0].type = PTR_TO_MEM;
10345 regs[BPF_REG_0].mem_size = meta.r0_size;
10347 if (meta.r0_rdonly)
10348 regs[BPF_REG_0].type |= MEM_RDONLY;
10350 /* Ensures we don't access the memory after a release_reference() */
10351 if (meta.ref_obj_id)
10352 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10354 mark_reg_known_zero(env, regs, BPF_REG_0);
10355 regs[BPF_REG_0].btf = desc_btf;
10356 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
10357 regs[BPF_REG_0].btf_id = ptr_type_id;
10360 if (is_kfunc_ret_null(&meta)) {
10361 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
10362 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
10363 regs[BPF_REG_0].id = ++env->id_gen;
10365 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
10366 if (is_kfunc_acquire(&meta)) {
10367 int id = acquire_reference_state(env, insn_idx);
10371 if (is_kfunc_ret_null(&meta))
10372 regs[BPF_REG_0].id = id;
10373 regs[BPF_REG_0].ref_obj_id = id;
10374 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10375 ref_set_non_owning(env, ®s[BPF_REG_0]);
10378 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove])
10379 invalidate_non_owning_refs(env);
10381 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
10382 regs[BPF_REG_0].id = ++env->id_gen;
10383 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
10385 nargs = btf_type_vlen(func_proto);
10386 args = (const struct btf_param *)(func_proto + 1);
10387 for (i = 0; i < nargs; i++) {
10390 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
10391 if (btf_type_is_ptr(t))
10392 mark_btf_func_reg_size(env, regno, sizeof(void *));
10394 /* scalar. ensured by btf_check_kfunc_arg_match() */
10395 mark_btf_func_reg_size(env, regno, t->size);
10401 static bool signed_add_overflows(s64 a, s64 b)
10403 /* Do the add in u64, where overflow is well-defined */
10404 s64 res = (s64)((u64)a + (u64)b);
10411 static bool signed_add32_overflows(s32 a, s32 b)
10413 /* Do the add in u32, where overflow is well-defined */
10414 s32 res = (s32)((u32)a + (u32)b);
10421 static bool signed_sub_overflows(s64 a, s64 b)
10423 /* Do the sub in u64, where overflow is well-defined */
10424 s64 res = (s64)((u64)a - (u64)b);
10431 static bool signed_sub32_overflows(s32 a, s32 b)
10433 /* Do the sub in u32, where overflow is well-defined */
10434 s32 res = (s32)((u32)a - (u32)b);
10441 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
10442 const struct bpf_reg_state *reg,
10443 enum bpf_reg_type type)
10445 bool known = tnum_is_const(reg->var_off);
10446 s64 val = reg->var_off.value;
10447 s64 smin = reg->smin_value;
10449 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
10450 verbose(env, "math between %s pointer and %lld is not allowed\n",
10451 reg_type_str(env, type), val);
10455 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
10456 verbose(env, "%s pointer offset %d is not allowed\n",
10457 reg_type_str(env, type), reg->off);
10461 if (smin == S64_MIN) {
10462 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
10463 reg_type_str(env, type));
10467 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
10468 verbose(env, "value %lld makes %s pointer be out of bounds\n",
10469 smin, reg_type_str(env, type));
10477 REASON_BOUNDS = -1,
10484 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
10485 u32 *alu_limit, bool mask_to_left)
10487 u32 max = 0, ptr_limit = 0;
10489 switch (ptr_reg->type) {
10491 /* Offset 0 is out-of-bounds, but acceptable start for the
10492 * left direction, see BPF_REG_FP. Also, unknown scalar
10493 * offset where we would need to deal with min/max bounds is
10494 * currently prohibited for unprivileged.
10496 max = MAX_BPF_STACK + mask_to_left;
10497 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
10499 case PTR_TO_MAP_VALUE:
10500 max = ptr_reg->map_ptr->value_size;
10501 ptr_limit = (mask_to_left ?
10502 ptr_reg->smin_value :
10503 ptr_reg->umax_value) + ptr_reg->off;
10506 return REASON_TYPE;
10509 if (ptr_limit >= max)
10510 return REASON_LIMIT;
10511 *alu_limit = ptr_limit;
10515 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
10516 const struct bpf_insn *insn)
10518 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
10521 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
10522 u32 alu_state, u32 alu_limit)
10524 /* If we arrived here from different branches with different
10525 * state or limits to sanitize, then this won't work.
10527 if (aux->alu_state &&
10528 (aux->alu_state != alu_state ||
10529 aux->alu_limit != alu_limit))
10530 return REASON_PATHS;
10532 /* Corresponding fixup done in do_misc_fixups(). */
10533 aux->alu_state = alu_state;
10534 aux->alu_limit = alu_limit;
10538 static int sanitize_val_alu(struct bpf_verifier_env *env,
10539 struct bpf_insn *insn)
10541 struct bpf_insn_aux_data *aux = cur_aux(env);
10543 if (can_skip_alu_sanitation(env, insn))
10546 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
10549 static bool sanitize_needed(u8 opcode)
10551 return opcode == BPF_ADD || opcode == BPF_SUB;
10554 struct bpf_sanitize_info {
10555 struct bpf_insn_aux_data aux;
10559 static struct bpf_verifier_state *
10560 sanitize_speculative_path(struct bpf_verifier_env *env,
10561 const struct bpf_insn *insn,
10562 u32 next_idx, u32 curr_idx)
10564 struct bpf_verifier_state *branch;
10565 struct bpf_reg_state *regs;
10567 branch = push_stack(env, next_idx, curr_idx, true);
10568 if (branch && insn) {
10569 regs = branch->frame[branch->curframe]->regs;
10570 if (BPF_SRC(insn->code) == BPF_K) {
10571 mark_reg_unknown(env, regs, insn->dst_reg);
10572 } else if (BPF_SRC(insn->code) == BPF_X) {
10573 mark_reg_unknown(env, regs, insn->dst_reg);
10574 mark_reg_unknown(env, regs, insn->src_reg);
10580 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
10581 struct bpf_insn *insn,
10582 const struct bpf_reg_state *ptr_reg,
10583 const struct bpf_reg_state *off_reg,
10584 struct bpf_reg_state *dst_reg,
10585 struct bpf_sanitize_info *info,
10586 const bool commit_window)
10588 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
10589 struct bpf_verifier_state *vstate = env->cur_state;
10590 bool off_is_imm = tnum_is_const(off_reg->var_off);
10591 bool off_is_neg = off_reg->smin_value < 0;
10592 bool ptr_is_dst_reg = ptr_reg == dst_reg;
10593 u8 opcode = BPF_OP(insn->code);
10594 u32 alu_state, alu_limit;
10595 struct bpf_reg_state tmp;
10599 if (can_skip_alu_sanitation(env, insn))
10602 /* We already marked aux for masking from non-speculative
10603 * paths, thus we got here in the first place. We only care
10604 * to explore bad access from here.
10606 if (vstate->speculative)
10609 if (!commit_window) {
10610 if (!tnum_is_const(off_reg->var_off) &&
10611 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
10612 return REASON_BOUNDS;
10614 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
10615 (opcode == BPF_SUB && !off_is_neg);
10618 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
10622 if (commit_window) {
10623 /* In commit phase we narrow the masking window based on
10624 * the observed pointer move after the simulated operation.
10626 alu_state = info->aux.alu_state;
10627 alu_limit = abs(info->aux.alu_limit - alu_limit);
10629 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
10630 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
10631 alu_state |= ptr_is_dst_reg ?
10632 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
10634 /* Limit pruning on unknown scalars to enable deep search for
10635 * potential masking differences from other program paths.
10638 env->explore_alu_limits = true;
10641 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
10645 /* If we're in commit phase, we're done here given we already
10646 * pushed the truncated dst_reg into the speculative verification
10649 * Also, when register is a known constant, we rewrite register-based
10650 * operation to immediate-based, and thus do not need masking (and as
10651 * a consequence, do not need to simulate the zero-truncation either).
10653 if (commit_window || off_is_imm)
10656 /* Simulate and find potential out-of-bounds access under
10657 * speculative execution from truncation as a result of
10658 * masking when off was not within expected range. If off
10659 * sits in dst, then we temporarily need to move ptr there
10660 * to simulate dst (== 0) +/-= ptr. Needed, for example,
10661 * for cases where we use K-based arithmetic in one direction
10662 * and truncated reg-based in the other in order to explore
10665 if (!ptr_is_dst_reg) {
10667 copy_register_state(dst_reg, ptr_reg);
10669 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
10671 if (!ptr_is_dst_reg && ret)
10673 return !ret ? REASON_STACK : 0;
10676 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
10678 struct bpf_verifier_state *vstate = env->cur_state;
10680 /* If we simulate paths under speculation, we don't update the
10681 * insn as 'seen' such that when we verify unreachable paths in
10682 * the non-speculative domain, sanitize_dead_code() can still
10683 * rewrite/sanitize them.
10685 if (!vstate->speculative)
10686 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10689 static int sanitize_err(struct bpf_verifier_env *env,
10690 const struct bpf_insn *insn, int reason,
10691 const struct bpf_reg_state *off_reg,
10692 const struct bpf_reg_state *dst_reg)
10694 static const char *err = "pointer arithmetic with it prohibited for !root";
10695 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
10696 u32 dst = insn->dst_reg, src = insn->src_reg;
10699 case REASON_BOUNDS:
10700 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
10701 off_reg == dst_reg ? dst : src, err);
10704 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
10705 off_reg == dst_reg ? src : dst, err);
10708 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
10712 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
10716 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
10720 verbose(env, "verifier internal error: unknown reason (%d)\n",
10728 /* check that stack access falls within stack limits and that 'reg' doesn't
10729 * have a variable offset.
10731 * Variable offset is prohibited for unprivileged mode for simplicity since it
10732 * requires corresponding support in Spectre masking for stack ALU. See also
10733 * retrieve_ptr_limit().
10736 * 'off' includes 'reg->off'.
10738 static int check_stack_access_for_ptr_arithmetic(
10739 struct bpf_verifier_env *env,
10741 const struct bpf_reg_state *reg,
10744 if (!tnum_is_const(reg->var_off)) {
10747 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
10748 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
10749 regno, tn_buf, off);
10753 if (off >= 0 || off < -MAX_BPF_STACK) {
10754 verbose(env, "R%d stack pointer arithmetic goes out of range, "
10755 "prohibited for !root; off=%d\n", regno, off);
10762 static int sanitize_check_bounds(struct bpf_verifier_env *env,
10763 const struct bpf_insn *insn,
10764 const struct bpf_reg_state *dst_reg)
10766 u32 dst = insn->dst_reg;
10768 /* For unprivileged we require that resulting offset must be in bounds
10769 * in order to be able to sanitize access later on.
10771 if (env->bypass_spec_v1)
10774 switch (dst_reg->type) {
10776 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
10777 dst_reg->off + dst_reg->var_off.value))
10780 case PTR_TO_MAP_VALUE:
10781 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
10782 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
10783 "prohibited for !root\n", dst);
10794 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
10795 * Caller should also handle BPF_MOV case separately.
10796 * If we return -EACCES, caller may want to try again treating pointer as a
10797 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
10799 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
10800 struct bpf_insn *insn,
10801 const struct bpf_reg_state *ptr_reg,
10802 const struct bpf_reg_state *off_reg)
10804 struct bpf_verifier_state *vstate = env->cur_state;
10805 struct bpf_func_state *state = vstate->frame[vstate->curframe];
10806 struct bpf_reg_state *regs = state->regs, *dst_reg;
10807 bool known = tnum_is_const(off_reg->var_off);
10808 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
10809 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
10810 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
10811 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
10812 struct bpf_sanitize_info info = {};
10813 u8 opcode = BPF_OP(insn->code);
10814 u32 dst = insn->dst_reg;
10817 dst_reg = ®s[dst];
10819 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
10820 smin_val > smax_val || umin_val > umax_val) {
10821 /* Taint dst register if offset had invalid bounds derived from
10822 * e.g. dead branches.
10824 __mark_reg_unknown(env, dst_reg);
10828 if (BPF_CLASS(insn->code) != BPF_ALU64) {
10829 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
10830 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10831 __mark_reg_unknown(env, dst_reg);
10836 "R%d 32-bit pointer arithmetic prohibited\n",
10841 if (ptr_reg->type & PTR_MAYBE_NULL) {
10842 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
10843 dst, reg_type_str(env, ptr_reg->type));
10847 switch (base_type(ptr_reg->type)) {
10848 case CONST_PTR_TO_MAP:
10849 /* smin_val represents the known value */
10850 if (known && smin_val == 0 && opcode == BPF_ADD)
10853 case PTR_TO_PACKET_END:
10854 case PTR_TO_SOCKET:
10855 case PTR_TO_SOCK_COMMON:
10856 case PTR_TO_TCP_SOCK:
10857 case PTR_TO_XDP_SOCK:
10858 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
10859 dst, reg_type_str(env, ptr_reg->type));
10865 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
10866 * The id may be overwritten later if we create a new variable offset.
10868 dst_reg->type = ptr_reg->type;
10869 dst_reg->id = ptr_reg->id;
10871 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
10872 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
10875 /* pointer types do not carry 32-bit bounds at the moment. */
10876 __mark_reg32_unbounded(dst_reg);
10878 if (sanitize_needed(opcode)) {
10879 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
10882 return sanitize_err(env, insn, ret, off_reg, dst_reg);
10887 /* We can take a fixed offset as long as it doesn't overflow
10888 * the s32 'off' field
10890 if (known && (ptr_reg->off + smin_val ==
10891 (s64)(s32)(ptr_reg->off + smin_val))) {
10892 /* pointer += K. Accumulate it into fixed offset */
10893 dst_reg->smin_value = smin_ptr;
10894 dst_reg->smax_value = smax_ptr;
10895 dst_reg->umin_value = umin_ptr;
10896 dst_reg->umax_value = umax_ptr;
10897 dst_reg->var_off = ptr_reg->var_off;
10898 dst_reg->off = ptr_reg->off + smin_val;
10899 dst_reg->raw = ptr_reg->raw;
10902 /* A new variable offset is created. Note that off_reg->off
10903 * == 0, since it's a scalar.
10904 * dst_reg gets the pointer type and since some positive
10905 * integer value was added to the pointer, give it a new 'id'
10906 * if it's a PTR_TO_PACKET.
10907 * this creates a new 'base' pointer, off_reg (variable) gets
10908 * added into the variable offset, and we copy the fixed offset
10911 if (signed_add_overflows(smin_ptr, smin_val) ||
10912 signed_add_overflows(smax_ptr, smax_val)) {
10913 dst_reg->smin_value = S64_MIN;
10914 dst_reg->smax_value = S64_MAX;
10916 dst_reg->smin_value = smin_ptr + smin_val;
10917 dst_reg->smax_value = smax_ptr + smax_val;
10919 if (umin_ptr + umin_val < umin_ptr ||
10920 umax_ptr + umax_val < umax_ptr) {
10921 dst_reg->umin_value = 0;
10922 dst_reg->umax_value = U64_MAX;
10924 dst_reg->umin_value = umin_ptr + umin_val;
10925 dst_reg->umax_value = umax_ptr + umax_val;
10927 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
10928 dst_reg->off = ptr_reg->off;
10929 dst_reg->raw = ptr_reg->raw;
10930 if (reg_is_pkt_pointer(ptr_reg)) {
10931 dst_reg->id = ++env->id_gen;
10932 /* something was added to pkt_ptr, set range to zero */
10933 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
10937 if (dst_reg == off_reg) {
10938 /* scalar -= pointer. Creates an unknown scalar */
10939 verbose(env, "R%d tried to subtract pointer from scalar\n",
10943 /* We don't allow subtraction from FP, because (according to
10944 * test_verifier.c test "invalid fp arithmetic", JITs might not
10945 * be able to deal with it.
10947 if (ptr_reg->type == PTR_TO_STACK) {
10948 verbose(env, "R%d subtraction from stack pointer prohibited\n",
10952 if (known && (ptr_reg->off - smin_val ==
10953 (s64)(s32)(ptr_reg->off - smin_val))) {
10954 /* pointer -= K. Subtract it from fixed offset */
10955 dst_reg->smin_value = smin_ptr;
10956 dst_reg->smax_value = smax_ptr;
10957 dst_reg->umin_value = umin_ptr;
10958 dst_reg->umax_value = umax_ptr;
10959 dst_reg->var_off = ptr_reg->var_off;
10960 dst_reg->id = ptr_reg->id;
10961 dst_reg->off = ptr_reg->off - smin_val;
10962 dst_reg->raw = ptr_reg->raw;
10965 /* A new variable offset is created. If the subtrahend is known
10966 * nonnegative, then any reg->range we had before is still good.
10968 if (signed_sub_overflows(smin_ptr, smax_val) ||
10969 signed_sub_overflows(smax_ptr, smin_val)) {
10970 /* Overflow possible, we know nothing */
10971 dst_reg->smin_value = S64_MIN;
10972 dst_reg->smax_value = S64_MAX;
10974 dst_reg->smin_value = smin_ptr - smax_val;
10975 dst_reg->smax_value = smax_ptr - smin_val;
10977 if (umin_ptr < umax_val) {
10978 /* Overflow possible, we know nothing */
10979 dst_reg->umin_value = 0;
10980 dst_reg->umax_value = U64_MAX;
10982 /* Cannot overflow (as long as bounds are consistent) */
10983 dst_reg->umin_value = umin_ptr - umax_val;
10984 dst_reg->umax_value = umax_ptr - umin_val;
10986 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
10987 dst_reg->off = ptr_reg->off;
10988 dst_reg->raw = ptr_reg->raw;
10989 if (reg_is_pkt_pointer(ptr_reg)) {
10990 dst_reg->id = ++env->id_gen;
10991 /* something was added to pkt_ptr, set range to zero */
10993 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
10999 /* bitwise ops on pointers are troublesome, prohibit. */
11000 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
11001 dst, bpf_alu_string[opcode >> 4]);
11004 /* other operators (e.g. MUL,LSH) produce non-pointer results */
11005 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
11006 dst, bpf_alu_string[opcode >> 4]);
11010 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
11012 reg_bounds_sync(dst_reg);
11013 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
11015 if (sanitize_needed(opcode)) {
11016 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
11019 return sanitize_err(env, insn, ret, off_reg, dst_reg);
11025 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
11026 struct bpf_reg_state *src_reg)
11028 s32 smin_val = src_reg->s32_min_value;
11029 s32 smax_val = src_reg->s32_max_value;
11030 u32 umin_val = src_reg->u32_min_value;
11031 u32 umax_val = src_reg->u32_max_value;
11033 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
11034 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
11035 dst_reg->s32_min_value = S32_MIN;
11036 dst_reg->s32_max_value = S32_MAX;
11038 dst_reg->s32_min_value += smin_val;
11039 dst_reg->s32_max_value += smax_val;
11041 if (dst_reg->u32_min_value + umin_val < umin_val ||
11042 dst_reg->u32_max_value + umax_val < umax_val) {
11043 dst_reg->u32_min_value = 0;
11044 dst_reg->u32_max_value = U32_MAX;
11046 dst_reg->u32_min_value += umin_val;
11047 dst_reg->u32_max_value += umax_val;
11051 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
11052 struct bpf_reg_state *src_reg)
11054 s64 smin_val = src_reg->smin_value;
11055 s64 smax_val = src_reg->smax_value;
11056 u64 umin_val = src_reg->umin_value;
11057 u64 umax_val = src_reg->umax_value;
11059 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
11060 signed_add_overflows(dst_reg->smax_value, smax_val)) {
11061 dst_reg->smin_value = S64_MIN;
11062 dst_reg->smax_value = S64_MAX;
11064 dst_reg->smin_value += smin_val;
11065 dst_reg->smax_value += smax_val;
11067 if (dst_reg->umin_value + umin_val < umin_val ||
11068 dst_reg->umax_value + umax_val < umax_val) {
11069 dst_reg->umin_value = 0;
11070 dst_reg->umax_value = U64_MAX;
11072 dst_reg->umin_value += umin_val;
11073 dst_reg->umax_value += umax_val;
11077 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
11078 struct bpf_reg_state *src_reg)
11080 s32 smin_val = src_reg->s32_min_value;
11081 s32 smax_val = src_reg->s32_max_value;
11082 u32 umin_val = src_reg->u32_min_value;
11083 u32 umax_val = src_reg->u32_max_value;
11085 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
11086 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
11087 /* Overflow possible, we know nothing */
11088 dst_reg->s32_min_value = S32_MIN;
11089 dst_reg->s32_max_value = S32_MAX;
11091 dst_reg->s32_min_value -= smax_val;
11092 dst_reg->s32_max_value -= smin_val;
11094 if (dst_reg->u32_min_value < umax_val) {
11095 /* Overflow possible, we know nothing */
11096 dst_reg->u32_min_value = 0;
11097 dst_reg->u32_max_value = U32_MAX;
11099 /* Cannot overflow (as long as bounds are consistent) */
11100 dst_reg->u32_min_value -= umax_val;
11101 dst_reg->u32_max_value -= umin_val;
11105 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
11106 struct bpf_reg_state *src_reg)
11108 s64 smin_val = src_reg->smin_value;
11109 s64 smax_val = src_reg->smax_value;
11110 u64 umin_val = src_reg->umin_value;
11111 u64 umax_val = src_reg->umax_value;
11113 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
11114 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
11115 /* Overflow possible, we know nothing */
11116 dst_reg->smin_value = S64_MIN;
11117 dst_reg->smax_value = S64_MAX;
11119 dst_reg->smin_value -= smax_val;
11120 dst_reg->smax_value -= smin_val;
11122 if (dst_reg->umin_value < umax_val) {
11123 /* Overflow possible, we know nothing */
11124 dst_reg->umin_value = 0;
11125 dst_reg->umax_value = U64_MAX;
11127 /* Cannot overflow (as long as bounds are consistent) */
11128 dst_reg->umin_value -= umax_val;
11129 dst_reg->umax_value -= umin_val;
11133 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
11134 struct bpf_reg_state *src_reg)
11136 s32 smin_val = src_reg->s32_min_value;
11137 u32 umin_val = src_reg->u32_min_value;
11138 u32 umax_val = src_reg->u32_max_value;
11140 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
11141 /* Ain't nobody got time to multiply that sign */
11142 __mark_reg32_unbounded(dst_reg);
11145 /* Both values are positive, so we can work with unsigned and
11146 * copy the result to signed (unless it exceeds S32_MAX).
11148 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
11149 /* Potential overflow, we know nothing */
11150 __mark_reg32_unbounded(dst_reg);
11153 dst_reg->u32_min_value *= umin_val;
11154 dst_reg->u32_max_value *= umax_val;
11155 if (dst_reg->u32_max_value > S32_MAX) {
11156 /* Overflow possible, we know nothing */
11157 dst_reg->s32_min_value = S32_MIN;
11158 dst_reg->s32_max_value = S32_MAX;
11160 dst_reg->s32_min_value = dst_reg->u32_min_value;
11161 dst_reg->s32_max_value = dst_reg->u32_max_value;
11165 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
11166 struct bpf_reg_state *src_reg)
11168 s64 smin_val = src_reg->smin_value;
11169 u64 umin_val = src_reg->umin_value;
11170 u64 umax_val = src_reg->umax_value;
11172 if (smin_val < 0 || dst_reg->smin_value < 0) {
11173 /* Ain't nobody got time to multiply that sign */
11174 __mark_reg64_unbounded(dst_reg);
11177 /* Both values are positive, so we can work with unsigned and
11178 * copy the result to signed (unless it exceeds S64_MAX).
11180 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
11181 /* Potential overflow, we know nothing */
11182 __mark_reg64_unbounded(dst_reg);
11185 dst_reg->umin_value *= umin_val;
11186 dst_reg->umax_value *= umax_val;
11187 if (dst_reg->umax_value > S64_MAX) {
11188 /* Overflow possible, we know nothing */
11189 dst_reg->smin_value = S64_MIN;
11190 dst_reg->smax_value = S64_MAX;
11192 dst_reg->smin_value = dst_reg->umin_value;
11193 dst_reg->smax_value = dst_reg->umax_value;
11197 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
11198 struct bpf_reg_state *src_reg)
11200 bool src_known = tnum_subreg_is_const(src_reg->var_off);
11201 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11202 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11203 s32 smin_val = src_reg->s32_min_value;
11204 u32 umax_val = src_reg->u32_max_value;
11206 if (src_known && dst_known) {
11207 __mark_reg32_known(dst_reg, var32_off.value);
11211 /* We get our minimum from the var_off, since that's inherently
11212 * bitwise. Our maximum is the minimum of the operands' maxima.
11214 dst_reg->u32_min_value = var32_off.value;
11215 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
11216 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11217 /* Lose signed bounds when ANDing negative numbers,
11218 * ain't nobody got time for that.
11220 dst_reg->s32_min_value = S32_MIN;
11221 dst_reg->s32_max_value = S32_MAX;
11223 /* ANDing two positives gives a positive, so safe to
11224 * cast result into s64.
11226 dst_reg->s32_min_value = dst_reg->u32_min_value;
11227 dst_reg->s32_max_value = dst_reg->u32_max_value;
11231 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
11232 struct bpf_reg_state *src_reg)
11234 bool src_known = tnum_is_const(src_reg->var_off);
11235 bool dst_known = tnum_is_const(dst_reg->var_off);
11236 s64 smin_val = src_reg->smin_value;
11237 u64 umax_val = src_reg->umax_value;
11239 if (src_known && dst_known) {
11240 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11244 /* We get our minimum from the var_off, since that's inherently
11245 * bitwise. Our maximum is the minimum of the operands' maxima.
11247 dst_reg->umin_value = dst_reg->var_off.value;
11248 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
11249 if (dst_reg->smin_value < 0 || smin_val < 0) {
11250 /* Lose signed bounds when ANDing negative numbers,
11251 * ain't nobody got time for that.
11253 dst_reg->smin_value = S64_MIN;
11254 dst_reg->smax_value = S64_MAX;
11256 /* ANDing two positives gives a positive, so safe to
11257 * cast result into s64.
11259 dst_reg->smin_value = dst_reg->umin_value;
11260 dst_reg->smax_value = dst_reg->umax_value;
11262 /* We may learn something more from the var_off */
11263 __update_reg_bounds(dst_reg);
11266 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
11267 struct bpf_reg_state *src_reg)
11269 bool src_known = tnum_subreg_is_const(src_reg->var_off);
11270 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11271 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11272 s32 smin_val = src_reg->s32_min_value;
11273 u32 umin_val = src_reg->u32_min_value;
11275 if (src_known && dst_known) {
11276 __mark_reg32_known(dst_reg, var32_off.value);
11280 /* We get our maximum from the var_off, and our minimum is the
11281 * maximum of the operands' minima
11283 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
11284 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11285 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11286 /* Lose signed bounds when ORing negative numbers,
11287 * ain't nobody got time for that.
11289 dst_reg->s32_min_value = S32_MIN;
11290 dst_reg->s32_max_value = S32_MAX;
11292 /* ORing two positives gives a positive, so safe to
11293 * cast result into s64.
11295 dst_reg->s32_min_value = dst_reg->u32_min_value;
11296 dst_reg->s32_max_value = dst_reg->u32_max_value;
11300 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
11301 struct bpf_reg_state *src_reg)
11303 bool src_known = tnum_is_const(src_reg->var_off);
11304 bool dst_known = tnum_is_const(dst_reg->var_off);
11305 s64 smin_val = src_reg->smin_value;
11306 u64 umin_val = src_reg->umin_value;
11308 if (src_known && dst_known) {
11309 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11313 /* We get our maximum from the var_off, and our minimum is the
11314 * maximum of the operands' minima
11316 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
11317 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11318 if (dst_reg->smin_value < 0 || smin_val < 0) {
11319 /* Lose signed bounds when ORing negative numbers,
11320 * ain't nobody got time for that.
11322 dst_reg->smin_value = S64_MIN;
11323 dst_reg->smax_value = S64_MAX;
11325 /* ORing two positives gives a positive, so safe to
11326 * cast result into s64.
11328 dst_reg->smin_value = dst_reg->umin_value;
11329 dst_reg->smax_value = dst_reg->umax_value;
11331 /* We may learn something more from the var_off */
11332 __update_reg_bounds(dst_reg);
11335 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
11336 struct bpf_reg_state *src_reg)
11338 bool src_known = tnum_subreg_is_const(src_reg->var_off);
11339 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11340 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11341 s32 smin_val = src_reg->s32_min_value;
11343 if (src_known && dst_known) {
11344 __mark_reg32_known(dst_reg, var32_off.value);
11348 /* We get both minimum and maximum from the var32_off. */
11349 dst_reg->u32_min_value = var32_off.value;
11350 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11352 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
11353 /* XORing two positive sign numbers gives a positive,
11354 * so safe to cast u32 result into s32.
11356 dst_reg->s32_min_value = dst_reg->u32_min_value;
11357 dst_reg->s32_max_value = dst_reg->u32_max_value;
11359 dst_reg->s32_min_value = S32_MIN;
11360 dst_reg->s32_max_value = S32_MAX;
11364 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
11365 struct bpf_reg_state *src_reg)
11367 bool src_known = tnum_is_const(src_reg->var_off);
11368 bool dst_known = tnum_is_const(dst_reg->var_off);
11369 s64 smin_val = src_reg->smin_value;
11371 if (src_known && dst_known) {
11372 /* dst_reg->var_off.value has been updated earlier */
11373 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11377 /* We get both minimum and maximum from the var_off. */
11378 dst_reg->umin_value = dst_reg->var_off.value;
11379 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11381 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
11382 /* XORing two positive sign numbers gives a positive,
11383 * so safe to cast u64 result into s64.
11385 dst_reg->smin_value = dst_reg->umin_value;
11386 dst_reg->smax_value = dst_reg->umax_value;
11388 dst_reg->smin_value = S64_MIN;
11389 dst_reg->smax_value = S64_MAX;
11392 __update_reg_bounds(dst_reg);
11395 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11396 u64 umin_val, u64 umax_val)
11398 /* We lose all sign bit information (except what we can pick
11401 dst_reg->s32_min_value = S32_MIN;
11402 dst_reg->s32_max_value = S32_MAX;
11403 /* If we might shift our top bit out, then we know nothing */
11404 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
11405 dst_reg->u32_min_value = 0;
11406 dst_reg->u32_max_value = U32_MAX;
11408 dst_reg->u32_min_value <<= umin_val;
11409 dst_reg->u32_max_value <<= umax_val;
11413 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11414 struct bpf_reg_state *src_reg)
11416 u32 umax_val = src_reg->u32_max_value;
11417 u32 umin_val = src_reg->u32_min_value;
11418 /* u32 alu operation will zext upper bits */
11419 struct tnum subreg = tnum_subreg(dst_reg->var_off);
11421 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11422 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
11423 /* Not required but being careful mark reg64 bounds as unknown so
11424 * that we are forced to pick them up from tnum and zext later and
11425 * if some path skips this step we are still safe.
11427 __mark_reg64_unbounded(dst_reg);
11428 __update_reg32_bounds(dst_reg);
11431 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
11432 u64 umin_val, u64 umax_val)
11434 /* Special case <<32 because it is a common compiler pattern to sign
11435 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
11436 * positive we know this shift will also be positive so we can track
11437 * bounds correctly. Otherwise we lose all sign bit information except
11438 * what we can pick up from var_off. Perhaps we can generalize this
11439 * later to shifts of any length.
11441 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
11442 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
11444 dst_reg->smax_value = S64_MAX;
11446 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
11447 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
11449 dst_reg->smin_value = S64_MIN;
11451 /* If we might shift our top bit out, then we know nothing */
11452 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
11453 dst_reg->umin_value = 0;
11454 dst_reg->umax_value = U64_MAX;
11456 dst_reg->umin_value <<= umin_val;
11457 dst_reg->umax_value <<= umax_val;
11461 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
11462 struct bpf_reg_state *src_reg)
11464 u64 umax_val = src_reg->umax_value;
11465 u64 umin_val = src_reg->umin_value;
11467 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
11468 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
11469 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11471 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
11472 /* We may learn something more from the var_off */
11473 __update_reg_bounds(dst_reg);
11476 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
11477 struct bpf_reg_state *src_reg)
11479 struct tnum subreg = tnum_subreg(dst_reg->var_off);
11480 u32 umax_val = src_reg->u32_max_value;
11481 u32 umin_val = src_reg->u32_min_value;
11483 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
11484 * be negative, then either:
11485 * 1) src_reg might be zero, so the sign bit of the result is
11486 * unknown, so we lose our signed bounds
11487 * 2) it's known negative, thus the unsigned bounds capture the
11489 * 3) the signed bounds cross zero, so they tell us nothing
11491 * If the value in dst_reg is known nonnegative, then again the
11492 * unsigned bounds capture the signed bounds.
11493 * Thus, in all cases it suffices to blow away our signed bounds
11494 * and rely on inferring new ones from the unsigned bounds and
11495 * var_off of the result.
11497 dst_reg->s32_min_value = S32_MIN;
11498 dst_reg->s32_max_value = S32_MAX;
11500 dst_reg->var_off = tnum_rshift(subreg, umin_val);
11501 dst_reg->u32_min_value >>= umax_val;
11502 dst_reg->u32_max_value >>= umin_val;
11504 __mark_reg64_unbounded(dst_reg);
11505 __update_reg32_bounds(dst_reg);
11508 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
11509 struct bpf_reg_state *src_reg)
11511 u64 umax_val = src_reg->umax_value;
11512 u64 umin_val = src_reg->umin_value;
11514 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
11515 * be negative, then either:
11516 * 1) src_reg might be zero, so the sign bit of the result is
11517 * unknown, so we lose our signed bounds
11518 * 2) it's known negative, thus the unsigned bounds capture the
11520 * 3) the signed bounds cross zero, so they tell us nothing
11522 * If the value in dst_reg is known nonnegative, then again the
11523 * unsigned bounds capture the signed bounds.
11524 * Thus, in all cases it suffices to blow away our signed bounds
11525 * and rely on inferring new ones from the unsigned bounds and
11526 * var_off of the result.
11528 dst_reg->smin_value = S64_MIN;
11529 dst_reg->smax_value = S64_MAX;
11530 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
11531 dst_reg->umin_value >>= umax_val;
11532 dst_reg->umax_value >>= umin_val;
11534 /* Its not easy to operate on alu32 bounds here because it depends
11535 * on bits being shifted in. Take easy way out and mark unbounded
11536 * so we can recalculate later from tnum.
11538 __mark_reg32_unbounded(dst_reg);
11539 __update_reg_bounds(dst_reg);
11542 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
11543 struct bpf_reg_state *src_reg)
11545 u64 umin_val = src_reg->u32_min_value;
11547 /* Upon reaching here, src_known is true and
11548 * umax_val is equal to umin_val.
11550 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
11551 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
11553 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
11555 /* blow away the dst_reg umin_value/umax_value and rely on
11556 * dst_reg var_off to refine the result.
11558 dst_reg->u32_min_value = 0;
11559 dst_reg->u32_max_value = U32_MAX;
11561 __mark_reg64_unbounded(dst_reg);
11562 __update_reg32_bounds(dst_reg);
11565 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
11566 struct bpf_reg_state *src_reg)
11568 u64 umin_val = src_reg->umin_value;
11570 /* Upon reaching here, src_known is true and umax_val is equal
11573 dst_reg->smin_value >>= umin_val;
11574 dst_reg->smax_value >>= umin_val;
11576 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
11578 /* blow away the dst_reg umin_value/umax_value and rely on
11579 * dst_reg var_off to refine the result.
11581 dst_reg->umin_value = 0;
11582 dst_reg->umax_value = U64_MAX;
11584 /* Its not easy to operate on alu32 bounds here because it depends
11585 * on bits being shifted in from upper 32-bits. Take easy way out
11586 * and mark unbounded so we can recalculate later from tnum.
11588 __mark_reg32_unbounded(dst_reg);
11589 __update_reg_bounds(dst_reg);
11592 /* WARNING: This function does calculations on 64-bit values, but the actual
11593 * execution may occur on 32-bit values. Therefore, things like bitshifts
11594 * need extra checks in the 32-bit case.
11596 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
11597 struct bpf_insn *insn,
11598 struct bpf_reg_state *dst_reg,
11599 struct bpf_reg_state src_reg)
11601 struct bpf_reg_state *regs = cur_regs(env);
11602 u8 opcode = BPF_OP(insn->code);
11604 s64 smin_val, smax_val;
11605 u64 umin_val, umax_val;
11606 s32 s32_min_val, s32_max_val;
11607 u32 u32_min_val, u32_max_val;
11608 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
11609 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
11612 smin_val = src_reg.smin_value;
11613 smax_val = src_reg.smax_value;
11614 umin_val = src_reg.umin_value;
11615 umax_val = src_reg.umax_value;
11617 s32_min_val = src_reg.s32_min_value;
11618 s32_max_val = src_reg.s32_max_value;
11619 u32_min_val = src_reg.u32_min_value;
11620 u32_max_val = src_reg.u32_max_value;
11623 src_known = tnum_subreg_is_const(src_reg.var_off);
11625 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
11626 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
11627 /* Taint dst register if offset had invalid bounds
11628 * derived from e.g. dead branches.
11630 __mark_reg_unknown(env, dst_reg);
11634 src_known = tnum_is_const(src_reg.var_off);
11636 (smin_val != smax_val || umin_val != umax_val)) ||
11637 smin_val > smax_val || umin_val > umax_val) {
11638 /* Taint dst register if offset had invalid bounds
11639 * derived from e.g. dead branches.
11641 __mark_reg_unknown(env, dst_reg);
11647 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
11648 __mark_reg_unknown(env, dst_reg);
11652 if (sanitize_needed(opcode)) {
11653 ret = sanitize_val_alu(env, insn);
11655 return sanitize_err(env, insn, ret, NULL, NULL);
11658 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
11659 * There are two classes of instructions: The first class we track both
11660 * alu32 and alu64 sign/unsigned bounds independently this provides the
11661 * greatest amount of precision when alu operations are mixed with jmp32
11662 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
11663 * and BPF_OR. This is possible because these ops have fairly easy to
11664 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
11665 * See alu32 verifier tests for examples. The second class of
11666 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
11667 * with regards to tracking sign/unsigned bounds because the bits may
11668 * cross subreg boundaries in the alu64 case. When this happens we mark
11669 * the reg unbounded in the subreg bound space and use the resulting
11670 * tnum to calculate an approximation of the sign/unsigned bounds.
11674 scalar32_min_max_add(dst_reg, &src_reg);
11675 scalar_min_max_add(dst_reg, &src_reg);
11676 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
11679 scalar32_min_max_sub(dst_reg, &src_reg);
11680 scalar_min_max_sub(dst_reg, &src_reg);
11681 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
11684 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
11685 scalar32_min_max_mul(dst_reg, &src_reg);
11686 scalar_min_max_mul(dst_reg, &src_reg);
11689 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
11690 scalar32_min_max_and(dst_reg, &src_reg);
11691 scalar_min_max_and(dst_reg, &src_reg);
11694 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
11695 scalar32_min_max_or(dst_reg, &src_reg);
11696 scalar_min_max_or(dst_reg, &src_reg);
11699 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
11700 scalar32_min_max_xor(dst_reg, &src_reg);
11701 scalar_min_max_xor(dst_reg, &src_reg);
11704 if (umax_val >= insn_bitness) {
11705 /* Shifts greater than 31 or 63 are undefined.
11706 * This includes shifts by a negative number.
11708 mark_reg_unknown(env, regs, insn->dst_reg);
11712 scalar32_min_max_lsh(dst_reg, &src_reg);
11714 scalar_min_max_lsh(dst_reg, &src_reg);
11717 if (umax_val >= insn_bitness) {
11718 /* Shifts greater than 31 or 63 are undefined.
11719 * This includes shifts by a negative number.
11721 mark_reg_unknown(env, regs, insn->dst_reg);
11725 scalar32_min_max_rsh(dst_reg, &src_reg);
11727 scalar_min_max_rsh(dst_reg, &src_reg);
11730 if (umax_val >= insn_bitness) {
11731 /* Shifts greater than 31 or 63 are undefined.
11732 * This includes shifts by a negative number.
11734 mark_reg_unknown(env, regs, insn->dst_reg);
11738 scalar32_min_max_arsh(dst_reg, &src_reg);
11740 scalar_min_max_arsh(dst_reg, &src_reg);
11743 mark_reg_unknown(env, regs, insn->dst_reg);
11747 /* ALU32 ops are zero extended into 64bit register */
11749 zext_32_to_64(dst_reg);
11750 reg_bounds_sync(dst_reg);
11754 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
11757 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
11758 struct bpf_insn *insn)
11760 struct bpf_verifier_state *vstate = env->cur_state;
11761 struct bpf_func_state *state = vstate->frame[vstate->curframe];
11762 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
11763 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
11764 u8 opcode = BPF_OP(insn->code);
11767 dst_reg = ®s[insn->dst_reg];
11769 if (dst_reg->type != SCALAR_VALUE)
11772 /* Make sure ID is cleared otherwise dst_reg min/max could be
11773 * incorrectly propagated into other registers by find_equal_scalars()
11776 if (BPF_SRC(insn->code) == BPF_X) {
11777 src_reg = ®s[insn->src_reg];
11778 if (src_reg->type != SCALAR_VALUE) {
11779 if (dst_reg->type != SCALAR_VALUE) {
11780 /* Combining two pointers by any ALU op yields
11781 * an arbitrary scalar. Disallow all math except
11782 * pointer subtraction
11784 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11785 mark_reg_unknown(env, regs, insn->dst_reg);
11788 verbose(env, "R%d pointer %s pointer prohibited\n",
11790 bpf_alu_string[opcode >> 4]);
11793 /* scalar += pointer
11794 * This is legal, but we have to reverse our
11795 * src/dest handling in computing the range
11797 err = mark_chain_precision(env, insn->dst_reg);
11800 return adjust_ptr_min_max_vals(env, insn,
11803 } else if (ptr_reg) {
11804 /* pointer += scalar */
11805 err = mark_chain_precision(env, insn->src_reg);
11808 return adjust_ptr_min_max_vals(env, insn,
11810 } else if (dst_reg->precise) {
11811 /* if dst_reg is precise, src_reg should be precise as well */
11812 err = mark_chain_precision(env, insn->src_reg);
11817 /* Pretend the src is a reg with a known value, since we only
11818 * need to be able to read from this state.
11820 off_reg.type = SCALAR_VALUE;
11821 __mark_reg_known(&off_reg, insn->imm);
11822 src_reg = &off_reg;
11823 if (ptr_reg) /* pointer += K */
11824 return adjust_ptr_min_max_vals(env, insn,
11828 /* Got here implies adding two SCALAR_VALUEs */
11829 if (WARN_ON_ONCE(ptr_reg)) {
11830 print_verifier_state(env, state, true);
11831 verbose(env, "verifier internal error: unexpected ptr_reg\n");
11834 if (WARN_ON(!src_reg)) {
11835 print_verifier_state(env, state, true);
11836 verbose(env, "verifier internal error: no src_reg\n");
11839 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
11842 /* check validity of 32-bit and 64-bit arithmetic operations */
11843 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
11845 struct bpf_reg_state *regs = cur_regs(env);
11846 u8 opcode = BPF_OP(insn->code);
11849 if (opcode == BPF_END || opcode == BPF_NEG) {
11850 if (opcode == BPF_NEG) {
11851 if (BPF_SRC(insn->code) != BPF_K ||
11852 insn->src_reg != BPF_REG_0 ||
11853 insn->off != 0 || insn->imm != 0) {
11854 verbose(env, "BPF_NEG uses reserved fields\n");
11858 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
11859 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
11860 BPF_CLASS(insn->code) == BPF_ALU64) {
11861 verbose(env, "BPF_END uses reserved fields\n");
11866 /* check src operand */
11867 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11871 if (is_pointer_value(env, insn->dst_reg)) {
11872 verbose(env, "R%d pointer arithmetic prohibited\n",
11877 /* check dest operand */
11878 err = check_reg_arg(env, insn->dst_reg, DST_OP);
11882 } else if (opcode == BPF_MOV) {
11884 if (BPF_SRC(insn->code) == BPF_X) {
11885 if (insn->imm != 0 || insn->off != 0) {
11886 verbose(env, "BPF_MOV uses reserved fields\n");
11890 /* check src operand */
11891 err = check_reg_arg(env, insn->src_reg, SRC_OP);
11895 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11896 verbose(env, "BPF_MOV uses reserved fields\n");
11901 /* check dest operand, mark as required later */
11902 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11906 if (BPF_SRC(insn->code) == BPF_X) {
11907 struct bpf_reg_state *src_reg = regs + insn->src_reg;
11908 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
11910 if (BPF_CLASS(insn->code) == BPF_ALU64) {
11912 * copy register state to dest reg
11914 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
11915 /* Assign src and dst registers the same ID
11916 * that will be used by find_equal_scalars()
11917 * to propagate min/max range.
11919 src_reg->id = ++env->id_gen;
11920 copy_register_state(dst_reg, src_reg);
11921 dst_reg->live |= REG_LIVE_WRITTEN;
11922 dst_reg->subreg_def = DEF_NOT_SUBREG;
11924 /* R1 = (u32) R2 */
11925 if (is_pointer_value(env, insn->src_reg)) {
11927 "R%d partial copy of pointer\n",
11930 } else if (src_reg->type == SCALAR_VALUE) {
11931 copy_register_state(dst_reg, src_reg);
11932 /* Make sure ID is cleared otherwise
11933 * dst_reg min/max could be incorrectly
11934 * propagated into src_reg by find_equal_scalars()
11937 dst_reg->live |= REG_LIVE_WRITTEN;
11938 dst_reg->subreg_def = env->insn_idx + 1;
11940 mark_reg_unknown(env, regs,
11943 zext_32_to_64(dst_reg);
11944 reg_bounds_sync(dst_reg);
11948 * remember the value we stored into this reg
11950 /* clear any state __mark_reg_known doesn't set */
11951 mark_reg_unknown(env, regs, insn->dst_reg);
11952 regs[insn->dst_reg].type = SCALAR_VALUE;
11953 if (BPF_CLASS(insn->code) == BPF_ALU64) {
11954 __mark_reg_known(regs + insn->dst_reg,
11957 __mark_reg_known(regs + insn->dst_reg,
11962 } else if (opcode > BPF_END) {
11963 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
11966 } else { /* all other ALU ops: and, sub, xor, add, ... */
11968 if (BPF_SRC(insn->code) == BPF_X) {
11969 if (insn->imm != 0 || insn->off != 0) {
11970 verbose(env, "BPF_ALU uses reserved fields\n");
11973 /* check src1 operand */
11974 err = check_reg_arg(env, insn->src_reg, SRC_OP);
11978 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11979 verbose(env, "BPF_ALU uses reserved fields\n");
11984 /* check src2 operand */
11985 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11989 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
11990 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
11991 verbose(env, "div by zero\n");
11995 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
11996 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
11997 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
11999 if (insn->imm < 0 || insn->imm >= size) {
12000 verbose(env, "invalid shift %d\n", insn->imm);
12005 /* check dest operand */
12006 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12010 return adjust_reg_min_max_vals(env, insn);
12016 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
12017 struct bpf_reg_state *dst_reg,
12018 enum bpf_reg_type type,
12019 bool range_right_open)
12021 struct bpf_func_state *state;
12022 struct bpf_reg_state *reg;
12025 if (dst_reg->off < 0 ||
12026 (dst_reg->off == 0 && range_right_open))
12027 /* This doesn't give us any range */
12030 if (dst_reg->umax_value > MAX_PACKET_OFF ||
12031 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
12032 /* Risk of overflow. For instance, ptr + (1<<63) may be less
12033 * than pkt_end, but that's because it's also less than pkt.
12037 new_range = dst_reg->off;
12038 if (range_right_open)
12041 /* Examples for register markings:
12043 * pkt_data in dst register:
12047 * if (r2 > pkt_end) goto <handle exception>
12052 * if (r2 < pkt_end) goto <access okay>
12053 * <handle exception>
12056 * r2 == dst_reg, pkt_end == src_reg
12057 * r2=pkt(id=n,off=8,r=0)
12058 * r3=pkt(id=n,off=0,r=0)
12060 * pkt_data in src register:
12064 * if (pkt_end >= r2) goto <access okay>
12065 * <handle exception>
12069 * if (pkt_end <= r2) goto <handle exception>
12073 * pkt_end == dst_reg, r2 == src_reg
12074 * r2=pkt(id=n,off=8,r=0)
12075 * r3=pkt(id=n,off=0,r=0)
12077 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
12078 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
12079 * and [r3, r3 + 8-1) respectively is safe to access depending on
12083 /* If our ids match, then we must have the same max_value. And we
12084 * don't care about the other reg's fixed offset, since if it's too big
12085 * the range won't allow anything.
12086 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
12088 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12089 if (reg->type == type && reg->id == dst_reg->id)
12090 /* keep the maximum range already checked */
12091 reg->range = max(reg->range, new_range);
12095 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
12097 struct tnum subreg = tnum_subreg(reg->var_off);
12098 s32 sval = (s32)val;
12102 if (tnum_is_const(subreg))
12103 return !!tnum_equals_const(subreg, val);
12106 if (tnum_is_const(subreg))
12107 return !tnum_equals_const(subreg, val);
12110 if ((~subreg.mask & subreg.value) & val)
12112 if (!((subreg.mask | subreg.value) & val))
12116 if (reg->u32_min_value > val)
12118 else if (reg->u32_max_value <= val)
12122 if (reg->s32_min_value > sval)
12124 else if (reg->s32_max_value <= sval)
12128 if (reg->u32_max_value < val)
12130 else if (reg->u32_min_value >= val)
12134 if (reg->s32_max_value < sval)
12136 else if (reg->s32_min_value >= sval)
12140 if (reg->u32_min_value >= val)
12142 else if (reg->u32_max_value < val)
12146 if (reg->s32_min_value >= sval)
12148 else if (reg->s32_max_value < sval)
12152 if (reg->u32_max_value <= val)
12154 else if (reg->u32_min_value > val)
12158 if (reg->s32_max_value <= sval)
12160 else if (reg->s32_min_value > sval)
12169 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
12171 s64 sval = (s64)val;
12175 if (tnum_is_const(reg->var_off))
12176 return !!tnum_equals_const(reg->var_off, val);
12179 if (tnum_is_const(reg->var_off))
12180 return !tnum_equals_const(reg->var_off, val);
12183 if ((~reg->var_off.mask & reg->var_off.value) & val)
12185 if (!((reg->var_off.mask | reg->var_off.value) & val))
12189 if (reg->umin_value > val)
12191 else if (reg->umax_value <= val)
12195 if (reg->smin_value > sval)
12197 else if (reg->smax_value <= sval)
12201 if (reg->umax_value < val)
12203 else if (reg->umin_value >= val)
12207 if (reg->smax_value < sval)
12209 else if (reg->smin_value >= sval)
12213 if (reg->umin_value >= val)
12215 else if (reg->umax_value < val)
12219 if (reg->smin_value >= sval)
12221 else if (reg->smax_value < sval)
12225 if (reg->umax_value <= val)
12227 else if (reg->umin_value > val)
12231 if (reg->smax_value <= sval)
12233 else if (reg->smin_value > sval)
12241 /* compute branch direction of the expression "if (reg opcode val) goto target;"
12243 * 1 - branch will be taken and "goto target" will be executed
12244 * 0 - branch will not be taken and fall-through to next insn
12245 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
12248 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
12251 if (__is_pointer_value(false, reg)) {
12252 if (!reg_type_not_null(reg->type))
12255 /* If pointer is valid tests against zero will fail so we can
12256 * use this to direct branch taken.
12272 return is_branch32_taken(reg, val, opcode);
12273 return is_branch64_taken(reg, val, opcode);
12276 static int flip_opcode(u32 opcode)
12278 /* How can we transform "a <op> b" into "b <op> a"? */
12279 static const u8 opcode_flip[16] = {
12280 /* these stay the same */
12281 [BPF_JEQ >> 4] = BPF_JEQ,
12282 [BPF_JNE >> 4] = BPF_JNE,
12283 [BPF_JSET >> 4] = BPF_JSET,
12284 /* these swap "lesser" and "greater" (L and G in the opcodes) */
12285 [BPF_JGE >> 4] = BPF_JLE,
12286 [BPF_JGT >> 4] = BPF_JLT,
12287 [BPF_JLE >> 4] = BPF_JGE,
12288 [BPF_JLT >> 4] = BPF_JGT,
12289 [BPF_JSGE >> 4] = BPF_JSLE,
12290 [BPF_JSGT >> 4] = BPF_JSLT,
12291 [BPF_JSLE >> 4] = BPF_JSGE,
12292 [BPF_JSLT >> 4] = BPF_JSGT
12294 return opcode_flip[opcode >> 4];
12297 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
12298 struct bpf_reg_state *src_reg,
12301 struct bpf_reg_state *pkt;
12303 if (src_reg->type == PTR_TO_PACKET_END) {
12305 } else if (dst_reg->type == PTR_TO_PACKET_END) {
12307 opcode = flip_opcode(opcode);
12312 if (pkt->range >= 0)
12317 /* pkt <= pkt_end */
12320 /* pkt > pkt_end */
12321 if (pkt->range == BEYOND_PKT_END)
12322 /* pkt has at last one extra byte beyond pkt_end */
12323 return opcode == BPF_JGT;
12326 /* pkt < pkt_end */
12329 /* pkt >= pkt_end */
12330 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
12331 return opcode == BPF_JGE;
12337 /* Adjusts the register min/max values in the case that the dst_reg is the
12338 * variable register that we are working on, and src_reg is a constant or we're
12339 * simply doing a BPF_K check.
12340 * In JEQ/JNE cases we also adjust the var_off values.
12342 static void reg_set_min_max(struct bpf_reg_state *true_reg,
12343 struct bpf_reg_state *false_reg,
12344 u64 val, u32 val32,
12345 u8 opcode, bool is_jmp32)
12347 struct tnum false_32off = tnum_subreg(false_reg->var_off);
12348 struct tnum false_64off = false_reg->var_off;
12349 struct tnum true_32off = tnum_subreg(true_reg->var_off);
12350 struct tnum true_64off = true_reg->var_off;
12351 s64 sval = (s64)val;
12352 s32 sval32 = (s32)val32;
12354 /* If the dst_reg is a pointer, we can't learn anything about its
12355 * variable offset from the compare (unless src_reg were a pointer into
12356 * the same object, but we don't bother with that.
12357 * Since false_reg and true_reg have the same type by construction, we
12358 * only need to check one of them for pointerness.
12360 if (__is_pointer_value(false, false_reg))
12364 /* JEQ/JNE comparison doesn't change the register equivalence.
12367 * if (r1 == 42) goto label;
12369 * label: // here both r1 and r2 are known to be 42.
12371 * Hence when marking register as known preserve it's ID.
12375 __mark_reg32_known(true_reg, val32);
12376 true_32off = tnum_subreg(true_reg->var_off);
12378 ___mark_reg_known(true_reg, val);
12379 true_64off = true_reg->var_off;
12384 __mark_reg32_known(false_reg, val32);
12385 false_32off = tnum_subreg(false_reg->var_off);
12387 ___mark_reg_known(false_reg, val);
12388 false_64off = false_reg->var_off;
12393 false_32off = tnum_and(false_32off, tnum_const(~val32));
12394 if (is_power_of_2(val32))
12395 true_32off = tnum_or(true_32off,
12396 tnum_const(val32));
12398 false_64off = tnum_and(false_64off, tnum_const(~val));
12399 if (is_power_of_2(val))
12400 true_64off = tnum_or(true_64off,
12408 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
12409 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
12411 false_reg->u32_max_value = min(false_reg->u32_max_value,
12413 true_reg->u32_min_value = max(true_reg->u32_min_value,
12416 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
12417 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
12419 false_reg->umax_value = min(false_reg->umax_value, false_umax);
12420 true_reg->umin_value = max(true_reg->umin_value, true_umin);
12428 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
12429 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
12431 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
12432 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
12434 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
12435 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
12437 false_reg->smax_value = min(false_reg->smax_value, false_smax);
12438 true_reg->smin_value = max(true_reg->smin_value, true_smin);
12446 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
12447 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
12449 false_reg->u32_min_value = max(false_reg->u32_min_value,
12451 true_reg->u32_max_value = min(true_reg->u32_max_value,
12454 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
12455 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
12457 false_reg->umin_value = max(false_reg->umin_value, false_umin);
12458 true_reg->umax_value = min(true_reg->umax_value, true_umax);
12466 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
12467 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
12469 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
12470 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
12472 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
12473 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
12475 false_reg->smin_value = max(false_reg->smin_value, false_smin);
12476 true_reg->smax_value = min(true_reg->smax_value, true_smax);
12485 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
12486 tnum_subreg(false_32off));
12487 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
12488 tnum_subreg(true_32off));
12489 __reg_combine_32_into_64(false_reg);
12490 __reg_combine_32_into_64(true_reg);
12492 false_reg->var_off = false_64off;
12493 true_reg->var_off = true_64off;
12494 __reg_combine_64_into_32(false_reg);
12495 __reg_combine_64_into_32(true_reg);
12499 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
12500 * the variable reg.
12502 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
12503 struct bpf_reg_state *false_reg,
12504 u64 val, u32 val32,
12505 u8 opcode, bool is_jmp32)
12507 opcode = flip_opcode(opcode);
12508 /* This uses zero as "not present in table"; luckily the zero opcode,
12509 * BPF_JA, can't get here.
12512 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
12515 /* Regs are known to be equal, so intersect their min/max/var_off */
12516 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
12517 struct bpf_reg_state *dst_reg)
12519 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
12520 dst_reg->umin_value);
12521 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
12522 dst_reg->umax_value);
12523 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
12524 dst_reg->smin_value);
12525 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
12526 dst_reg->smax_value);
12527 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
12529 reg_bounds_sync(src_reg);
12530 reg_bounds_sync(dst_reg);
12533 static void reg_combine_min_max(struct bpf_reg_state *true_src,
12534 struct bpf_reg_state *true_dst,
12535 struct bpf_reg_state *false_src,
12536 struct bpf_reg_state *false_dst,
12541 __reg_combine_min_max(true_src, true_dst);
12544 __reg_combine_min_max(false_src, false_dst);
12549 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
12550 struct bpf_reg_state *reg, u32 id,
12553 if (type_may_be_null(reg->type) && reg->id == id &&
12554 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
12555 /* Old offset (both fixed and variable parts) should have been
12556 * known-zero, because we don't allow pointer arithmetic on
12557 * pointers that might be NULL. If we see this happening, don't
12558 * convert the register.
12560 * But in some cases, some helpers that return local kptrs
12561 * advance offset for the returned pointer. In those cases, it
12562 * is fine to expect to see reg->off.
12564 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
12566 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
12567 WARN_ON_ONCE(reg->off))
12571 reg->type = SCALAR_VALUE;
12572 /* We don't need id and ref_obj_id from this point
12573 * onwards anymore, thus we should better reset it,
12574 * so that state pruning has chances to take effect.
12577 reg->ref_obj_id = 0;
12582 mark_ptr_not_null_reg(reg);
12584 if (!reg_may_point_to_spin_lock(reg)) {
12585 /* For not-NULL ptr, reg->ref_obj_id will be reset
12586 * in release_reference().
12588 * reg->id is still used by spin_lock ptr. Other
12589 * than spin_lock ptr type, reg->id can be reset.
12596 /* The logic is similar to find_good_pkt_pointers(), both could eventually
12597 * be folded together at some point.
12599 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
12602 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12603 struct bpf_reg_state *regs = state->regs, *reg;
12604 u32 ref_obj_id = regs[regno].ref_obj_id;
12605 u32 id = regs[regno].id;
12607 if (ref_obj_id && ref_obj_id == id && is_null)
12608 /* regs[regno] is in the " == NULL" branch.
12609 * No one could have freed the reference state before
12610 * doing the NULL check.
12612 WARN_ON_ONCE(release_reference_state(state, id));
12614 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12615 mark_ptr_or_null_reg(state, reg, id, is_null);
12619 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
12620 struct bpf_reg_state *dst_reg,
12621 struct bpf_reg_state *src_reg,
12622 struct bpf_verifier_state *this_branch,
12623 struct bpf_verifier_state *other_branch)
12625 if (BPF_SRC(insn->code) != BPF_X)
12628 /* Pointers are always 64-bit. */
12629 if (BPF_CLASS(insn->code) == BPF_JMP32)
12632 switch (BPF_OP(insn->code)) {
12634 if ((dst_reg->type == PTR_TO_PACKET &&
12635 src_reg->type == PTR_TO_PACKET_END) ||
12636 (dst_reg->type == PTR_TO_PACKET_META &&
12637 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12638 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
12639 find_good_pkt_pointers(this_branch, dst_reg,
12640 dst_reg->type, false);
12641 mark_pkt_end(other_branch, insn->dst_reg, true);
12642 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
12643 src_reg->type == PTR_TO_PACKET) ||
12644 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12645 src_reg->type == PTR_TO_PACKET_META)) {
12646 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
12647 find_good_pkt_pointers(other_branch, src_reg,
12648 src_reg->type, true);
12649 mark_pkt_end(this_branch, insn->src_reg, false);
12655 if ((dst_reg->type == PTR_TO_PACKET &&
12656 src_reg->type == PTR_TO_PACKET_END) ||
12657 (dst_reg->type == PTR_TO_PACKET_META &&
12658 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12659 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
12660 find_good_pkt_pointers(other_branch, dst_reg,
12661 dst_reg->type, true);
12662 mark_pkt_end(this_branch, insn->dst_reg, false);
12663 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
12664 src_reg->type == PTR_TO_PACKET) ||
12665 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12666 src_reg->type == PTR_TO_PACKET_META)) {
12667 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
12668 find_good_pkt_pointers(this_branch, src_reg,
12669 src_reg->type, false);
12670 mark_pkt_end(other_branch, insn->src_reg, true);
12676 if ((dst_reg->type == PTR_TO_PACKET &&
12677 src_reg->type == PTR_TO_PACKET_END) ||
12678 (dst_reg->type == PTR_TO_PACKET_META &&
12679 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12680 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
12681 find_good_pkt_pointers(this_branch, dst_reg,
12682 dst_reg->type, true);
12683 mark_pkt_end(other_branch, insn->dst_reg, false);
12684 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
12685 src_reg->type == PTR_TO_PACKET) ||
12686 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12687 src_reg->type == PTR_TO_PACKET_META)) {
12688 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
12689 find_good_pkt_pointers(other_branch, src_reg,
12690 src_reg->type, false);
12691 mark_pkt_end(this_branch, insn->src_reg, true);
12697 if ((dst_reg->type == PTR_TO_PACKET &&
12698 src_reg->type == PTR_TO_PACKET_END) ||
12699 (dst_reg->type == PTR_TO_PACKET_META &&
12700 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12701 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
12702 find_good_pkt_pointers(other_branch, dst_reg,
12703 dst_reg->type, false);
12704 mark_pkt_end(this_branch, insn->dst_reg, true);
12705 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
12706 src_reg->type == PTR_TO_PACKET) ||
12707 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12708 src_reg->type == PTR_TO_PACKET_META)) {
12709 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
12710 find_good_pkt_pointers(this_branch, src_reg,
12711 src_reg->type, true);
12712 mark_pkt_end(other_branch, insn->src_reg, false);
12724 static void find_equal_scalars(struct bpf_verifier_state *vstate,
12725 struct bpf_reg_state *known_reg)
12727 struct bpf_func_state *state;
12728 struct bpf_reg_state *reg;
12730 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12731 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
12732 copy_register_state(reg, known_reg);
12736 static int check_cond_jmp_op(struct bpf_verifier_env *env,
12737 struct bpf_insn *insn, int *insn_idx)
12739 struct bpf_verifier_state *this_branch = env->cur_state;
12740 struct bpf_verifier_state *other_branch;
12741 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
12742 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
12743 struct bpf_reg_state *eq_branch_regs;
12744 u8 opcode = BPF_OP(insn->code);
12749 /* Only conditional jumps are expected to reach here. */
12750 if (opcode == BPF_JA || opcode > BPF_JSLE) {
12751 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
12755 if (BPF_SRC(insn->code) == BPF_X) {
12756 if (insn->imm != 0) {
12757 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12761 /* check src1 operand */
12762 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12766 if (is_pointer_value(env, insn->src_reg)) {
12767 verbose(env, "R%d pointer comparison prohibited\n",
12771 src_reg = ®s[insn->src_reg];
12773 if (insn->src_reg != BPF_REG_0) {
12774 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12779 /* check src2 operand */
12780 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12784 dst_reg = ®s[insn->dst_reg];
12785 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
12787 if (BPF_SRC(insn->code) == BPF_K) {
12788 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
12789 } else if (src_reg->type == SCALAR_VALUE &&
12790 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
12791 pred = is_branch_taken(dst_reg,
12792 tnum_subreg(src_reg->var_off).value,
12795 } else if (src_reg->type == SCALAR_VALUE &&
12796 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
12797 pred = is_branch_taken(dst_reg,
12798 src_reg->var_off.value,
12801 } else if (reg_is_pkt_pointer_any(dst_reg) &&
12802 reg_is_pkt_pointer_any(src_reg) &&
12804 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
12808 /* If we get here with a dst_reg pointer type it is because
12809 * above is_branch_taken() special cased the 0 comparison.
12811 if (!__is_pointer_value(false, dst_reg))
12812 err = mark_chain_precision(env, insn->dst_reg);
12813 if (BPF_SRC(insn->code) == BPF_X && !err &&
12814 !__is_pointer_value(false, src_reg))
12815 err = mark_chain_precision(env, insn->src_reg);
12821 /* Only follow the goto, ignore fall-through. If needed, push
12822 * the fall-through branch for simulation under speculative
12825 if (!env->bypass_spec_v1 &&
12826 !sanitize_speculative_path(env, insn, *insn_idx + 1,
12829 *insn_idx += insn->off;
12831 } else if (pred == 0) {
12832 /* Only follow the fall-through branch, since that's where the
12833 * program will go. If needed, push the goto branch for
12834 * simulation under speculative execution.
12836 if (!env->bypass_spec_v1 &&
12837 !sanitize_speculative_path(env, insn,
12838 *insn_idx + insn->off + 1,
12844 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
12848 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
12850 /* detect if we are comparing against a constant value so we can adjust
12851 * our min/max values for our dst register.
12852 * this is only legit if both are scalars (or pointers to the same
12853 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
12854 * because otherwise the different base pointers mean the offsets aren't
12857 if (BPF_SRC(insn->code) == BPF_X) {
12858 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
12860 if (dst_reg->type == SCALAR_VALUE &&
12861 src_reg->type == SCALAR_VALUE) {
12862 if (tnum_is_const(src_reg->var_off) ||
12864 tnum_is_const(tnum_subreg(src_reg->var_off))))
12865 reg_set_min_max(&other_branch_regs[insn->dst_reg],
12867 src_reg->var_off.value,
12868 tnum_subreg(src_reg->var_off).value,
12870 else if (tnum_is_const(dst_reg->var_off) ||
12872 tnum_is_const(tnum_subreg(dst_reg->var_off))))
12873 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
12875 dst_reg->var_off.value,
12876 tnum_subreg(dst_reg->var_off).value,
12878 else if (!is_jmp32 &&
12879 (opcode == BPF_JEQ || opcode == BPF_JNE))
12880 /* Comparing for equality, we can combine knowledge */
12881 reg_combine_min_max(&other_branch_regs[insn->src_reg],
12882 &other_branch_regs[insn->dst_reg],
12883 src_reg, dst_reg, opcode);
12885 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
12886 find_equal_scalars(this_branch, src_reg);
12887 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
12891 } else if (dst_reg->type == SCALAR_VALUE) {
12892 reg_set_min_max(&other_branch_regs[insn->dst_reg],
12893 dst_reg, insn->imm, (u32)insn->imm,
12897 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
12898 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
12899 find_equal_scalars(this_branch, dst_reg);
12900 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
12903 /* if one pointer register is compared to another pointer
12904 * register check if PTR_MAYBE_NULL could be lifted.
12905 * E.g. register A - maybe null
12906 * register B - not null
12907 * for JNE A, B, ... - A is not null in the false branch;
12908 * for JEQ A, B, ... - A is not null in the true branch.
12910 * Since PTR_TO_BTF_ID points to a kernel struct that does
12911 * not need to be null checked by the BPF program, i.e.,
12912 * could be null even without PTR_MAYBE_NULL marking, so
12913 * only propagate nullness when neither reg is that type.
12915 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
12916 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
12917 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
12918 base_type(src_reg->type) != PTR_TO_BTF_ID &&
12919 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
12920 eq_branch_regs = NULL;
12923 eq_branch_regs = other_branch_regs;
12926 eq_branch_regs = regs;
12932 if (eq_branch_regs) {
12933 if (type_may_be_null(src_reg->type))
12934 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
12936 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
12940 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
12941 * NOTE: these optimizations below are related with pointer comparison
12942 * which will never be JMP32.
12944 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
12945 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
12946 type_may_be_null(dst_reg->type)) {
12947 /* Mark all identical registers in each branch as either
12948 * safe or unknown depending R == 0 or R != 0 conditional.
12950 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
12951 opcode == BPF_JNE);
12952 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
12953 opcode == BPF_JEQ);
12954 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
12955 this_branch, other_branch) &&
12956 is_pointer_value(env, insn->dst_reg)) {
12957 verbose(env, "R%d pointer comparison prohibited\n",
12961 if (env->log.level & BPF_LOG_LEVEL)
12962 print_insn_state(env, this_branch->frame[this_branch->curframe]);
12966 /* verify BPF_LD_IMM64 instruction */
12967 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
12969 struct bpf_insn_aux_data *aux = cur_aux(env);
12970 struct bpf_reg_state *regs = cur_regs(env);
12971 struct bpf_reg_state *dst_reg;
12972 struct bpf_map *map;
12975 if (BPF_SIZE(insn->code) != BPF_DW) {
12976 verbose(env, "invalid BPF_LD_IMM insn\n");
12979 if (insn->off != 0) {
12980 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
12984 err = check_reg_arg(env, insn->dst_reg, DST_OP);
12988 dst_reg = ®s[insn->dst_reg];
12989 if (insn->src_reg == 0) {
12990 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
12992 dst_reg->type = SCALAR_VALUE;
12993 __mark_reg_known(®s[insn->dst_reg], imm);
12997 /* All special src_reg cases are listed below. From this point onwards
12998 * we either succeed and assign a corresponding dst_reg->type after
12999 * zeroing the offset, or fail and reject the program.
13001 mark_reg_known_zero(env, regs, insn->dst_reg);
13003 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
13004 dst_reg->type = aux->btf_var.reg_type;
13005 switch (base_type(dst_reg->type)) {
13007 dst_reg->mem_size = aux->btf_var.mem_size;
13009 case PTR_TO_BTF_ID:
13010 dst_reg->btf = aux->btf_var.btf;
13011 dst_reg->btf_id = aux->btf_var.btf_id;
13014 verbose(env, "bpf verifier is misconfigured\n");
13020 if (insn->src_reg == BPF_PSEUDO_FUNC) {
13021 struct bpf_prog_aux *aux = env->prog->aux;
13022 u32 subprogno = find_subprog(env,
13023 env->insn_idx + insn->imm + 1);
13025 if (!aux->func_info) {
13026 verbose(env, "missing btf func_info\n");
13029 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
13030 verbose(env, "callback function not static\n");
13034 dst_reg->type = PTR_TO_FUNC;
13035 dst_reg->subprogno = subprogno;
13039 map = env->used_maps[aux->map_index];
13040 dst_reg->map_ptr = map;
13042 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
13043 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
13044 dst_reg->type = PTR_TO_MAP_VALUE;
13045 dst_reg->off = aux->map_off;
13046 WARN_ON_ONCE(map->max_entries != 1);
13047 /* We want reg->id to be same (0) as map_value is not distinct */
13048 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
13049 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
13050 dst_reg->type = CONST_PTR_TO_MAP;
13052 verbose(env, "bpf verifier is misconfigured\n");
13059 static bool may_access_skb(enum bpf_prog_type type)
13062 case BPF_PROG_TYPE_SOCKET_FILTER:
13063 case BPF_PROG_TYPE_SCHED_CLS:
13064 case BPF_PROG_TYPE_SCHED_ACT:
13071 /* verify safety of LD_ABS|LD_IND instructions:
13072 * - they can only appear in the programs where ctx == skb
13073 * - since they are wrappers of function calls, they scratch R1-R5 registers,
13074 * preserve R6-R9, and store return value into R0
13077 * ctx == skb == R6 == CTX
13080 * SRC == any register
13081 * IMM == 32-bit immediate
13084 * R0 - 8/16/32-bit skb data converted to cpu endianness
13086 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
13088 struct bpf_reg_state *regs = cur_regs(env);
13089 static const int ctx_reg = BPF_REG_6;
13090 u8 mode = BPF_MODE(insn->code);
13093 if (!may_access_skb(resolve_prog_type(env->prog))) {
13094 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
13098 if (!env->ops->gen_ld_abs) {
13099 verbose(env, "bpf verifier is misconfigured\n");
13103 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
13104 BPF_SIZE(insn->code) == BPF_DW ||
13105 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
13106 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
13110 /* check whether implicit source operand (register R6) is readable */
13111 err = check_reg_arg(env, ctx_reg, SRC_OP);
13115 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
13116 * gen_ld_abs() may terminate the program at runtime, leading to
13119 err = check_reference_leak(env);
13121 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
13125 if (env->cur_state->active_lock.ptr) {
13126 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
13130 if (env->cur_state->active_rcu_lock) {
13131 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
13135 if (regs[ctx_reg].type != PTR_TO_CTX) {
13137 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
13141 if (mode == BPF_IND) {
13142 /* check explicit source operand */
13143 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13148 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
13152 /* reset caller saved regs to unreadable */
13153 for (i = 0; i < CALLER_SAVED_REGS; i++) {
13154 mark_reg_not_init(env, regs, caller_saved[i]);
13155 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
13158 /* mark destination R0 register as readable, since it contains
13159 * the value fetched from the packet.
13160 * Already marked as written above.
13162 mark_reg_unknown(env, regs, BPF_REG_0);
13163 /* ld_abs load up to 32-bit skb data. */
13164 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
13168 static int check_return_code(struct bpf_verifier_env *env)
13170 struct tnum enforce_attach_type_range = tnum_unknown;
13171 const struct bpf_prog *prog = env->prog;
13172 struct bpf_reg_state *reg;
13173 struct tnum range = tnum_range(0, 1);
13174 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13176 struct bpf_func_state *frame = env->cur_state->frame[0];
13177 const bool is_subprog = frame->subprogno;
13179 /* LSM and struct_ops func-ptr's return type could be "void" */
13181 switch (prog_type) {
13182 case BPF_PROG_TYPE_LSM:
13183 if (prog->expected_attach_type == BPF_LSM_CGROUP)
13184 /* See below, can be 0 or 0-1 depending on hook. */
13187 case BPF_PROG_TYPE_STRUCT_OPS:
13188 if (!prog->aux->attach_func_proto->type)
13196 /* eBPF calling convention is such that R0 is used
13197 * to return the value from eBPF program.
13198 * Make sure that it's readable at this time
13199 * of bpf_exit, which means that program wrote
13200 * something into it earlier
13202 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
13206 if (is_pointer_value(env, BPF_REG_0)) {
13207 verbose(env, "R0 leaks addr as return value\n");
13211 reg = cur_regs(env) + BPF_REG_0;
13213 if (frame->in_async_callback_fn) {
13214 /* enforce return zero from async callbacks like timer */
13215 if (reg->type != SCALAR_VALUE) {
13216 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
13217 reg_type_str(env, reg->type));
13221 if (!tnum_in(tnum_const(0), reg->var_off)) {
13222 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
13229 if (reg->type != SCALAR_VALUE) {
13230 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
13231 reg_type_str(env, reg->type));
13237 switch (prog_type) {
13238 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
13239 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
13240 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
13241 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
13242 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
13243 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
13244 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
13245 range = tnum_range(1, 1);
13246 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
13247 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
13248 range = tnum_range(0, 3);
13250 case BPF_PROG_TYPE_CGROUP_SKB:
13251 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
13252 range = tnum_range(0, 3);
13253 enforce_attach_type_range = tnum_range(2, 3);
13256 case BPF_PROG_TYPE_CGROUP_SOCK:
13257 case BPF_PROG_TYPE_SOCK_OPS:
13258 case BPF_PROG_TYPE_CGROUP_DEVICE:
13259 case BPF_PROG_TYPE_CGROUP_SYSCTL:
13260 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
13262 case BPF_PROG_TYPE_RAW_TRACEPOINT:
13263 if (!env->prog->aux->attach_btf_id)
13265 range = tnum_const(0);
13267 case BPF_PROG_TYPE_TRACING:
13268 switch (env->prog->expected_attach_type) {
13269 case BPF_TRACE_FENTRY:
13270 case BPF_TRACE_FEXIT:
13271 range = tnum_const(0);
13273 case BPF_TRACE_RAW_TP:
13274 case BPF_MODIFY_RETURN:
13276 case BPF_TRACE_ITER:
13282 case BPF_PROG_TYPE_SK_LOOKUP:
13283 range = tnum_range(SK_DROP, SK_PASS);
13286 case BPF_PROG_TYPE_LSM:
13287 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
13288 /* Regular BPF_PROG_TYPE_LSM programs can return
13293 if (!env->prog->aux->attach_func_proto->type) {
13294 /* Make sure programs that attach to void
13295 * hooks don't try to modify return value.
13297 range = tnum_range(1, 1);
13301 case BPF_PROG_TYPE_EXT:
13302 /* freplace program can return anything as its return value
13303 * depends on the to-be-replaced kernel func or bpf program.
13309 if (reg->type != SCALAR_VALUE) {
13310 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
13311 reg_type_str(env, reg->type));
13315 if (!tnum_in(range, reg->var_off)) {
13316 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
13317 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
13318 prog_type == BPF_PROG_TYPE_LSM &&
13319 !prog->aux->attach_func_proto->type)
13320 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
13324 if (!tnum_is_unknown(enforce_attach_type_range) &&
13325 tnum_in(enforce_attach_type_range, reg->var_off))
13326 env->prog->enforce_expected_attach_type = 1;
13330 /* non-recursive DFS pseudo code
13331 * 1 procedure DFS-iterative(G,v):
13332 * 2 label v as discovered
13333 * 3 let S be a stack
13335 * 5 while S is not empty
13337 * 7 if t is what we're looking for:
13339 * 9 for all edges e in G.adjacentEdges(t) do
13340 * 10 if edge e is already labelled
13341 * 11 continue with the next edge
13342 * 12 w <- G.adjacentVertex(t,e)
13343 * 13 if vertex w is not discovered and not explored
13344 * 14 label e as tree-edge
13345 * 15 label w as discovered
13348 * 18 else if vertex w is discovered
13349 * 19 label e as back-edge
13351 * 21 // vertex w is explored
13352 * 22 label e as forward- or cross-edge
13353 * 23 label t as explored
13357 * 0x10 - discovered
13358 * 0x11 - discovered and fall-through edge labelled
13359 * 0x12 - discovered and fall-through and branch edges labelled
13370 static u32 state_htab_size(struct bpf_verifier_env *env)
13372 return env->prog->len;
13375 static struct bpf_verifier_state_list **explored_state(
13376 struct bpf_verifier_env *env,
13379 struct bpf_verifier_state *cur = env->cur_state;
13380 struct bpf_func_state *state = cur->frame[cur->curframe];
13382 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
13385 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
13387 env->insn_aux_data[idx].prune_point = true;
13390 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
13392 return env->insn_aux_data[insn_idx].prune_point;
13396 DONE_EXPLORING = 0,
13397 KEEP_EXPLORING = 1,
13400 /* t, w, e - match pseudo-code above:
13401 * t - index of current instruction
13402 * w - next instruction
13405 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
13408 int *insn_stack = env->cfg.insn_stack;
13409 int *insn_state = env->cfg.insn_state;
13411 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
13412 return DONE_EXPLORING;
13414 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
13415 return DONE_EXPLORING;
13417 if (w < 0 || w >= env->prog->len) {
13418 verbose_linfo(env, t, "%d: ", t);
13419 verbose(env, "jump out of range from insn %d to %d\n", t, w);
13424 /* mark branch target for state pruning */
13425 mark_prune_point(env, w);
13426 mark_jmp_point(env, w);
13429 if (insn_state[w] == 0) {
13431 insn_state[t] = DISCOVERED | e;
13432 insn_state[w] = DISCOVERED;
13433 if (env->cfg.cur_stack >= env->prog->len)
13435 insn_stack[env->cfg.cur_stack++] = w;
13436 return KEEP_EXPLORING;
13437 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
13438 if (loop_ok && env->bpf_capable)
13439 return DONE_EXPLORING;
13440 verbose_linfo(env, t, "%d: ", t);
13441 verbose_linfo(env, w, "%d: ", w);
13442 verbose(env, "back-edge from insn %d to %d\n", t, w);
13444 } else if (insn_state[w] == EXPLORED) {
13445 /* forward- or cross-edge */
13446 insn_state[t] = DISCOVERED | e;
13448 verbose(env, "insn state internal bug\n");
13451 return DONE_EXPLORING;
13454 static int visit_func_call_insn(int t, struct bpf_insn *insns,
13455 struct bpf_verifier_env *env,
13460 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
13464 mark_prune_point(env, t + 1);
13465 /* when we exit from subprog, we need to record non-linear history */
13466 mark_jmp_point(env, t + 1);
13468 if (visit_callee) {
13469 mark_prune_point(env, t);
13470 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
13471 /* It's ok to allow recursion from CFG point of
13472 * view. __check_func_call() will do the actual
13475 bpf_pseudo_func(insns + t));
13480 /* Visits the instruction at index t and returns one of the following:
13481 * < 0 - an error occurred
13482 * DONE_EXPLORING - the instruction was fully explored
13483 * KEEP_EXPLORING - there is still work to be done before it is fully explored
13485 static int visit_insn(int t, struct bpf_verifier_env *env)
13487 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
13490 if (bpf_pseudo_func(insn))
13491 return visit_func_call_insn(t, insns, env, true);
13493 /* All non-branch instructions have a single fall-through edge. */
13494 if (BPF_CLASS(insn->code) != BPF_JMP &&
13495 BPF_CLASS(insn->code) != BPF_JMP32)
13496 return push_insn(t, t + 1, FALLTHROUGH, env, false);
13498 switch (BPF_OP(insn->code)) {
13500 return DONE_EXPLORING;
13503 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
13504 /* Mark this call insn as a prune point to trigger
13505 * is_state_visited() check before call itself is
13506 * processed by __check_func_call(). Otherwise new
13507 * async state will be pushed for further exploration.
13509 mark_prune_point(env, t);
13510 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
13513 if (BPF_SRC(insn->code) != BPF_K)
13516 /* unconditional jump with single edge */
13517 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
13522 mark_prune_point(env, t + insn->off + 1);
13523 mark_jmp_point(env, t + insn->off + 1);
13528 /* conditional jump with two edges */
13529 mark_prune_point(env, t);
13531 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
13535 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
13539 /* non-recursive depth-first-search to detect loops in BPF program
13540 * loop == back-edge in directed graph
13542 static int check_cfg(struct bpf_verifier_env *env)
13544 int insn_cnt = env->prog->len;
13545 int *insn_stack, *insn_state;
13549 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
13553 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
13555 kvfree(insn_state);
13559 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
13560 insn_stack[0] = 0; /* 0 is the first instruction */
13561 env->cfg.cur_stack = 1;
13563 while (env->cfg.cur_stack > 0) {
13564 int t = insn_stack[env->cfg.cur_stack - 1];
13566 ret = visit_insn(t, env);
13568 case DONE_EXPLORING:
13569 insn_state[t] = EXPLORED;
13570 env->cfg.cur_stack--;
13572 case KEEP_EXPLORING:
13576 verbose(env, "visit_insn internal bug\n");
13583 if (env->cfg.cur_stack < 0) {
13584 verbose(env, "pop stack internal bug\n");
13589 for (i = 0; i < insn_cnt; i++) {
13590 if (insn_state[i] != EXPLORED) {
13591 verbose(env, "unreachable insn %d\n", i);
13596 ret = 0; /* cfg looks good */
13599 kvfree(insn_state);
13600 kvfree(insn_stack);
13601 env->cfg.insn_state = env->cfg.insn_stack = NULL;
13605 static int check_abnormal_return(struct bpf_verifier_env *env)
13609 for (i = 1; i < env->subprog_cnt; i++) {
13610 if (env->subprog_info[i].has_ld_abs) {
13611 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
13614 if (env->subprog_info[i].has_tail_call) {
13615 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
13622 /* The minimum supported BTF func info size */
13623 #define MIN_BPF_FUNCINFO_SIZE 8
13624 #define MAX_FUNCINFO_REC_SIZE 252
13626 static int check_btf_func(struct bpf_verifier_env *env,
13627 const union bpf_attr *attr,
13630 const struct btf_type *type, *func_proto, *ret_type;
13631 u32 i, nfuncs, urec_size, min_size;
13632 u32 krec_size = sizeof(struct bpf_func_info);
13633 struct bpf_func_info *krecord;
13634 struct bpf_func_info_aux *info_aux = NULL;
13635 struct bpf_prog *prog;
13636 const struct btf *btf;
13638 u32 prev_offset = 0;
13639 bool scalar_return;
13642 nfuncs = attr->func_info_cnt;
13644 if (check_abnormal_return(env))
13649 if (nfuncs != env->subprog_cnt) {
13650 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
13654 urec_size = attr->func_info_rec_size;
13655 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
13656 urec_size > MAX_FUNCINFO_REC_SIZE ||
13657 urec_size % sizeof(u32)) {
13658 verbose(env, "invalid func info rec size %u\n", urec_size);
13663 btf = prog->aux->btf;
13665 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
13666 min_size = min_t(u32, krec_size, urec_size);
13668 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
13671 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
13675 for (i = 0; i < nfuncs; i++) {
13676 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
13678 if (ret == -E2BIG) {
13679 verbose(env, "nonzero tailing record in func info");
13680 /* set the size kernel expects so loader can zero
13681 * out the rest of the record.
13683 if (copy_to_bpfptr_offset(uattr,
13684 offsetof(union bpf_attr, func_info_rec_size),
13685 &min_size, sizeof(min_size)))
13691 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
13696 /* check insn_off */
13699 if (krecord[i].insn_off) {
13701 "nonzero insn_off %u for the first func info record",
13702 krecord[i].insn_off);
13705 } else if (krecord[i].insn_off <= prev_offset) {
13707 "same or smaller insn offset (%u) than previous func info record (%u)",
13708 krecord[i].insn_off, prev_offset);
13712 if (env->subprog_info[i].start != krecord[i].insn_off) {
13713 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
13717 /* check type_id */
13718 type = btf_type_by_id(btf, krecord[i].type_id);
13719 if (!type || !btf_type_is_func(type)) {
13720 verbose(env, "invalid type id %d in func info",
13721 krecord[i].type_id);
13724 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
13726 func_proto = btf_type_by_id(btf, type->type);
13727 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
13728 /* btf_func_check() already verified it during BTF load */
13730 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
13732 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
13733 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
13734 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
13737 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
13738 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
13742 prev_offset = krecord[i].insn_off;
13743 bpfptr_add(&urecord, urec_size);
13746 prog->aux->func_info = krecord;
13747 prog->aux->func_info_cnt = nfuncs;
13748 prog->aux->func_info_aux = info_aux;
13757 static void adjust_btf_func(struct bpf_verifier_env *env)
13759 struct bpf_prog_aux *aux = env->prog->aux;
13762 if (!aux->func_info)
13765 for (i = 0; i < env->subprog_cnt; i++)
13766 aux->func_info[i].insn_off = env->subprog_info[i].start;
13769 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
13770 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
13772 static int check_btf_line(struct bpf_verifier_env *env,
13773 const union bpf_attr *attr,
13776 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
13777 struct bpf_subprog_info *sub;
13778 struct bpf_line_info *linfo;
13779 struct bpf_prog *prog;
13780 const struct btf *btf;
13784 nr_linfo = attr->line_info_cnt;
13787 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
13790 rec_size = attr->line_info_rec_size;
13791 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
13792 rec_size > MAX_LINEINFO_REC_SIZE ||
13793 rec_size & (sizeof(u32) - 1))
13796 /* Need to zero it in case the userspace may
13797 * pass in a smaller bpf_line_info object.
13799 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
13800 GFP_KERNEL | __GFP_NOWARN);
13805 btf = prog->aux->btf;
13808 sub = env->subprog_info;
13809 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
13810 expected_size = sizeof(struct bpf_line_info);
13811 ncopy = min_t(u32, expected_size, rec_size);
13812 for (i = 0; i < nr_linfo; i++) {
13813 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
13815 if (err == -E2BIG) {
13816 verbose(env, "nonzero tailing record in line_info");
13817 if (copy_to_bpfptr_offset(uattr,
13818 offsetof(union bpf_attr, line_info_rec_size),
13819 &expected_size, sizeof(expected_size)))
13825 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
13831 * Check insn_off to ensure
13832 * 1) strictly increasing AND
13833 * 2) bounded by prog->len
13835 * The linfo[0].insn_off == 0 check logically falls into
13836 * the later "missing bpf_line_info for func..." case
13837 * because the first linfo[0].insn_off must be the
13838 * first sub also and the first sub must have
13839 * subprog_info[0].start == 0.
13841 if ((i && linfo[i].insn_off <= prev_offset) ||
13842 linfo[i].insn_off >= prog->len) {
13843 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
13844 i, linfo[i].insn_off, prev_offset,
13850 if (!prog->insnsi[linfo[i].insn_off].code) {
13852 "Invalid insn code at line_info[%u].insn_off\n",
13858 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
13859 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
13860 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
13865 if (s != env->subprog_cnt) {
13866 if (linfo[i].insn_off == sub[s].start) {
13867 sub[s].linfo_idx = i;
13869 } else if (sub[s].start < linfo[i].insn_off) {
13870 verbose(env, "missing bpf_line_info for func#%u\n", s);
13876 prev_offset = linfo[i].insn_off;
13877 bpfptr_add(&ulinfo, rec_size);
13880 if (s != env->subprog_cnt) {
13881 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
13882 env->subprog_cnt - s, s);
13887 prog->aux->linfo = linfo;
13888 prog->aux->nr_linfo = nr_linfo;
13897 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
13898 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
13900 static int check_core_relo(struct bpf_verifier_env *env,
13901 const union bpf_attr *attr,
13904 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
13905 struct bpf_core_relo core_relo = {};
13906 struct bpf_prog *prog = env->prog;
13907 const struct btf *btf = prog->aux->btf;
13908 struct bpf_core_ctx ctx = {
13912 bpfptr_t u_core_relo;
13915 nr_core_relo = attr->core_relo_cnt;
13918 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
13921 rec_size = attr->core_relo_rec_size;
13922 if (rec_size < MIN_CORE_RELO_SIZE ||
13923 rec_size > MAX_CORE_RELO_SIZE ||
13924 rec_size % sizeof(u32))
13927 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
13928 expected_size = sizeof(struct bpf_core_relo);
13929 ncopy = min_t(u32, expected_size, rec_size);
13931 /* Unlike func_info and line_info, copy and apply each CO-RE
13932 * relocation record one at a time.
13934 for (i = 0; i < nr_core_relo; i++) {
13935 /* future proofing when sizeof(bpf_core_relo) changes */
13936 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
13938 if (err == -E2BIG) {
13939 verbose(env, "nonzero tailing record in core_relo");
13940 if (copy_to_bpfptr_offset(uattr,
13941 offsetof(union bpf_attr, core_relo_rec_size),
13942 &expected_size, sizeof(expected_size)))
13948 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
13953 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
13954 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
13955 i, core_relo.insn_off, prog->len);
13960 err = bpf_core_apply(&ctx, &core_relo, i,
13961 &prog->insnsi[core_relo.insn_off / 8]);
13964 bpfptr_add(&u_core_relo, rec_size);
13969 static int check_btf_info(struct bpf_verifier_env *env,
13970 const union bpf_attr *attr,
13976 if (!attr->func_info_cnt && !attr->line_info_cnt) {
13977 if (check_abnormal_return(env))
13982 btf = btf_get_by_fd(attr->prog_btf_fd);
13984 return PTR_ERR(btf);
13985 if (btf_is_kernel(btf)) {
13989 env->prog->aux->btf = btf;
13991 err = check_btf_func(env, attr, uattr);
13995 err = check_btf_line(env, attr, uattr);
13999 err = check_core_relo(env, attr, uattr);
14006 /* check %cur's range satisfies %old's */
14007 static bool range_within(struct bpf_reg_state *old,
14008 struct bpf_reg_state *cur)
14010 return old->umin_value <= cur->umin_value &&
14011 old->umax_value >= cur->umax_value &&
14012 old->smin_value <= cur->smin_value &&
14013 old->smax_value >= cur->smax_value &&
14014 old->u32_min_value <= cur->u32_min_value &&
14015 old->u32_max_value >= cur->u32_max_value &&
14016 old->s32_min_value <= cur->s32_min_value &&
14017 old->s32_max_value >= cur->s32_max_value;
14020 /* If in the old state two registers had the same id, then they need to have
14021 * the same id in the new state as well. But that id could be different from
14022 * the old state, so we need to track the mapping from old to new ids.
14023 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
14024 * regs with old id 5 must also have new id 9 for the new state to be safe. But
14025 * regs with a different old id could still have new id 9, we don't care about
14027 * So we look through our idmap to see if this old id has been seen before. If
14028 * so, we require the new id to match; otherwise, we add the id pair to the map.
14030 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
14034 /* either both IDs should be set or both should be zero */
14035 if (!!old_id != !!cur_id)
14038 if (old_id == 0) /* cur_id == 0 as well */
14041 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
14042 if (!idmap[i].old) {
14043 /* Reached an empty slot; haven't seen this id before */
14044 idmap[i].old = old_id;
14045 idmap[i].cur = cur_id;
14048 if (idmap[i].old == old_id)
14049 return idmap[i].cur == cur_id;
14051 /* We ran out of idmap slots, which should be impossible */
14056 static void clean_func_state(struct bpf_verifier_env *env,
14057 struct bpf_func_state *st)
14059 enum bpf_reg_liveness live;
14062 for (i = 0; i < BPF_REG_FP; i++) {
14063 live = st->regs[i].live;
14064 /* liveness must not touch this register anymore */
14065 st->regs[i].live |= REG_LIVE_DONE;
14066 if (!(live & REG_LIVE_READ))
14067 /* since the register is unused, clear its state
14068 * to make further comparison simpler
14070 __mark_reg_not_init(env, &st->regs[i]);
14073 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
14074 live = st->stack[i].spilled_ptr.live;
14075 /* liveness must not touch this stack slot anymore */
14076 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
14077 if (!(live & REG_LIVE_READ)) {
14078 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
14079 for (j = 0; j < BPF_REG_SIZE; j++)
14080 st->stack[i].slot_type[j] = STACK_INVALID;
14085 static void clean_verifier_state(struct bpf_verifier_env *env,
14086 struct bpf_verifier_state *st)
14090 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
14091 /* all regs in this state in all frames were already marked */
14094 for (i = 0; i <= st->curframe; i++)
14095 clean_func_state(env, st->frame[i]);
14098 /* the parentage chains form a tree.
14099 * the verifier states are added to state lists at given insn and
14100 * pushed into state stack for future exploration.
14101 * when the verifier reaches bpf_exit insn some of the verifer states
14102 * stored in the state lists have their final liveness state already,
14103 * but a lot of states will get revised from liveness point of view when
14104 * the verifier explores other branches.
14107 * 2: if r1 == 100 goto pc+1
14110 * when the verifier reaches exit insn the register r0 in the state list of
14111 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
14112 * of insn 2 and goes exploring further. At the insn 4 it will walk the
14113 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
14115 * Since the verifier pushes the branch states as it sees them while exploring
14116 * the program the condition of walking the branch instruction for the second
14117 * time means that all states below this branch were already explored and
14118 * their final liveness marks are already propagated.
14119 * Hence when the verifier completes the search of state list in is_state_visited()
14120 * we can call this clean_live_states() function to mark all liveness states
14121 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
14122 * will not be used.
14123 * This function also clears the registers and stack for states that !READ
14124 * to simplify state merging.
14126 * Important note here that walking the same branch instruction in the callee
14127 * doesn't meant that the states are DONE. The verifier has to compare
14130 static void clean_live_states(struct bpf_verifier_env *env, int insn,
14131 struct bpf_verifier_state *cur)
14133 struct bpf_verifier_state_list *sl;
14136 sl = *explored_state(env, insn);
14138 if (sl->state.branches)
14140 if (sl->state.insn_idx != insn ||
14141 sl->state.curframe != cur->curframe)
14143 for (i = 0; i <= cur->curframe; i++)
14144 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
14146 clean_verifier_state(env, &sl->state);
14152 static bool regs_exact(const struct bpf_reg_state *rold,
14153 const struct bpf_reg_state *rcur,
14154 struct bpf_id_pair *idmap)
14156 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
14157 check_ids(rold->id, rcur->id, idmap) &&
14158 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
14161 /* Returns true if (rold safe implies rcur safe) */
14162 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
14163 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
14165 if (!(rold->live & REG_LIVE_READ))
14166 /* explored state didn't use this */
14168 if (rold->type == NOT_INIT)
14169 /* explored state can't have used this */
14171 if (rcur->type == NOT_INIT)
14174 /* Enforce that register types have to match exactly, including their
14175 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
14178 * One can make a point that using a pointer register as unbounded
14179 * SCALAR would be technically acceptable, but this could lead to
14180 * pointer leaks because scalars are allowed to leak while pointers
14181 * are not. We could make this safe in special cases if root is
14182 * calling us, but it's probably not worth the hassle.
14184 * Also, register types that are *not* MAYBE_NULL could technically be
14185 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
14186 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
14187 * to the same map).
14188 * However, if the old MAYBE_NULL register then got NULL checked,
14189 * doing so could have affected others with the same id, and we can't
14190 * check for that because we lost the id when we converted to
14191 * a non-MAYBE_NULL variant.
14192 * So, as a general rule we don't allow mixing MAYBE_NULL and
14193 * non-MAYBE_NULL registers as well.
14195 if (rold->type != rcur->type)
14198 switch (base_type(rold->type)) {
14200 if (regs_exact(rold, rcur, idmap))
14202 if (env->explore_alu_limits)
14204 if (!rold->precise)
14206 /* new val must satisfy old val knowledge */
14207 return range_within(rold, rcur) &&
14208 tnum_in(rold->var_off, rcur->var_off);
14209 case PTR_TO_MAP_KEY:
14210 case PTR_TO_MAP_VALUE:
14213 case PTR_TO_TP_BUFFER:
14214 /* If the new min/max/var_off satisfy the old ones and
14215 * everything else matches, we are OK.
14217 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
14218 range_within(rold, rcur) &&
14219 tnum_in(rold->var_off, rcur->var_off) &&
14220 check_ids(rold->id, rcur->id, idmap) &&
14221 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
14222 case PTR_TO_PACKET_META:
14223 case PTR_TO_PACKET:
14224 /* We must have at least as much range as the old ptr
14225 * did, so that any accesses which were safe before are
14226 * still safe. This is true even if old range < old off,
14227 * since someone could have accessed through (ptr - k), or
14228 * even done ptr -= k in a register, to get a safe access.
14230 if (rold->range > rcur->range)
14232 /* If the offsets don't match, we can't trust our alignment;
14233 * nor can we be sure that we won't fall out of range.
14235 if (rold->off != rcur->off)
14237 /* id relations must be preserved */
14238 if (!check_ids(rold->id, rcur->id, idmap))
14240 /* new val must satisfy old val knowledge */
14241 return range_within(rold, rcur) &&
14242 tnum_in(rold->var_off, rcur->var_off);
14244 /* two stack pointers are equal only if they're pointing to
14245 * the same stack frame, since fp-8 in foo != fp-8 in bar
14247 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
14249 return regs_exact(rold, rcur, idmap);
14253 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
14254 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
14258 /* walk slots of the explored stack and ignore any additional
14259 * slots in the current stack, since explored(safe) state
14262 for (i = 0; i < old->allocated_stack; i++) {
14263 spi = i / BPF_REG_SIZE;
14265 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
14266 i += BPF_REG_SIZE - 1;
14267 /* explored state didn't use this */
14271 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
14274 if (env->allow_uninit_stack &&
14275 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
14278 /* explored stack has more populated slots than current stack
14279 * and these slots were used
14281 if (i >= cur->allocated_stack)
14284 /* if old state was safe with misc data in the stack
14285 * it will be safe with zero-initialized stack.
14286 * The opposite is not true
14288 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
14289 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
14291 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
14292 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
14293 /* Ex: old explored (safe) state has STACK_SPILL in
14294 * this stack slot, but current has STACK_MISC ->
14295 * this verifier states are not equivalent,
14296 * return false to continue verification of this path
14299 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
14301 /* Both old and cur are having same slot_type */
14302 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
14304 /* when explored and current stack slot are both storing
14305 * spilled registers, check that stored pointers types
14306 * are the same as well.
14307 * Ex: explored safe path could have stored
14308 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
14309 * but current path has stored:
14310 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
14311 * such verifier states are not equivalent.
14312 * return false to continue verification of this path
14314 if (!regsafe(env, &old->stack[spi].spilled_ptr,
14315 &cur->stack[spi].spilled_ptr, idmap))
14320 const struct bpf_reg_state *old_reg, *cur_reg;
14322 old_reg = &old->stack[spi].spilled_ptr;
14323 cur_reg = &cur->stack[spi].spilled_ptr;
14324 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
14325 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
14326 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
14332 case STACK_INVALID:
14334 /* Ensure that new unhandled slot types return false by default */
14342 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
14343 struct bpf_id_pair *idmap)
14347 if (old->acquired_refs != cur->acquired_refs)
14350 for (i = 0; i < old->acquired_refs; i++) {
14351 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
14358 /* compare two verifier states
14360 * all states stored in state_list are known to be valid, since
14361 * verifier reached 'bpf_exit' instruction through them
14363 * this function is called when verifier exploring different branches of
14364 * execution popped from the state stack. If it sees an old state that has
14365 * more strict register state and more strict stack state then this execution
14366 * branch doesn't need to be explored further, since verifier already
14367 * concluded that more strict state leads to valid finish.
14369 * Therefore two states are equivalent if register state is more conservative
14370 * and explored stack state is more conservative than the current one.
14373 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
14374 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
14376 * In other words if current stack state (one being explored) has more
14377 * valid slots than old one that already passed validation, it means
14378 * the verifier can stop exploring and conclude that current state is valid too
14380 * Similarly with registers. If explored state has register type as invalid
14381 * whereas register type in current state is meaningful, it means that
14382 * the current state will reach 'bpf_exit' instruction safely
14384 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
14385 struct bpf_func_state *cur)
14389 for (i = 0; i < MAX_BPF_REG; i++)
14390 if (!regsafe(env, &old->regs[i], &cur->regs[i],
14391 env->idmap_scratch))
14394 if (!stacksafe(env, old, cur, env->idmap_scratch))
14397 if (!refsafe(old, cur, env->idmap_scratch))
14403 static bool states_equal(struct bpf_verifier_env *env,
14404 struct bpf_verifier_state *old,
14405 struct bpf_verifier_state *cur)
14409 if (old->curframe != cur->curframe)
14412 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
14414 /* Verification state from speculative execution simulation
14415 * must never prune a non-speculative execution one.
14417 if (old->speculative && !cur->speculative)
14420 if (old->active_lock.ptr != cur->active_lock.ptr)
14423 /* Old and cur active_lock's have to be either both present
14426 if (!!old->active_lock.id != !!cur->active_lock.id)
14429 if (old->active_lock.id &&
14430 !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
14433 if (old->active_rcu_lock != cur->active_rcu_lock)
14436 /* for states to be equal callsites have to be the same
14437 * and all frame states need to be equivalent
14439 for (i = 0; i <= old->curframe; i++) {
14440 if (old->frame[i]->callsite != cur->frame[i]->callsite)
14442 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
14448 /* Return 0 if no propagation happened. Return negative error code if error
14449 * happened. Otherwise, return the propagated bit.
14451 static int propagate_liveness_reg(struct bpf_verifier_env *env,
14452 struct bpf_reg_state *reg,
14453 struct bpf_reg_state *parent_reg)
14455 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
14456 u8 flag = reg->live & REG_LIVE_READ;
14459 /* When comes here, read flags of PARENT_REG or REG could be any of
14460 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
14461 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
14463 if (parent_flag == REG_LIVE_READ64 ||
14464 /* Or if there is no read flag from REG. */
14466 /* Or if the read flag from REG is the same as PARENT_REG. */
14467 parent_flag == flag)
14470 err = mark_reg_read(env, reg, parent_reg, flag);
14477 /* A write screens off any subsequent reads; but write marks come from the
14478 * straight-line code between a state and its parent. When we arrive at an
14479 * equivalent state (jump target or such) we didn't arrive by the straight-line
14480 * code, so read marks in the state must propagate to the parent regardless
14481 * of the state's write marks. That's what 'parent == state->parent' comparison
14482 * in mark_reg_read() is for.
14484 static int propagate_liveness(struct bpf_verifier_env *env,
14485 const struct bpf_verifier_state *vstate,
14486 struct bpf_verifier_state *vparent)
14488 struct bpf_reg_state *state_reg, *parent_reg;
14489 struct bpf_func_state *state, *parent;
14490 int i, frame, err = 0;
14492 if (vparent->curframe != vstate->curframe) {
14493 WARN(1, "propagate_live: parent frame %d current frame %d\n",
14494 vparent->curframe, vstate->curframe);
14497 /* Propagate read liveness of registers... */
14498 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
14499 for (frame = 0; frame <= vstate->curframe; frame++) {
14500 parent = vparent->frame[frame];
14501 state = vstate->frame[frame];
14502 parent_reg = parent->regs;
14503 state_reg = state->regs;
14504 /* We don't need to worry about FP liveness, it's read-only */
14505 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
14506 err = propagate_liveness_reg(env, &state_reg[i],
14510 if (err == REG_LIVE_READ64)
14511 mark_insn_zext(env, &parent_reg[i]);
14514 /* Propagate stack slots. */
14515 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
14516 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
14517 parent_reg = &parent->stack[i].spilled_ptr;
14518 state_reg = &state->stack[i].spilled_ptr;
14519 err = propagate_liveness_reg(env, state_reg,
14528 /* find precise scalars in the previous equivalent state and
14529 * propagate them into the current state
14531 static int propagate_precision(struct bpf_verifier_env *env,
14532 const struct bpf_verifier_state *old)
14534 struct bpf_reg_state *state_reg;
14535 struct bpf_func_state *state;
14536 int i, err = 0, fr;
14538 for (fr = old->curframe; fr >= 0; fr--) {
14539 state = old->frame[fr];
14540 state_reg = state->regs;
14541 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
14542 if (state_reg->type != SCALAR_VALUE ||
14543 !state_reg->precise)
14545 if (env->log.level & BPF_LOG_LEVEL2)
14546 verbose(env, "frame %d: propagating r%d\n", i, fr);
14547 err = mark_chain_precision_frame(env, fr, i);
14552 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
14553 if (!is_spilled_reg(&state->stack[i]))
14555 state_reg = &state->stack[i].spilled_ptr;
14556 if (state_reg->type != SCALAR_VALUE ||
14557 !state_reg->precise)
14559 if (env->log.level & BPF_LOG_LEVEL2)
14560 verbose(env, "frame %d: propagating fp%d\n",
14561 (-i - 1) * BPF_REG_SIZE, fr);
14562 err = mark_chain_precision_stack_frame(env, fr, i);
14570 static bool states_maybe_looping(struct bpf_verifier_state *old,
14571 struct bpf_verifier_state *cur)
14573 struct bpf_func_state *fold, *fcur;
14574 int i, fr = cur->curframe;
14576 if (old->curframe != fr)
14579 fold = old->frame[fr];
14580 fcur = cur->frame[fr];
14581 for (i = 0; i < MAX_BPF_REG; i++)
14582 if (memcmp(&fold->regs[i], &fcur->regs[i],
14583 offsetof(struct bpf_reg_state, parent)))
14589 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
14591 struct bpf_verifier_state_list *new_sl;
14592 struct bpf_verifier_state_list *sl, **pprev;
14593 struct bpf_verifier_state *cur = env->cur_state, *new;
14594 int i, j, err, states_cnt = 0;
14595 bool add_new_state = env->test_state_freq ? true : false;
14597 /* bpf progs typically have pruning point every 4 instructions
14598 * http://vger.kernel.org/bpfconf2019.html#session-1
14599 * Do not add new state for future pruning if the verifier hasn't seen
14600 * at least 2 jumps and at least 8 instructions.
14601 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
14602 * In tests that amounts to up to 50% reduction into total verifier
14603 * memory consumption and 20% verifier time speedup.
14605 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
14606 env->insn_processed - env->prev_insn_processed >= 8)
14607 add_new_state = true;
14609 pprev = explored_state(env, insn_idx);
14612 clean_live_states(env, insn_idx, cur);
14616 if (sl->state.insn_idx != insn_idx)
14619 if (sl->state.branches) {
14620 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
14622 if (frame->in_async_callback_fn &&
14623 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
14624 /* Different async_entry_cnt means that the verifier is
14625 * processing another entry into async callback.
14626 * Seeing the same state is not an indication of infinite
14627 * loop or infinite recursion.
14628 * But finding the same state doesn't mean that it's safe
14629 * to stop processing the current state. The previous state
14630 * hasn't yet reached bpf_exit, since state.branches > 0.
14631 * Checking in_async_callback_fn alone is not enough either.
14632 * Since the verifier still needs to catch infinite loops
14633 * inside async callbacks.
14635 } else if (states_maybe_looping(&sl->state, cur) &&
14636 states_equal(env, &sl->state, cur)) {
14637 verbose_linfo(env, insn_idx, "; ");
14638 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
14641 /* if the verifier is processing a loop, avoid adding new state
14642 * too often, since different loop iterations have distinct
14643 * states and may not help future pruning.
14644 * This threshold shouldn't be too low to make sure that
14645 * a loop with large bound will be rejected quickly.
14646 * The most abusive loop will be:
14648 * if r1 < 1000000 goto pc-2
14649 * 1M insn_procssed limit / 100 == 10k peak states.
14650 * This threshold shouldn't be too high either, since states
14651 * at the end of the loop are likely to be useful in pruning.
14653 if (!env->test_state_freq &&
14654 env->jmps_processed - env->prev_jmps_processed < 20 &&
14655 env->insn_processed - env->prev_insn_processed < 100)
14656 add_new_state = false;
14659 if (states_equal(env, &sl->state, cur)) {
14661 /* reached equivalent register/stack state,
14662 * prune the search.
14663 * Registers read by the continuation are read by us.
14664 * If we have any write marks in env->cur_state, they
14665 * will prevent corresponding reads in the continuation
14666 * from reaching our parent (an explored_state). Our
14667 * own state will get the read marks recorded, but
14668 * they'll be immediately forgotten as we're pruning
14669 * this state and will pop a new one.
14671 err = propagate_liveness(env, &sl->state, cur);
14673 /* if previous state reached the exit with precision and
14674 * current state is equivalent to it (except precsion marks)
14675 * the precision needs to be propagated back in
14676 * the current state.
14678 err = err ? : push_jmp_history(env, cur);
14679 err = err ? : propagate_precision(env, &sl->state);
14685 /* when new state is not going to be added do not increase miss count.
14686 * Otherwise several loop iterations will remove the state
14687 * recorded earlier. The goal of these heuristics is to have
14688 * states from some iterations of the loop (some in the beginning
14689 * and some at the end) to help pruning.
14693 /* heuristic to determine whether this state is beneficial
14694 * to keep checking from state equivalence point of view.
14695 * Higher numbers increase max_states_per_insn and verification time,
14696 * but do not meaningfully decrease insn_processed.
14698 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
14699 /* the state is unlikely to be useful. Remove it to
14700 * speed up verification
14703 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
14704 u32 br = sl->state.branches;
14707 "BUG live_done but branches_to_explore %d\n",
14709 free_verifier_state(&sl->state, false);
14711 env->peak_states--;
14713 /* cannot free this state, since parentage chain may
14714 * walk it later. Add it for free_list instead to
14715 * be freed at the end of verification
14717 sl->next = env->free_list;
14718 env->free_list = sl;
14728 if (env->max_states_per_insn < states_cnt)
14729 env->max_states_per_insn = states_cnt;
14731 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
14734 if (!add_new_state)
14737 /* There were no equivalent states, remember the current one.
14738 * Technically the current state is not proven to be safe yet,
14739 * but it will either reach outer most bpf_exit (which means it's safe)
14740 * or it will be rejected. When there are no loops the verifier won't be
14741 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
14742 * again on the way to bpf_exit.
14743 * When looping the sl->state.branches will be > 0 and this state
14744 * will not be considered for equivalence until branches == 0.
14746 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
14749 env->total_states++;
14750 env->peak_states++;
14751 env->prev_jmps_processed = env->jmps_processed;
14752 env->prev_insn_processed = env->insn_processed;
14754 /* forget precise markings we inherited, see __mark_chain_precision */
14755 if (env->bpf_capable)
14756 mark_all_scalars_imprecise(env, cur);
14758 /* add new state to the head of linked list */
14759 new = &new_sl->state;
14760 err = copy_verifier_state(new, cur);
14762 free_verifier_state(new, false);
14766 new->insn_idx = insn_idx;
14767 WARN_ONCE(new->branches != 1,
14768 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
14771 cur->first_insn_idx = insn_idx;
14772 clear_jmp_history(cur);
14773 new_sl->next = *explored_state(env, insn_idx);
14774 *explored_state(env, insn_idx) = new_sl;
14775 /* connect new state to parentage chain. Current frame needs all
14776 * registers connected. Only r6 - r9 of the callers are alive (pushed
14777 * to the stack implicitly by JITs) so in callers' frames connect just
14778 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
14779 * the state of the call instruction (with WRITTEN set), and r0 comes
14780 * from callee with its full parentage chain, anyway.
14782 /* clear write marks in current state: the writes we did are not writes
14783 * our child did, so they don't screen off its reads from us.
14784 * (There are no read marks in current state, because reads always mark
14785 * their parent and current state never has children yet. Only
14786 * explored_states can get read marks.)
14788 for (j = 0; j <= cur->curframe; j++) {
14789 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
14790 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
14791 for (i = 0; i < BPF_REG_FP; i++)
14792 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
14795 /* all stack frames are accessible from callee, clear them all */
14796 for (j = 0; j <= cur->curframe; j++) {
14797 struct bpf_func_state *frame = cur->frame[j];
14798 struct bpf_func_state *newframe = new->frame[j];
14800 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
14801 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
14802 frame->stack[i].spilled_ptr.parent =
14803 &newframe->stack[i].spilled_ptr;
14809 /* Return true if it's OK to have the same insn return a different type. */
14810 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
14812 switch (base_type(type)) {
14814 case PTR_TO_SOCKET:
14815 case PTR_TO_SOCK_COMMON:
14816 case PTR_TO_TCP_SOCK:
14817 case PTR_TO_XDP_SOCK:
14818 case PTR_TO_BTF_ID:
14825 /* If an instruction was previously used with particular pointer types, then we
14826 * need to be careful to avoid cases such as the below, where it may be ok
14827 * for one branch accessing the pointer, but not ok for the other branch:
14832 * R1 = some_other_valid_ptr;
14835 * R2 = *(u32 *)(R1 + 0);
14837 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
14839 return src != prev && (!reg_type_mismatch_ok(src) ||
14840 !reg_type_mismatch_ok(prev));
14843 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
14844 bool allow_trust_missmatch)
14846 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
14848 if (*prev_type == NOT_INIT) {
14849 /* Saw a valid insn
14850 * dst_reg = *(u32 *)(src_reg + off)
14851 * save type to validate intersecting paths
14854 } else if (reg_type_mismatch(type, *prev_type)) {
14855 /* Abuser program is trying to use the same insn
14856 * dst_reg = *(u32*) (src_reg + off)
14857 * with different pointer types:
14858 * src_reg == ctx in one branch and
14859 * src_reg == stack|map in some other branch.
14862 if (allow_trust_missmatch &&
14863 base_type(type) == PTR_TO_BTF_ID &&
14864 base_type(*prev_type) == PTR_TO_BTF_ID) {
14866 * Have to support a use case when one path through
14867 * the program yields TRUSTED pointer while another
14868 * is UNTRUSTED. Fallback to UNTRUSTED to generate
14871 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
14873 verbose(env, "same insn cannot be used with different pointers\n");
14881 static int do_check(struct bpf_verifier_env *env)
14883 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14884 struct bpf_verifier_state *state = env->cur_state;
14885 struct bpf_insn *insns = env->prog->insnsi;
14886 struct bpf_reg_state *regs;
14887 int insn_cnt = env->prog->len;
14888 bool do_print_state = false;
14889 int prev_insn_idx = -1;
14892 struct bpf_insn *insn;
14896 env->prev_insn_idx = prev_insn_idx;
14897 if (env->insn_idx >= insn_cnt) {
14898 verbose(env, "invalid insn idx %d insn_cnt %d\n",
14899 env->insn_idx, insn_cnt);
14903 insn = &insns[env->insn_idx];
14904 class = BPF_CLASS(insn->code);
14906 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
14908 "BPF program is too large. Processed %d insn\n",
14909 env->insn_processed);
14913 state->last_insn_idx = env->prev_insn_idx;
14915 if (is_prune_point(env, env->insn_idx)) {
14916 err = is_state_visited(env, env->insn_idx);
14920 /* found equivalent state, can prune the search */
14921 if (env->log.level & BPF_LOG_LEVEL) {
14922 if (do_print_state)
14923 verbose(env, "\nfrom %d to %d%s: safe\n",
14924 env->prev_insn_idx, env->insn_idx,
14925 env->cur_state->speculative ?
14926 " (speculative execution)" : "");
14928 verbose(env, "%d: safe\n", env->insn_idx);
14930 goto process_bpf_exit;
14934 if (is_jmp_point(env, env->insn_idx)) {
14935 err = push_jmp_history(env, state);
14940 if (signal_pending(current))
14943 if (need_resched())
14946 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
14947 verbose(env, "\nfrom %d to %d%s:",
14948 env->prev_insn_idx, env->insn_idx,
14949 env->cur_state->speculative ?
14950 " (speculative execution)" : "");
14951 print_verifier_state(env, state->frame[state->curframe], true);
14952 do_print_state = false;
14955 if (env->log.level & BPF_LOG_LEVEL) {
14956 const struct bpf_insn_cbs cbs = {
14957 .cb_call = disasm_kfunc_name,
14958 .cb_print = verbose,
14959 .private_data = env,
14962 if (verifier_state_scratched(env))
14963 print_insn_state(env, state->frame[state->curframe]);
14965 verbose_linfo(env, env->insn_idx, "; ");
14966 env->prev_log_len = env->log.len_used;
14967 verbose(env, "%d: ", env->insn_idx);
14968 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
14969 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
14970 env->prev_log_len = env->log.len_used;
14973 if (bpf_prog_is_offloaded(env->prog->aux)) {
14974 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
14975 env->prev_insn_idx);
14980 regs = cur_regs(env);
14981 sanitize_mark_insn_seen(env);
14982 prev_insn_idx = env->insn_idx;
14984 if (class == BPF_ALU || class == BPF_ALU64) {
14985 err = check_alu_op(env, insn);
14989 } else if (class == BPF_LDX) {
14990 enum bpf_reg_type src_reg_type;
14992 /* check for reserved fields is already done */
14994 /* check src operand */
14995 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14999 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15003 src_reg_type = regs[insn->src_reg].type;
15005 /* check that memory (src_reg + off) is readable,
15006 * the state of dst_reg will be updated by this func
15008 err = check_mem_access(env, env->insn_idx, insn->src_reg,
15009 insn->off, BPF_SIZE(insn->code),
15010 BPF_READ, insn->dst_reg, false);
15014 err = save_aux_ptr_type(env, src_reg_type, true);
15017 } else if (class == BPF_STX) {
15018 enum bpf_reg_type dst_reg_type;
15020 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
15021 err = check_atomic(env, env->insn_idx, insn);
15028 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
15029 verbose(env, "BPF_STX uses reserved fields\n");
15033 /* check src1 operand */
15034 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15037 /* check src2 operand */
15038 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15042 dst_reg_type = regs[insn->dst_reg].type;
15044 /* check that memory (dst_reg + off) is writeable */
15045 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15046 insn->off, BPF_SIZE(insn->code),
15047 BPF_WRITE, insn->src_reg, false);
15051 err = save_aux_ptr_type(env, dst_reg_type, false);
15054 } else if (class == BPF_ST) {
15055 enum bpf_reg_type dst_reg_type;
15057 if (BPF_MODE(insn->code) != BPF_MEM ||
15058 insn->src_reg != BPF_REG_0) {
15059 verbose(env, "BPF_ST uses reserved fields\n");
15062 /* check src operand */
15063 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15067 dst_reg_type = regs[insn->dst_reg].type;
15069 /* check that memory (dst_reg + off) is writeable */
15070 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15071 insn->off, BPF_SIZE(insn->code),
15072 BPF_WRITE, -1, false);
15076 err = save_aux_ptr_type(env, dst_reg_type, false);
15079 } else if (class == BPF_JMP || class == BPF_JMP32) {
15080 u8 opcode = BPF_OP(insn->code);
15082 env->jmps_processed++;
15083 if (opcode == BPF_CALL) {
15084 if (BPF_SRC(insn->code) != BPF_K ||
15085 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
15086 && insn->off != 0) ||
15087 (insn->src_reg != BPF_REG_0 &&
15088 insn->src_reg != BPF_PSEUDO_CALL &&
15089 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
15090 insn->dst_reg != BPF_REG_0 ||
15091 class == BPF_JMP32) {
15092 verbose(env, "BPF_CALL uses reserved fields\n");
15096 if (env->cur_state->active_lock.ptr) {
15097 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
15098 (insn->src_reg == BPF_PSEUDO_CALL) ||
15099 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
15100 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
15101 verbose(env, "function calls are not allowed while holding a lock\n");
15105 if (insn->src_reg == BPF_PSEUDO_CALL)
15106 err = check_func_call(env, insn, &env->insn_idx);
15107 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
15108 err = check_kfunc_call(env, insn, &env->insn_idx);
15110 err = check_helper_call(env, insn, &env->insn_idx);
15114 mark_reg_scratched(env, BPF_REG_0);
15115 } else if (opcode == BPF_JA) {
15116 if (BPF_SRC(insn->code) != BPF_K ||
15118 insn->src_reg != BPF_REG_0 ||
15119 insn->dst_reg != BPF_REG_0 ||
15120 class == BPF_JMP32) {
15121 verbose(env, "BPF_JA uses reserved fields\n");
15125 env->insn_idx += insn->off + 1;
15128 } else if (opcode == BPF_EXIT) {
15129 if (BPF_SRC(insn->code) != BPF_K ||
15131 insn->src_reg != BPF_REG_0 ||
15132 insn->dst_reg != BPF_REG_0 ||
15133 class == BPF_JMP32) {
15134 verbose(env, "BPF_EXIT uses reserved fields\n");
15138 if (env->cur_state->active_lock.ptr &&
15139 !in_rbtree_lock_required_cb(env)) {
15140 verbose(env, "bpf_spin_unlock is missing\n");
15144 if (env->cur_state->active_rcu_lock) {
15145 verbose(env, "bpf_rcu_read_unlock is missing\n");
15149 /* We must do check_reference_leak here before
15150 * prepare_func_exit to handle the case when
15151 * state->curframe > 0, it may be a callback
15152 * function, for which reference_state must
15153 * match caller reference state when it exits.
15155 err = check_reference_leak(env);
15159 if (state->curframe) {
15160 /* exit from nested function */
15161 err = prepare_func_exit(env, &env->insn_idx);
15164 do_print_state = true;
15168 err = check_return_code(env);
15172 mark_verifier_state_scratched(env);
15173 update_branch_counts(env, env->cur_state);
15174 err = pop_stack(env, &prev_insn_idx,
15175 &env->insn_idx, pop_log);
15177 if (err != -ENOENT)
15181 do_print_state = true;
15185 err = check_cond_jmp_op(env, insn, &env->insn_idx);
15189 } else if (class == BPF_LD) {
15190 u8 mode = BPF_MODE(insn->code);
15192 if (mode == BPF_ABS || mode == BPF_IND) {
15193 err = check_ld_abs(env, insn);
15197 } else if (mode == BPF_IMM) {
15198 err = check_ld_imm(env, insn);
15203 sanitize_mark_insn_seen(env);
15205 verbose(env, "invalid BPF_LD mode\n");
15209 verbose(env, "unknown insn class %d\n", class);
15219 static int find_btf_percpu_datasec(struct btf *btf)
15221 const struct btf_type *t;
15226 * Both vmlinux and module each have their own ".data..percpu"
15227 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
15228 * types to look at only module's own BTF types.
15230 n = btf_nr_types(btf);
15231 if (btf_is_module(btf))
15232 i = btf_nr_types(btf_vmlinux);
15236 for(; i < n; i++) {
15237 t = btf_type_by_id(btf, i);
15238 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
15241 tname = btf_name_by_offset(btf, t->name_off);
15242 if (!strcmp(tname, ".data..percpu"))
15249 /* replace pseudo btf_id with kernel symbol address */
15250 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
15251 struct bpf_insn *insn,
15252 struct bpf_insn_aux_data *aux)
15254 const struct btf_var_secinfo *vsi;
15255 const struct btf_type *datasec;
15256 struct btf_mod_pair *btf_mod;
15257 const struct btf_type *t;
15258 const char *sym_name;
15259 bool percpu = false;
15260 u32 type, id = insn->imm;
15264 int i, btf_fd, err;
15266 btf_fd = insn[1].imm;
15268 btf = btf_get_by_fd(btf_fd);
15270 verbose(env, "invalid module BTF object FD specified.\n");
15274 if (!btf_vmlinux) {
15275 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
15282 t = btf_type_by_id(btf, id);
15284 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
15289 if (!btf_type_is_var(t)) {
15290 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
15295 sym_name = btf_name_by_offset(btf, t->name_off);
15296 addr = kallsyms_lookup_name(sym_name);
15298 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
15304 datasec_id = find_btf_percpu_datasec(btf);
15305 if (datasec_id > 0) {
15306 datasec = btf_type_by_id(btf, datasec_id);
15307 for_each_vsi(i, datasec, vsi) {
15308 if (vsi->type == id) {
15315 insn[0].imm = (u32)addr;
15316 insn[1].imm = addr >> 32;
15319 t = btf_type_skip_modifiers(btf, type, NULL);
15321 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
15322 aux->btf_var.btf = btf;
15323 aux->btf_var.btf_id = type;
15324 } else if (!btf_type_is_struct(t)) {
15325 const struct btf_type *ret;
15329 /* resolve the type size of ksym. */
15330 ret = btf_resolve_size(btf, t, &tsize);
15332 tname = btf_name_by_offset(btf, t->name_off);
15333 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
15334 tname, PTR_ERR(ret));
15338 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
15339 aux->btf_var.mem_size = tsize;
15341 aux->btf_var.reg_type = PTR_TO_BTF_ID;
15342 aux->btf_var.btf = btf;
15343 aux->btf_var.btf_id = type;
15346 /* check whether we recorded this BTF (and maybe module) already */
15347 for (i = 0; i < env->used_btf_cnt; i++) {
15348 if (env->used_btfs[i].btf == btf) {
15354 if (env->used_btf_cnt >= MAX_USED_BTFS) {
15359 btf_mod = &env->used_btfs[env->used_btf_cnt];
15360 btf_mod->btf = btf;
15361 btf_mod->module = NULL;
15363 /* if we reference variables from kernel module, bump its refcount */
15364 if (btf_is_module(btf)) {
15365 btf_mod->module = btf_try_get_module(btf);
15366 if (!btf_mod->module) {
15372 env->used_btf_cnt++;
15380 static bool is_tracing_prog_type(enum bpf_prog_type type)
15383 case BPF_PROG_TYPE_KPROBE:
15384 case BPF_PROG_TYPE_TRACEPOINT:
15385 case BPF_PROG_TYPE_PERF_EVENT:
15386 case BPF_PROG_TYPE_RAW_TRACEPOINT:
15387 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
15394 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
15395 struct bpf_map *map,
15396 struct bpf_prog *prog)
15399 enum bpf_prog_type prog_type = resolve_prog_type(prog);
15401 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
15402 btf_record_has_field(map->record, BPF_RB_ROOT)) {
15403 if (is_tracing_prog_type(prog_type)) {
15404 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
15409 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
15410 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
15411 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
15415 if (is_tracing_prog_type(prog_type)) {
15416 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
15420 if (prog->aux->sleepable) {
15421 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
15426 if (btf_record_has_field(map->record, BPF_TIMER)) {
15427 if (is_tracing_prog_type(prog_type)) {
15428 verbose(env, "tracing progs cannot use bpf_timer yet\n");
15433 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
15434 !bpf_offload_prog_map_match(prog, map)) {
15435 verbose(env, "offload device mismatch between prog and map\n");
15439 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
15440 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
15444 if (prog->aux->sleepable)
15445 switch (map->map_type) {
15446 case BPF_MAP_TYPE_HASH:
15447 case BPF_MAP_TYPE_LRU_HASH:
15448 case BPF_MAP_TYPE_ARRAY:
15449 case BPF_MAP_TYPE_PERCPU_HASH:
15450 case BPF_MAP_TYPE_PERCPU_ARRAY:
15451 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
15452 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
15453 case BPF_MAP_TYPE_HASH_OF_MAPS:
15454 case BPF_MAP_TYPE_RINGBUF:
15455 case BPF_MAP_TYPE_USER_RINGBUF:
15456 case BPF_MAP_TYPE_INODE_STORAGE:
15457 case BPF_MAP_TYPE_SK_STORAGE:
15458 case BPF_MAP_TYPE_TASK_STORAGE:
15459 case BPF_MAP_TYPE_CGRP_STORAGE:
15463 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
15470 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
15472 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
15473 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
15476 /* find and rewrite pseudo imm in ld_imm64 instructions:
15478 * 1. if it accesses map FD, replace it with actual map pointer.
15479 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
15481 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
15483 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
15485 struct bpf_insn *insn = env->prog->insnsi;
15486 int insn_cnt = env->prog->len;
15489 err = bpf_prog_calc_tag(env->prog);
15493 for (i = 0; i < insn_cnt; i++, insn++) {
15494 if (BPF_CLASS(insn->code) == BPF_LDX &&
15495 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
15496 verbose(env, "BPF_LDX uses reserved fields\n");
15500 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
15501 struct bpf_insn_aux_data *aux;
15502 struct bpf_map *map;
15507 if (i == insn_cnt - 1 || insn[1].code != 0 ||
15508 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
15509 insn[1].off != 0) {
15510 verbose(env, "invalid bpf_ld_imm64 insn\n");
15514 if (insn[0].src_reg == 0)
15515 /* valid generic load 64-bit imm */
15518 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
15519 aux = &env->insn_aux_data[i];
15520 err = check_pseudo_btf_id(env, insn, aux);
15526 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
15527 aux = &env->insn_aux_data[i];
15528 aux->ptr_type = PTR_TO_FUNC;
15532 /* In final convert_pseudo_ld_imm64() step, this is
15533 * converted into regular 64-bit imm load insn.
15535 switch (insn[0].src_reg) {
15536 case BPF_PSEUDO_MAP_VALUE:
15537 case BPF_PSEUDO_MAP_IDX_VALUE:
15539 case BPF_PSEUDO_MAP_FD:
15540 case BPF_PSEUDO_MAP_IDX:
15541 if (insn[1].imm == 0)
15545 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
15549 switch (insn[0].src_reg) {
15550 case BPF_PSEUDO_MAP_IDX_VALUE:
15551 case BPF_PSEUDO_MAP_IDX:
15552 if (bpfptr_is_null(env->fd_array)) {
15553 verbose(env, "fd_idx without fd_array is invalid\n");
15556 if (copy_from_bpfptr_offset(&fd, env->fd_array,
15557 insn[0].imm * sizeof(fd),
15567 map = __bpf_map_get(f);
15569 verbose(env, "fd %d is not pointing to valid bpf_map\n",
15571 return PTR_ERR(map);
15574 err = check_map_prog_compatibility(env, map, env->prog);
15580 aux = &env->insn_aux_data[i];
15581 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
15582 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
15583 addr = (unsigned long)map;
15585 u32 off = insn[1].imm;
15587 if (off >= BPF_MAX_VAR_OFF) {
15588 verbose(env, "direct value offset of %u is not allowed\n", off);
15593 if (!map->ops->map_direct_value_addr) {
15594 verbose(env, "no direct value access support for this map type\n");
15599 err = map->ops->map_direct_value_addr(map, &addr, off);
15601 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
15602 map->value_size, off);
15607 aux->map_off = off;
15611 insn[0].imm = (u32)addr;
15612 insn[1].imm = addr >> 32;
15614 /* check whether we recorded this map already */
15615 for (j = 0; j < env->used_map_cnt; j++) {
15616 if (env->used_maps[j] == map) {
15617 aux->map_index = j;
15623 if (env->used_map_cnt >= MAX_USED_MAPS) {
15628 /* hold the map. If the program is rejected by verifier,
15629 * the map will be released by release_maps() or it
15630 * will be used by the valid program until it's unloaded
15631 * and all maps are released in free_used_maps()
15635 aux->map_index = env->used_map_cnt;
15636 env->used_maps[env->used_map_cnt++] = map;
15638 if (bpf_map_is_cgroup_storage(map) &&
15639 bpf_cgroup_storage_assign(env->prog->aux, map)) {
15640 verbose(env, "only one cgroup storage of each type is allowed\n");
15652 /* Basic sanity check before we invest more work here. */
15653 if (!bpf_opcode_in_insntable(insn->code)) {
15654 verbose(env, "unknown opcode %02x\n", insn->code);
15659 /* now all pseudo BPF_LD_IMM64 instructions load valid
15660 * 'struct bpf_map *' into a register instead of user map_fd.
15661 * These pointers will be used later by verifier to validate map access.
15666 /* drop refcnt of maps used by the rejected program */
15667 static void release_maps(struct bpf_verifier_env *env)
15669 __bpf_free_used_maps(env->prog->aux, env->used_maps,
15670 env->used_map_cnt);
15673 /* drop refcnt of maps used by the rejected program */
15674 static void release_btfs(struct bpf_verifier_env *env)
15676 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
15677 env->used_btf_cnt);
15680 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
15681 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
15683 struct bpf_insn *insn = env->prog->insnsi;
15684 int insn_cnt = env->prog->len;
15687 for (i = 0; i < insn_cnt; i++, insn++) {
15688 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
15690 if (insn->src_reg == BPF_PSEUDO_FUNC)
15696 /* single env->prog->insni[off] instruction was replaced with the range
15697 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
15698 * [0, off) and [off, end) to new locations, so the patched range stays zero
15700 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
15701 struct bpf_insn_aux_data *new_data,
15702 struct bpf_prog *new_prog, u32 off, u32 cnt)
15704 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
15705 struct bpf_insn *insn = new_prog->insnsi;
15706 u32 old_seen = old_data[off].seen;
15710 /* aux info at OFF always needs adjustment, no matter fast path
15711 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
15712 * original insn at old prog.
15714 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
15718 prog_len = new_prog->len;
15720 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
15721 memcpy(new_data + off + cnt - 1, old_data + off,
15722 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
15723 for (i = off; i < off + cnt - 1; i++) {
15724 /* Expand insni[off]'s seen count to the patched range. */
15725 new_data[i].seen = old_seen;
15726 new_data[i].zext_dst = insn_has_def32(env, insn + i);
15728 env->insn_aux_data = new_data;
15732 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
15738 /* NOTE: fake 'exit' subprog should be updated as well. */
15739 for (i = 0; i <= env->subprog_cnt; i++) {
15740 if (env->subprog_info[i].start <= off)
15742 env->subprog_info[i].start += len - 1;
15746 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
15748 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
15749 int i, sz = prog->aux->size_poke_tab;
15750 struct bpf_jit_poke_descriptor *desc;
15752 for (i = 0; i < sz; i++) {
15754 if (desc->insn_idx <= off)
15756 desc->insn_idx += len - 1;
15760 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
15761 const struct bpf_insn *patch, u32 len)
15763 struct bpf_prog *new_prog;
15764 struct bpf_insn_aux_data *new_data = NULL;
15767 new_data = vzalloc(array_size(env->prog->len + len - 1,
15768 sizeof(struct bpf_insn_aux_data)));
15773 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
15774 if (IS_ERR(new_prog)) {
15775 if (PTR_ERR(new_prog) == -ERANGE)
15777 "insn %d cannot be patched due to 16-bit range\n",
15778 env->insn_aux_data[off].orig_idx);
15782 adjust_insn_aux_data(env, new_data, new_prog, off, len);
15783 adjust_subprog_starts(env, off, len);
15784 adjust_poke_descs(new_prog, off, len);
15788 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
15793 /* find first prog starting at or after off (first to remove) */
15794 for (i = 0; i < env->subprog_cnt; i++)
15795 if (env->subprog_info[i].start >= off)
15797 /* find first prog starting at or after off + cnt (first to stay) */
15798 for (j = i; j < env->subprog_cnt; j++)
15799 if (env->subprog_info[j].start >= off + cnt)
15801 /* if j doesn't start exactly at off + cnt, we are just removing
15802 * the front of previous prog
15804 if (env->subprog_info[j].start != off + cnt)
15808 struct bpf_prog_aux *aux = env->prog->aux;
15811 /* move fake 'exit' subprog as well */
15812 move = env->subprog_cnt + 1 - j;
15814 memmove(env->subprog_info + i,
15815 env->subprog_info + j,
15816 sizeof(*env->subprog_info) * move);
15817 env->subprog_cnt -= j - i;
15819 /* remove func_info */
15820 if (aux->func_info) {
15821 move = aux->func_info_cnt - j;
15823 memmove(aux->func_info + i,
15824 aux->func_info + j,
15825 sizeof(*aux->func_info) * move);
15826 aux->func_info_cnt -= j - i;
15827 /* func_info->insn_off is set after all code rewrites,
15828 * in adjust_btf_func() - no need to adjust
15832 /* convert i from "first prog to remove" to "first to adjust" */
15833 if (env->subprog_info[i].start == off)
15837 /* update fake 'exit' subprog as well */
15838 for (; i <= env->subprog_cnt; i++)
15839 env->subprog_info[i].start -= cnt;
15844 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
15847 struct bpf_prog *prog = env->prog;
15848 u32 i, l_off, l_cnt, nr_linfo;
15849 struct bpf_line_info *linfo;
15851 nr_linfo = prog->aux->nr_linfo;
15855 linfo = prog->aux->linfo;
15857 /* find first line info to remove, count lines to be removed */
15858 for (i = 0; i < nr_linfo; i++)
15859 if (linfo[i].insn_off >= off)
15864 for (; i < nr_linfo; i++)
15865 if (linfo[i].insn_off < off + cnt)
15870 /* First live insn doesn't match first live linfo, it needs to "inherit"
15871 * last removed linfo. prog is already modified, so prog->len == off
15872 * means no live instructions after (tail of the program was removed).
15874 if (prog->len != off && l_cnt &&
15875 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
15877 linfo[--i].insn_off = off + cnt;
15880 /* remove the line info which refer to the removed instructions */
15882 memmove(linfo + l_off, linfo + i,
15883 sizeof(*linfo) * (nr_linfo - i));
15885 prog->aux->nr_linfo -= l_cnt;
15886 nr_linfo = prog->aux->nr_linfo;
15889 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
15890 for (i = l_off; i < nr_linfo; i++)
15891 linfo[i].insn_off -= cnt;
15893 /* fix up all subprogs (incl. 'exit') which start >= off */
15894 for (i = 0; i <= env->subprog_cnt; i++)
15895 if (env->subprog_info[i].linfo_idx > l_off) {
15896 /* program may have started in the removed region but
15897 * may not be fully removed
15899 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
15900 env->subprog_info[i].linfo_idx -= l_cnt;
15902 env->subprog_info[i].linfo_idx = l_off;
15908 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
15910 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15911 unsigned int orig_prog_len = env->prog->len;
15914 if (bpf_prog_is_offloaded(env->prog->aux))
15915 bpf_prog_offload_remove_insns(env, off, cnt);
15917 err = bpf_remove_insns(env->prog, off, cnt);
15921 err = adjust_subprog_starts_after_remove(env, off, cnt);
15925 err = bpf_adj_linfo_after_remove(env, off, cnt);
15929 memmove(aux_data + off, aux_data + off + cnt,
15930 sizeof(*aux_data) * (orig_prog_len - off - cnt));
15935 /* The verifier does more data flow analysis than llvm and will not
15936 * explore branches that are dead at run time. Malicious programs can
15937 * have dead code too. Therefore replace all dead at-run-time code
15940 * Just nops are not optimal, e.g. if they would sit at the end of the
15941 * program and through another bug we would manage to jump there, then
15942 * we'd execute beyond program memory otherwise. Returning exception
15943 * code also wouldn't work since we can have subprogs where the dead
15944 * code could be located.
15946 static void sanitize_dead_code(struct bpf_verifier_env *env)
15948 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15949 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
15950 struct bpf_insn *insn = env->prog->insnsi;
15951 const int insn_cnt = env->prog->len;
15954 for (i = 0; i < insn_cnt; i++) {
15955 if (aux_data[i].seen)
15957 memcpy(insn + i, &trap, sizeof(trap));
15958 aux_data[i].zext_dst = false;
15962 static bool insn_is_cond_jump(u8 code)
15966 if (BPF_CLASS(code) == BPF_JMP32)
15969 if (BPF_CLASS(code) != BPF_JMP)
15973 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
15976 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
15978 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15979 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
15980 struct bpf_insn *insn = env->prog->insnsi;
15981 const int insn_cnt = env->prog->len;
15984 for (i = 0; i < insn_cnt; i++, insn++) {
15985 if (!insn_is_cond_jump(insn->code))
15988 if (!aux_data[i + 1].seen)
15989 ja.off = insn->off;
15990 else if (!aux_data[i + 1 + insn->off].seen)
15995 if (bpf_prog_is_offloaded(env->prog->aux))
15996 bpf_prog_offload_replace_insn(env, i, &ja);
15998 memcpy(insn, &ja, sizeof(ja));
16002 static int opt_remove_dead_code(struct bpf_verifier_env *env)
16004 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16005 int insn_cnt = env->prog->len;
16008 for (i = 0; i < insn_cnt; i++) {
16012 while (i + j < insn_cnt && !aux_data[i + j].seen)
16017 err = verifier_remove_insns(env, i, j);
16020 insn_cnt = env->prog->len;
16026 static int opt_remove_nops(struct bpf_verifier_env *env)
16028 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
16029 struct bpf_insn *insn = env->prog->insnsi;
16030 int insn_cnt = env->prog->len;
16033 for (i = 0; i < insn_cnt; i++) {
16034 if (memcmp(&insn[i], &ja, sizeof(ja)))
16037 err = verifier_remove_insns(env, i, 1);
16047 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
16048 const union bpf_attr *attr)
16050 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
16051 struct bpf_insn_aux_data *aux = env->insn_aux_data;
16052 int i, patch_len, delta = 0, len = env->prog->len;
16053 struct bpf_insn *insns = env->prog->insnsi;
16054 struct bpf_prog *new_prog;
16057 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
16058 zext_patch[1] = BPF_ZEXT_REG(0);
16059 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
16060 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
16061 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
16062 for (i = 0; i < len; i++) {
16063 int adj_idx = i + delta;
16064 struct bpf_insn insn;
16067 insn = insns[adj_idx];
16068 load_reg = insn_def_regno(&insn);
16069 if (!aux[adj_idx].zext_dst) {
16077 class = BPF_CLASS(code);
16078 if (load_reg == -1)
16081 /* NOTE: arg "reg" (the fourth one) is only used for
16082 * BPF_STX + SRC_OP, so it is safe to pass NULL
16085 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
16086 if (class == BPF_LD &&
16087 BPF_MODE(code) == BPF_IMM)
16092 /* ctx load could be transformed into wider load. */
16093 if (class == BPF_LDX &&
16094 aux[adj_idx].ptr_type == PTR_TO_CTX)
16097 imm_rnd = get_random_u32();
16098 rnd_hi32_patch[0] = insn;
16099 rnd_hi32_patch[1].imm = imm_rnd;
16100 rnd_hi32_patch[3].dst_reg = load_reg;
16101 patch = rnd_hi32_patch;
16103 goto apply_patch_buffer;
16106 /* Add in an zero-extend instruction if a) the JIT has requested
16107 * it or b) it's a CMPXCHG.
16109 * The latter is because: BPF_CMPXCHG always loads a value into
16110 * R0, therefore always zero-extends. However some archs'
16111 * equivalent instruction only does this load when the
16112 * comparison is successful. This detail of CMPXCHG is
16113 * orthogonal to the general zero-extension behaviour of the
16114 * CPU, so it's treated independently of bpf_jit_needs_zext.
16116 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
16119 /* Zero-extension is done by the caller. */
16120 if (bpf_pseudo_kfunc_call(&insn))
16123 if (WARN_ON(load_reg == -1)) {
16124 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
16128 zext_patch[0] = insn;
16129 zext_patch[1].dst_reg = load_reg;
16130 zext_patch[1].src_reg = load_reg;
16131 patch = zext_patch;
16133 apply_patch_buffer:
16134 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
16137 env->prog = new_prog;
16138 insns = new_prog->insnsi;
16139 aux = env->insn_aux_data;
16140 delta += patch_len - 1;
16146 /* convert load instructions that access fields of a context type into a
16147 * sequence of instructions that access fields of the underlying structure:
16148 * struct __sk_buff -> struct sk_buff
16149 * struct bpf_sock_ops -> struct sock
16151 static int convert_ctx_accesses(struct bpf_verifier_env *env)
16153 const struct bpf_verifier_ops *ops = env->ops;
16154 int i, cnt, size, ctx_field_size, delta = 0;
16155 const int insn_cnt = env->prog->len;
16156 struct bpf_insn insn_buf[16], *insn;
16157 u32 target_size, size_default, off;
16158 struct bpf_prog *new_prog;
16159 enum bpf_access_type type;
16160 bool is_narrower_load;
16162 if (ops->gen_prologue || env->seen_direct_write) {
16163 if (!ops->gen_prologue) {
16164 verbose(env, "bpf verifier is misconfigured\n");
16167 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
16169 if (cnt >= ARRAY_SIZE(insn_buf)) {
16170 verbose(env, "bpf verifier is misconfigured\n");
16173 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
16177 env->prog = new_prog;
16182 if (bpf_prog_is_offloaded(env->prog->aux))
16185 insn = env->prog->insnsi + delta;
16187 for (i = 0; i < insn_cnt; i++, insn++) {
16188 bpf_convert_ctx_access_t convert_ctx_access;
16190 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
16191 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
16192 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
16193 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
16195 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
16196 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
16197 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
16198 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
16199 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
16200 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
16201 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
16202 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
16208 if (type == BPF_WRITE &&
16209 env->insn_aux_data[i + delta].sanitize_stack_spill) {
16210 struct bpf_insn patch[] = {
16215 cnt = ARRAY_SIZE(patch);
16216 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
16221 env->prog = new_prog;
16222 insn = new_prog->insnsi + i + delta;
16226 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
16228 if (!ops->convert_ctx_access)
16230 convert_ctx_access = ops->convert_ctx_access;
16232 case PTR_TO_SOCKET:
16233 case PTR_TO_SOCK_COMMON:
16234 convert_ctx_access = bpf_sock_convert_ctx_access;
16236 case PTR_TO_TCP_SOCK:
16237 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
16239 case PTR_TO_XDP_SOCK:
16240 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
16242 case PTR_TO_BTF_ID:
16243 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
16244 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
16245 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
16246 * be said once it is marked PTR_UNTRUSTED, hence we must handle
16247 * any faults for loads into such types. BPF_WRITE is disallowed
16250 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
16251 if (type == BPF_READ) {
16252 insn->code = BPF_LDX | BPF_PROBE_MEM |
16253 BPF_SIZE((insn)->code);
16254 env->prog->aux->num_exentries++;
16261 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
16262 size = BPF_LDST_BYTES(insn);
16264 /* If the read access is a narrower load of the field,
16265 * convert to a 4/8-byte load, to minimum program type specific
16266 * convert_ctx_access changes. If conversion is successful,
16267 * we will apply proper mask to the result.
16269 is_narrower_load = size < ctx_field_size;
16270 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
16272 if (is_narrower_load) {
16275 if (type == BPF_WRITE) {
16276 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
16281 if (ctx_field_size == 4)
16283 else if (ctx_field_size == 8)
16284 size_code = BPF_DW;
16286 insn->off = off & ~(size_default - 1);
16287 insn->code = BPF_LDX | BPF_MEM | size_code;
16291 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
16293 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
16294 (ctx_field_size && !target_size)) {
16295 verbose(env, "bpf verifier is misconfigured\n");
16299 if (is_narrower_load && size < target_size) {
16300 u8 shift = bpf_ctx_narrow_access_offset(
16301 off, size, size_default) * 8;
16302 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
16303 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
16306 if (ctx_field_size <= 4) {
16308 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
16311 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
16312 (1 << size * 8) - 1);
16315 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
16318 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
16319 (1ULL << size * 8) - 1);
16323 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16329 /* keep walking new program and skip insns we just inserted */
16330 env->prog = new_prog;
16331 insn = new_prog->insnsi + i + delta;
16337 static int jit_subprogs(struct bpf_verifier_env *env)
16339 struct bpf_prog *prog = env->prog, **func, *tmp;
16340 int i, j, subprog_start, subprog_end = 0, len, subprog;
16341 struct bpf_map *map_ptr;
16342 struct bpf_insn *insn;
16343 void *old_bpf_func;
16344 int err, num_exentries;
16346 if (env->subprog_cnt <= 1)
16349 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16350 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
16353 /* Upon error here we cannot fall back to interpreter but
16354 * need a hard reject of the program. Thus -EFAULT is
16355 * propagated in any case.
16357 subprog = find_subprog(env, i + insn->imm + 1);
16359 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
16360 i + insn->imm + 1);
16363 /* temporarily remember subprog id inside insn instead of
16364 * aux_data, since next loop will split up all insns into funcs
16366 insn->off = subprog;
16367 /* remember original imm in case JIT fails and fallback
16368 * to interpreter will be needed
16370 env->insn_aux_data[i].call_imm = insn->imm;
16371 /* point imm to __bpf_call_base+1 from JITs point of view */
16373 if (bpf_pseudo_func(insn))
16374 /* jit (e.g. x86_64) may emit fewer instructions
16375 * if it learns a u32 imm is the same as a u64 imm.
16376 * Force a non zero here.
16381 err = bpf_prog_alloc_jited_linfo(prog);
16383 goto out_undo_insn;
16386 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
16388 goto out_undo_insn;
16390 for (i = 0; i < env->subprog_cnt; i++) {
16391 subprog_start = subprog_end;
16392 subprog_end = env->subprog_info[i + 1].start;
16394 len = subprog_end - subprog_start;
16395 /* bpf_prog_run() doesn't call subprogs directly,
16396 * hence main prog stats include the runtime of subprogs.
16397 * subprogs don't have IDs and not reachable via prog_get_next_id
16398 * func[i]->stats will never be accessed and stays NULL
16400 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
16403 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
16404 len * sizeof(struct bpf_insn));
16405 func[i]->type = prog->type;
16406 func[i]->len = len;
16407 if (bpf_prog_calc_tag(func[i]))
16409 func[i]->is_func = 1;
16410 func[i]->aux->func_idx = i;
16411 /* Below members will be freed only at prog->aux */
16412 func[i]->aux->btf = prog->aux->btf;
16413 func[i]->aux->func_info = prog->aux->func_info;
16414 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
16415 func[i]->aux->poke_tab = prog->aux->poke_tab;
16416 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
16418 for (j = 0; j < prog->aux->size_poke_tab; j++) {
16419 struct bpf_jit_poke_descriptor *poke;
16421 poke = &prog->aux->poke_tab[j];
16422 if (poke->insn_idx < subprog_end &&
16423 poke->insn_idx >= subprog_start)
16424 poke->aux = func[i]->aux;
16427 func[i]->aux->name[0] = 'F';
16428 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
16429 func[i]->jit_requested = 1;
16430 func[i]->blinding_requested = prog->blinding_requested;
16431 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
16432 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
16433 func[i]->aux->linfo = prog->aux->linfo;
16434 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
16435 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
16436 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
16438 insn = func[i]->insnsi;
16439 for (j = 0; j < func[i]->len; j++, insn++) {
16440 if (BPF_CLASS(insn->code) == BPF_LDX &&
16441 BPF_MODE(insn->code) == BPF_PROBE_MEM)
16444 func[i]->aux->num_exentries = num_exentries;
16445 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
16446 func[i] = bpf_int_jit_compile(func[i]);
16447 if (!func[i]->jited) {
16454 /* at this point all bpf functions were successfully JITed
16455 * now populate all bpf_calls with correct addresses and
16456 * run last pass of JIT
16458 for (i = 0; i < env->subprog_cnt; i++) {
16459 insn = func[i]->insnsi;
16460 for (j = 0; j < func[i]->len; j++, insn++) {
16461 if (bpf_pseudo_func(insn)) {
16462 subprog = insn->off;
16463 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
16464 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
16467 if (!bpf_pseudo_call(insn))
16469 subprog = insn->off;
16470 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
16473 /* we use the aux data to keep a list of the start addresses
16474 * of the JITed images for each function in the program
16476 * for some architectures, such as powerpc64, the imm field
16477 * might not be large enough to hold the offset of the start
16478 * address of the callee's JITed image from __bpf_call_base
16480 * in such cases, we can lookup the start address of a callee
16481 * by using its subprog id, available from the off field of
16482 * the call instruction, as an index for this list
16484 func[i]->aux->func = func;
16485 func[i]->aux->func_cnt = env->subprog_cnt;
16487 for (i = 0; i < env->subprog_cnt; i++) {
16488 old_bpf_func = func[i]->bpf_func;
16489 tmp = bpf_int_jit_compile(func[i]);
16490 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
16491 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
16498 /* finally lock prog and jit images for all functions and
16499 * populate kallsysm
16501 for (i = 0; i < env->subprog_cnt; i++) {
16502 bpf_prog_lock_ro(func[i]);
16503 bpf_prog_kallsyms_add(func[i]);
16506 /* Last step: make now unused interpreter insns from main
16507 * prog consistent for later dump requests, so they can
16508 * later look the same as if they were interpreted only.
16510 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16511 if (bpf_pseudo_func(insn)) {
16512 insn[0].imm = env->insn_aux_data[i].call_imm;
16513 insn[1].imm = insn->off;
16517 if (!bpf_pseudo_call(insn))
16519 insn->off = env->insn_aux_data[i].call_imm;
16520 subprog = find_subprog(env, i + insn->off + 1);
16521 insn->imm = subprog;
16525 prog->bpf_func = func[0]->bpf_func;
16526 prog->jited_len = func[0]->jited_len;
16527 prog->aux->func = func;
16528 prog->aux->func_cnt = env->subprog_cnt;
16529 bpf_prog_jit_attempt_done(prog);
16532 /* We failed JIT'ing, so at this point we need to unregister poke
16533 * descriptors from subprogs, so that kernel is not attempting to
16534 * patch it anymore as we're freeing the subprog JIT memory.
16536 for (i = 0; i < prog->aux->size_poke_tab; i++) {
16537 map_ptr = prog->aux->poke_tab[i].tail_call.map;
16538 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
16540 /* At this point we're guaranteed that poke descriptors are not
16541 * live anymore. We can just unlink its descriptor table as it's
16542 * released with the main prog.
16544 for (i = 0; i < env->subprog_cnt; i++) {
16547 func[i]->aux->poke_tab = NULL;
16548 bpf_jit_free(func[i]);
16552 /* cleanup main prog to be interpreted */
16553 prog->jit_requested = 0;
16554 prog->blinding_requested = 0;
16555 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16556 if (!bpf_pseudo_call(insn))
16559 insn->imm = env->insn_aux_data[i].call_imm;
16561 bpf_prog_jit_attempt_done(prog);
16565 static int fixup_call_args(struct bpf_verifier_env *env)
16567 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
16568 struct bpf_prog *prog = env->prog;
16569 struct bpf_insn *insn = prog->insnsi;
16570 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
16575 if (env->prog->jit_requested &&
16576 !bpf_prog_is_offloaded(env->prog->aux)) {
16577 err = jit_subprogs(env);
16580 if (err == -EFAULT)
16583 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
16584 if (has_kfunc_call) {
16585 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
16588 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
16589 /* When JIT fails the progs with bpf2bpf calls and tail_calls
16590 * have to be rejected, since interpreter doesn't support them yet.
16592 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
16595 for (i = 0; i < prog->len; i++, insn++) {
16596 if (bpf_pseudo_func(insn)) {
16597 /* When JIT fails the progs with callback calls
16598 * have to be rejected, since interpreter doesn't support them yet.
16600 verbose(env, "callbacks are not allowed in non-JITed programs\n");
16604 if (!bpf_pseudo_call(insn))
16606 depth = get_callee_stack_depth(env, insn, i);
16609 bpf_patch_call_args(insn, depth);
16616 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
16617 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
16619 const struct bpf_kfunc_desc *desc;
16623 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
16629 if (bpf_dev_bound_kfunc_id(insn->imm)) {
16630 xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm);
16632 insn->imm = BPF_CALL_IMM(xdp_kfunc);
16636 /* fallback to default kfunc when not supported by netdev */
16639 /* insn->imm has the btf func_id. Replace it with
16640 * an address (relative to __bpf_call_base).
16642 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
16644 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
16649 insn->imm = desc->imm;
16652 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
16653 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
16654 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
16655 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
16657 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
16658 insn_buf[1] = addr[0];
16659 insn_buf[2] = addr[1];
16660 insn_buf[3] = *insn;
16662 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
16663 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
16664 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
16666 insn_buf[0] = addr[0];
16667 insn_buf[1] = addr[1];
16668 insn_buf[2] = *insn;
16670 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
16671 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
16672 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
16674 } else if (desc->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
16675 bool seen_direct_write = env->seen_direct_write;
16676 bool is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
16679 insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly);
16681 /* restore env->seen_direct_write to its original value, since
16682 * may_access_direct_pkt_data mutates it
16684 env->seen_direct_write = seen_direct_write;
16689 /* Do various post-verification rewrites in a single program pass.
16690 * These rewrites simplify JIT and interpreter implementations.
16692 static int do_misc_fixups(struct bpf_verifier_env *env)
16694 struct bpf_prog *prog = env->prog;
16695 enum bpf_attach_type eatype = prog->expected_attach_type;
16696 enum bpf_prog_type prog_type = resolve_prog_type(prog);
16697 struct bpf_insn *insn = prog->insnsi;
16698 const struct bpf_func_proto *fn;
16699 const int insn_cnt = prog->len;
16700 const struct bpf_map_ops *ops;
16701 struct bpf_insn_aux_data *aux;
16702 struct bpf_insn insn_buf[16];
16703 struct bpf_prog *new_prog;
16704 struct bpf_map *map_ptr;
16705 int i, ret, cnt, delta = 0;
16707 for (i = 0; i < insn_cnt; i++, insn++) {
16708 /* Make divide-by-zero exceptions impossible. */
16709 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
16710 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
16711 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
16712 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
16713 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
16714 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
16715 struct bpf_insn *patchlet;
16716 struct bpf_insn chk_and_div[] = {
16717 /* [R,W]x div 0 -> 0 */
16718 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
16719 BPF_JNE | BPF_K, insn->src_reg,
16721 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
16722 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
16725 struct bpf_insn chk_and_mod[] = {
16726 /* [R,W]x mod 0 -> [R,W]x */
16727 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
16728 BPF_JEQ | BPF_K, insn->src_reg,
16729 0, 1 + (is64 ? 0 : 1), 0),
16731 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
16732 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
16735 patchlet = isdiv ? chk_and_div : chk_and_mod;
16736 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
16737 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
16739 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
16744 env->prog = prog = new_prog;
16745 insn = new_prog->insnsi + i + delta;
16749 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
16750 if (BPF_CLASS(insn->code) == BPF_LD &&
16751 (BPF_MODE(insn->code) == BPF_ABS ||
16752 BPF_MODE(insn->code) == BPF_IND)) {
16753 cnt = env->ops->gen_ld_abs(insn, insn_buf);
16754 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
16755 verbose(env, "bpf verifier is misconfigured\n");
16759 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16764 env->prog = prog = new_prog;
16765 insn = new_prog->insnsi + i + delta;
16769 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
16770 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
16771 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
16772 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
16773 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
16774 struct bpf_insn *patch = &insn_buf[0];
16775 bool issrc, isneg, isimm;
16778 aux = &env->insn_aux_data[i + delta];
16779 if (!aux->alu_state ||
16780 aux->alu_state == BPF_ALU_NON_POINTER)
16783 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
16784 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
16785 BPF_ALU_SANITIZE_SRC;
16786 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
16788 off_reg = issrc ? insn->src_reg : insn->dst_reg;
16790 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16793 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16794 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16795 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
16796 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
16797 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
16798 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
16799 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
16802 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
16803 insn->src_reg = BPF_REG_AX;
16805 insn->code = insn->code == code_add ?
16806 code_sub : code_add;
16808 if (issrc && isneg && !isimm)
16809 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16810 cnt = patch - insn_buf;
16812 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16817 env->prog = prog = new_prog;
16818 insn = new_prog->insnsi + i + delta;
16822 if (insn->code != (BPF_JMP | BPF_CALL))
16824 if (insn->src_reg == BPF_PSEUDO_CALL)
16826 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
16827 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
16833 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16838 env->prog = prog = new_prog;
16839 insn = new_prog->insnsi + i + delta;
16843 if (insn->imm == BPF_FUNC_get_route_realm)
16844 prog->dst_needed = 1;
16845 if (insn->imm == BPF_FUNC_get_prandom_u32)
16846 bpf_user_rnd_init_once();
16847 if (insn->imm == BPF_FUNC_override_return)
16848 prog->kprobe_override = 1;
16849 if (insn->imm == BPF_FUNC_tail_call) {
16850 /* If we tail call into other programs, we
16851 * cannot make any assumptions since they can
16852 * be replaced dynamically during runtime in
16853 * the program array.
16855 prog->cb_access = 1;
16856 if (!allow_tail_call_in_subprogs(env))
16857 prog->aux->stack_depth = MAX_BPF_STACK;
16858 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
16860 /* mark bpf_tail_call as different opcode to avoid
16861 * conditional branch in the interpreter for every normal
16862 * call and to prevent accidental JITing by JIT compiler
16863 * that doesn't support bpf_tail_call yet
16866 insn->code = BPF_JMP | BPF_TAIL_CALL;
16868 aux = &env->insn_aux_data[i + delta];
16869 if (env->bpf_capable && !prog->blinding_requested &&
16870 prog->jit_requested &&
16871 !bpf_map_key_poisoned(aux) &&
16872 !bpf_map_ptr_poisoned(aux) &&
16873 !bpf_map_ptr_unpriv(aux)) {
16874 struct bpf_jit_poke_descriptor desc = {
16875 .reason = BPF_POKE_REASON_TAIL_CALL,
16876 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
16877 .tail_call.key = bpf_map_key_immediate(aux),
16878 .insn_idx = i + delta,
16881 ret = bpf_jit_add_poke_descriptor(prog, &desc);
16883 verbose(env, "adding tail call poke descriptor failed\n");
16887 insn->imm = ret + 1;
16891 if (!bpf_map_ptr_unpriv(aux))
16894 /* instead of changing every JIT dealing with tail_call
16895 * emit two extra insns:
16896 * if (index >= max_entries) goto out;
16897 * index &= array->index_mask;
16898 * to avoid out-of-bounds cpu speculation
16900 if (bpf_map_ptr_poisoned(aux)) {
16901 verbose(env, "tail_call abusing map_ptr\n");
16905 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
16906 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
16907 map_ptr->max_entries, 2);
16908 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
16909 container_of(map_ptr,
16912 insn_buf[2] = *insn;
16914 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16919 env->prog = prog = new_prog;
16920 insn = new_prog->insnsi + i + delta;
16924 if (insn->imm == BPF_FUNC_timer_set_callback) {
16925 /* The verifier will process callback_fn as many times as necessary
16926 * with different maps and the register states prepared by
16927 * set_timer_callback_state will be accurate.
16929 * The following use case is valid:
16930 * map1 is shared by prog1, prog2, prog3.
16931 * prog1 calls bpf_timer_init for some map1 elements
16932 * prog2 calls bpf_timer_set_callback for some map1 elements.
16933 * Those that were not bpf_timer_init-ed will return -EINVAL.
16934 * prog3 calls bpf_timer_start for some map1 elements.
16935 * Those that were not both bpf_timer_init-ed and
16936 * bpf_timer_set_callback-ed will return -EINVAL.
16938 struct bpf_insn ld_addrs[2] = {
16939 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
16942 insn_buf[0] = ld_addrs[0];
16943 insn_buf[1] = ld_addrs[1];
16944 insn_buf[2] = *insn;
16947 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16952 env->prog = prog = new_prog;
16953 insn = new_prog->insnsi + i + delta;
16954 goto patch_call_imm;
16957 if (is_storage_get_function(insn->imm)) {
16958 if (!env->prog->aux->sleepable ||
16959 env->insn_aux_data[i + delta].storage_get_func_atomic)
16960 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
16962 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
16963 insn_buf[1] = *insn;
16966 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16971 env->prog = prog = new_prog;
16972 insn = new_prog->insnsi + i + delta;
16973 goto patch_call_imm;
16976 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
16977 * and other inlining handlers are currently limited to 64 bit
16980 if (prog->jit_requested && BITS_PER_LONG == 64 &&
16981 (insn->imm == BPF_FUNC_map_lookup_elem ||
16982 insn->imm == BPF_FUNC_map_update_elem ||
16983 insn->imm == BPF_FUNC_map_delete_elem ||
16984 insn->imm == BPF_FUNC_map_push_elem ||
16985 insn->imm == BPF_FUNC_map_pop_elem ||
16986 insn->imm == BPF_FUNC_map_peek_elem ||
16987 insn->imm == BPF_FUNC_redirect_map ||
16988 insn->imm == BPF_FUNC_for_each_map_elem ||
16989 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
16990 aux = &env->insn_aux_data[i + delta];
16991 if (bpf_map_ptr_poisoned(aux))
16992 goto patch_call_imm;
16994 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
16995 ops = map_ptr->ops;
16996 if (insn->imm == BPF_FUNC_map_lookup_elem &&
16997 ops->map_gen_lookup) {
16998 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
16999 if (cnt == -EOPNOTSUPP)
17000 goto patch_map_ops_generic;
17001 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
17002 verbose(env, "bpf verifier is misconfigured\n");
17006 new_prog = bpf_patch_insn_data(env, i + delta,
17012 env->prog = prog = new_prog;
17013 insn = new_prog->insnsi + i + delta;
17017 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
17018 (void *(*)(struct bpf_map *map, void *key))NULL));
17019 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
17020 (int (*)(struct bpf_map *map, void *key))NULL));
17021 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
17022 (int (*)(struct bpf_map *map, void *key, void *value,
17024 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
17025 (int (*)(struct bpf_map *map, void *value,
17027 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
17028 (int (*)(struct bpf_map *map, void *value))NULL));
17029 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
17030 (int (*)(struct bpf_map *map, void *value))NULL));
17031 BUILD_BUG_ON(!__same_type(ops->map_redirect,
17032 (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
17033 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
17034 (int (*)(struct bpf_map *map,
17035 bpf_callback_t callback_fn,
17036 void *callback_ctx,
17038 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
17039 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
17041 patch_map_ops_generic:
17042 switch (insn->imm) {
17043 case BPF_FUNC_map_lookup_elem:
17044 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
17046 case BPF_FUNC_map_update_elem:
17047 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
17049 case BPF_FUNC_map_delete_elem:
17050 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
17052 case BPF_FUNC_map_push_elem:
17053 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
17055 case BPF_FUNC_map_pop_elem:
17056 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
17058 case BPF_FUNC_map_peek_elem:
17059 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
17061 case BPF_FUNC_redirect_map:
17062 insn->imm = BPF_CALL_IMM(ops->map_redirect);
17064 case BPF_FUNC_for_each_map_elem:
17065 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
17067 case BPF_FUNC_map_lookup_percpu_elem:
17068 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
17072 goto patch_call_imm;
17075 /* Implement bpf_jiffies64 inline. */
17076 if (prog->jit_requested && BITS_PER_LONG == 64 &&
17077 insn->imm == BPF_FUNC_jiffies64) {
17078 struct bpf_insn ld_jiffies_addr[2] = {
17079 BPF_LD_IMM64(BPF_REG_0,
17080 (unsigned long)&jiffies),
17083 insn_buf[0] = ld_jiffies_addr[0];
17084 insn_buf[1] = ld_jiffies_addr[1];
17085 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
17089 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
17095 env->prog = prog = new_prog;
17096 insn = new_prog->insnsi + i + delta;
17100 /* Implement bpf_get_func_arg inline. */
17101 if (prog_type == BPF_PROG_TYPE_TRACING &&
17102 insn->imm == BPF_FUNC_get_func_arg) {
17103 /* Load nr_args from ctx - 8 */
17104 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17105 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
17106 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
17107 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
17108 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
17109 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17110 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
17111 insn_buf[7] = BPF_JMP_A(1);
17112 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
17115 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17120 env->prog = prog = new_prog;
17121 insn = new_prog->insnsi + i + delta;
17125 /* Implement bpf_get_func_ret inline. */
17126 if (prog_type == BPF_PROG_TYPE_TRACING &&
17127 insn->imm == BPF_FUNC_get_func_ret) {
17128 if (eatype == BPF_TRACE_FEXIT ||
17129 eatype == BPF_MODIFY_RETURN) {
17130 /* Load nr_args from ctx - 8 */
17131 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17132 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
17133 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
17134 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17135 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
17136 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
17139 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
17143 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17148 env->prog = prog = new_prog;
17149 insn = new_prog->insnsi + i + delta;
17153 /* Implement get_func_arg_cnt inline. */
17154 if (prog_type == BPF_PROG_TYPE_TRACING &&
17155 insn->imm == BPF_FUNC_get_func_arg_cnt) {
17156 /* Load nr_args from ctx - 8 */
17157 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17159 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17163 env->prog = prog = new_prog;
17164 insn = new_prog->insnsi + i + delta;
17168 /* Implement bpf_get_func_ip inline. */
17169 if (prog_type == BPF_PROG_TYPE_TRACING &&
17170 insn->imm == BPF_FUNC_get_func_ip) {
17171 /* Load IP address from ctx - 16 */
17172 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
17174 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17178 env->prog = prog = new_prog;
17179 insn = new_prog->insnsi + i + delta;
17184 fn = env->ops->get_func_proto(insn->imm, env->prog);
17185 /* all functions that have prototype and verifier allowed
17186 * programs to call them, must be real in-kernel functions
17190 "kernel subsystem misconfigured func %s#%d\n",
17191 func_id_name(insn->imm), insn->imm);
17194 insn->imm = fn->func - __bpf_call_base;
17197 /* Since poke tab is now finalized, publish aux to tracker. */
17198 for (i = 0; i < prog->aux->size_poke_tab; i++) {
17199 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17200 if (!map_ptr->ops->map_poke_track ||
17201 !map_ptr->ops->map_poke_untrack ||
17202 !map_ptr->ops->map_poke_run) {
17203 verbose(env, "bpf verifier is misconfigured\n");
17207 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
17209 verbose(env, "tracking tail call prog failed\n");
17214 sort_kfunc_descs_by_imm(env->prog);
17219 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
17222 u32 callback_subprogno,
17225 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
17226 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
17227 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
17228 int reg_loop_max = BPF_REG_6;
17229 int reg_loop_cnt = BPF_REG_7;
17230 int reg_loop_ctx = BPF_REG_8;
17232 struct bpf_prog *new_prog;
17233 u32 callback_start;
17234 u32 call_insn_offset;
17235 s32 callback_offset;
17237 /* This represents an inlined version of bpf_iter.c:bpf_loop,
17238 * be careful to modify this code in sync.
17240 struct bpf_insn insn_buf[] = {
17241 /* Return error and jump to the end of the patch if
17242 * expected number of iterations is too big.
17244 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
17245 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
17246 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
17247 /* spill R6, R7, R8 to use these as loop vars */
17248 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
17249 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
17250 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
17251 /* initialize loop vars */
17252 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
17253 BPF_MOV32_IMM(reg_loop_cnt, 0),
17254 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
17256 * if reg_loop_cnt >= reg_loop_max skip the loop body
17258 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
17260 * correct callback offset would be set after patching
17262 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
17263 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
17265 /* increment loop counter */
17266 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
17267 /* jump to loop header if callback returned 0 */
17268 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
17269 /* return value of bpf_loop,
17270 * set R0 to the number of iterations
17272 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
17273 /* restore original values of R6, R7, R8 */
17274 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
17275 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
17276 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
17279 *cnt = ARRAY_SIZE(insn_buf);
17280 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
17284 /* callback start is known only after patching */
17285 callback_start = env->subprog_info[callback_subprogno].start;
17286 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
17287 call_insn_offset = position + 12;
17288 callback_offset = callback_start - call_insn_offset - 1;
17289 new_prog->insnsi[call_insn_offset].imm = callback_offset;
17294 static bool is_bpf_loop_call(struct bpf_insn *insn)
17296 return insn->code == (BPF_JMP | BPF_CALL) &&
17297 insn->src_reg == 0 &&
17298 insn->imm == BPF_FUNC_loop;
17301 /* For all sub-programs in the program (including main) check
17302 * insn_aux_data to see if there are bpf_loop calls that require
17303 * inlining. If such calls are found the calls are replaced with a
17304 * sequence of instructions produced by `inline_bpf_loop` function and
17305 * subprog stack_depth is increased by the size of 3 registers.
17306 * This stack space is used to spill values of the R6, R7, R8. These
17307 * registers are used to store the loop bound, counter and context
17310 static int optimize_bpf_loop(struct bpf_verifier_env *env)
17312 struct bpf_subprog_info *subprogs = env->subprog_info;
17313 int i, cur_subprog = 0, cnt, delta = 0;
17314 struct bpf_insn *insn = env->prog->insnsi;
17315 int insn_cnt = env->prog->len;
17316 u16 stack_depth = subprogs[cur_subprog].stack_depth;
17317 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
17318 u16 stack_depth_extra = 0;
17320 for (i = 0; i < insn_cnt; i++, insn++) {
17321 struct bpf_loop_inline_state *inline_state =
17322 &env->insn_aux_data[i + delta].loop_inline_state;
17324 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
17325 struct bpf_prog *new_prog;
17327 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
17328 new_prog = inline_bpf_loop(env,
17330 -(stack_depth + stack_depth_extra),
17331 inline_state->callback_subprogno,
17337 env->prog = new_prog;
17338 insn = new_prog->insnsi + i + delta;
17341 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
17342 subprogs[cur_subprog].stack_depth += stack_depth_extra;
17344 stack_depth = subprogs[cur_subprog].stack_depth;
17345 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
17346 stack_depth_extra = 0;
17350 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
17355 static void free_states(struct bpf_verifier_env *env)
17357 struct bpf_verifier_state_list *sl, *sln;
17360 sl = env->free_list;
17363 free_verifier_state(&sl->state, false);
17367 env->free_list = NULL;
17369 if (!env->explored_states)
17372 for (i = 0; i < state_htab_size(env); i++) {
17373 sl = env->explored_states[i];
17377 free_verifier_state(&sl->state, false);
17381 env->explored_states[i] = NULL;
17385 static int do_check_common(struct bpf_verifier_env *env, int subprog)
17387 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17388 struct bpf_verifier_state *state;
17389 struct bpf_reg_state *regs;
17392 env->prev_linfo = NULL;
17395 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
17398 state->curframe = 0;
17399 state->speculative = false;
17400 state->branches = 1;
17401 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
17402 if (!state->frame[0]) {
17406 env->cur_state = state;
17407 init_func_state(env, state->frame[0],
17408 BPF_MAIN_FUNC /* callsite */,
17411 state->first_insn_idx = env->subprog_info[subprog].start;
17412 state->last_insn_idx = -1;
17414 regs = state->frame[state->curframe]->regs;
17415 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
17416 ret = btf_prepare_func_args(env, subprog, regs);
17419 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
17420 if (regs[i].type == PTR_TO_CTX)
17421 mark_reg_known_zero(env, regs, i);
17422 else if (regs[i].type == SCALAR_VALUE)
17423 mark_reg_unknown(env, regs, i);
17424 else if (base_type(regs[i].type) == PTR_TO_MEM) {
17425 const u32 mem_size = regs[i].mem_size;
17427 mark_reg_known_zero(env, regs, i);
17428 regs[i].mem_size = mem_size;
17429 regs[i].id = ++env->id_gen;
17433 /* 1st arg to a function */
17434 regs[BPF_REG_1].type = PTR_TO_CTX;
17435 mark_reg_known_zero(env, regs, BPF_REG_1);
17436 ret = btf_check_subprog_arg_match(env, subprog, regs);
17437 if (ret == -EFAULT)
17438 /* unlikely verifier bug. abort.
17439 * ret == 0 and ret < 0 are sadly acceptable for
17440 * main() function due to backward compatibility.
17441 * Like socket filter program may be written as:
17442 * int bpf_prog(struct pt_regs *ctx)
17443 * and never dereference that ctx in the program.
17444 * 'struct pt_regs' is a type mismatch for socket
17445 * filter that should be using 'struct __sk_buff'.
17450 ret = do_check(env);
17452 /* check for NULL is necessary, since cur_state can be freed inside
17453 * do_check() under memory pressure.
17455 if (env->cur_state) {
17456 free_verifier_state(env->cur_state, true);
17457 env->cur_state = NULL;
17459 while (!pop_stack(env, NULL, NULL, false));
17460 if (!ret && pop_log)
17461 bpf_vlog_reset(&env->log, 0);
17466 /* Verify all global functions in a BPF program one by one based on their BTF.
17467 * All global functions must pass verification. Otherwise the whole program is rejected.
17478 * foo() will be verified first for R1=any_scalar_value. During verification it
17479 * will be assumed that bar() already verified successfully and call to bar()
17480 * from foo() will be checked for type match only. Later bar() will be verified
17481 * independently to check that it's safe for R1=any_scalar_value.
17483 static int do_check_subprogs(struct bpf_verifier_env *env)
17485 struct bpf_prog_aux *aux = env->prog->aux;
17488 if (!aux->func_info)
17491 for (i = 1; i < env->subprog_cnt; i++) {
17492 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
17494 env->insn_idx = env->subprog_info[i].start;
17495 WARN_ON_ONCE(env->insn_idx == 0);
17496 ret = do_check_common(env, i);
17499 } else if (env->log.level & BPF_LOG_LEVEL) {
17501 "Func#%d is safe for any args that match its prototype\n",
17508 static int do_check_main(struct bpf_verifier_env *env)
17513 ret = do_check_common(env, 0);
17515 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
17520 static void print_verification_stats(struct bpf_verifier_env *env)
17524 if (env->log.level & BPF_LOG_STATS) {
17525 verbose(env, "verification time %lld usec\n",
17526 div_u64(env->verification_time, 1000));
17527 verbose(env, "stack depth ");
17528 for (i = 0; i < env->subprog_cnt; i++) {
17529 u32 depth = env->subprog_info[i].stack_depth;
17531 verbose(env, "%d", depth);
17532 if (i + 1 < env->subprog_cnt)
17535 verbose(env, "\n");
17537 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
17538 "total_states %d peak_states %d mark_read %d\n",
17539 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
17540 env->max_states_per_insn, env->total_states,
17541 env->peak_states, env->longest_mark_read_walk);
17544 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
17546 const struct btf_type *t, *func_proto;
17547 const struct bpf_struct_ops *st_ops;
17548 const struct btf_member *member;
17549 struct bpf_prog *prog = env->prog;
17550 u32 btf_id, member_idx;
17553 if (!prog->gpl_compatible) {
17554 verbose(env, "struct ops programs must have a GPL compatible license\n");
17558 btf_id = prog->aux->attach_btf_id;
17559 st_ops = bpf_struct_ops_find(btf_id);
17561 verbose(env, "attach_btf_id %u is not a supported struct\n",
17567 member_idx = prog->expected_attach_type;
17568 if (member_idx >= btf_type_vlen(t)) {
17569 verbose(env, "attach to invalid member idx %u of struct %s\n",
17570 member_idx, st_ops->name);
17574 member = &btf_type_member(t)[member_idx];
17575 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
17576 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
17579 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
17580 mname, member_idx, st_ops->name);
17584 if (st_ops->check_member) {
17585 int err = st_ops->check_member(t, member, prog);
17588 verbose(env, "attach to unsupported member %s of struct %s\n",
17589 mname, st_ops->name);
17594 prog->aux->attach_func_proto = func_proto;
17595 prog->aux->attach_func_name = mname;
17596 env->ops = st_ops->verifier_ops;
17600 #define SECURITY_PREFIX "security_"
17602 static int check_attach_modify_return(unsigned long addr, const char *func_name)
17604 if (within_error_injection_list(addr) ||
17605 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
17611 /* list of non-sleepable functions that are otherwise on
17612 * ALLOW_ERROR_INJECTION list
17614 BTF_SET_START(btf_non_sleepable_error_inject)
17615 /* Three functions below can be called from sleepable and non-sleepable context.
17616 * Assume non-sleepable from bpf safety point of view.
17618 BTF_ID(func, __filemap_add_folio)
17619 BTF_ID(func, should_fail_alloc_page)
17620 BTF_ID(func, should_failslab)
17621 BTF_SET_END(btf_non_sleepable_error_inject)
17623 static int check_non_sleepable_error_inject(u32 btf_id)
17625 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
17628 int bpf_check_attach_target(struct bpf_verifier_log *log,
17629 const struct bpf_prog *prog,
17630 const struct bpf_prog *tgt_prog,
17632 struct bpf_attach_target_info *tgt_info)
17634 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
17635 const char prefix[] = "btf_trace_";
17636 int ret = 0, subprog = -1, i;
17637 const struct btf_type *t;
17638 bool conservative = true;
17644 bpf_log(log, "Tracing programs must provide btf_id\n");
17647 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
17650 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
17653 t = btf_type_by_id(btf, btf_id);
17655 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
17658 tname = btf_name_by_offset(btf, t->name_off);
17660 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
17664 struct bpf_prog_aux *aux = tgt_prog->aux;
17666 if (bpf_prog_is_dev_bound(prog->aux) &&
17667 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
17668 bpf_log(log, "Target program bound device mismatch");
17672 for (i = 0; i < aux->func_info_cnt; i++)
17673 if (aux->func_info[i].type_id == btf_id) {
17677 if (subprog == -1) {
17678 bpf_log(log, "Subprog %s doesn't exist\n", tname);
17681 conservative = aux->func_info_aux[subprog].unreliable;
17682 if (prog_extension) {
17683 if (conservative) {
17685 "Cannot replace static functions\n");
17688 if (!prog->jit_requested) {
17690 "Extension programs should be JITed\n");
17694 if (!tgt_prog->jited) {
17695 bpf_log(log, "Can attach to only JITed progs\n");
17698 if (tgt_prog->type == prog->type) {
17699 /* Cannot fentry/fexit another fentry/fexit program.
17700 * Cannot attach program extension to another extension.
17701 * It's ok to attach fentry/fexit to extension program.
17703 bpf_log(log, "Cannot recursively attach\n");
17706 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
17708 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
17709 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
17710 /* Program extensions can extend all program types
17711 * except fentry/fexit. The reason is the following.
17712 * The fentry/fexit programs are used for performance
17713 * analysis, stats and can be attached to any program
17714 * type except themselves. When extension program is
17715 * replacing XDP function it is necessary to allow
17716 * performance analysis of all functions. Both original
17717 * XDP program and its program extension. Hence
17718 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
17719 * allowed. If extending of fentry/fexit was allowed it
17720 * would be possible to create long call chain
17721 * fentry->extension->fentry->extension beyond
17722 * reasonable stack size. Hence extending fentry is not
17725 bpf_log(log, "Cannot extend fentry/fexit\n");
17729 if (prog_extension) {
17730 bpf_log(log, "Cannot replace kernel functions\n");
17735 switch (prog->expected_attach_type) {
17736 case BPF_TRACE_RAW_TP:
17739 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
17742 if (!btf_type_is_typedef(t)) {
17743 bpf_log(log, "attach_btf_id %u is not a typedef\n",
17747 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
17748 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
17752 tname += sizeof(prefix) - 1;
17753 t = btf_type_by_id(btf, t->type);
17754 if (!btf_type_is_ptr(t))
17755 /* should never happen in valid vmlinux build */
17757 t = btf_type_by_id(btf, t->type);
17758 if (!btf_type_is_func_proto(t))
17759 /* should never happen in valid vmlinux build */
17763 case BPF_TRACE_ITER:
17764 if (!btf_type_is_func(t)) {
17765 bpf_log(log, "attach_btf_id %u is not a function\n",
17769 t = btf_type_by_id(btf, t->type);
17770 if (!btf_type_is_func_proto(t))
17772 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
17777 if (!prog_extension)
17780 case BPF_MODIFY_RETURN:
17782 case BPF_LSM_CGROUP:
17783 case BPF_TRACE_FENTRY:
17784 case BPF_TRACE_FEXIT:
17785 if (!btf_type_is_func(t)) {
17786 bpf_log(log, "attach_btf_id %u is not a function\n",
17790 if (prog_extension &&
17791 btf_check_type_match(log, prog, btf, t))
17793 t = btf_type_by_id(btf, t->type);
17794 if (!btf_type_is_func_proto(t))
17797 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
17798 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
17799 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
17802 if (tgt_prog && conservative)
17805 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
17811 addr = (long) tgt_prog->bpf_func;
17813 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
17815 addr = kallsyms_lookup_name(tname);
17818 "The address of function %s cannot be found\n",
17824 if (prog->aux->sleepable) {
17826 switch (prog->type) {
17827 case BPF_PROG_TYPE_TRACING:
17829 /* fentry/fexit/fmod_ret progs can be sleepable if they are
17830 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
17832 if (!check_non_sleepable_error_inject(btf_id) &&
17833 within_error_injection_list(addr))
17835 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
17836 * in the fmodret id set with the KF_SLEEPABLE flag.
17839 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
17841 if (flags && (*flags & KF_SLEEPABLE))
17845 case BPF_PROG_TYPE_LSM:
17846 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
17847 * Only some of them are sleepable.
17849 if (bpf_lsm_is_sleepable_hook(btf_id))
17856 bpf_log(log, "%s is not sleepable\n", tname);
17859 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
17861 bpf_log(log, "can't modify return codes of BPF programs\n");
17865 if (btf_kfunc_is_modify_return(btf, btf_id) ||
17866 !check_attach_modify_return(addr, tname))
17869 bpf_log(log, "%s() is not modifiable\n", tname);
17876 tgt_info->tgt_addr = addr;
17877 tgt_info->tgt_name = tname;
17878 tgt_info->tgt_type = t;
17882 BTF_SET_START(btf_id_deny)
17885 BTF_ID(func, migrate_disable)
17886 BTF_ID(func, migrate_enable)
17888 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
17889 BTF_ID(func, rcu_read_unlock_strict)
17891 BTF_SET_END(btf_id_deny)
17893 static bool can_be_sleepable(struct bpf_prog *prog)
17895 if (prog->type == BPF_PROG_TYPE_TRACING) {
17896 switch (prog->expected_attach_type) {
17897 case BPF_TRACE_FENTRY:
17898 case BPF_TRACE_FEXIT:
17899 case BPF_MODIFY_RETURN:
17900 case BPF_TRACE_ITER:
17906 return prog->type == BPF_PROG_TYPE_LSM ||
17907 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
17908 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
17911 static int check_attach_btf_id(struct bpf_verifier_env *env)
17913 struct bpf_prog *prog = env->prog;
17914 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
17915 struct bpf_attach_target_info tgt_info = {};
17916 u32 btf_id = prog->aux->attach_btf_id;
17917 struct bpf_trampoline *tr;
17921 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
17922 if (prog->aux->sleepable)
17923 /* attach_btf_id checked to be zero already */
17925 verbose(env, "Syscall programs can only be sleepable\n");
17929 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
17930 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
17934 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
17935 return check_struct_ops_btf_id(env);
17937 if (prog->type != BPF_PROG_TYPE_TRACING &&
17938 prog->type != BPF_PROG_TYPE_LSM &&
17939 prog->type != BPF_PROG_TYPE_EXT)
17942 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
17946 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
17947 /* to make freplace equivalent to their targets, they need to
17948 * inherit env->ops and expected_attach_type for the rest of the
17951 env->ops = bpf_verifier_ops[tgt_prog->type];
17952 prog->expected_attach_type = tgt_prog->expected_attach_type;
17955 /* store info about the attachment target that will be used later */
17956 prog->aux->attach_func_proto = tgt_info.tgt_type;
17957 prog->aux->attach_func_name = tgt_info.tgt_name;
17960 prog->aux->saved_dst_prog_type = tgt_prog->type;
17961 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
17964 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
17965 prog->aux->attach_btf_trace = true;
17967 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
17968 if (!bpf_iter_prog_supported(prog))
17973 if (prog->type == BPF_PROG_TYPE_LSM) {
17974 ret = bpf_lsm_verify_prog(&env->log, prog);
17977 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
17978 btf_id_set_contains(&btf_id_deny, btf_id)) {
17982 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
17983 tr = bpf_trampoline_get(key, &tgt_info);
17987 prog->aux->dst_trampoline = tr;
17991 struct btf *bpf_get_btf_vmlinux(void)
17993 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
17994 mutex_lock(&bpf_verifier_lock);
17996 btf_vmlinux = btf_parse_vmlinux();
17997 mutex_unlock(&bpf_verifier_lock);
17999 return btf_vmlinux;
18002 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
18004 u64 start_time = ktime_get_ns();
18005 struct bpf_verifier_env *env;
18006 struct bpf_verifier_log *log;
18007 int i, len, ret = -EINVAL;
18010 /* no program is valid */
18011 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
18014 /* 'struct bpf_verifier_env' can be global, but since it's not small,
18015 * allocate/free it every time bpf_check() is called
18017 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
18022 len = (*prog)->len;
18023 env->insn_aux_data =
18024 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
18026 if (!env->insn_aux_data)
18028 for (i = 0; i < len; i++)
18029 env->insn_aux_data[i].orig_idx = i;
18031 env->ops = bpf_verifier_ops[env->prog->type];
18032 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
18033 is_priv = bpf_capable();
18035 bpf_get_btf_vmlinux();
18037 /* grab the mutex to protect few globals used by verifier */
18039 mutex_lock(&bpf_verifier_lock);
18041 if (attr->log_level || attr->log_buf || attr->log_size) {
18042 /* user requested verbose verifier output
18043 * and supplied buffer to store the verification trace
18045 log->level = attr->log_level;
18046 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
18047 log->len_total = attr->log_size;
18049 /* log attributes have to be sane */
18050 if (!bpf_verifier_log_attr_valid(log)) {
18056 mark_verifier_state_clean(env);
18058 if (IS_ERR(btf_vmlinux)) {
18059 /* Either gcc or pahole or kernel are broken. */
18060 verbose(env, "in-kernel BTF is malformed\n");
18061 ret = PTR_ERR(btf_vmlinux);
18062 goto skip_full_check;
18065 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
18066 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
18067 env->strict_alignment = true;
18068 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
18069 env->strict_alignment = false;
18071 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
18072 env->allow_uninit_stack = bpf_allow_uninit_stack();
18073 env->bypass_spec_v1 = bpf_bypass_spec_v1();
18074 env->bypass_spec_v4 = bpf_bypass_spec_v4();
18075 env->bpf_capable = bpf_capable();
18078 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
18080 env->explored_states = kvcalloc(state_htab_size(env),
18081 sizeof(struct bpf_verifier_state_list *),
18084 if (!env->explored_states)
18085 goto skip_full_check;
18087 ret = add_subprog_and_kfunc(env);
18089 goto skip_full_check;
18091 ret = check_subprogs(env);
18093 goto skip_full_check;
18095 ret = check_btf_info(env, attr, uattr);
18097 goto skip_full_check;
18099 ret = check_attach_btf_id(env);
18101 goto skip_full_check;
18103 ret = resolve_pseudo_ldimm64(env);
18105 goto skip_full_check;
18107 if (bpf_prog_is_offloaded(env->prog->aux)) {
18108 ret = bpf_prog_offload_verifier_prep(env->prog);
18110 goto skip_full_check;
18113 ret = check_cfg(env);
18115 goto skip_full_check;
18117 ret = do_check_subprogs(env);
18118 ret = ret ?: do_check_main(env);
18120 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
18121 ret = bpf_prog_offload_finalize(env);
18124 kvfree(env->explored_states);
18127 ret = check_max_stack_depth(env);
18129 /* instruction rewrites happen after this point */
18131 ret = optimize_bpf_loop(env);
18135 opt_hard_wire_dead_code_branches(env);
18137 ret = opt_remove_dead_code(env);
18139 ret = opt_remove_nops(env);
18142 sanitize_dead_code(env);
18146 /* program is valid, convert *(u32*)(ctx + off) accesses */
18147 ret = convert_ctx_accesses(env);
18150 ret = do_misc_fixups(env);
18152 /* do 32-bit optimization after insn patching has done so those patched
18153 * insns could be handled correctly.
18155 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
18156 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
18157 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
18162 ret = fixup_call_args(env);
18164 env->verification_time = ktime_get_ns() - start_time;
18165 print_verification_stats(env);
18166 env->prog->aux->verified_insns = env->insn_processed;
18168 if (log->level && bpf_verifier_log_full(log))
18170 if (log->level && !log->ubuf) {
18172 goto err_release_maps;
18176 goto err_release_maps;
18178 if (env->used_map_cnt) {
18179 /* if program passed verifier, update used_maps in bpf_prog_info */
18180 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
18181 sizeof(env->used_maps[0]),
18184 if (!env->prog->aux->used_maps) {
18186 goto err_release_maps;
18189 memcpy(env->prog->aux->used_maps, env->used_maps,
18190 sizeof(env->used_maps[0]) * env->used_map_cnt);
18191 env->prog->aux->used_map_cnt = env->used_map_cnt;
18193 if (env->used_btf_cnt) {
18194 /* if program passed verifier, update used_btfs in bpf_prog_aux */
18195 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
18196 sizeof(env->used_btfs[0]),
18198 if (!env->prog->aux->used_btfs) {
18200 goto err_release_maps;
18203 memcpy(env->prog->aux->used_btfs, env->used_btfs,
18204 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
18205 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
18207 if (env->used_map_cnt || env->used_btf_cnt) {
18208 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
18209 * bpf_ld_imm64 instructions
18211 convert_pseudo_ld_imm64(env);
18214 adjust_btf_func(env);
18217 if (!env->prog->aux->used_maps)
18218 /* if we didn't copy map pointers into bpf_prog_info, release
18219 * them now. Otherwise free_used_maps() will release them.
18222 if (!env->prog->aux->used_btfs)
18225 /* extension progs temporarily inherit the attach_type of their targets
18226 for verification purposes, so set it back to zero before returning
18228 if (env->prog->type == BPF_PROG_TYPE_EXT)
18229 env->prog->expected_attach_type = 0;
18234 mutex_unlock(&bpf_verifier_lock);
18235 vfree(env->insn_aux_data);