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/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/btf_ids.h>
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
30 [_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #define BPF_LINK_TYPE(_id, _name)
33 #include <linux/bpf_types.h>
39 /* bpf_check() is a static code analyzer that walks eBPF program
40 * instruction by instruction and updates register/stack state.
41 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
43 * The first pass is depth-first-search to check that the program is a DAG.
44 * It rejects the following programs:
45 * - larger than BPF_MAXINSNS insns
46 * - if loop is present (detected via back-edge)
47 * - unreachable insns exist (shouldn't be a forest. program = one function)
48 * - out of bounds or malformed jumps
49 * The second pass is all possible path descent from the 1st insn.
50 * Since it's analyzing all pathes through the program, the length of the
51 * analysis is limited to 64k insn, which may be hit even if total number of
52 * insn is less then 4K, but there are too many branches that change stack/regs.
53 * Number of 'branches to be analyzed' is limited to 1k
55 * On entry to each instruction, each register has a type, and the instruction
56 * changes the types of the registers depending on instruction semantics.
57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60 * All registers are 64-bit.
61 * R0 - return register
62 * R1-R5 argument passing registers
63 * R6-R9 callee saved registers
64 * R10 - frame pointer read-only
66 * At the start of BPF program the register R1 contains a pointer to bpf_context
67 * and has type PTR_TO_CTX.
69 * Verifier tracks arithmetic operations on pointers in case:
70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72 * 1st insn copies R10 (which has FRAME_PTR) type into R1
73 * and 2nd arithmetic instruction is pattern matched to recognize
74 * that it wants to construct a pointer to some element within stack.
75 * So after 2nd insn, the register R1 has type PTR_TO_STACK
76 * (and -20 constant is saved for further stack bounds checking).
77 * Meaning that this reg is a pointer to stack plus known immediate constant.
79 * Most of the time the registers have SCALAR_VALUE type, which
80 * means the register has some value, but it's not a valid pointer.
81 * (like pointer plus pointer becomes SCALAR_VALUE type)
83 * When verifier sees load or store instructions the type of base register
84 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85 * four pointer types recognized by check_mem_access() function.
87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88 * and the range of [ptr, ptr + map's value_size) is accessible.
90 * registers used to pass values to function calls are checked against
91 * function argument constraints.
93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94 * It means that the register type passed to this function must be
95 * PTR_TO_STACK and it will be used inside the function as
96 * 'pointer to map element key'
98 * For example the argument constraints for bpf_map_lookup_elem():
99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100 * .arg1_type = ARG_CONST_MAP_PTR,
101 * .arg2_type = ARG_PTR_TO_MAP_KEY,
103 * ret_type says that this function returns 'pointer to map elem value or null'
104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105 * 2nd argument should be a pointer to stack, which will be used inside
106 * the helper function as a pointer to map element key.
108 * On the kernel side the helper function looks like:
109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112 * void *key = (void *) (unsigned long) r2;
115 * here kernel can access 'key' and 'map' pointers safely, knowing that
116 * [key, key + map->key_size) bytes are valid and were initialized on
117 * the stack of eBPF program.
120 * Corresponding eBPF program may look like:
121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125 * here verifier looks at prototype of map_lookup_elem() and sees:
126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131 * and were initialized prior to this call.
132 * If it's ok, then verifier allows this BPF_CALL insn and looks at
133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135 * returns ether pointer to map value or NULL.
137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138 * insn, the register holding that pointer in the true branch changes state to
139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140 * branch. See check_cond_jmp_op().
142 * After the call R0 is set to return type of the function and registers R1-R5
143 * are set to NOT_INIT to indicate that they are no longer readable.
145 * The following reference types represent a potential reference to a kernel
146 * resource which, after first being allocated, must be checked and freed by
148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
150 * When the verifier sees a helper call return a reference type, it allocates a
151 * pointer id for the reference and stores it in the current function state.
152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154 * passes through a NULL-check conditional. For the branch wherein the state is
155 * changed to CONST_IMM, the verifier releases the reference.
157 * For each helper function that allocates a reference, such as
158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159 * bpf_sk_release(). When a reference type passes into the release function,
160 * the verifier also releases the reference. If any unchecked or unreleased
161 * reference remains at the end of the program, the verifier rejects it.
164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
165 struct bpf_verifier_stack_elem {
166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
170 struct bpf_verifier_state st;
173 struct bpf_verifier_stack_elem *next;
174 /* length of verifier log at the time this state was pushed on stack */
178 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
179 #define BPF_COMPLEXITY_LIMIT_STATES 64
181 #define BPF_MAP_KEY_POISON (1ULL << 63)
182 #define BPF_MAP_KEY_SEEN (1ULL << 62)
184 #define BPF_MAP_PTR_UNPRIV 1UL
185 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
186 POISON_POINTER_DELTA))
187 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
189 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
194 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
199 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 const struct bpf_map *map, bool unpriv)
202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 unpriv |= bpf_map_ptr_unpriv(aux);
204 aux->map_ptr_state = (unsigned long)map |
205 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
208 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
210 return aux->map_key_state & BPF_MAP_KEY_POISON;
213 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
215 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
218 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
220 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
223 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
225 bool poisoned = bpf_map_key_poisoned(aux);
227 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
231 static bool bpf_pseudo_call(const struct bpf_insn *insn)
233 return insn->code == (BPF_JMP | BPF_CALL) &&
234 insn->src_reg == BPF_PSEUDO_CALL;
237 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
239 return insn->code == (BPF_JMP | BPF_CALL) &&
240 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
243 static bool bpf_pseudo_func(const struct bpf_insn *insn)
245 return insn->code == (BPF_LD | BPF_IMM | BPF_DW) &&
246 insn->src_reg == BPF_PSEUDO_FUNC;
249 struct bpf_call_arg_meta {
250 struct bpf_map *map_ptr;
266 struct btf *btf_vmlinux;
268 static DEFINE_MUTEX(bpf_verifier_lock);
270 static const struct bpf_line_info *
271 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
273 const struct bpf_line_info *linfo;
274 const struct bpf_prog *prog;
278 nr_linfo = prog->aux->nr_linfo;
280 if (!nr_linfo || insn_off >= prog->len)
283 linfo = prog->aux->linfo;
284 for (i = 1; i < nr_linfo; i++)
285 if (insn_off < linfo[i].insn_off)
288 return &linfo[i - 1];
291 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
296 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
298 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
299 "verifier log line truncated - local buffer too short\n");
301 n = min(log->len_total - log->len_used - 1, n);
304 if (log->level == BPF_LOG_KERNEL) {
305 pr_err("BPF:%s\n", log->kbuf);
308 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
314 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
318 if (!bpf_verifier_log_needed(log))
321 log->len_used = new_pos;
322 if (put_user(zero, log->ubuf + new_pos))
326 /* log_level controls verbosity level of eBPF verifier.
327 * bpf_verifier_log_write() is used to dump the verification trace to the log,
328 * so the user can figure out what's wrong with the program
330 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
331 const char *fmt, ...)
335 if (!bpf_verifier_log_needed(&env->log))
339 bpf_verifier_vlog(&env->log, fmt, args);
342 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
344 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
346 struct bpf_verifier_env *env = private_data;
349 if (!bpf_verifier_log_needed(&env->log))
353 bpf_verifier_vlog(&env->log, fmt, args);
357 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
358 const char *fmt, ...)
362 if (!bpf_verifier_log_needed(log))
366 bpf_verifier_vlog(log, fmt, args);
370 static const char *ltrim(const char *s)
378 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
380 const char *prefix_fmt, ...)
382 const struct bpf_line_info *linfo;
384 if (!bpf_verifier_log_needed(&env->log))
387 linfo = find_linfo(env, insn_off);
388 if (!linfo || linfo == env->prev_linfo)
394 va_start(args, prefix_fmt);
395 bpf_verifier_vlog(&env->log, prefix_fmt, args);
400 ltrim(btf_name_by_offset(env->prog->aux->btf,
403 env->prev_linfo = linfo;
406 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
407 struct bpf_reg_state *reg,
408 struct tnum *range, const char *ctx,
409 const char *reg_name)
413 verbose(env, "At %s the register %s ", ctx, reg_name);
414 if (!tnum_is_unknown(reg->var_off)) {
415 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
416 verbose(env, "has value %s", tn_buf);
418 verbose(env, "has unknown scalar value");
420 tnum_strn(tn_buf, sizeof(tn_buf), *range);
421 verbose(env, " should have been in %s\n", tn_buf);
424 static bool type_is_pkt_pointer(enum bpf_reg_type type)
426 return type == PTR_TO_PACKET ||
427 type == PTR_TO_PACKET_META;
430 static bool type_is_sk_pointer(enum bpf_reg_type type)
432 return type == PTR_TO_SOCKET ||
433 type == PTR_TO_SOCK_COMMON ||
434 type == PTR_TO_TCP_SOCK ||
435 type == PTR_TO_XDP_SOCK;
438 static bool reg_type_not_null(enum bpf_reg_type type)
440 return type == PTR_TO_SOCKET ||
441 type == PTR_TO_TCP_SOCK ||
442 type == PTR_TO_MAP_VALUE ||
443 type == PTR_TO_MAP_KEY ||
444 type == PTR_TO_SOCK_COMMON;
447 static bool reg_type_may_be_null(enum bpf_reg_type type)
449 return type == PTR_TO_MAP_VALUE_OR_NULL ||
450 type == PTR_TO_SOCKET_OR_NULL ||
451 type == PTR_TO_SOCK_COMMON_OR_NULL ||
452 type == PTR_TO_TCP_SOCK_OR_NULL ||
453 type == PTR_TO_BTF_ID_OR_NULL ||
454 type == PTR_TO_MEM_OR_NULL ||
455 type == PTR_TO_RDONLY_BUF_OR_NULL ||
456 type == PTR_TO_RDWR_BUF_OR_NULL;
459 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
461 return reg->type == PTR_TO_MAP_VALUE &&
462 map_value_has_spin_lock(reg->map_ptr);
465 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
467 return type == PTR_TO_SOCKET ||
468 type == PTR_TO_SOCKET_OR_NULL ||
469 type == PTR_TO_TCP_SOCK ||
470 type == PTR_TO_TCP_SOCK_OR_NULL ||
471 type == PTR_TO_MEM ||
472 type == PTR_TO_MEM_OR_NULL;
475 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
477 return type == ARG_PTR_TO_SOCK_COMMON;
480 static bool arg_type_may_be_null(enum bpf_arg_type type)
482 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
483 type == ARG_PTR_TO_MEM_OR_NULL ||
484 type == ARG_PTR_TO_CTX_OR_NULL ||
485 type == ARG_PTR_TO_SOCKET_OR_NULL ||
486 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
487 type == ARG_PTR_TO_STACK_OR_NULL;
490 /* Determine whether the function releases some resources allocated by another
491 * function call. The first reference type argument will be assumed to be
492 * released by release_reference().
494 static bool is_release_function(enum bpf_func_id func_id)
496 return func_id == BPF_FUNC_sk_release ||
497 func_id == BPF_FUNC_ringbuf_submit ||
498 func_id == BPF_FUNC_ringbuf_discard;
501 static bool may_be_acquire_function(enum bpf_func_id func_id)
503 return func_id == BPF_FUNC_sk_lookup_tcp ||
504 func_id == BPF_FUNC_sk_lookup_udp ||
505 func_id == BPF_FUNC_skc_lookup_tcp ||
506 func_id == BPF_FUNC_map_lookup_elem ||
507 func_id == BPF_FUNC_ringbuf_reserve;
510 static bool is_acquire_function(enum bpf_func_id func_id,
511 const struct bpf_map *map)
513 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
515 if (func_id == BPF_FUNC_sk_lookup_tcp ||
516 func_id == BPF_FUNC_sk_lookup_udp ||
517 func_id == BPF_FUNC_skc_lookup_tcp ||
518 func_id == BPF_FUNC_ringbuf_reserve)
521 if (func_id == BPF_FUNC_map_lookup_elem &&
522 (map_type == BPF_MAP_TYPE_SOCKMAP ||
523 map_type == BPF_MAP_TYPE_SOCKHASH))
529 static bool is_ptr_cast_function(enum bpf_func_id func_id)
531 return func_id == BPF_FUNC_tcp_sock ||
532 func_id == BPF_FUNC_sk_fullsock ||
533 func_id == BPF_FUNC_skc_to_tcp_sock ||
534 func_id == BPF_FUNC_skc_to_tcp6_sock ||
535 func_id == BPF_FUNC_skc_to_udp6_sock ||
536 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537 func_id == BPF_FUNC_skc_to_tcp_request_sock;
540 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
542 return BPF_CLASS(insn->code) == BPF_STX &&
543 BPF_MODE(insn->code) == BPF_ATOMIC &&
544 insn->imm == BPF_CMPXCHG;
547 /* string representation of 'enum bpf_reg_type' */
548 static const char * const reg_type_str[] = {
550 [SCALAR_VALUE] = "inv",
551 [PTR_TO_CTX] = "ctx",
552 [CONST_PTR_TO_MAP] = "map_ptr",
553 [PTR_TO_MAP_VALUE] = "map_value",
554 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
555 [PTR_TO_STACK] = "fp",
556 [PTR_TO_PACKET] = "pkt",
557 [PTR_TO_PACKET_META] = "pkt_meta",
558 [PTR_TO_PACKET_END] = "pkt_end",
559 [PTR_TO_FLOW_KEYS] = "flow_keys",
560 [PTR_TO_SOCKET] = "sock",
561 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
562 [PTR_TO_SOCK_COMMON] = "sock_common",
563 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
564 [PTR_TO_TCP_SOCK] = "tcp_sock",
565 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
566 [PTR_TO_TP_BUFFER] = "tp_buffer",
567 [PTR_TO_XDP_SOCK] = "xdp_sock",
568 [PTR_TO_BTF_ID] = "ptr_",
569 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
570 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
571 [PTR_TO_MEM] = "mem",
572 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
573 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
574 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
575 [PTR_TO_RDWR_BUF] = "rdwr_buf",
576 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
577 [PTR_TO_FUNC] = "func",
578 [PTR_TO_MAP_KEY] = "map_key",
581 static char slot_type_char[] = {
582 [STACK_INVALID] = '?',
588 static void print_liveness(struct bpf_verifier_env *env,
589 enum bpf_reg_liveness live)
591 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
593 if (live & REG_LIVE_READ)
595 if (live & REG_LIVE_WRITTEN)
597 if (live & REG_LIVE_DONE)
601 static struct bpf_func_state *func(struct bpf_verifier_env *env,
602 const struct bpf_reg_state *reg)
604 struct bpf_verifier_state *cur = env->cur_state;
606 return cur->frame[reg->frameno];
609 static const char *kernel_type_name(const struct btf* btf, u32 id)
611 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
614 static void print_verifier_state(struct bpf_verifier_env *env,
615 const struct bpf_func_state *state)
617 const struct bpf_reg_state *reg;
622 verbose(env, " frame%d:", state->frameno);
623 for (i = 0; i < MAX_BPF_REG; i++) {
624 reg = &state->regs[i];
628 verbose(env, " R%d", i);
629 print_liveness(env, reg->live);
630 verbose(env, "=%s", reg_type_str[t]);
631 if (t == SCALAR_VALUE && reg->precise)
633 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
634 tnum_is_const(reg->var_off)) {
635 /* reg->off should be 0 for SCALAR_VALUE */
636 verbose(env, "%lld", reg->var_off.value + reg->off);
638 if (t == PTR_TO_BTF_ID ||
639 t == PTR_TO_BTF_ID_OR_NULL ||
640 t == PTR_TO_PERCPU_BTF_ID)
641 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
642 verbose(env, "(id=%d", reg->id);
643 if (reg_type_may_be_refcounted_or_null(t))
644 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
645 if (t != SCALAR_VALUE)
646 verbose(env, ",off=%d", reg->off);
647 if (type_is_pkt_pointer(t))
648 verbose(env, ",r=%d", reg->range);
649 else if (t == CONST_PTR_TO_MAP ||
650 t == PTR_TO_MAP_KEY ||
651 t == PTR_TO_MAP_VALUE ||
652 t == PTR_TO_MAP_VALUE_OR_NULL)
653 verbose(env, ",ks=%d,vs=%d",
654 reg->map_ptr->key_size,
655 reg->map_ptr->value_size);
656 if (tnum_is_const(reg->var_off)) {
657 /* Typically an immediate SCALAR_VALUE, but
658 * could be a pointer whose offset is too big
661 verbose(env, ",imm=%llx", reg->var_off.value);
663 if (reg->smin_value != reg->umin_value &&
664 reg->smin_value != S64_MIN)
665 verbose(env, ",smin_value=%lld",
666 (long long)reg->smin_value);
667 if (reg->smax_value != reg->umax_value &&
668 reg->smax_value != S64_MAX)
669 verbose(env, ",smax_value=%lld",
670 (long long)reg->smax_value);
671 if (reg->umin_value != 0)
672 verbose(env, ",umin_value=%llu",
673 (unsigned long long)reg->umin_value);
674 if (reg->umax_value != U64_MAX)
675 verbose(env, ",umax_value=%llu",
676 (unsigned long long)reg->umax_value);
677 if (!tnum_is_unknown(reg->var_off)) {
680 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
681 verbose(env, ",var_off=%s", tn_buf);
683 if (reg->s32_min_value != reg->smin_value &&
684 reg->s32_min_value != S32_MIN)
685 verbose(env, ",s32_min_value=%d",
686 (int)(reg->s32_min_value));
687 if (reg->s32_max_value != reg->smax_value &&
688 reg->s32_max_value != S32_MAX)
689 verbose(env, ",s32_max_value=%d",
690 (int)(reg->s32_max_value));
691 if (reg->u32_min_value != reg->umin_value &&
692 reg->u32_min_value != U32_MIN)
693 verbose(env, ",u32_min_value=%d",
694 (int)(reg->u32_min_value));
695 if (reg->u32_max_value != reg->umax_value &&
696 reg->u32_max_value != U32_MAX)
697 verbose(env, ",u32_max_value=%d",
698 (int)(reg->u32_max_value));
703 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
704 char types_buf[BPF_REG_SIZE + 1];
708 for (j = 0; j < BPF_REG_SIZE; j++) {
709 if (state->stack[i].slot_type[j] != STACK_INVALID)
711 types_buf[j] = slot_type_char[
712 state->stack[i].slot_type[j]];
714 types_buf[BPF_REG_SIZE] = 0;
717 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
718 print_liveness(env, state->stack[i].spilled_ptr.live);
719 if (state->stack[i].slot_type[0] == STACK_SPILL) {
720 reg = &state->stack[i].spilled_ptr;
722 verbose(env, "=%s", reg_type_str[t]);
723 if (t == SCALAR_VALUE && reg->precise)
725 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
726 verbose(env, "%lld", reg->var_off.value + reg->off);
728 verbose(env, "=%s", types_buf);
731 if (state->acquired_refs && state->refs[0].id) {
732 verbose(env, " refs=%d", state->refs[0].id);
733 for (i = 1; i < state->acquired_refs; i++)
734 if (state->refs[i].id)
735 verbose(env, ",%d", state->refs[i].id);
740 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
741 static int copy_##NAME##_state(struct bpf_func_state *dst, \
742 const struct bpf_func_state *src) \
746 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
747 /* internal bug, make state invalid to reject the program */ \
748 memset(dst, 0, sizeof(*dst)); \
751 memcpy(dst->FIELD, src->FIELD, \
752 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
755 /* copy_reference_state() */
756 COPY_STATE_FN(reference, acquired_refs, refs, 1)
757 /* copy_stack_state() */
758 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
761 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
762 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
765 u32 old_size = state->COUNT; \
766 struct bpf_##NAME##_state *new_##FIELD; \
767 int slot = size / SIZE; \
769 if (size <= old_size || !size) { \
772 state->COUNT = slot * SIZE; \
773 if (!size && old_size) { \
774 kfree(state->FIELD); \
775 state->FIELD = NULL; \
779 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
785 memcpy(new_##FIELD, state->FIELD, \
786 sizeof(*new_##FIELD) * (old_size / SIZE)); \
787 memset(new_##FIELD + old_size / SIZE, 0, \
788 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
790 state->COUNT = slot * SIZE; \
791 kfree(state->FIELD); \
792 state->FIELD = new_##FIELD; \
795 /* realloc_reference_state() */
796 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
797 /* realloc_stack_state() */
798 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
799 #undef REALLOC_STATE_FN
801 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
802 * make it consume minimal amount of memory. check_stack_write() access from
803 * the program calls into realloc_func_state() to grow the stack size.
804 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
805 * which realloc_stack_state() copies over. It points to previous
806 * bpf_verifier_state which is never reallocated.
808 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
809 int refs_size, bool copy_old)
811 int err = realloc_reference_state(state, refs_size, copy_old);
814 return realloc_stack_state(state, stack_size, copy_old);
817 /* Acquire a pointer id from the env and update the state->refs to include
818 * this new pointer reference.
819 * On success, returns a valid pointer id to associate with the register
820 * On failure, returns a negative errno.
822 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
824 struct bpf_func_state *state = cur_func(env);
825 int new_ofs = state->acquired_refs;
828 err = realloc_reference_state(state, state->acquired_refs + 1, true);
832 state->refs[new_ofs].id = id;
833 state->refs[new_ofs].insn_idx = insn_idx;
838 /* release function corresponding to acquire_reference_state(). Idempotent. */
839 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
843 last_idx = state->acquired_refs - 1;
844 for (i = 0; i < state->acquired_refs; i++) {
845 if (state->refs[i].id == ptr_id) {
846 if (last_idx && i != last_idx)
847 memcpy(&state->refs[i], &state->refs[last_idx],
848 sizeof(*state->refs));
849 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
850 state->acquired_refs--;
857 static int transfer_reference_state(struct bpf_func_state *dst,
858 struct bpf_func_state *src)
860 int err = realloc_reference_state(dst, src->acquired_refs, false);
863 err = copy_reference_state(dst, src);
869 static void free_func_state(struct bpf_func_state *state)
878 static void clear_jmp_history(struct bpf_verifier_state *state)
880 kfree(state->jmp_history);
881 state->jmp_history = NULL;
882 state->jmp_history_cnt = 0;
885 static void free_verifier_state(struct bpf_verifier_state *state,
890 for (i = 0; i <= state->curframe; i++) {
891 free_func_state(state->frame[i]);
892 state->frame[i] = NULL;
894 clear_jmp_history(state);
899 /* copy verifier state from src to dst growing dst stack space
900 * when necessary to accommodate larger src stack
902 static int copy_func_state(struct bpf_func_state *dst,
903 const struct bpf_func_state *src)
907 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
911 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
912 err = copy_reference_state(dst, src);
915 return copy_stack_state(dst, src);
918 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
919 const struct bpf_verifier_state *src)
921 struct bpf_func_state *dst;
922 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
925 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
926 kfree(dst_state->jmp_history);
927 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
928 if (!dst_state->jmp_history)
931 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
932 dst_state->jmp_history_cnt = src->jmp_history_cnt;
934 /* if dst has more stack frames then src frame, free them */
935 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
936 free_func_state(dst_state->frame[i]);
937 dst_state->frame[i] = NULL;
939 dst_state->speculative = src->speculative;
940 dst_state->curframe = src->curframe;
941 dst_state->active_spin_lock = src->active_spin_lock;
942 dst_state->branches = src->branches;
943 dst_state->parent = src->parent;
944 dst_state->first_insn_idx = src->first_insn_idx;
945 dst_state->last_insn_idx = src->last_insn_idx;
946 for (i = 0; i <= src->curframe; i++) {
947 dst = dst_state->frame[i];
949 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
952 dst_state->frame[i] = dst;
954 err = copy_func_state(dst, src->frame[i]);
961 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
964 u32 br = --st->branches;
966 /* WARN_ON(br > 1) technically makes sense here,
967 * but see comment in push_stack(), hence:
969 WARN_ONCE((int)br < 0,
970 "BUG update_branch_counts:branches_to_explore=%d\n",
978 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
979 int *insn_idx, bool pop_log)
981 struct bpf_verifier_state *cur = env->cur_state;
982 struct bpf_verifier_stack_elem *elem, *head = env->head;
985 if (env->head == NULL)
989 err = copy_verifier_state(cur, &head->st);
994 bpf_vlog_reset(&env->log, head->log_pos);
996 *insn_idx = head->insn_idx;
998 *prev_insn_idx = head->prev_insn_idx;
1000 free_verifier_state(&head->st, false);
1007 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1008 int insn_idx, int prev_insn_idx,
1011 struct bpf_verifier_state *cur = env->cur_state;
1012 struct bpf_verifier_stack_elem *elem;
1015 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1019 elem->insn_idx = insn_idx;
1020 elem->prev_insn_idx = prev_insn_idx;
1021 elem->next = env->head;
1022 elem->log_pos = env->log.len_used;
1025 err = copy_verifier_state(&elem->st, cur);
1028 elem->st.speculative |= speculative;
1029 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1030 verbose(env, "The sequence of %d jumps is too complex.\n",
1034 if (elem->st.parent) {
1035 ++elem->st.parent->branches;
1036 /* WARN_ON(branches > 2) technically makes sense here,
1038 * 1. speculative states will bump 'branches' for non-branch
1040 * 2. is_state_visited() heuristics may decide not to create
1041 * a new state for a sequence of branches and all such current
1042 * and cloned states will be pointing to a single parent state
1043 * which might have large 'branches' count.
1048 free_verifier_state(env->cur_state, true);
1049 env->cur_state = NULL;
1050 /* pop all elements and return */
1051 while (!pop_stack(env, NULL, NULL, false));
1055 #define CALLER_SAVED_REGS 6
1056 static const int caller_saved[CALLER_SAVED_REGS] = {
1057 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1060 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1061 struct bpf_reg_state *reg);
1063 /* This helper doesn't clear reg->id */
1064 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1066 reg->var_off = tnum_const(imm);
1067 reg->smin_value = (s64)imm;
1068 reg->smax_value = (s64)imm;
1069 reg->umin_value = imm;
1070 reg->umax_value = imm;
1072 reg->s32_min_value = (s32)imm;
1073 reg->s32_max_value = (s32)imm;
1074 reg->u32_min_value = (u32)imm;
1075 reg->u32_max_value = (u32)imm;
1078 /* Mark the unknown part of a register (variable offset or scalar value) as
1079 * known to have the value @imm.
1081 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1083 /* Clear id, off, and union(map_ptr, range) */
1084 memset(((u8 *)reg) + sizeof(reg->type), 0,
1085 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1086 ___mark_reg_known(reg, imm);
1089 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1091 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1092 reg->s32_min_value = (s32)imm;
1093 reg->s32_max_value = (s32)imm;
1094 reg->u32_min_value = (u32)imm;
1095 reg->u32_max_value = (u32)imm;
1098 /* Mark the 'variable offset' part of a register as zero. This should be
1099 * used only on registers holding a pointer type.
1101 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1103 __mark_reg_known(reg, 0);
1106 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1108 __mark_reg_known(reg, 0);
1109 reg->type = SCALAR_VALUE;
1112 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1113 struct bpf_reg_state *regs, u32 regno)
1115 if (WARN_ON(regno >= MAX_BPF_REG)) {
1116 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1117 /* Something bad happened, let's kill all regs */
1118 for (regno = 0; regno < MAX_BPF_REG; regno++)
1119 __mark_reg_not_init(env, regs + regno);
1122 __mark_reg_known_zero(regs + regno);
1125 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1127 switch (reg->type) {
1128 case PTR_TO_MAP_VALUE_OR_NULL: {
1129 const struct bpf_map *map = reg->map_ptr;
1131 if (map->inner_map_meta) {
1132 reg->type = CONST_PTR_TO_MAP;
1133 reg->map_ptr = map->inner_map_meta;
1134 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1135 reg->type = PTR_TO_XDP_SOCK;
1136 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1137 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1138 reg->type = PTR_TO_SOCKET;
1140 reg->type = PTR_TO_MAP_VALUE;
1144 case PTR_TO_SOCKET_OR_NULL:
1145 reg->type = PTR_TO_SOCKET;
1147 case PTR_TO_SOCK_COMMON_OR_NULL:
1148 reg->type = PTR_TO_SOCK_COMMON;
1150 case PTR_TO_TCP_SOCK_OR_NULL:
1151 reg->type = PTR_TO_TCP_SOCK;
1153 case PTR_TO_BTF_ID_OR_NULL:
1154 reg->type = PTR_TO_BTF_ID;
1156 case PTR_TO_MEM_OR_NULL:
1157 reg->type = PTR_TO_MEM;
1159 case PTR_TO_RDONLY_BUF_OR_NULL:
1160 reg->type = PTR_TO_RDONLY_BUF;
1162 case PTR_TO_RDWR_BUF_OR_NULL:
1163 reg->type = PTR_TO_RDWR_BUF;
1166 WARN_ONCE(1, "unknown nullable register type");
1170 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1172 return type_is_pkt_pointer(reg->type);
1175 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1177 return reg_is_pkt_pointer(reg) ||
1178 reg->type == PTR_TO_PACKET_END;
1181 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1182 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1183 enum bpf_reg_type which)
1185 /* The register can already have a range from prior markings.
1186 * This is fine as long as it hasn't been advanced from its
1189 return reg->type == which &&
1192 tnum_equals_const(reg->var_off, 0);
1195 /* Reset the min/max bounds of a register */
1196 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1198 reg->smin_value = S64_MIN;
1199 reg->smax_value = S64_MAX;
1200 reg->umin_value = 0;
1201 reg->umax_value = U64_MAX;
1203 reg->s32_min_value = S32_MIN;
1204 reg->s32_max_value = S32_MAX;
1205 reg->u32_min_value = 0;
1206 reg->u32_max_value = U32_MAX;
1209 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1211 reg->smin_value = S64_MIN;
1212 reg->smax_value = S64_MAX;
1213 reg->umin_value = 0;
1214 reg->umax_value = U64_MAX;
1217 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1219 reg->s32_min_value = S32_MIN;
1220 reg->s32_max_value = S32_MAX;
1221 reg->u32_min_value = 0;
1222 reg->u32_max_value = U32_MAX;
1225 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1227 struct tnum var32_off = tnum_subreg(reg->var_off);
1229 /* min signed is max(sign bit) | min(other bits) */
1230 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1231 var32_off.value | (var32_off.mask & S32_MIN));
1232 /* max signed is min(sign bit) | max(other bits) */
1233 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1234 var32_off.value | (var32_off.mask & S32_MAX));
1235 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1236 reg->u32_max_value = min(reg->u32_max_value,
1237 (u32)(var32_off.value | var32_off.mask));
1240 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1242 /* min signed is max(sign bit) | min(other bits) */
1243 reg->smin_value = max_t(s64, reg->smin_value,
1244 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1245 /* max signed is min(sign bit) | max(other bits) */
1246 reg->smax_value = min_t(s64, reg->smax_value,
1247 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1248 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1249 reg->umax_value = min(reg->umax_value,
1250 reg->var_off.value | reg->var_off.mask);
1253 static void __update_reg_bounds(struct bpf_reg_state *reg)
1255 __update_reg32_bounds(reg);
1256 __update_reg64_bounds(reg);
1259 /* Uses signed min/max values to inform unsigned, and vice-versa */
1260 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1262 /* Learn sign from signed bounds.
1263 * If we cannot cross the sign boundary, then signed and unsigned bounds
1264 * are the same, so combine. This works even in the negative case, e.g.
1265 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1267 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1268 reg->s32_min_value = reg->u32_min_value =
1269 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1270 reg->s32_max_value = reg->u32_max_value =
1271 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1274 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1275 * boundary, so we must be careful.
1277 if ((s32)reg->u32_max_value >= 0) {
1278 /* Positive. We can't learn anything from the smin, but smax
1279 * is positive, hence safe.
1281 reg->s32_min_value = reg->u32_min_value;
1282 reg->s32_max_value = reg->u32_max_value =
1283 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1284 } else if ((s32)reg->u32_min_value < 0) {
1285 /* Negative. We can't learn anything from the smax, but smin
1286 * is negative, hence safe.
1288 reg->s32_min_value = reg->u32_min_value =
1289 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1290 reg->s32_max_value = reg->u32_max_value;
1294 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1296 /* Learn sign from signed bounds.
1297 * If we cannot cross the sign boundary, then signed and unsigned bounds
1298 * are the same, so combine. This works even in the negative case, e.g.
1299 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1301 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1302 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1304 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1308 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1309 * boundary, so we must be careful.
1311 if ((s64)reg->umax_value >= 0) {
1312 /* Positive. We can't learn anything from the smin, but smax
1313 * is positive, hence safe.
1315 reg->smin_value = reg->umin_value;
1316 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1318 } else if ((s64)reg->umin_value < 0) {
1319 /* Negative. We can't learn anything from the smax, but smin
1320 * is negative, hence safe.
1322 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1324 reg->smax_value = reg->umax_value;
1328 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1330 __reg32_deduce_bounds(reg);
1331 __reg64_deduce_bounds(reg);
1334 /* Attempts to improve var_off based on unsigned min/max information */
1335 static void __reg_bound_offset(struct bpf_reg_state *reg)
1337 struct tnum var64_off = tnum_intersect(reg->var_off,
1338 tnum_range(reg->umin_value,
1340 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1341 tnum_range(reg->u32_min_value,
1342 reg->u32_max_value));
1344 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1347 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1349 reg->umin_value = reg->u32_min_value;
1350 reg->umax_value = reg->u32_max_value;
1351 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1352 * but must be positive otherwise set to worse case bounds
1353 * and refine later from tnum.
1355 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1356 reg->smax_value = reg->s32_max_value;
1358 reg->smax_value = U32_MAX;
1359 if (reg->s32_min_value >= 0)
1360 reg->smin_value = reg->s32_min_value;
1362 reg->smin_value = 0;
1365 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1367 /* special case when 64-bit register has upper 32-bit register
1368 * zeroed. Typically happens after zext or <<32, >>32 sequence
1369 * allowing us to use 32-bit bounds directly,
1371 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1372 __reg_assign_32_into_64(reg);
1374 /* Otherwise the best we can do is push lower 32bit known and
1375 * unknown bits into register (var_off set from jmp logic)
1376 * then learn as much as possible from the 64-bit tnum
1377 * known and unknown bits. The previous smin/smax bounds are
1378 * invalid here because of jmp32 compare so mark them unknown
1379 * so they do not impact tnum bounds calculation.
1381 __mark_reg64_unbounded(reg);
1382 __update_reg_bounds(reg);
1385 /* Intersecting with the old var_off might have improved our bounds
1386 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1387 * then new var_off is (0; 0x7f...fc) which improves our umax.
1389 __reg_deduce_bounds(reg);
1390 __reg_bound_offset(reg);
1391 __update_reg_bounds(reg);
1394 static bool __reg64_bound_s32(s64 a)
1396 return a > S32_MIN && a < S32_MAX;
1399 static bool __reg64_bound_u32(u64 a)
1401 return a > U32_MIN && a < U32_MAX;
1404 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1406 __mark_reg32_unbounded(reg);
1408 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1409 reg->s32_min_value = (s32)reg->smin_value;
1410 reg->s32_max_value = (s32)reg->smax_value;
1412 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1413 reg->u32_min_value = (u32)reg->umin_value;
1414 reg->u32_max_value = (u32)reg->umax_value;
1417 /* Intersecting with the old var_off might have improved our bounds
1418 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1419 * then new var_off is (0; 0x7f...fc) which improves our umax.
1421 __reg_deduce_bounds(reg);
1422 __reg_bound_offset(reg);
1423 __update_reg_bounds(reg);
1426 /* Mark a register as having a completely unknown (scalar) value. */
1427 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1428 struct bpf_reg_state *reg)
1431 * Clear type, id, off, and union(map_ptr, range) and
1432 * padding between 'type' and union
1434 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1435 reg->type = SCALAR_VALUE;
1436 reg->var_off = tnum_unknown;
1438 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1439 __mark_reg_unbounded(reg);
1442 static void mark_reg_unknown(struct bpf_verifier_env *env,
1443 struct bpf_reg_state *regs, u32 regno)
1445 if (WARN_ON(regno >= MAX_BPF_REG)) {
1446 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1447 /* Something bad happened, let's kill all regs except FP */
1448 for (regno = 0; regno < BPF_REG_FP; regno++)
1449 __mark_reg_not_init(env, regs + regno);
1452 __mark_reg_unknown(env, regs + regno);
1455 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1456 struct bpf_reg_state *reg)
1458 __mark_reg_unknown(env, reg);
1459 reg->type = NOT_INIT;
1462 static void mark_reg_not_init(struct bpf_verifier_env *env,
1463 struct bpf_reg_state *regs, u32 regno)
1465 if (WARN_ON(regno >= MAX_BPF_REG)) {
1466 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1467 /* Something bad happened, let's kill all regs except FP */
1468 for (regno = 0; regno < BPF_REG_FP; regno++)
1469 __mark_reg_not_init(env, regs + regno);
1472 __mark_reg_not_init(env, regs + regno);
1475 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1476 struct bpf_reg_state *regs, u32 regno,
1477 enum bpf_reg_type reg_type,
1478 struct btf *btf, u32 btf_id)
1480 if (reg_type == SCALAR_VALUE) {
1481 mark_reg_unknown(env, regs, regno);
1484 mark_reg_known_zero(env, regs, regno);
1485 regs[regno].type = PTR_TO_BTF_ID;
1486 regs[regno].btf = btf;
1487 regs[regno].btf_id = btf_id;
1490 #define DEF_NOT_SUBREG (0)
1491 static void init_reg_state(struct bpf_verifier_env *env,
1492 struct bpf_func_state *state)
1494 struct bpf_reg_state *regs = state->regs;
1497 for (i = 0; i < MAX_BPF_REG; i++) {
1498 mark_reg_not_init(env, regs, i);
1499 regs[i].live = REG_LIVE_NONE;
1500 regs[i].parent = NULL;
1501 regs[i].subreg_def = DEF_NOT_SUBREG;
1505 regs[BPF_REG_FP].type = PTR_TO_STACK;
1506 mark_reg_known_zero(env, regs, BPF_REG_FP);
1507 regs[BPF_REG_FP].frameno = state->frameno;
1510 #define BPF_MAIN_FUNC (-1)
1511 static void init_func_state(struct bpf_verifier_env *env,
1512 struct bpf_func_state *state,
1513 int callsite, int frameno, int subprogno)
1515 state->callsite = callsite;
1516 state->frameno = frameno;
1517 state->subprogno = subprogno;
1518 init_reg_state(env, state);
1522 SRC_OP, /* register is used as source operand */
1523 DST_OP, /* register is used as destination operand */
1524 DST_OP_NO_MARK /* same as above, check only, don't mark */
1527 static int cmp_subprogs(const void *a, const void *b)
1529 return ((struct bpf_subprog_info *)a)->start -
1530 ((struct bpf_subprog_info *)b)->start;
1533 static int find_subprog(struct bpf_verifier_env *env, int off)
1535 struct bpf_subprog_info *p;
1537 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1538 sizeof(env->subprog_info[0]), cmp_subprogs);
1541 return p - env->subprog_info;
1545 static int add_subprog(struct bpf_verifier_env *env, int off)
1547 int insn_cnt = env->prog->len;
1550 if (off >= insn_cnt || off < 0) {
1551 verbose(env, "call to invalid destination\n");
1554 ret = find_subprog(env, off);
1557 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1558 verbose(env, "too many subprograms\n");
1561 /* determine subprog starts. The end is one before the next starts */
1562 env->subprog_info[env->subprog_cnt++].start = off;
1563 sort(env->subprog_info, env->subprog_cnt,
1564 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1565 return env->subprog_cnt - 1;
1568 struct bpf_kfunc_desc {
1569 struct btf_func_model func_model;
1574 #define MAX_KFUNC_DESCS 256
1575 struct bpf_kfunc_desc_tab {
1576 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1580 static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1582 const struct bpf_kfunc_desc *d0 = a;
1583 const struct bpf_kfunc_desc *d1 = b;
1585 /* func_id is not greater than BTF_MAX_TYPE */
1586 return d0->func_id - d1->func_id;
1589 static const struct bpf_kfunc_desc *
1590 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1592 struct bpf_kfunc_desc desc = {
1595 struct bpf_kfunc_desc_tab *tab;
1597 tab = prog->aux->kfunc_tab;
1598 return bsearch(&desc, tab->descs, tab->nr_descs,
1599 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1602 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1604 const struct btf_type *func, *func_proto;
1605 struct bpf_kfunc_desc_tab *tab;
1606 struct bpf_prog_aux *prog_aux;
1607 struct bpf_kfunc_desc *desc;
1608 const char *func_name;
1612 prog_aux = env->prog->aux;
1613 tab = prog_aux->kfunc_tab;
1616 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1620 if (!env->prog->jit_requested) {
1621 verbose(env, "JIT is required for calling kernel function\n");
1625 if (!bpf_jit_supports_kfunc_call()) {
1626 verbose(env, "JIT does not support calling kernel function\n");
1630 if (!env->prog->gpl_compatible) {
1631 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1635 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1638 prog_aux->kfunc_tab = tab;
1641 if (find_kfunc_desc(env->prog, func_id))
1644 if (tab->nr_descs == MAX_KFUNC_DESCS) {
1645 verbose(env, "too many different kernel function calls\n");
1649 func = btf_type_by_id(btf_vmlinux, func_id);
1650 if (!func || !btf_type_is_func(func)) {
1651 verbose(env, "kernel btf_id %u is not a function\n",
1655 func_proto = btf_type_by_id(btf_vmlinux, func->type);
1656 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1657 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1662 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1663 addr = kallsyms_lookup_name(func_name);
1665 verbose(env, "cannot find address for kernel function %s\n",
1670 desc = &tab->descs[tab->nr_descs++];
1671 desc->func_id = func_id;
1672 desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1673 err = btf_distill_func_proto(&env->log, btf_vmlinux,
1674 func_proto, func_name,
1677 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1678 kfunc_desc_cmp_by_id, NULL);
1682 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1684 const struct bpf_kfunc_desc *d0 = a;
1685 const struct bpf_kfunc_desc *d1 = b;
1687 if (d0->imm > d1->imm)
1689 else if (d0->imm < d1->imm)
1694 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1696 struct bpf_kfunc_desc_tab *tab;
1698 tab = prog->aux->kfunc_tab;
1702 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1703 kfunc_desc_cmp_by_imm, NULL);
1706 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1708 return !!prog->aux->kfunc_tab;
1711 const struct btf_func_model *
1712 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1713 const struct bpf_insn *insn)
1715 const struct bpf_kfunc_desc desc = {
1718 const struct bpf_kfunc_desc *res;
1719 struct bpf_kfunc_desc_tab *tab;
1721 tab = prog->aux->kfunc_tab;
1722 res = bsearch(&desc, tab->descs, tab->nr_descs,
1723 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1725 return res ? &res->func_model : NULL;
1728 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1730 struct bpf_subprog_info *subprog = env->subprog_info;
1731 struct bpf_insn *insn = env->prog->insnsi;
1732 int i, ret, insn_cnt = env->prog->len;
1734 /* Add entry function. */
1735 ret = add_subprog(env, 0);
1739 for (i = 0; i < insn_cnt; i++, insn++) {
1740 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1741 !bpf_pseudo_kfunc_call(insn))
1744 if (!env->bpf_capable) {
1745 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1749 if (bpf_pseudo_func(insn)) {
1750 ret = add_subprog(env, i + insn->imm + 1);
1752 /* remember subprog */
1754 } else if (bpf_pseudo_call(insn)) {
1755 ret = add_subprog(env, i + insn->imm + 1);
1757 ret = add_kfunc_call(env, insn->imm);
1764 /* Add a fake 'exit' subprog which could simplify subprog iteration
1765 * logic. 'subprog_cnt' should not be increased.
1767 subprog[env->subprog_cnt].start = insn_cnt;
1769 if (env->log.level & BPF_LOG_LEVEL2)
1770 for (i = 0; i < env->subprog_cnt; i++)
1771 verbose(env, "func#%d @%d\n", i, subprog[i].start);
1776 static int check_subprogs(struct bpf_verifier_env *env)
1778 int i, subprog_start, subprog_end, off, cur_subprog = 0;
1779 struct bpf_subprog_info *subprog = env->subprog_info;
1780 struct bpf_insn *insn = env->prog->insnsi;
1781 int insn_cnt = env->prog->len;
1783 /* now check that all jumps are within the same subprog */
1784 subprog_start = subprog[cur_subprog].start;
1785 subprog_end = subprog[cur_subprog + 1].start;
1786 for (i = 0; i < insn_cnt; i++) {
1787 u8 code = insn[i].code;
1789 if (code == (BPF_JMP | BPF_CALL) &&
1790 insn[i].imm == BPF_FUNC_tail_call &&
1791 insn[i].src_reg != BPF_PSEUDO_CALL)
1792 subprog[cur_subprog].has_tail_call = true;
1793 if (BPF_CLASS(code) == BPF_LD &&
1794 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1795 subprog[cur_subprog].has_ld_abs = true;
1796 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1798 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1800 off = i + insn[i].off + 1;
1801 if (off < subprog_start || off >= subprog_end) {
1802 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1806 if (i == subprog_end - 1) {
1807 /* to avoid fall-through from one subprog into another
1808 * the last insn of the subprog should be either exit
1809 * or unconditional jump back
1811 if (code != (BPF_JMP | BPF_EXIT) &&
1812 code != (BPF_JMP | BPF_JA)) {
1813 verbose(env, "last insn is not an exit or jmp\n");
1816 subprog_start = subprog_end;
1818 if (cur_subprog < env->subprog_cnt)
1819 subprog_end = subprog[cur_subprog + 1].start;
1825 /* Parentage chain of this register (or stack slot) should take care of all
1826 * issues like callee-saved registers, stack slot allocation time, etc.
1828 static int mark_reg_read(struct bpf_verifier_env *env,
1829 const struct bpf_reg_state *state,
1830 struct bpf_reg_state *parent, u8 flag)
1832 bool writes = parent == state->parent; /* Observe write marks */
1836 /* if read wasn't screened by an earlier write ... */
1837 if (writes && state->live & REG_LIVE_WRITTEN)
1839 if (parent->live & REG_LIVE_DONE) {
1840 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1841 reg_type_str[parent->type],
1842 parent->var_off.value, parent->off);
1845 /* The first condition is more likely to be true than the
1846 * second, checked it first.
1848 if ((parent->live & REG_LIVE_READ) == flag ||
1849 parent->live & REG_LIVE_READ64)
1850 /* The parentage chain never changes and
1851 * this parent was already marked as LIVE_READ.
1852 * There is no need to keep walking the chain again and
1853 * keep re-marking all parents as LIVE_READ.
1854 * This case happens when the same register is read
1855 * multiple times without writes into it in-between.
1856 * Also, if parent has the stronger REG_LIVE_READ64 set,
1857 * then no need to set the weak REG_LIVE_READ32.
1860 /* ... then we depend on parent's value */
1861 parent->live |= flag;
1862 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1863 if (flag == REG_LIVE_READ64)
1864 parent->live &= ~REG_LIVE_READ32;
1866 parent = state->parent;
1871 if (env->longest_mark_read_walk < cnt)
1872 env->longest_mark_read_walk = cnt;
1876 /* This function is supposed to be used by the following 32-bit optimization
1877 * code only. It returns TRUE if the source or destination register operates
1878 * on 64-bit, otherwise return FALSE.
1880 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1881 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1886 class = BPF_CLASS(code);
1888 if (class == BPF_JMP) {
1889 /* BPF_EXIT for "main" will reach here. Return TRUE
1894 if (op == BPF_CALL) {
1895 /* BPF to BPF call will reach here because of marking
1896 * caller saved clobber with DST_OP_NO_MARK for which we
1897 * don't care the register def because they are anyway
1898 * marked as NOT_INIT already.
1900 if (insn->src_reg == BPF_PSEUDO_CALL)
1902 /* Helper call will reach here because of arg type
1903 * check, conservatively return TRUE.
1912 if (class == BPF_ALU64 || class == BPF_JMP ||
1913 /* BPF_END always use BPF_ALU class. */
1914 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1917 if (class == BPF_ALU || class == BPF_JMP32)
1920 if (class == BPF_LDX) {
1922 return BPF_SIZE(code) == BPF_DW;
1923 /* LDX source must be ptr. */
1927 if (class == BPF_STX) {
1928 /* BPF_STX (including atomic variants) has multiple source
1929 * operands, one of which is a ptr. Check whether the caller is
1932 if (t == SRC_OP && reg->type != SCALAR_VALUE)
1934 return BPF_SIZE(code) == BPF_DW;
1937 if (class == BPF_LD) {
1938 u8 mode = BPF_MODE(code);
1941 if (mode == BPF_IMM)
1944 /* Both LD_IND and LD_ABS return 32-bit data. */
1948 /* Implicit ctx ptr. */
1949 if (regno == BPF_REG_6)
1952 /* Explicit source could be any width. */
1956 if (class == BPF_ST)
1957 /* The only source register for BPF_ST is a ptr. */
1960 /* Conservatively return true at default. */
1964 /* Return the regno defined by the insn, or -1. */
1965 static int insn_def_regno(const struct bpf_insn *insn)
1967 switch (BPF_CLASS(insn->code)) {
1973 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1974 (insn->imm & BPF_FETCH)) {
1975 if (insn->imm == BPF_CMPXCHG)
1978 return insn->src_reg;
1983 return insn->dst_reg;
1987 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1988 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1990 int dst_reg = insn_def_regno(insn);
1995 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
1998 static void mark_insn_zext(struct bpf_verifier_env *env,
1999 struct bpf_reg_state *reg)
2001 s32 def_idx = reg->subreg_def;
2003 if (def_idx == DEF_NOT_SUBREG)
2006 env->insn_aux_data[def_idx - 1].zext_dst = true;
2007 /* The dst will be zero extended, so won't be sub-register anymore. */
2008 reg->subreg_def = DEF_NOT_SUBREG;
2011 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2012 enum reg_arg_type t)
2014 struct bpf_verifier_state *vstate = env->cur_state;
2015 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2016 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2017 struct bpf_reg_state *reg, *regs = state->regs;
2020 if (regno >= MAX_BPF_REG) {
2021 verbose(env, "R%d is invalid\n", regno);
2026 rw64 = is_reg64(env, insn, regno, reg, t);
2028 /* check whether register used as source operand can be read */
2029 if (reg->type == NOT_INIT) {
2030 verbose(env, "R%d !read_ok\n", regno);
2033 /* We don't need to worry about FP liveness because it's read-only */
2034 if (regno == BPF_REG_FP)
2038 mark_insn_zext(env, reg);
2040 return mark_reg_read(env, reg, reg->parent,
2041 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2043 /* check whether register used as dest operand can be written to */
2044 if (regno == BPF_REG_FP) {
2045 verbose(env, "frame pointer is read only\n");
2048 reg->live |= REG_LIVE_WRITTEN;
2049 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2051 mark_reg_unknown(env, regs, regno);
2056 /* for any branch, call, exit record the history of jmps in the given state */
2057 static int push_jmp_history(struct bpf_verifier_env *env,
2058 struct bpf_verifier_state *cur)
2060 u32 cnt = cur->jmp_history_cnt;
2061 struct bpf_idx_pair *p;
2064 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2067 p[cnt - 1].idx = env->insn_idx;
2068 p[cnt - 1].prev_idx = env->prev_insn_idx;
2069 cur->jmp_history = p;
2070 cur->jmp_history_cnt = cnt;
2074 /* Backtrack one insn at a time. If idx is not at the top of recorded
2075 * history then previous instruction came from straight line execution.
2077 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2082 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2083 i = st->jmp_history[cnt - 1].prev_idx;
2091 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2093 const struct btf_type *func;
2095 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2098 func = btf_type_by_id(btf_vmlinux, insn->imm);
2099 return btf_name_by_offset(btf_vmlinux, func->name_off);
2102 /* For given verifier state backtrack_insn() is called from the last insn to
2103 * the first insn. Its purpose is to compute a bitmask of registers and
2104 * stack slots that needs precision in the parent verifier state.
2106 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2107 u32 *reg_mask, u64 *stack_mask)
2109 const struct bpf_insn_cbs cbs = {
2110 .cb_call = disasm_kfunc_name,
2111 .cb_print = verbose,
2112 .private_data = env,
2114 struct bpf_insn *insn = env->prog->insnsi + idx;
2115 u8 class = BPF_CLASS(insn->code);
2116 u8 opcode = BPF_OP(insn->code);
2117 u8 mode = BPF_MODE(insn->code);
2118 u32 dreg = 1u << insn->dst_reg;
2119 u32 sreg = 1u << insn->src_reg;
2122 if (insn->code == 0)
2124 if (env->log.level & BPF_LOG_LEVEL) {
2125 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2126 verbose(env, "%d: ", idx);
2127 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2130 if (class == BPF_ALU || class == BPF_ALU64) {
2131 if (!(*reg_mask & dreg))
2133 if (opcode == BPF_MOV) {
2134 if (BPF_SRC(insn->code) == BPF_X) {
2136 * dreg needs precision after this insn
2137 * sreg needs precision before this insn
2143 * dreg needs precision after this insn.
2144 * Corresponding register is already marked
2145 * as precise=true in this verifier state.
2146 * No further markings in parent are necessary
2151 if (BPF_SRC(insn->code) == BPF_X) {
2153 * both dreg and sreg need precision
2158 * dreg still needs precision before this insn
2161 } else if (class == BPF_LDX) {
2162 if (!(*reg_mask & dreg))
2166 /* scalars can only be spilled into stack w/o losing precision.
2167 * Load from any other memory can be zero extended.
2168 * The desire to keep that precision is already indicated
2169 * by 'precise' mark in corresponding register of this state.
2170 * No further tracking necessary.
2172 if (insn->src_reg != BPF_REG_FP)
2174 if (BPF_SIZE(insn->code) != BPF_DW)
2177 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2178 * that [fp - off] slot contains scalar that needs to be
2179 * tracked with precision
2181 spi = (-insn->off - 1) / BPF_REG_SIZE;
2183 verbose(env, "BUG spi %d\n", spi);
2184 WARN_ONCE(1, "verifier backtracking bug");
2187 *stack_mask |= 1ull << spi;
2188 } else if (class == BPF_STX || class == BPF_ST) {
2189 if (*reg_mask & dreg)
2190 /* stx & st shouldn't be using _scalar_ dst_reg
2191 * to access memory. It means backtracking
2192 * encountered a case of pointer subtraction.
2195 /* scalars can only be spilled into stack */
2196 if (insn->dst_reg != BPF_REG_FP)
2198 if (BPF_SIZE(insn->code) != BPF_DW)
2200 spi = (-insn->off - 1) / BPF_REG_SIZE;
2202 verbose(env, "BUG spi %d\n", spi);
2203 WARN_ONCE(1, "verifier backtracking bug");
2206 if (!(*stack_mask & (1ull << spi)))
2208 *stack_mask &= ~(1ull << spi);
2209 if (class == BPF_STX)
2211 } else if (class == BPF_JMP || class == BPF_JMP32) {
2212 if (opcode == BPF_CALL) {
2213 if (insn->src_reg == BPF_PSEUDO_CALL)
2215 /* regular helper call sets R0 */
2217 if (*reg_mask & 0x3f) {
2218 /* if backtracing was looking for registers R1-R5
2219 * they should have been found already.
2221 verbose(env, "BUG regs %x\n", *reg_mask);
2222 WARN_ONCE(1, "verifier backtracking bug");
2225 } else if (opcode == BPF_EXIT) {
2228 } else if (class == BPF_LD) {
2229 if (!(*reg_mask & dreg))
2232 /* It's ld_imm64 or ld_abs or ld_ind.
2233 * For ld_imm64 no further tracking of precision
2234 * into parent is necessary
2236 if (mode == BPF_IND || mode == BPF_ABS)
2237 /* to be analyzed */
2243 /* the scalar precision tracking algorithm:
2244 * . at the start all registers have precise=false.
2245 * . scalar ranges are tracked as normal through alu and jmp insns.
2246 * . once precise value of the scalar register is used in:
2247 * . ptr + scalar alu
2248 * . if (scalar cond K|scalar)
2249 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2250 * backtrack through the verifier states and mark all registers and
2251 * stack slots with spilled constants that these scalar regisers
2252 * should be precise.
2253 * . during state pruning two registers (or spilled stack slots)
2254 * are equivalent if both are not precise.
2256 * Note the verifier cannot simply walk register parentage chain,
2257 * since many different registers and stack slots could have been
2258 * used to compute single precise scalar.
2260 * The approach of starting with precise=true for all registers and then
2261 * backtrack to mark a register as not precise when the verifier detects
2262 * that program doesn't care about specific value (e.g., when helper
2263 * takes register as ARG_ANYTHING parameter) is not safe.
2265 * It's ok to walk single parentage chain of the verifier states.
2266 * It's possible that this backtracking will go all the way till 1st insn.
2267 * All other branches will be explored for needing precision later.
2269 * The backtracking needs to deal with cases like:
2270 * 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)
2273 * if r5 > 0x79f goto pc+7
2274 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2277 * call bpf_perf_event_output#25
2278 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2282 * call foo // uses callee's r6 inside to compute r0
2286 * to track above reg_mask/stack_mask needs to be independent for each frame.
2288 * Also if parent's curframe > frame where backtracking started,
2289 * the verifier need to mark registers in both frames, otherwise callees
2290 * may incorrectly prune callers. This is similar to
2291 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2293 * For now backtracking falls back into conservative marking.
2295 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2296 struct bpf_verifier_state *st)
2298 struct bpf_func_state *func;
2299 struct bpf_reg_state *reg;
2302 /* big hammer: mark all scalars precise in this path.
2303 * pop_stack may still get !precise scalars.
2305 for (; st; st = st->parent)
2306 for (i = 0; i <= st->curframe; i++) {
2307 func = st->frame[i];
2308 for (j = 0; j < BPF_REG_FP; j++) {
2309 reg = &func->regs[j];
2310 if (reg->type != SCALAR_VALUE)
2312 reg->precise = true;
2314 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2315 if (func->stack[j].slot_type[0] != STACK_SPILL)
2317 reg = &func->stack[j].spilled_ptr;
2318 if (reg->type != SCALAR_VALUE)
2320 reg->precise = true;
2325 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2328 struct bpf_verifier_state *st = env->cur_state;
2329 int first_idx = st->first_insn_idx;
2330 int last_idx = env->insn_idx;
2331 struct bpf_func_state *func;
2332 struct bpf_reg_state *reg;
2333 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2334 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2335 bool skip_first = true;
2336 bool new_marks = false;
2339 if (!env->bpf_capable)
2342 func = st->frame[st->curframe];
2344 reg = &func->regs[regno];
2345 if (reg->type != SCALAR_VALUE) {
2346 WARN_ONCE(1, "backtracing misuse");
2353 reg->precise = true;
2357 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2361 reg = &func->stack[spi].spilled_ptr;
2362 if (reg->type != SCALAR_VALUE) {
2370 reg->precise = true;
2376 if (!reg_mask && !stack_mask)
2379 DECLARE_BITMAP(mask, 64);
2380 u32 history = st->jmp_history_cnt;
2382 if (env->log.level & BPF_LOG_LEVEL)
2383 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2384 for (i = last_idx;;) {
2389 err = backtrack_insn(env, i, ®_mask, &stack_mask);
2391 if (err == -ENOTSUPP) {
2392 mark_all_scalars_precise(env, st);
2397 if (!reg_mask && !stack_mask)
2398 /* Found assignment(s) into tracked register in this state.
2399 * Since this state is already marked, just return.
2400 * Nothing to be tracked further in the parent state.
2405 i = get_prev_insn_idx(st, i, &history);
2406 if (i >= env->prog->len) {
2407 /* This can happen if backtracking reached insn 0
2408 * and there are still reg_mask or stack_mask
2410 * It means the backtracking missed the spot where
2411 * particular register was initialized with a constant.
2413 verbose(env, "BUG backtracking idx %d\n", i);
2414 WARN_ONCE(1, "verifier backtracking bug");
2423 func = st->frame[st->curframe];
2424 bitmap_from_u64(mask, reg_mask);
2425 for_each_set_bit(i, mask, 32) {
2426 reg = &func->regs[i];
2427 if (reg->type != SCALAR_VALUE) {
2428 reg_mask &= ~(1u << i);
2433 reg->precise = true;
2436 bitmap_from_u64(mask, stack_mask);
2437 for_each_set_bit(i, mask, 64) {
2438 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2439 /* the sequence of instructions:
2441 * 3: (7b) *(u64 *)(r3 -8) = r0
2442 * 4: (79) r4 = *(u64 *)(r10 -8)
2443 * doesn't contain jmps. It's backtracked
2444 * as a single block.
2445 * During backtracking insn 3 is not recognized as
2446 * stack access, so at the end of backtracking
2447 * stack slot fp-8 is still marked in stack_mask.
2448 * However the parent state may not have accessed
2449 * fp-8 and it's "unallocated" stack space.
2450 * In such case fallback to conservative.
2452 mark_all_scalars_precise(env, st);
2456 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2457 stack_mask &= ~(1ull << i);
2460 reg = &func->stack[i].spilled_ptr;
2461 if (reg->type != SCALAR_VALUE) {
2462 stack_mask &= ~(1ull << i);
2467 reg->precise = true;
2469 if (env->log.level & BPF_LOG_LEVEL) {
2470 print_verifier_state(env, func);
2471 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2472 new_marks ? "didn't have" : "already had",
2473 reg_mask, stack_mask);
2476 if (!reg_mask && !stack_mask)
2481 last_idx = st->last_insn_idx;
2482 first_idx = st->first_insn_idx;
2487 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2489 return __mark_chain_precision(env, regno, -1);
2492 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2494 return __mark_chain_precision(env, -1, spi);
2497 static bool is_spillable_regtype(enum bpf_reg_type type)
2500 case PTR_TO_MAP_VALUE:
2501 case PTR_TO_MAP_VALUE_OR_NULL:
2505 case PTR_TO_PACKET_META:
2506 case PTR_TO_PACKET_END:
2507 case PTR_TO_FLOW_KEYS:
2508 case CONST_PTR_TO_MAP:
2510 case PTR_TO_SOCKET_OR_NULL:
2511 case PTR_TO_SOCK_COMMON:
2512 case PTR_TO_SOCK_COMMON_OR_NULL:
2513 case PTR_TO_TCP_SOCK:
2514 case PTR_TO_TCP_SOCK_OR_NULL:
2515 case PTR_TO_XDP_SOCK:
2517 case PTR_TO_BTF_ID_OR_NULL:
2518 case PTR_TO_RDONLY_BUF:
2519 case PTR_TO_RDONLY_BUF_OR_NULL:
2520 case PTR_TO_RDWR_BUF:
2521 case PTR_TO_RDWR_BUF_OR_NULL:
2522 case PTR_TO_PERCPU_BTF_ID:
2524 case PTR_TO_MEM_OR_NULL:
2526 case PTR_TO_MAP_KEY:
2533 /* Does this register contain a constant zero? */
2534 static bool register_is_null(struct bpf_reg_state *reg)
2536 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2539 static bool register_is_const(struct bpf_reg_state *reg)
2541 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2544 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2546 return tnum_is_unknown(reg->var_off) &&
2547 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2548 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2549 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2550 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2553 static bool register_is_bounded(struct bpf_reg_state *reg)
2555 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2558 static bool __is_pointer_value(bool allow_ptr_leaks,
2559 const struct bpf_reg_state *reg)
2561 if (allow_ptr_leaks)
2564 return reg->type != SCALAR_VALUE;
2567 static void save_register_state(struct bpf_func_state *state,
2568 int spi, struct bpf_reg_state *reg)
2572 state->stack[spi].spilled_ptr = *reg;
2573 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2575 for (i = 0; i < BPF_REG_SIZE; i++)
2576 state->stack[spi].slot_type[i] = STACK_SPILL;
2579 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2580 * stack boundary and alignment are checked in check_mem_access()
2582 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2583 /* stack frame we're writing to */
2584 struct bpf_func_state *state,
2585 int off, int size, int value_regno,
2588 struct bpf_func_state *cur; /* state of the current function */
2589 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2590 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2591 struct bpf_reg_state *reg = NULL;
2593 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2594 state->acquired_refs, true);
2597 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2598 * so it's aligned access and [off, off + size) are within stack limits
2600 if (!env->allow_ptr_leaks &&
2601 state->stack[spi].slot_type[0] == STACK_SPILL &&
2602 size != BPF_REG_SIZE) {
2603 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2607 cur = env->cur_state->frame[env->cur_state->curframe];
2608 if (value_regno >= 0)
2609 reg = &cur->regs[value_regno];
2611 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2612 !register_is_null(reg) && env->bpf_capable) {
2613 if (dst_reg != BPF_REG_FP) {
2614 /* The backtracking logic can only recognize explicit
2615 * stack slot address like [fp - 8]. Other spill of
2616 * scalar via different register has to be conervative.
2617 * Backtrack from here and mark all registers as precise
2618 * that contributed into 'reg' being a constant.
2620 err = mark_chain_precision(env, value_regno);
2624 save_register_state(state, spi, reg);
2625 } else if (reg && is_spillable_regtype(reg->type)) {
2626 /* register containing pointer is being spilled into stack */
2627 if (size != BPF_REG_SIZE) {
2628 verbose_linfo(env, insn_idx, "; ");
2629 verbose(env, "invalid size of register spill\n");
2633 if (state != cur && reg->type == PTR_TO_STACK) {
2634 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2638 if (!env->bypass_spec_v4) {
2639 bool sanitize = false;
2641 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2642 register_is_const(&state->stack[spi].spilled_ptr))
2644 for (i = 0; i < BPF_REG_SIZE; i++)
2645 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2650 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2651 int soff = (-spi - 1) * BPF_REG_SIZE;
2653 /* detected reuse of integer stack slot with a pointer
2654 * which means either llvm is reusing stack slot or
2655 * an attacker is trying to exploit CVE-2018-3639
2656 * (speculative store bypass)
2657 * Have to sanitize that slot with preemptive
2660 if (*poff && *poff != soff) {
2661 /* disallow programs where single insn stores
2662 * into two different stack slots, since verifier
2663 * cannot sanitize them
2666 "insn %d cannot access two stack slots fp%d and fp%d",
2667 insn_idx, *poff, soff);
2673 save_register_state(state, spi, reg);
2675 u8 type = STACK_MISC;
2677 /* regular write of data into stack destroys any spilled ptr */
2678 state->stack[spi].spilled_ptr.type = NOT_INIT;
2679 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2680 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2681 for (i = 0; i < BPF_REG_SIZE; i++)
2682 state->stack[spi].slot_type[i] = STACK_MISC;
2684 /* only mark the slot as written if all 8 bytes were written
2685 * otherwise read propagation may incorrectly stop too soon
2686 * when stack slots are partially written.
2687 * This heuristic means that read propagation will be
2688 * conservative, since it will add reg_live_read marks
2689 * to stack slots all the way to first state when programs
2690 * writes+reads less than 8 bytes
2692 if (size == BPF_REG_SIZE)
2693 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2695 /* when we zero initialize stack slots mark them as such */
2696 if (reg && register_is_null(reg)) {
2697 /* backtracking doesn't work for STACK_ZERO yet. */
2698 err = mark_chain_precision(env, value_regno);
2704 /* Mark slots affected by this stack write. */
2705 for (i = 0; i < size; i++)
2706 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2712 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2713 * known to contain a variable offset.
2714 * This function checks whether the write is permitted and conservatively
2715 * tracks the effects of the write, considering that each stack slot in the
2716 * dynamic range is potentially written to.
2718 * 'off' includes 'regno->off'.
2719 * 'value_regno' can be -1, meaning that an unknown value is being written to
2722 * Spilled pointers in range are not marked as written because we don't know
2723 * what's going to be actually written. This means that read propagation for
2724 * future reads cannot be terminated by this write.
2726 * For privileged programs, uninitialized stack slots are considered
2727 * initialized by this write (even though we don't know exactly what offsets
2728 * are going to be written to). The idea is that we don't want the verifier to
2729 * reject future reads that access slots written to through variable offsets.
2731 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2732 /* func where register points to */
2733 struct bpf_func_state *state,
2734 int ptr_regno, int off, int size,
2735 int value_regno, int insn_idx)
2737 struct bpf_func_state *cur; /* state of the current function */
2738 int min_off, max_off;
2740 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2741 bool writing_zero = false;
2742 /* set if the fact that we're writing a zero is used to let any
2743 * stack slots remain STACK_ZERO
2745 bool zero_used = false;
2747 cur = env->cur_state->frame[env->cur_state->curframe];
2748 ptr_reg = &cur->regs[ptr_regno];
2749 min_off = ptr_reg->smin_value + off;
2750 max_off = ptr_reg->smax_value + off + size;
2751 if (value_regno >= 0)
2752 value_reg = &cur->regs[value_regno];
2753 if (value_reg && register_is_null(value_reg))
2754 writing_zero = true;
2756 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2757 state->acquired_refs, true);
2762 /* Variable offset writes destroy any spilled pointers in range. */
2763 for (i = min_off; i < max_off; i++) {
2764 u8 new_type, *stype;
2768 spi = slot / BPF_REG_SIZE;
2769 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2771 if (!env->allow_ptr_leaks
2772 && *stype != NOT_INIT
2773 && *stype != SCALAR_VALUE) {
2774 /* Reject the write if there's are spilled pointers in
2775 * range. If we didn't reject here, the ptr status
2776 * would be erased below (even though not all slots are
2777 * actually overwritten), possibly opening the door to
2780 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2785 /* Erase all spilled pointers. */
2786 state->stack[spi].spilled_ptr.type = NOT_INIT;
2788 /* Update the slot type. */
2789 new_type = STACK_MISC;
2790 if (writing_zero && *stype == STACK_ZERO) {
2791 new_type = STACK_ZERO;
2794 /* If the slot is STACK_INVALID, we check whether it's OK to
2795 * pretend that it will be initialized by this write. The slot
2796 * might not actually be written to, and so if we mark it as
2797 * initialized future reads might leak uninitialized memory.
2798 * For privileged programs, we will accept such reads to slots
2799 * that may or may not be written because, if we're reject
2800 * them, the error would be too confusing.
2802 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2803 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2810 /* backtracking doesn't work for STACK_ZERO yet. */
2811 err = mark_chain_precision(env, value_regno);
2818 /* When register 'dst_regno' is assigned some values from stack[min_off,
2819 * max_off), we set the register's type according to the types of the
2820 * respective stack slots. If all the stack values are known to be zeros, then
2821 * so is the destination reg. Otherwise, the register is considered to be
2822 * SCALAR. This function does not deal with register filling; the caller must
2823 * ensure that all spilled registers in the stack range have been marked as
2826 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2827 /* func where src register points to */
2828 struct bpf_func_state *ptr_state,
2829 int min_off, int max_off, int dst_regno)
2831 struct bpf_verifier_state *vstate = env->cur_state;
2832 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2837 for (i = min_off; i < max_off; i++) {
2839 spi = slot / BPF_REG_SIZE;
2840 stype = ptr_state->stack[spi].slot_type;
2841 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2845 if (zeros == max_off - min_off) {
2846 /* any access_size read into register is zero extended,
2847 * so the whole register == const_zero
2849 __mark_reg_const_zero(&state->regs[dst_regno]);
2850 /* backtracking doesn't support STACK_ZERO yet,
2851 * so mark it precise here, so that later
2852 * backtracking can stop here.
2853 * Backtracking may not need this if this register
2854 * doesn't participate in pointer adjustment.
2855 * Forward propagation of precise flag is not
2856 * necessary either. This mark is only to stop
2857 * backtracking. Any register that contributed
2858 * to const 0 was marked precise before spill.
2860 state->regs[dst_regno].precise = true;
2862 /* have read misc data from the stack */
2863 mark_reg_unknown(env, state->regs, dst_regno);
2865 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2868 /* Read the stack at 'off' and put the results into the register indicated by
2869 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2872 * 'dst_regno' can be -1, meaning that the read value is not going to a
2875 * The access is assumed to be within the current stack bounds.
2877 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2878 /* func where src register points to */
2879 struct bpf_func_state *reg_state,
2880 int off, int size, int dst_regno)
2882 struct bpf_verifier_state *vstate = env->cur_state;
2883 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2884 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2885 struct bpf_reg_state *reg;
2888 stype = reg_state->stack[spi].slot_type;
2889 reg = ®_state->stack[spi].spilled_ptr;
2891 if (stype[0] == STACK_SPILL) {
2892 if (size != BPF_REG_SIZE) {
2893 if (reg->type != SCALAR_VALUE) {
2894 verbose_linfo(env, env->insn_idx, "; ");
2895 verbose(env, "invalid size of register fill\n");
2898 if (dst_regno >= 0) {
2899 mark_reg_unknown(env, state->regs, dst_regno);
2900 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2902 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2905 for (i = 1; i < BPF_REG_SIZE; i++) {
2906 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2907 verbose(env, "corrupted spill memory\n");
2912 if (dst_regno >= 0) {
2913 /* restore register state from stack */
2914 state->regs[dst_regno] = *reg;
2915 /* mark reg as written since spilled pointer state likely
2916 * has its liveness marks cleared by is_state_visited()
2917 * which resets stack/reg liveness for state transitions
2919 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2920 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2921 /* If dst_regno==-1, the caller is asking us whether
2922 * it is acceptable to use this value as a SCALAR_VALUE
2924 * We must not allow unprivileged callers to do that
2925 * with spilled pointers.
2927 verbose(env, "leaking pointer from stack off %d\n",
2931 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2935 for (i = 0; i < size; i++) {
2936 type = stype[(slot - i) % BPF_REG_SIZE];
2937 if (type == STACK_MISC)
2939 if (type == STACK_ZERO)
2941 verbose(env, "invalid read from stack off %d+%d size %d\n",
2945 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2947 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2952 enum stack_access_src {
2953 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2954 ACCESS_HELPER = 2, /* the access is performed by a helper */
2957 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2958 int regno, int off, int access_size,
2959 bool zero_size_allowed,
2960 enum stack_access_src type,
2961 struct bpf_call_arg_meta *meta);
2963 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2965 return cur_regs(env) + regno;
2968 /* Read the stack at 'ptr_regno + off' and put the result into the register
2970 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2971 * but not its variable offset.
2972 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2974 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2975 * filling registers (i.e. reads of spilled register cannot be detected when
2976 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2977 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2978 * offset; for a fixed offset check_stack_read_fixed_off should be used
2981 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2982 int ptr_regno, int off, int size, int dst_regno)
2984 /* The state of the source register. */
2985 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2986 struct bpf_func_state *ptr_state = func(env, reg);
2988 int min_off, max_off;
2990 /* Note that we pass a NULL meta, so raw access will not be permitted.
2992 err = check_stack_range_initialized(env, ptr_regno, off, size,
2993 false, ACCESS_DIRECT, NULL);
2997 min_off = reg->smin_value + off;
2998 max_off = reg->smax_value + off;
2999 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3003 /* check_stack_read dispatches to check_stack_read_fixed_off or
3004 * check_stack_read_var_off.
3006 * The caller must ensure that the offset falls within the allocated stack
3009 * 'dst_regno' is a register which will receive the value from the stack. It
3010 * can be -1, meaning that the read value is not going to a register.
3012 static int check_stack_read(struct bpf_verifier_env *env,
3013 int ptr_regno, int off, int size,
3016 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3017 struct bpf_func_state *state = func(env, reg);
3019 /* Some accesses are only permitted with a static offset. */
3020 bool var_off = !tnum_is_const(reg->var_off);
3022 /* The offset is required to be static when reads don't go to a
3023 * register, in order to not leak pointers (see
3024 * check_stack_read_fixed_off).
3026 if (dst_regno < 0 && var_off) {
3029 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3030 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3034 /* Variable offset is prohibited for unprivileged mode for simplicity
3035 * since it requires corresponding support in Spectre masking for stack
3036 * ALU. See also retrieve_ptr_limit().
3038 if (!env->bypass_spec_v1 && var_off) {
3041 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3042 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3048 off += reg->var_off.value;
3049 err = check_stack_read_fixed_off(env, state, off, size,
3052 /* Variable offset stack reads need more conservative handling
3053 * than fixed offset ones. Note that dst_regno >= 0 on this
3056 err = check_stack_read_var_off(env, ptr_regno, off, size,
3063 /* check_stack_write dispatches to check_stack_write_fixed_off or
3064 * check_stack_write_var_off.
3066 * 'ptr_regno' is the register used as a pointer into the stack.
3067 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3068 * 'value_regno' is the register whose value we're writing to the stack. It can
3069 * be -1, meaning that we're not writing from a register.
3071 * The caller must ensure that the offset falls within the maximum stack size.
3073 static int check_stack_write(struct bpf_verifier_env *env,
3074 int ptr_regno, int off, int size,
3075 int value_regno, int insn_idx)
3077 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3078 struct bpf_func_state *state = func(env, reg);
3081 if (tnum_is_const(reg->var_off)) {
3082 off += reg->var_off.value;
3083 err = check_stack_write_fixed_off(env, state, off, size,
3084 value_regno, insn_idx);
3086 /* Variable offset stack reads need more conservative handling
3087 * than fixed offset ones.
3089 err = check_stack_write_var_off(env, state,
3090 ptr_regno, off, size,
3091 value_regno, insn_idx);
3096 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3097 int off, int size, enum bpf_access_type type)
3099 struct bpf_reg_state *regs = cur_regs(env);
3100 struct bpf_map *map = regs[regno].map_ptr;
3101 u32 cap = bpf_map_flags_to_cap(map);
3103 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3104 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3105 map->value_size, off, size);
3109 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3110 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3111 map->value_size, off, size);
3118 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3119 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3120 int off, int size, u32 mem_size,
3121 bool zero_size_allowed)
3123 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3124 struct bpf_reg_state *reg;
3126 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3129 reg = &cur_regs(env)[regno];
3130 switch (reg->type) {
3131 case PTR_TO_MAP_KEY:
3132 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3133 mem_size, off, size);
3135 case PTR_TO_MAP_VALUE:
3136 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3137 mem_size, off, size);
3140 case PTR_TO_PACKET_META:
3141 case PTR_TO_PACKET_END:
3142 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3143 off, size, regno, reg->id, off, mem_size);
3147 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3148 mem_size, off, size);
3154 /* check read/write into a memory region with possible variable offset */
3155 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3156 int off, int size, u32 mem_size,
3157 bool zero_size_allowed)
3159 struct bpf_verifier_state *vstate = env->cur_state;
3160 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3161 struct bpf_reg_state *reg = &state->regs[regno];
3164 /* We may have adjusted the register pointing to memory region, so we
3165 * need to try adding each of min_value and max_value to off
3166 * to make sure our theoretical access will be safe.
3168 if (env->log.level & BPF_LOG_LEVEL)
3169 print_verifier_state(env, state);
3171 /* The minimum value is only important with signed
3172 * comparisons where we can't assume the floor of a
3173 * value is 0. If we are using signed variables for our
3174 * index'es we need to make sure that whatever we use
3175 * will have a set floor within our range.
3177 if (reg->smin_value < 0 &&
3178 (reg->smin_value == S64_MIN ||
3179 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3180 reg->smin_value + off < 0)) {
3181 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3185 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3186 mem_size, zero_size_allowed);
3188 verbose(env, "R%d min value is outside of the allowed memory range\n",
3193 /* If we haven't set a max value then we need to bail since we can't be
3194 * sure we won't do bad things.
3195 * If reg->umax_value + off could overflow, treat that as unbounded too.
3197 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3198 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3202 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3203 mem_size, zero_size_allowed);
3205 verbose(env, "R%d max value is outside of the allowed memory range\n",
3213 /* check read/write into a map element with possible variable offset */
3214 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3215 int off, int size, bool zero_size_allowed)
3217 struct bpf_verifier_state *vstate = env->cur_state;
3218 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3219 struct bpf_reg_state *reg = &state->regs[regno];
3220 struct bpf_map *map = reg->map_ptr;
3223 err = check_mem_region_access(env, regno, off, size, map->value_size,
3228 if (map_value_has_spin_lock(map)) {
3229 u32 lock = map->spin_lock_off;
3231 /* if any part of struct bpf_spin_lock can be touched by
3232 * load/store reject this program.
3233 * To check that [x1, x2) overlaps with [y1, y2)
3234 * it is sufficient to check x1 < y2 && y1 < x2.
3236 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3237 lock < reg->umax_value + off + size) {
3238 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3245 #define MAX_PACKET_OFF 0xffff
3247 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3249 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3252 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3253 const struct bpf_call_arg_meta *meta,
3254 enum bpf_access_type t)
3256 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3258 switch (prog_type) {
3259 /* Program types only with direct read access go here! */
3260 case BPF_PROG_TYPE_LWT_IN:
3261 case BPF_PROG_TYPE_LWT_OUT:
3262 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3263 case BPF_PROG_TYPE_SK_REUSEPORT:
3264 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3265 case BPF_PROG_TYPE_CGROUP_SKB:
3270 /* Program types with direct read + write access go here! */
3271 case BPF_PROG_TYPE_SCHED_CLS:
3272 case BPF_PROG_TYPE_SCHED_ACT:
3273 case BPF_PROG_TYPE_XDP:
3274 case BPF_PROG_TYPE_LWT_XMIT:
3275 case BPF_PROG_TYPE_SK_SKB:
3276 case BPF_PROG_TYPE_SK_MSG:
3278 return meta->pkt_access;
3280 env->seen_direct_write = true;
3283 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3285 env->seen_direct_write = true;
3294 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3295 int size, bool zero_size_allowed)
3297 struct bpf_reg_state *regs = cur_regs(env);
3298 struct bpf_reg_state *reg = ®s[regno];
3301 /* We may have added a variable offset to the packet pointer; but any
3302 * reg->range we have comes after that. We are only checking the fixed
3306 /* We don't allow negative numbers, because we aren't tracking enough
3307 * detail to prove they're safe.
3309 if (reg->smin_value < 0) {
3310 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3315 err = reg->range < 0 ? -EINVAL :
3316 __check_mem_access(env, regno, off, size, reg->range,
3319 verbose(env, "R%d offset is outside of the packet\n", regno);
3323 /* __check_mem_access has made sure "off + size - 1" is within u16.
3324 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3325 * otherwise find_good_pkt_pointers would have refused to set range info
3326 * that __check_mem_access would have rejected this pkt access.
3327 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3329 env->prog->aux->max_pkt_offset =
3330 max_t(u32, env->prog->aux->max_pkt_offset,
3331 off + reg->umax_value + size - 1);
3336 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
3337 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3338 enum bpf_access_type t, enum bpf_reg_type *reg_type,
3339 struct btf **btf, u32 *btf_id)
3341 struct bpf_insn_access_aux info = {
3342 .reg_type = *reg_type,
3346 if (env->ops->is_valid_access &&
3347 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3348 /* A non zero info.ctx_field_size indicates that this field is a
3349 * candidate for later verifier transformation to load the whole
3350 * field and then apply a mask when accessed with a narrower
3351 * access than actual ctx access size. A zero info.ctx_field_size
3352 * will only allow for whole field access and rejects any other
3353 * type of narrower access.
3355 *reg_type = info.reg_type;
3357 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3359 *btf_id = info.btf_id;
3361 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3363 /* remember the offset of last byte accessed in ctx */
3364 if (env->prog->aux->max_ctx_offset < off + size)
3365 env->prog->aux->max_ctx_offset = off + size;
3369 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3373 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3376 if (size < 0 || off < 0 ||
3377 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3378 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3385 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3386 u32 regno, int off, int size,
3387 enum bpf_access_type t)
3389 struct bpf_reg_state *regs = cur_regs(env);
3390 struct bpf_reg_state *reg = ®s[regno];
3391 struct bpf_insn_access_aux info = {};
3394 if (reg->smin_value < 0) {
3395 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3400 switch (reg->type) {
3401 case PTR_TO_SOCK_COMMON:
3402 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3405 valid = bpf_sock_is_valid_access(off, size, t, &info);
3407 case PTR_TO_TCP_SOCK:
3408 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3410 case PTR_TO_XDP_SOCK:
3411 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3419 env->insn_aux_data[insn_idx].ctx_field_size =
3420 info.ctx_field_size;
3424 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3425 regno, reg_type_str[reg->type], off, size);
3430 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3432 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3435 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3437 const struct bpf_reg_state *reg = reg_state(env, regno);
3439 return reg->type == PTR_TO_CTX;
3442 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3444 const struct bpf_reg_state *reg = reg_state(env, regno);
3446 return type_is_sk_pointer(reg->type);
3449 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3451 const struct bpf_reg_state *reg = reg_state(env, regno);
3453 return type_is_pkt_pointer(reg->type);
3456 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3458 const struct bpf_reg_state *reg = reg_state(env, regno);
3460 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3461 return reg->type == PTR_TO_FLOW_KEYS;
3464 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3465 const struct bpf_reg_state *reg,
3466 int off, int size, bool strict)
3468 struct tnum reg_off;
3471 /* Byte size accesses are always allowed. */
3472 if (!strict || size == 1)
3475 /* For platforms that do not have a Kconfig enabling
3476 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3477 * NET_IP_ALIGN is universally set to '2'. And on platforms
3478 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3479 * to this code only in strict mode where we want to emulate
3480 * the NET_IP_ALIGN==2 checking. Therefore use an
3481 * unconditional IP align value of '2'.
3485 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3486 if (!tnum_is_aligned(reg_off, size)) {
3489 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3491 "misaligned packet access off %d+%s+%d+%d size %d\n",
3492 ip_align, tn_buf, reg->off, off, size);
3499 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3500 const struct bpf_reg_state *reg,
3501 const char *pointer_desc,
3502 int off, int size, bool strict)
3504 struct tnum reg_off;
3506 /* Byte size accesses are always allowed. */
3507 if (!strict || size == 1)
3510 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3511 if (!tnum_is_aligned(reg_off, size)) {
3514 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3515 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3516 pointer_desc, tn_buf, reg->off, off, size);
3523 static int check_ptr_alignment(struct bpf_verifier_env *env,
3524 const struct bpf_reg_state *reg, int off,
3525 int size, bool strict_alignment_once)
3527 bool strict = env->strict_alignment || strict_alignment_once;
3528 const char *pointer_desc = "";
3530 switch (reg->type) {
3532 case PTR_TO_PACKET_META:
3533 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3534 * right in front, treat it the very same way.
3536 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3537 case PTR_TO_FLOW_KEYS:
3538 pointer_desc = "flow keys ";
3540 case PTR_TO_MAP_KEY:
3541 pointer_desc = "key ";
3543 case PTR_TO_MAP_VALUE:
3544 pointer_desc = "value ";
3547 pointer_desc = "context ";
3550 pointer_desc = "stack ";
3551 /* The stack spill tracking logic in check_stack_write_fixed_off()
3552 * and check_stack_read_fixed_off() relies on stack accesses being
3558 pointer_desc = "sock ";
3560 case PTR_TO_SOCK_COMMON:
3561 pointer_desc = "sock_common ";
3563 case PTR_TO_TCP_SOCK:
3564 pointer_desc = "tcp_sock ";
3566 case PTR_TO_XDP_SOCK:
3567 pointer_desc = "xdp_sock ";
3572 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3576 static int update_stack_depth(struct bpf_verifier_env *env,
3577 const struct bpf_func_state *func,
3580 u16 stack = env->subprog_info[func->subprogno].stack_depth;
3585 /* update known max for given subprogram */
3586 env->subprog_info[func->subprogno].stack_depth = -off;
3590 /* starting from main bpf function walk all instructions of the function
3591 * and recursively walk all callees that given function can call.
3592 * Ignore jump and exit insns.
3593 * Since recursion is prevented by check_cfg() this algorithm
3594 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3596 static int check_max_stack_depth(struct bpf_verifier_env *env)
3598 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3599 struct bpf_subprog_info *subprog = env->subprog_info;
3600 struct bpf_insn *insn = env->prog->insnsi;
3601 bool tail_call_reachable = false;
3602 int ret_insn[MAX_CALL_FRAMES];
3603 int ret_prog[MAX_CALL_FRAMES];
3607 /* protect against potential stack overflow that might happen when
3608 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3609 * depth for such case down to 256 so that the worst case scenario
3610 * would result in 8k stack size (32 which is tailcall limit * 256 =
3613 * To get the idea what might happen, see an example:
3614 * func1 -> sub rsp, 128
3615 * subfunc1 -> sub rsp, 256
3616 * tailcall1 -> add rsp, 256
3617 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3618 * subfunc2 -> sub rsp, 64
3619 * subfunc22 -> sub rsp, 128
3620 * tailcall2 -> add rsp, 128
3621 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3623 * tailcall will unwind the current stack frame but it will not get rid
3624 * of caller's stack as shown on the example above.
3626 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3628 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3632 /* round up to 32-bytes, since this is granularity
3633 * of interpreter stack size
3635 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3636 if (depth > MAX_BPF_STACK) {
3637 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3642 subprog_end = subprog[idx + 1].start;
3643 for (; i < subprog_end; i++) {
3644 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3646 /* remember insn and function to return to */
3647 ret_insn[frame] = i + 1;
3648 ret_prog[frame] = idx;
3650 /* find the callee */
3651 i = i + insn[i].imm + 1;
3652 idx = find_subprog(env, i);
3654 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3659 if (subprog[idx].has_tail_call)
3660 tail_call_reachable = true;
3663 if (frame >= MAX_CALL_FRAMES) {
3664 verbose(env, "the call stack of %d frames is too deep !\n",
3670 /* if tail call got detected across bpf2bpf calls then mark each of the
3671 * currently present subprog frames as tail call reachable subprogs;
3672 * this info will be utilized by JIT so that we will be preserving the
3673 * tail call counter throughout bpf2bpf calls combined with tailcalls
3675 if (tail_call_reachable)
3676 for (j = 0; j < frame; j++)
3677 subprog[ret_prog[j]].tail_call_reachable = true;
3679 /* end of for() loop means the last insn of the 'subprog'
3680 * was reached. Doesn't matter whether it was JA or EXIT
3684 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3686 i = ret_insn[frame];
3687 idx = ret_prog[frame];
3691 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3692 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3693 const struct bpf_insn *insn, int idx)
3695 int start = idx + insn->imm + 1, subprog;
3697 subprog = find_subprog(env, start);
3699 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3703 return env->subprog_info[subprog].stack_depth;
3707 int check_ctx_reg(struct bpf_verifier_env *env,
3708 const struct bpf_reg_state *reg, int regno)
3710 /* Access to ctx or passing it to a helper is only allowed in
3711 * its original, unmodified form.
3715 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3720 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3723 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3724 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3731 static int __check_buffer_access(struct bpf_verifier_env *env,
3732 const char *buf_info,
3733 const struct bpf_reg_state *reg,
3734 int regno, int off, int size)
3738 "R%d invalid %s buffer access: off=%d, size=%d\n",
3739 regno, buf_info, off, size);
3742 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3745 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3747 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3748 regno, off, tn_buf);
3755 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3756 const struct bpf_reg_state *reg,
3757 int regno, int off, int size)
3761 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3765 if (off + size > env->prog->aux->max_tp_access)
3766 env->prog->aux->max_tp_access = off + size;
3771 static int check_buffer_access(struct bpf_verifier_env *env,
3772 const struct bpf_reg_state *reg,
3773 int regno, int off, int size,
3774 bool zero_size_allowed,
3775 const char *buf_info,
3780 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3784 if (off + size > *max_access)
3785 *max_access = off + size;
3790 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3791 static void zext_32_to_64(struct bpf_reg_state *reg)
3793 reg->var_off = tnum_subreg(reg->var_off);
3794 __reg_assign_32_into_64(reg);
3797 /* truncate register to smaller size (in bytes)
3798 * must be called with size < BPF_REG_SIZE
3800 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3804 /* clear high bits in bit representation */
3805 reg->var_off = tnum_cast(reg->var_off, size);
3807 /* fix arithmetic bounds */
3808 mask = ((u64)1 << (size * 8)) - 1;
3809 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3810 reg->umin_value &= mask;
3811 reg->umax_value &= mask;
3813 reg->umin_value = 0;
3814 reg->umax_value = mask;
3816 reg->smin_value = reg->umin_value;
3817 reg->smax_value = reg->umax_value;
3819 /* If size is smaller than 32bit register the 32bit register
3820 * values are also truncated so we push 64-bit bounds into
3821 * 32-bit bounds. Above were truncated < 32-bits already.
3825 __reg_combine_64_into_32(reg);
3828 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3830 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3833 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3839 err = map->ops->map_direct_value_addr(map, &addr, off);
3842 ptr = (void *)(long)addr + off;
3846 *val = (u64)*(u8 *)ptr;
3849 *val = (u64)*(u16 *)ptr;
3852 *val = (u64)*(u32 *)ptr;
3863 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3864 struct bpf_reg_state *regs,
3865 int regno, int off, int size,
3866 enum bpf_access_type atype,
3869 struct bpf_reg_state *reg = regs + regno;
3870 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3871 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3877 "R%d is ptr_%s invalid negative access: off=%d\n",
3881 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3884 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3886 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3887 regno, tname, off, tn_buf);
3891 if (env->ops->btf_struct_access) {
3892 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3893 off, size, atype, &btf_id);
3895 if (atype != BPF_READ) {
3896 verbose(env, "only read is supported\n");
3900 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3907 if (atype == BPF_READ && value_regno >= 0)
3908 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3913 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3914 struct bpf_reg_state *regs,
3915 int regno, int off, int size,
3916 enum bpf_access_type atype,
3919 struct bpf_reg_state *reg = regs + regno;
3920 struct bpf_map *map = reg->map_ptr;
3921 const struct btf_type *t;
3927 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3931 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3932 verbose(env, "map_ptr access not supported for map type %d\n",
3937 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3938 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3940 if (!env->allow_ptr_to_map_access) {
3942 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3948 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3953 if (atype != BPF_READ) {
3954 verbose(env, "only read from %s is supported\n", tname);
3958 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
3962 if (value_regno >= 0)
3963 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
3968 /* Check that the stack access at the given offset is within bounds. The
3969 * maximum valid offset is -1.
3971 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3972 * -state->allocated_stack for reads.
3974 static int check_stack_slot_within_bounds(int off,
3975 struct bpf_func_state *state,
3976 enum bpf_access_type t)
3981 min_valid_off = -MAX_BPF_STACK;
3983 min_valid_off = -state->allocated_stack;
3985 if (off < min_valid_off || off > -1)
3990 /* Check that the stack access at 'regno + off' falls within the maximum stack
3993 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3995 static int check_stack_access_within_bounds(
3996 struct bpf_verifier_env *env,
3997 int regno, int off, int access_size,
3998 enum stack_access_src src, enum bpf_access_type type)
4000 struct bpf_reg_state *regs = cur_regs(env);
4001 struct bpf_reg_state *reg = regs + regno;
4002 struct bpf_func_state *state = func(env, reg);
4003 int min_off, max_off;
4007 if (src == ACCESS_HELPER)
4008 /* We don't know if helpers are reading or writing (or both). */
4009 err_extra = " indirect access to";
4010 else if (type == BPF_READ)
4011 err_extra = " read from";
4013 err_extra = " write to";
4015 if (tnum_is_const(reg->var_off)) {
4016 min_off = reg->var_off.value + off;
4017 if (access_size > 0)
4018 max_off = min_off + access_size - 1;
4022 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4023 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4024 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4028 min_off = reg->smin_value + off;
4029 if (access_size > 0)
4030 max_off = reg->smax_value + off + access_size - 1;
4035 err = check_stack_slot_within_bounds(min_off, state, type);
4037 err = check_stack_slot_within_bounds(max_off, state, type);
4040 if (tnum_is_const(reg->var_off)) {
4041 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4042 err_extra, regno, off, access_size);
4046 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4047 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4048 err_extra, regno, tn_buf, access_size);
4054 /* check whether memory at (regno + off) is accessible for t = (read | write)
4055 * if t==write, value_regno is a register which value is stored into memory
4056 * if t==read, value_regno is a register which will receive the value from memory
4057 * if t==write && value_regno==-1, some unknown value is stored into memory
4058 * if t==read && value_regno==-1, don't care what we read from memory
4060 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4061 int off, int bpf_size, enum bpf_access_type t,
4062 int value_regno, bool strict_alignment_once)
4064 struct bpf_reg_state *regs = cur_regs(env);
4065 struct bpf_reg_state *reg = regs + regno;
4066 struct bpf_func_state *state;
4069 size = bpf_size_to_bytes(bpf_size);
4073 /* alignment checks will add in reg->off themselves */
4074 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4078 /* for access checks, reg->off is just part of off */
4081 if (reg->type == PTR_TO_MAP_KEY) {
4082 if (t == BPF_WRITE) {
4083 verbose(env, "write to change key R%d not allowed\n", regno);
4087 err = check_mem_region_access(env, regno, off, size,
4088 reg->map_ptr->key_size, false);
4091 if (value_regno >= 0)
4092 mark_reg_unknown(env, regs, value_regno);
4093 } else if (reg->type == PTR_TO_MAP_VALUE) {
4094 if (t == BPF_WRITE && value_regno >= 0 &&
4095 is_pointer_value(env, value_regno)) {
4096 verbose(env, "R%d leaks addr into map\n", value_regno);
4099 err = check_map_access_type(env, regno, off, size, t);
4102 err = check_map_access(env, regno, off, size, false);
4103 if (!err && t == BPF_READ && value_regno >= 0) {
4104 struct bpf_map *map = reg->map_ptr;
4106 /* if map is read-only, track its contents as scalars */
4107 if (tnum_is_const(reg->var_off) &&
4108 bpf_map_is_rdonly(map) &&
4109 map->ops->map_direct_value_addr) {
4110 int map_off = off + reg->var_off.value;
4113 err = bpf_map_direct_read(map, map_off, size,
4118 regs[value_regno].type = SCALAR_VALUE;
4119 __mark_reg_known(®s[value_regno], val);
4121 mark_reg_unknown(env, regs, value_regno);
4124 } else if (reg->type == PTR_TO_MEM) {
4125 if (t == BPF_WRITE && value_regno >= 0 &&
4126 is_pointer_value(env, value_regno)) {
4127 verbose(env, "R%d leaks addr into mem\n", value_regno);
4130 err = check_mem_region_access(env, regno, off, size,
4131 reg->mem_size, false);
4132 if (!err && t == BPF_READ && value_regno >= 0)
4133 mark_reg_unknown(env, regs, value_regno);
4134 } else if (reg->type == PTR_TO_CTX) {
4135 enum bpf_reg_type reg_type = SCALAR_VALUE;
4136 struct btf *btf = NULL;
4139 if (t == BPF_WRITE && value_regno >= 0 &&
4140 is_pointer_value(env, value_regno)) {
4141 verbose(env, "R%d leaks addr into ctx\n", value_regno);
4145 err = check_ctx_reg(env, reg, regno);
4149 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, &btf_id);
4151 verbose_linfo(env, insn_idx, "; ");
4152 if (!err && t == BPF_READ && value_regno >= 0) {
4153 /* ctx access returns either a scalar, or a
4154 * PTR_TO_PACKET[_META,_END]. In the latter
4155 * case, we know the offset is zero.
4157 if (reg_type == SCALAR_VALUE) {
4158 mark_reg_unknown(env, regs, value_regno);
4160 mark_reg_known_zero(env, regs,
4162 if (reg_type_may_be_null(reg_type))
4163 regs[value_regno].id = ++env->id_gen;
4164 /* A load of ctx field could have different
4165 * actual load size with the one encoded in the
4166 * insn. When the dst is PTR, it is for sure not
4169 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4170 if (reg_type == PTR_TO_BTF_ID ||
4171 reg_type == PTR_TO_BTF_ID_OR_NULL) {
4172 regs[value_regno].btf = btf;
4173 regs[value_regno].btf_id = btf_id;
4176 regs[value_regno].type = reg_type;
4179 } else if (reg->type == PTR_TO_STACK) {
4180 /* Basic bounds checks. */
4181 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4185 state = func(env, reg);
4186 err = update_stack_depth(env, state, off);
4191 err = check_stack_read(env, regno, off, size,
4194 err = check_stack_write(env, regno, off, size,
4195 value_regno, insn_idx);
4196 } else if (reg_is_pkt_pointer(reg)) {
4197 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4198 verbose(env, "cannot write into packet\n");
4201 if (t == BPF_WRITE && value_regno >= 0 &&
4202 is_pointer_value(env, value_regno)) {
4203 verbose(env, "R%d leaks addr into packet\n",
4207 err = check_packet_access(env, regno, off, size, false);
4208 if (!err && t == BPF_READ && value_regno >= 0)
4209 mark_reg_unknown(env, regs, value_regno);
4210 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4211 if (t == BPF_WRITE && value_regno >= 0 &&
4212 is_pointer_value(env, value_regno)) {
4213 verbose(env, "R%d leaks addr into flow keys\n",
4218 err = check_flow_keys_access(env, off, size);
4219 if (!err && t == BPF_READ && value_regno >= 0)
4220 mark_reg_unknown(env, regs, value_regno);
4221 } else if (type_is_sk_pointer(reg->type)) {
4222 if (t == BPF_WRITE) {
4223 verbose(env, "R%d cannot write into %s\n",
4224 regno, reg_type_str[reg->type]);
4227 err = check_sock_access(env, insn_idx, regno, off, size, t);
4228 if (!err && value_regno >= 0)
4229 mark_reg_unknown(env, regs, value_regno);
4230 } else if (reg->type == PTR_TO_TP_BUFFER) {
4231 err = check_tp_buffer_access(env, reg, regno, off, size);
4232 if (!err && t == BPF_READ && value_regno >= 0)
4233 mark_reg_unknown(env, regs, value_regno);
4234 } else if (reg->type == PTR_TO_BTF_ID) {
4235 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4237 } else if (reg->type == CONST_PTR_TO_MAP) {
4238 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4240 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4241 if (t == BPF_WRITE) {
4242 verbose(env, "R%d cannot write into %s\n",
4243 regno, reg_type_str[reg->type]);
4246 err = check_buffer_access(env, reg, regno, off, size, false,
4248 &env->prog->aux->max_rdonly_access);
4249 if (!err && value_regno >= 0)
4250 mark_reg_unknown(env, regs, value_regno);
4251 } else if (reg->type == PTR_TO_RDWR_BUF) {
4252 err = check_buffer_access(env, reg, regno, off, size, false,
4254 &env->prog->aux->max_rdwr_access);
4255 if (!err && t == BPF_READ && value_regno >= 0)
4256 mark_reg_unknown(env, regs, value_regno);
4258 verbose(env, "R%d invalid mem access '%s'\n", regno,
4259 reg_type_str[reg->type]);
4263 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4264 regs[value_regno].type == SCALAR_VALUE) {
4265 /* b/h/w load zero-extends, mark upper bits as known 0 */
4266 coerce_reg_to_size(®s[value_regno], size);
4271 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4276 switch (insn->imm) {
4278 case BPF_ADD | BPF_FETCH:
4280 case BPF_AND | BPF_FETCH:
4282 case BPF_OR | BPF_FETCH:
4284 case BPF_XOR | BPF_FETCH:
4289 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4293 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4294 verbose(env, "invalid atomic operand size\n");
4298 /* check src1 operand */
4299 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4303 /* check src2 operand */
4304 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4308 if (insn->imm == BPF_CMPXCHG) {
4309 /* Check comparison of R0 with memory location */
4310 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4315 if (is_pointer_value(env, insn->src_reg)) {
4316 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4320 if (is_ctx_reg(env, insn->dst_reg) ||
4321 is_pkt_reg(env, insn->dst_reg) ||
4322 is_flow_key_reg(env, insn->dst_reg) ||
4323 is_sk_reg(env, insn->dst_reg)) {
4324 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4326 reg_type_str[reg_state(env, insn->dst_reg)->type]);
4330 if (insn->imm & BPF_FETCH) {
4331 if (insn->imm == BPF_CMPXCHG)
4332 load_reg = BPF_REG_0;
4334 load_reg = insn->src_reg;
4336 /* check and record load of old value */
4337 err = check_reg_arg(env, load_reg, DST_OP);
4341 /* This instruction accesses a memory location but doesn't
4342 * actually load it into a register.
4347 /* check whether we can read the memory */
4348 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4349 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4353 /* check whether we can write into the same memory */
4354 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4355 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4362 /* When register 'regno' is used to read the stack (either directly or through
4363 * a helper function) make sure that it's within stack boundary and, depending
4364 * on the access type, that all elements of the stack are initialized.
4366 * 'off' includes 'regno->off', but not its dynamic part (if any).
4368 * All registers that have been spilled on the stack in the slots within the
4369 * read offsets are marked as read.
4371 static int check_stack_range_initialized(
4372 struct bpf_verifier_env *env, int regno, int off,
4373 int access_size, bool zero_size_allowed,
4374 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4376 struct bpf_reg_state *reg = reg_state(env, regno);
4377 struct bpf_func_state *state = func(env, reg);
4378 int err, min_off, max_off, i, j, slot, spi;
4379 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4380 enum bpf_access_type bounds_check_type;
4381 /* Some accesses can write anything into the stack, others are
4384 bool clobber = false;
4386 if (access_size == 0 && !zero_size_allowed) {
4387 verbose(env, "invalid zero-sized read\n");
4391 if (type == ACCESS_HELPER) {
4392 /* The bounds checks for writes are more permissive than for
4393 * reads. However, if raw_mode is not set, we'll do extra
4396 bounds_check_type = BPF_WRITE;
4399 bounds_check_type = BPF_READ;
4401 err = check_stack_access_within_bounds(env, regno, off, access_size,
4402 type, bounds_check_type);
4407 if (tnum_is_const(reg->var_off)) {
4408 min_off = max_off = reg->var_off.value + off;
4410 /* Variable offset is prohibited for unprivileged mode for
4411 * simplicity since it requires corresponding support in
4412 * Spectre masking for stack ALU.
4413 * See also retrieve_ptr_limit().
4415 if (!env->bypass_spec_v1) {
4418 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4419 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4420 regno, err_extra, tn_buf);
4423 /* Only initialized buffer on stack is allowed to be accessed
4424 * with variable offset. With uninitialized buffer it's hard to
4425 * guarantee that whole memory is marked as initialized on
4426 * helper return since specific bounds are unknown what may
4427 * cause uninitialized stack leaking.
4429 if (meta && meta->raw_mode)
4432 min_off = reg->smin_value + off;
4433 max_off = reg->smax_value + off;
4436 if (meta && meta->raw_mode) {
4437 meta->access_size = access_size;
4438 meta->regno = regno;
4442 for (i = min_off; i < max_off + access_size; i++) {
4446 spi = slot / BPF_REG_SIZE;
4447 if (state->allocated_stack <= slot)
4449 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4450 if (*stype == STACK_MISC)
4452 if (*stype == STACK_ZERO) {
4454 /* helper can write anything into the stack */
4455 *stype = STACK_MISC;
4460 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4461 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4464 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4465 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4466 env->allow_ptr_leaks)) {
4468 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4469 for (j = 0; j < BPF_REG_SIZE; j++)
4470 state->stack[spi].slot_type[j] = STACK_MISC;
4476 if (tnum_is_const(reg->var_off)) {
4477 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4478 err_extra, regno, min_off, i - min_off, access_size);
4482 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4483 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4484 err_extra, regno, tn_buf, i - min_off, access_size);
4488 /* reading any byte out of 8-byte 'spill_slot' will cause
4489 * the whole slot to be marked as 'read'
4491 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4492 state->stack[spi].spilled_ptr.parent,
4495 return update_stack_depth(env, state, min_off);
4498 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4499 int access_size, bool zero_size_allowed,
4500 struct bpf_call_arg_meta *meta)
4502 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4504 switch (reg->type) {
4506 case PTR_TO_PACKET_META:
4507 return check_packet_access(env, regno, reg->off, access_size,
4509 case PTR_TO_MAP_KEY:
4510 return check_mem_region_access(env, regno, reg->off, access_size,
4511 reg->map_ptr->key_size, false);
4512 case PTR_TO_MAP_VALUE:
4513 if (check_map_access_type(env, regno, reg->off, access_size,
4514 meta && meta->raw_mode ? BPF_WRITE :
4517 return check_map_access(env, regno, reg->off, access_size,
4520 return check_mem_region_access(env, regno, reg->off,
4521 access_size, reg->mem_size,
4523 case PTR_TO_RDONLY_BUF:
4524 if (meta && meta->raw_mode)
4526 return check_buffer_access(env, reg, regno, reg->off,
4527 access_size, zero_size_allowed,
4529 &env->prog->aux->max_rdonly_access);
4530 case PTR_TO_RDWR_BUF:
4531 return check_buffer_access(env, reg, regno, reg->off,
4532 access_size, zero_size_allowed,
4534 &env->prog->aux->max_rdwr_access);
4536 return check_stack_range_initialized(
4538 regno, reg->off, access_size,
4539 zero_size_allowed, ACCESS_HELPER, meta);
4540 default: /* scalar_value or invalid ptr */
4541 /* Allow zero-byte read from NULL, regardless of pointer type */
4542 if (zero_size_allowed && access_size == 0 &&
4543 register_is_null(reg))
4546 verbose(env, "R%d type=%s expected=%s\n", regno,
4547 reg_type_str[reg->type],
4548 reg_type_str[PTR_TO_STACK]);
4553 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4554 u32 regno, u32 mem_size)
4556 if (register_is_null(reg))
4559 if (reg_type_may_be_null(reg->type)) {
4560 /* Assuming that the register contains a value check if the memory
4561 * access is safe. Temporarily save and restore the register's state as
4562 * the conversion shouldn't be visible to a caller.
4564 const struct bpf_reg_state saved_reg = *reg;
4567 mark_ptr_not_null_reg(reg);
4568 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4573 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4576 /* Implementation details:
4577 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4578 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4579 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4580 * value_or_null->value transition, since the verifier only cares about
4581 * the range of access to valid map value pointer and doesn't care about actual
4582 * address of the map element.
4583 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4584 * reg->id > 0 after value_or_null->value transition. By doing so
4585 * two bpf_map_lookups will be considered two different pointers that
4586 * point to different bpf_spin_locks.
4587 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4589 * Since only one bpf_spin_lock is allowed the checks are simpler than
4590 * reg_is_refcounted() logic. The verifier needs to remember only
4591 * one spin_lock instead of array of acquired_refs.
4592 * cur_state->active_spin_lock remembers which map value element got locked
4593 * and clears it after bpf_spin_unlock.
4595 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4598 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4599 struct bpf_verifier_state *cur = env->cur_state;
4600 bool is_const = tnum_is_const(reg->var_off);
4601 struct bpf_map *map = reg->map_ptr;
4602 u64 val = reg->var_off.value;
4606 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4612 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4616 if (!map_value_has_spin_lock(map)) {
4617 if (map->spin_lock_off == -E2BIG)
4619 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4621 else if (map->spin_lock_off == -ENOENT)
4623 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4627 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4631 if (map->spin_lock_off != val + reg->off) {
4632 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4637 if (cur->active_spin_lock) {
4639 "Locking two bpf_spin_locks are not allowed\n");
4642 cur->active_spin_lock = reg->id;
4644 if (!cur->active_spin_lock) {
4645 verbose(env, "bpf_spin_unlock without taking a lock\n");
4648 if (cur->active_spin_lock != reg->id) {
4649 verbose(env, "bpf_spin_unlock of different lock\n");
4652 cur->active_spin_lock = 0;
4657 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4659 return type == ARG_PTR_TO_MEM ||
4660 type == ARG_PTR_TO_MEM_OR_NULL ||
4661 type == ARG_PTR_TO_UNINIT_MEM;
4664 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4666 return type == ARG_CONST_SIZE ||
4667 type == ARG_CONST_SIZE_OR_ZERO;
4670 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4672 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4675 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4677 return type == ARG_PTR_TO_INT ||
4678 type == ARG_PTR_TO_LONG;
4681 static int int_ptr_type_to_size(enum bpf_arg_type type)
4683 if (type == ARG_PTR_TO_INT)
4685 else if (type == ARG_PTR_TO_LONG)
4691 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4692 const struct bpf_call_arg_meta *meta,
4693 enum bpf_arg_type *arg_type)
4695 if (!meta->map_ptr) {
4696 /* kernel subsystem misconfigured verifier */
4697 verbose(env, "invalid map_ptr to access map->type\n");
4701 switch (meta->map_ptr->map_type) {
4702 case BPF_MAP_TYPE_SOCKMAP:
4703 case BPF_MAP_TYPE_SOCKHASH:
4704 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4705 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4707 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4718 struct bpf_reg_types {
4719 const enum bpf_reg_type types[10];
4723 static const struct bpf_reg_types map_key_value_types = {
4733 static const struct bpf_reg_types sock_types = {
4743 static const struct bpf_reg_types btf_id_sock_common_types = {
4751 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4755 static const struct bpf_reg_types mem_types = {
4768 static const struct bpf_reg_types int_ptr_types = {
4778 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4779 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4780 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4781 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4782 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4783 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4784 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4785 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4786 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4787 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
4788 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
4790 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4791 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4792 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4793 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4794 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4795 [ARG_CONST_SIZE] = &scalar_types,
4796 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4797 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4798 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4799 [ARG_PTR_TO_CTX] = &context_types,
4800 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4801 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
4803 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4805 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4806 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4807 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4808 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4809 [ARG_PTR_TO_MEM] = &mem_types,
4810 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4811 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4812 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4813 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4814 [ARG_PTR_TO_INT] = &int_ptr_types,
4815 [ARG_PTR_TO_LONG] = &int_ptr_types,
4816 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
4817 [ARG_PTR_TO_FUNC] = &func_ptr_types,
4818 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types,
4819 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
4822 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4823 enum bpf_arg_type arg_type,
4824 const u32 *arg_btf_id)
4826 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4827 enum bpf_reg_type expected, type = reg->type;
4828 const struct bpf_reg_types *compatible;
4831 compatible = compatible_reg_types[arg_type];
4833 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4837 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4838 expected = compatible->types[i];
4839 if (expected == NOT_INIT)
4842 if (type == expected)
4846 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4847 for (j = 0; j + 1 < i; j++)
4848 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4849 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4853 if (type == PTR_TO_BTF_ID) {
4855 if (!compatible->btf_id) {
4856 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4859 arg_btf_id = compatible->btf_id;
4862 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4863 btf_vmlinux, *arg_btf_id)) {
4864 verbose(env, "R%d is of type %s but %s is expected\n",
4865 regno, kernel_type_name(reg->btf, reg->btf_id),
4866 kernel_type_name(btf_vmlinux, *arg_btf_id));
4870 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4871 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4880 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4881 struct bpf_call_arg_meta *meta,
4882 const struct bpf_func_proto *fn)
4884 u32 regno = BPF_REG_1 + arg;
4885 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4886 enum bpf_arg_type arg_type = fn->arg_type[arg];
4887 enum bpf_reg_type type = reg->type;
4890 if (arg_type == ARG_DONTCARE)
4893 err = check_reg_arg(env, regno, SRC_OP);
4897 if (arg_type == ARG_ANYTHING) {
4898 if (is_pointer_value(env, regno)) {
4899 verbose(env, "R%d leaks addr into helper function\n",
4906 if (type_is_pkt_pointer(type) &&
4907 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4908 verbose(env, "helper access to the packet is not allowed\n");
4912 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4913 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4914 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4915 err = resolve_map_arg_type(env, meta, &arg_type);
4920 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4921 /* A NULL register has a SCALAR_VALUE type, so skip
4924 goto skip_type_check;
4926 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4930 if (type == PTR_TO_CTX) {
4931 err = check_ctx_reg(env, reg, regno);
4937 if (reg->ref_obj_id) {
4938 if (meta->ref_obj_id) {
4939 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4940 regno, reg->ref_obj_id,
4944 meta->ref_obj_id = reg->ref_obj_id;
4947 if (arg_type == ARG_CONST_MAP_PTR) {
4948 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4949 meta->map_ptr = reg->map_ptr;
4950 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4951 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4952 * check that [key, key + map->key_size) are within
4953 * stack limits and initialized
4955 if (!meta->map_ptr) {
4956 /* in function declaration map_ptr must come before
4957 * map_key, so that it's verified and known before
4958 * we have to check map_key here. Otherwise it means
4959 * that kernel subsystem misconfigured verifier
4961 verbose(env, "invalid map_ptr to access map->key\n");
4964 err = check_helper_mem_access(env, regno,
4965 meta->map_ptr->key_size, false,
4967 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4968 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4969 !register_is_null(reg)) ||
4970 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4971 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4972 * check [value, value + map->value_size) validity
4974 if (!meta->map_ptr) {
4975 /* kernel subsystem misconfigured verifier */
4976 verbose(env, "invalid map_ptr to access map->value\n");
4979 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4980 err = check_helper_mem_access(env, regno,
4981 meta->map_ptr->value_size, false,
4983 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4985 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4988 meta->ret_btf = reg->btf;
4989 meta->ret_btf_id = reg->btf_id;
4990 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4991 if (meta->func_id == BPF_FUNC_spin_lock) {
4992 if (process_spin_lock(env, regno, true))
4994 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4995 if (process_spin_lock(env, regno, false))
4998 verbose(env, "verifier internal error\n");
5001 } else if (arg_type == ARG_PTR_TO_FUNC) {
5002 meta->subprogno = reg->subprogno;
5003 } else if (arg_type_is_mem_ptr(arg_type)) {
5004 /* The access to this pointer is only checked when we hit the
5005 * next is_mem_size argument below.
5007 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5008 } else if (arg_type_is_mem_size(arg_type)) {
5009 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5011 /* This is used to refine r0 return value bounds for helpers
5012 * that enforce this value as an upper bound on return values.
5013 * See do_refine_retval_range() for helpers that can refine
5014 * the return value. C type of helper is u32 so we pull register
5015 * bound from umax_value however, if negative verifier errors
5016 * out. Only upper bounds can be learned because retval is an
5017 * int type and negative retvals are allowed.
5019 meta->msize_max_value = reg->umax_value;
5021 /* The register is SCALAR_VALUE; the access check
5022 * happens using its boundaries.
5024 if (!tnum_is_const(reg->var_off))
5025 /* For unprivileged variable accesses, disable raw
5026 * mode so that the program is required to
5027 * initialize all the memory that the helper could
5028 * just partially fill up.
5032 if (reg->smin_value < 0) {
5033 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5038 if (reg->umin_value == 0) {
5039 err = check_helper_mem_access(env, regno - 1, 0,
5046 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5047 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5051 err = check_helper_mem_access(env, regno - 1,
5053 zero_size_allowed, meta);
5055 err = mark_chain_precision(env, regno);
5056 } else if (arg_type_is_alloc_size(arg_type)) {
5057 if (!tnum_is_const(reg->var_off)) {
5058 verbose(env, "R%d is not a known constant'\n",
5062 meta->mem_size = reg->var_off.value;
5063 } else if (arg_type_is_int_ptr(arg_type)) {
5064 int size = int_ptr_type_to_size(arg_type);
5066 err = check_helper_mem_access(env, regno, size, false, meta);
5069 err = check_ptr_alignment(env, reg, 0, size, true);
5070 } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5071 struct bpf_map *map = reg->map_ptr;
5076 if (!bpf_map_is_rdonly(map)) {
5077 verbose(env, "R%d does not point to a readonly map'\n", regno);
5081 if (!tnum_is_const(reg->var_off)) {
5082 verbose(env, "R%d is not a constant address'\n", regno);
5086 if (!map->ops->map_direct_value_addr) {
5087 verbose(env, "no direct value access support for this map type\n");
5091 err = check_map_access(env, regno, reg->off,
5092 map->value_size - reg->off, false);
5096 map_off = reg->off + reg->var_off.value;
5097 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5099 verbose(env, "direct value access on string failed\n");
5103 str_ptr = (char *)(long)(map_addr);
5104 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5105 verbose(env, "string is not zero-terminated\n");
5113 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5115 enum bpf_attach_type eatype = env->prog->expected_attach_type;
5116 enum bpf_prog_type type = resolve_prog_type(env->prog);
5118 if (func_id != BPF_FUNC_map_update_elem)
5121 /* It's not possible to get access to a locked struct sock in these
5122 * contexts, so updating is safe.
5125 case BPF_PROG_TYPE_TRACING:
5126 if (eatype == BPF_TRACE_ITER)
5129 case BPF_PROG_TYPE_SOCKET_FILTER:
5130 case BPF_PROG_TYPE_SCHED_CLS:
5131 case BPF_PROG_TYPE_SCHED_ACT:
5132 case BPF_PROG_TYPE_XDP:
5133 case BPF_PROG_TYPE_SK_REUSEPORT:
5134 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5135 case BPF_PROG_TYPE_SK_LOOKUP:
5141 verbose(env, "cannot update sockmap in this context\n");
5145 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5147 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5150 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5151 struct bpf_map *map, int func_id)
5156 /* We need a two way check, first is from map perspective ... */
5157 switch (map->map_type) {
5158 case BPF_MAP_TYPE_PROG_ARRAY:
5159 if (func_id != BPF_FUNC_tail_call)
5162 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5163 if (func_id != BPF_FUNC_perf_event_read &&
5164 func_id != BPF_FUNC_perf_event_output &&
5165 func_id != BPF_FUNC_skb_output &&
5166 func_id != BPF_FUNC_perf_event_read_value &&
5167 func_id != BPF_FUNC_xdp_output)
5170 case BPF_MAP_TYPE_RINGBUF:
5171 if (func_id != BPF_FUNC_ringbuf_output &&
5172 func_id != BPF_FUNC_ringbuf_reserve &&
5173 func_id != BPF_FUNC_ringbuf_submit &&
5174 func_id != BPF_FUNC_ringbuf_discard &&
5175 func_id != BPF_FUNC_ringbuf_query)
5178 case BPF_MAP_TYPE_STACK_TRACE:
5179 if (func_id != BPF_FUNC_get_stackid)
5182 case BPF_MAP_TYPE_CGROUP_ARRAY:
5183 if (func_id != BPF_FUNC_skb_under_cgroup &&
5184 func_id != BPF_FUNC_current_task_under_cgroup)
5187 case BPF_MAP_TYPE_CGROUP_STORAGE:
5188 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5189 if (func_id != BPF_FUNC_get_local_storage)
5192 case BPF_MAP_TYPE_DEVMAP:
5193 case BPF_MAP_TYPE_DEVMAP_HASH:
5194 if (func_id != BPF_FUNC_redirect_map &&
5195 func_id != BPF_FUNC_map_lookup_elem)
5198 /* Restrict bpf side of cpumap and xskmap, open when use-cases
5201 case BPF_MAP_TYPE_CPUMAP:
5202 if (func_id != BPF_FUNC_redirect_map)
5205 case BPF_MAP_TYPE_XSKMAP:
5206 if (func_id != BPF_FUNC_redirect_map &&
5207 func_id != BPF_FUNC_map_lookup_elem)
5210 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5211 case BPF_MAP_TYPE_HASH_OF_MAPS:
5212 if (func_id != BPF_FUNC_map_lookup_elem)
5215 case BPF_MAP_TYPE_SOCKMAP:
5216 if (func_id != BPF_FUNC_sk_redirect_map &&
5217 func_id != BPF_FUNC_sock_map_update &&
5218 func_id != BPF_FUNC_map_delete_elem &&
5219 func_id != BPF_FUNC_msg_redirect_map &&
5220 func_id != BPF_FUNC_sk_select_reuseport &&
5221 func_id != BPF_FUNC_map_lookup_elem &&
5222 !may_update_sockmap(env, func_id))
5225 case BPF_MAP_TYPE_SOCKHASH:
5226 if (func_id != BPF_FUNC_sk_redirect_hash &&
5227 func_id != BPF_FUNC_sock_hash_update &&
5228 func_id != BPF_FUNC_map_delete_elem &&
5229 func_id != BPF_FUNC_msg_redirect_hash &&
5230 func_id != BPF_FUNC_sk_select_reuseport &&
5231 func_id != BPF_FUNC_map_lookup_elem &&
5232 !may_update_sockmap(env, func_id))
5235 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5236 if (func_id != BPF_FUNC_sk_select_reuseport)
5239 case BPF_MAP_TYPE_QUEUE:
5240 case BPF_MAP_TYPE_STACK:
5241 if (func_id != BPF_FUNC_map_peek_elem &&
5242 func_id != BPF_FUNC_map_pop_elem &&
5243 func_id != BPF_FUNC_map_push_elem)
5246 case BPF_MAP_TYPE_SK_STORAGE:
5247 if (func_id != BPF_FUNC_sk_storage_get &&
5248 func_id != BPF_FUNC_sk_storage_delete)
5251 case BPF_MAP_TYPE_INODE_STORAGE:
5252 if (func_id != BPF_FUNC_inode_storage_get &&
5253 func_id != BPF_FUNC_inode_storage_delete)
5256 case BPF_MAP_TYPE_TASK_STORAGE:
5257 if (func_id != BPF_FUNC_task_storage_get &&
5258 func_id != BPF_FUNC_task_storage_delete)
5265 /* ... and second from the function itself. */
5267 case BPF_FUNC_tail_call:
5268 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5270 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5271 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5275 case BPF_FUNC_perf_event_read:
5276 case BPF_FUNC_perf_event_output:
5277 case BPF_FUNC_perf_event_read_value:
5278 case BPF_FUNC_skb_output:
5279 case BPF_FUNC_xdp_output:
5280 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5283 case BPF_FUNC_get_stackid:
5284 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5287 case BPF_FUNC_current_task_under_cgroup:
5288 case BPF_FUNC_skb_under_cgroup:
5289 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5292 case BPF_FUNC_redirect_map:
5293 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5294 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5295 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5296 map->map_type != BPF_MAP_TYPE_XSKMAP)
5299 case BPF_FUNC_sk_redirect_map:
5300 case BPF_FUNC_msg_redirect_map:
5301 case BPF_FUNC_sock_map_update:
5302 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5305 case BPF_FUNC_sk_redirect_hash:
5306 case BPF_FUNC_msg_redirect_hash:
5307 case BPF_FUNC_sock_hash_update:
5308 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5311 case BPF_FUNC_get_local_storage:
5312 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5313 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5316 case BPF_FUNC_sk_select_reuseport:
5317 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5318 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5319 map->map_type != BPF_MAP_TYPE_SOCKHASH)
5322 case BPF_FUNC_map_peek_elem:
5323 case BPF_FUNC_map_pop_elem:
5324 case BPF_FUNC_map_push_elem:
5325 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5326 map->map_type != BPF_MAP_TYPE_STACK)
5329 case BPF_FUNC_sk_storage_get:
5330 case BPF_FUNC_sk_storage_delete:
5331 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5334 case BPF_FUNC_inode_storage_get:
5335 case BPF_FUNC_inode_storage_delete:
5336 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5339 case BPF_FUNC_task_storage_get:
5340 case BPF_FUNC_task_storage_delete:
5341 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5350 verbose(env, "cannot pass map_type %d into func %s#%d\n",
5351 map->map_type, func_id_name(func_id), func_id);
5355 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5359 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5361 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5363 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5365 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5367 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5370 /* We only support one arg being in raw mode at the moment,
5371 * which is sufficient for the helper functions we have
5377 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5378 enum bpf_arg_type arg_next)
5380 return (arg_type_is_mem_ptr(arg_curr) &&
5381 !arg_type_is_mem_size(arg_next)) ||
5382 (!arg_type_is_mem_ptr(arg_curr) &&
5383 arg_type_is_mem_size(arg_next));
5386 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5388 /* bpf_xxx(..., buf, len) call will access 'len'
5389 * bytes from memory 'buf'. Both arg types need
5390 * to be paired, so make sure there's no buggy
5391 * helper function specification.
5393 if (arg_type_is_mem_size(fn->arg1_type) ||
5394 arg_type_is_mem_ptr(fn->arg5_type) ||
5395 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5396 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5397 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5398 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5404 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5408 if (arg_type_may_be_refcounted(fn->arg1_type))
5410 if (arg_type_may_be_refcounted(fn->arg2_type))
5412 if (arg_type_may_be_refcounted(fn->arg3_type))
5414 if (arg_type_may_be_refcounted(fn->arg4_type))
5416 if (arg_type_may_be_refcounted(fn->arg5_type))
5419 /* A reference acquiring function cannot acquire
5420 * another refcounted ptr.
5422 if (may_be_acquire_function(func_id) && count)
5425 /* We only support one arg being unreferenced at the moment,
5426 * which is sufficient for the helper functions we have right now.
5431 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5435 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5436 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5439 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5446 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5448 return check_raw_mode_ok(fn) &&
5449 check_arg_pair_ok(fn) &&
5450 check_btf_id_ok(fn) &&
5451 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5454 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5455 * are now invalid, so turn them into unknown SCALAR_VALUE.
5457 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5458 struct bpf_func_state *state)
5460 struct bpf_reg_state *regs = state->regs, *reg;
5463 for (i = 0; i < MAX_BPF_REG; i++)
5464 if (reg_is_pkt_pointer_any(®s[i]))
5465 mark_reg_unknown(env, regs, i);
5467 bpf_for_each_spilled_reg(i, state, reg) {
5470 if (reg_is_pkt_pointer_any(reg))
5471 __mark_reg_unknown(env, reg);
5475 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5477 struct bpf_verifier_state *vstate = env->cur_state;
5480 for (i = 0; i <= vstate->curframe; i++)
5481 __clear_all_pkt_pointers(env, vstate->frame[i]);
5486 BEYOND_PKT_END = -2,
5489 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5491 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5492 struct bpf_reg_state *reg = &state->regs[regn];
5494 if (reg->type != PTR_TO_PACKET)
5495 /* PTR_TO_PACKET_META is not supported yet */
5498 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5499 * How far beyond pkt_end it goes is unknown.
5500 * if (!range_open) it's the case of pkt >= pkt_end
5501 * if (range_open) it's the case of pkt > pkt_end
5502 * hence this pointer is at least 1 byte bigger than pkt_end
5505 reg->range = BEYOND_PKT_END;
5507 reg->range = AT_PKT_END;
5510 static void release_reg_references(struct bpf_verifier_env *env,
5511 struct bpf_func_state *state,
5514 struct bpf_reg_state *regs = state->regs, *reg;
5517 for (i = 0; i < MAX_BPF_REG; i++)
5518 if (regs[i].ref_obj_id == ref_obj_id)
5519 mark_reg_unknown(env, regs, i);
5521 bpf_for_each_spilled_reg(i, state, reg) {
5524 if (reg->ref_obj_id == ref_obj_id)
5525 __mark_reg_unknown(env, reg);
5529 /* The pointer with the specified id has released its reference to kernel
5530 * resources. Identify all copies of the same pointer and clear the reference.
5532 static int release_reference(struct bpf_verifier_env *env,
5535 struct bpf_verifier_state *vstate = env->cur_state;
5539 err = release_reference_state(cur_func(env), ref_obj_id);
5543 for (i = 0; i <= vstate->curframe; i++)
5544 release_reg_references(env, vstate->frame[i], ref_obj_id);
5549 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5550 struct bpf_reg_state *regs)
5554 /* after the call registers r0 - r5 were scratched */
5555 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5556 mark_reg_not_init(env, regs, caller_saved[i]);
5557 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5561 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5562 struct bpf_func_state *caller,
5563 struct bpf_func_state *callee,
5566 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5567 int *insn_idx, int subprog,
5568 set_callee_state_fn set_callee_state_cb)
5570 struct bpf_verifier_state *state = env->cur_state;
5571 struct bpf_func_info_aux *func_info_aux;
5572 struct bpf_func_state *caller, *callee;
5574 bool is_global = false;
5576 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5577 verbose(env, "the call stack of %d frames is too deep\n",
5578 state->curframe + 2);
5582 caller = state->frame[state->curframe];
5583 if (state->frame[state->curframe + 1]) {
5584 verbose(env, "verifier bug. Frame %d already allocated\n",
5585 state->curframe + 1);
5589 func_info_aux = env->prog->aux->func_info_aux;
5591 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5592 err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5597 verbose(env, "Caller passes invalid args into func#%d\n",
5601 if (env->log.level & BPF_LOG_LEVEL)
5603 "Func#%d is global and valid. Skipping.\n",
5605 clear_caller_saved_regs(env, caller->regs);
5607 /* All global functions return a 64-bit SCALAR_VALUE */
5608 mark_reg_unknown(env, caller->regs, BPF_REG_0);
5609 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5611 /* continue with next insn after call */
5616 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5619 state->frame[state->curframe + 1] = callee;
5621 /* callee cannot access r0, r6 - r9 for reading and has to write
5622 * into its own stack before reading from it.
5623 * callee can read/write into caller's stack
5625 init_func_state(env, callee,
5626 /* remember the callsite, it will be used by bpf_exit */
5627 *insn_idx /* callsite */,
5628 state->curframe + 1 /* frameno within this callchain */,
5629 subprog /* subprog number within this prog */);
5631 /* Transfer references to the callee */
5632 err = transfer_reference_state(callee, caller);
5636 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5640 clear_caller_saved_regs(env, caller->regs);
5642 /* only increment it after check_reg_arg() finished */
5645 /* and go analyze first insn of the callee */
5646 *insn_idx = env->subprog_info[subprog].start - 1;
5648 if (env->log.level & BPF_LOG_LEVEL) {
5649 verbose(env, "caller:\n");
5650 print_verifier_state(env, caller);
5651 verbose(env, "callee:\n");
5652 print_verifier_state(env, callee);
5657 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5658 struct bpf_func_state *caller,
5659 struct bpf_func_state *callee)
5661 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5662 * void *callback_ctx, u64 flags);
5663 * callback_fn(struct bpf_map *map, void *key, void *value,
5664 * void *callback_ctx);
5666 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5668 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5669 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5670 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5672 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5673 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5674 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5676 /* pointer to stack or null */
5677 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5680 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5684 static int set_callee_state(struct bpf_verifier_env *env,
5685 struct bpf_func_state *caller,
5686 struct bpf_func_state *callee, int insn_idx)
5690 /* copy r1 - r5 args that callee can access. The copy includes parent
5691 * pointers, which connects us up to the liveness chain
5693 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5694 callee->regs[i] = caller->regs[i];
5698 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5701 int subprog, target_insn;
5703 target_insn = *insn_idx + insn->imm + 1;
5704 subprog = find_subprog(env, target_insn);
5706 verbose(env, "verifier bug. No program starts at insn %d\n",
5711 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5714 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5715 struct bpf_func_state *caller,
5716 struct bpf_func_state *callee,
5719 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5720 struct bpf_map *map;
5723 if (bpf_map_ptr_poisoned(insn_aux)) {
5724 verbose(env, "tail_call abusing map_ptr\n");
5728 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5729 if (!map->ops->map_set_for_each_callback_args ||
5730 !map->ops->map_for_each_callback) {
5731 verbose(env, "callback function not allowed for map\n");
5735 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5739 callee->in_callback_fn = true;
5743 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5745 struct bpf_verifier_state *state = env->cur_state;
5746 struct bpf_func_state *caller, *callee;
5747 struct bpf_reg_state *r0;
5750 callee = state->frame[state->curframe];
5751 r0 = &callee->regs[BPF_REG_0];
5752 if (r0->type == PTR_TO_STACK) {
5753 /* technically it's ok to return caller's stack pointer
5754 * (or caller's caller's pointer) back to the caller,
5755 * since these pointers are valid. Only current stack
5756 * pointer will be invalid as soon as function exits,
5757 * but let's be conservative
5759 verbose(env, "cannot return stack pointer to the caller\n");
5764 caller = state->frame[state->curframe];
5765 if (callee->in_callback_fn) {
5766 /* enforce R0 return value range [0, 1]. */
5767 struct tnum range = tnum_range(0, 1);
5769 if (r0->type != SCALAR_VALUE) {
5770 verbose(env, "R0 not a scalar value\n");
5773 if (!tnum_in(range, r0->var_off)) {
5774 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5778 /* return to the caller whatever r0 had in the callee */
5779 caller->regs[BPF_REG_0] = *r0;
5782 /* Transfer references to the caller */
5783 err = transfer_reference_state(caller, callee);
5787 *insn_idx = callee->callsite + 1;
5788 if (env->log.level & BPF_LOG_LEVEL) {
5789 verbose(env, "returning from callee:\n");
5790 print_verifier_state(env, callee);
5791 verbose(env, "to caller at %d:\n", *insn_idx);
5792 print_verifier_state(env, caller);
5794 /* clear everything in the callee */
5795 free_func_state(callee);
5796 state->frame[state->curframe + 1] = NULL;
5800 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5802 struct bpf_call_arg_meta *meta)
5804 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
5806 if (ret_type != RET_INTEGER ||
5807 (func_id != BPF_FUNC_get_stack &&
5808 func_id != BPF_FUNC_get_task_stack &&
5809 func_id != BPF_FUNC_probe_read_str &&
5810 func_id != BPF_FUNC_probe_read_kernel_str &&
5811 func_id != BPF_FUNC_probe_read_user_str))
5814 ret_reg->smax_value = meta->msize_max_value;
5815 ret_reg->s32_max_value = meta->msize_max_value;
5816 ret_reg->smin_value = -MAX_ERRNO;
5817 ret_reg->s32_min_value = -MAX_ERRNO;
5818 __reg_deduce_bounds(ret_reg);
5819 __reg_bound_offset(ret_reg);
5820 __update_reg_bounds(ret_reg);
5824 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5825 int func_id, int insn_idx)
5827 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5828 struct bpf_map *map = meta->map_ptr;
5830 if (func_id != BPF_FUNC_tail_call &&
5831 func_id != BPF_FUNC_map_lookup_elem &&
5832 func_id != BPF_FUNC_map_update_elem &&
5833 func_id != BPF_FUNC_map_delete_elem &&
5834 func_id != BPF_FUNC_map_push_elem &&
5835 func_id != BPF_FUNC_map_pop_elem &&
5836 func_id != BPF_FUNC_map_peek_elem &&
5837 func_id != BPF_FUNC_for_each_map_elem &&
5838 func_id != BPF_FUNC_redirect_map)
5842 verbose(env, "kernel subsystem misconfigured verifier\n");
5846 /* In case of read-only, some additional restrictions
5847 * need to be applied in order to prevent altering the
5848 * state of the map from program side.
5850 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5851 (func_id == BPF_FUNC_map_delete_elem ||
5852 func_id == BPF_FUNC_map_update_elem ||
5853 func_id == BPF_FUNC_map_push_elem ||
5854 func_id == BPF_FUNC_map_pop_elem)) {
5855 verbose(env, "write into map forbidden\n");
5859 if (!BPF_MAP_PTR(aux->map_ptr_state))
5860 bpf_map_ptr_store(aux, meta->map_ptr,
5861 !meta->map_ptr->bypass_spec_v1);
5862 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5863 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5864 !meta->map_ptr->bypass_spec_v1);
5869 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5870 int func_id, int insn_idx)
5872 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5873 struct bpf_reg_state *regs = cur_regs(env), *reg;
5874 struct bpf_map *map = meta->map_ptr;
5879 if (func_id != BPF_FUNC_tail_call)
5881 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5882 verbose(env, "kernel subsystem misconfigured verifier\n");
5886 range = tnum_range(0, map->max_entries - 1);
5887 reg = ®s[BPF_REG_3];
5889 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5890 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5894 err = mark_chain_precision(env, BPF_REG_3);
5898 val = reg->var_off.value;
5899 if (bpf_map_key_unseen(aux))
5900 bpf_map_key_store(aux, val);
5901 else if (!bpf_map_key_poisoned(aux) &&
5902 bpf_map_key_immediate(aux) != val)
5903 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5907 static int check_reference_leak(struct bpf_verifier_env *env)
5909 struct bpf_func_state *state = cur_func(env);
5912 for (i = 0; i < state->acquired_refs; i++) {
5913 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5914 state->refs[i].id, state->refs[i].insn_idx);
5916 return state->acquired_refs ? -EINVAL : 0;
5919 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
5920 struct bpf_reg_state *regs)
5922 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
5923 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
5924 struct bpf_map *fmt_map = fmt_reg->map_ptr;
5925 int err, fmt_map_off, num_args;
5929 /* data must be an array of u64 */
5930 if (data_len_reg->var_off.value % 8)
5932 num_args = data_len_reg->var_off.value / 8;
5934 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
5935 * and map_direct_value_addr is set.
5937 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
5938 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
5941 verbose(env, "verifier bug\n");
5944 fmt = (char *)(long)fmt_addr + fmt_map_off;
5946 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
5947 * can focus on validating the format specifiers.
5949 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
5951 verbose(env, "Invalid format string\n");
5956 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5959 const struct bpf_func_proto *fn = NULL;
5960 struct bpf_reg_state *regs;
5961 struct bpf_call_arg_meta meta;
5962 int insn_idx = *insn_idx_p;
5964 int i, err, func_id;
5966 /* find function prototype */
5967 func_id = insn->imm;
5968 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5969 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5974 if (env->ops->get_func_proto)
5975 fn = env->ops->get_func_proto(func_id, env->prog);
5977 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5982 /* eBPF programs must be GPL compatible to use GPL-ed functions */
5983 if (!env->prog->gpl_compatible && fn->gpl_only) {
5984 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5988 if (fn->allowed && !fn->allowed(env->prog)) {
5989 verbose(env, "helper call is not allowed in probe\n");
5993 /* With LD_ABS/IND some JITs save/restore skb from r1. */
5994 changes_data = bpf_helper_changes_pkt_data(fn->func);
5995 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5996 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5997 func_id_name(func_id), func_id);
6001 memset(&meta, 0, sizeof(meta));
6002 meta.pkt_access = fn->pkt_access;
6004 err = check_func_proto(fn, func_id);
6006 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6007 func_id_name(func_id), func_id);
6011 meta.func_id = func_id;
6013 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6014 err = check_func_arg(env, i, &meta, fn);
6019 err = record_func_map(env, &meta, func_id, insn_idx);
6023 err = record_func_key(env, &meta, func_id, insn_idx);
6027 /* Mark slots with STACK_MISC in case of raw mode, stack offset
6028 * is inferred from register state.
6030 for (i = 0; i < meta.access_size; i++) {
6031 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6032 BPF_WRITE, -1, false);
6037 if (func_id == BPF_FUNC_tail_call) {
6038 err = check_reference_leak(env);
6040 verbose(env, "tail_call would lead to reference leak\n");
6043 } else if (is_release_function(func_id)) {
6044 err = release_reference(env, meta.ref_obj_id);
6046 verbose(env, "func %s#%d reference has not been acquired before\n",
6047 func_id_name(func_id), func_id);
6052 regs = cur_regs(env);
6054 /* check that flags argument in get_local_storage(map, flags) is 0,
6055 * this is required because get_local_storage() can't return an error.
6057 if (func_id == BPF_FUNC_get_local_storage &&
6058 !register_is_null(®s[BPF_REG_2])) {
6059 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6063 if (func_id == BPF_FUNC_for_each_map_elem) {
6064 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6065 set_map_elem_callback_state);
6070 if (func_id == BPF_FUNC_snprintf) {
6071 err = check_bpf_snprintf_call(env, regs);
6076 /* reset caller saved regs */
6077 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6078 mark_reg_not_init(env, regs, caller_saved[i]);
6079 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6082 /* helper call returns 64-bit value. */
6083 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6085 /* update return register (already marked as written above) */
6086 if (fn->ret_type == RET_INTEGER) {
6087 /* sets type to SCALAR_VALUE */
6088 mark_reg_unknown(env, regs, BPF_REG_0);
6089 } else if (fn->ret_type == RET_VOID) {
6090 regs[BPF_REG_0].type = NOT_INIT;
6091 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6092 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6093 /* There is no offset yet applied, variable or fixed */
6094 mark_reg_known_zero(env, regs, BPF_REG_0);
6095 /* remember map_ptr, so that check_map_access()
6096 * can check 'value_size' boundary of memory access
6097 * to map element returned from bpf_map_lookup_elem()
6099 if (meta.map_ptr == NULL) {
6101 "kernel subsystem misconfigured verifier\n");
6104 regs[BPF_REG_0].map_ptr = meta.map_ptr;
6105 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6106 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
6107 if (map_value_has_spin_lock(meta.map_ptr))
6108 regs[BPF_REG_0].id = ++env->id_gen;
6110 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
6112 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6113 mark_reg_known_zero(env, regs, BPF_REG_0);
6114 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
6115 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6116 mark_reg_known_zero(env, regs, BPF_REG_0);
6117 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
6118 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6119 mark_reg_known_zero(env, regs, BPF_REG_0);
6120 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
6121 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6122 mark_reg_known_zero(env, regs, BPF_REG_0);
6123 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
6124 regs[BPF_REG_0].mem_size = meta.mem_size;
6125 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6126 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
6127 const struct btf_type *t;
6129 mark_reg_known_zero(env, regs, BPF_REG_0);
6130 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6131 if (!btf_type_is_struct(t)) {
6133 const struct btf_type *ret;
6136 /* resolve the type size of ksym. */
6137 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6139 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6140 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6141 tname, PTR_ERR(ret));
6144 regs[BPF_REG_0].type =
6145 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6146 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
6147 regs[BPF_REG_0].mem_size = tsize;
6149 regs[BPF_REG_0].type =
6150 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6151 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
6152 regs[BPF_REG_0].btf = meta.ret_btf;
6153 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6155 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6156 fn->ret_type == RET_PTR_TO_BTF_ID) {
6159 mark_reg_known_zero(env, regs, BPF_REG_0);
6160 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6162 PTR_TO_BTF_ID_OR_NULL;
6163 ret_btf_id = *fn->ret_btf_id;
6164 if (ret_btf_id == 0) {
6165 verbose(env, "invalid return type %d of func %s#%d\n",
6166 fn->ret_type, func_id_name(func_id), func_id);
6169 /* current BPF helper definitions are only coming from
6170 * built-in code with type IDs from vmlinux BTF
6172 regs[BPF_REG_0].btf = btf_vmlinux;
6173 regs[BPF_REG_0].btf_id = ret_btf_id;
6175 verbose(env, "unknown return type %d of func %s#%d\n",
6176 fn->ret_type, func_id_name(func_id), func_id);
6180 if (reg_type_may_be_null(regs[BPF_REG_0].type))
6181 regs[BPF_REG_0].id = ++env->id_gen;
6183 if (is_ptr_cast_function(func_id)) {
6184 /* For release_reference() */
6185 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6186 } else if (is_acquire_function(func_id, meta.map_ptr)) {
6187 int id = acquire_reference_state(env, insn_idx);
6191 /* For mark_ptr_or_null_reg() */
6192 regs[BPF_REG_0].id = id;
6193 /* For release_reference() */
6194 regs[BPF_REG_0].ref_obj_id = id;
6197 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6199 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6203 if ((func_id == BPF_FUNC_get_stack ||
6204 func_id == BPF_FUNC_get_task_stack) &&
6205 !env->prog->has_callchain_buf) {
6206 const char *err_str;
6208 #ifdef CONFIG_PERF_EVENTS
6209 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6210 err_str = "cannot get callchain buffer for func %s#%d\n";
6213 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6216 verbose(env, err_str, func_id_name(func_id), func_id);
6220 env->prog->has_callchain_buf = true;
6223 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6224 env->prog->call_get_stack = true;
6227 clear_all_pkt_pointers(env);
6231 /* mark_btf_func_reg_size() is used when the reg size is determined by
6232 * the BTF func_proto's return value size and argument.
6234 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6237 struct bpf_reg_state *reg = &cur_regs(env)[regno];
6239 if (regno == BPF_REG_0) {
6240 /* Function return value */
6241 reg->live |= REG_LIVE_WRITTEN;
6242 reg->subreg_def = reg_size == sizeof(u64) ?
6243 DEF_NOT_SUBREG : env->insn_idx + 1;
6245 /* Function argument */
6246 if (reg_size == sizeof(u64)) {
6247 mark_insn_zext(env, reg);
6248 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6250 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6255 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6257 const struct btf_type *t, *func, *func_proto, *ptr_type;
6258 struct bpf_reg_state *regs = cur_regs(env);
6259 const char *func_name, *ptr_type_name;
6260 u32 i, nargs, func_id, ptr_type_id;
6261 const struct btf_param *args;
6264 func_id = insn->imm;
6265 func = btf_type_by_id(btf_vmlinux, func_id);
6266 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6267 func_proto = btf_type_by_id(btf_vmlinux, func->type);
6269 if (!env->ops->check_kfunc_call ||
6270 !env->ops->check_kfunc_call(func_id)) {
6271 verbose(env, "calling kernel function %s is not allowed\n",
6276 /* Check the arguments */
6277 err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6281 for (i = 0; i < CALLER_SAVED_REGS; i++)
6282 mark_reg_not_init(env, regs, caller_saved[i]);
6284 /* Check return type */
6285 t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6286 if (btf_type_is_scalar(t)) {
6287 mark_reg_unknown(env, regs, BPF_REG_0);
6288 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6289 } else if (btf_type_is_ptr(t)) {
6290 ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6292 if (!btf_type_is_struct(ptr_type)) {
6293 ptr_type_name = btf_name_by_offset(btf_vmlinux,
6294 ptr_type->name_off);
6295 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6296 func_name, btf_type_str(ptr_type),
6300 mark_reg_known_zero(env, regs, BPF_REG_0);
6301 regs[BPF_REG_0].btf = btf_vmlinux;
6302 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6303 regs[BPF_REG_0].btf_id = ptr_type_id;
6304 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6305 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6307 nargs = btf_type_vlen(func_proto);
6308 args = (const struct btf_param *)(func_proto + 1);
6309 for (i = 0; i < nargs; i++) {
6312 t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6313 if (btf_type_is_ptr(t))
6314 mark_btf_func_reg_size(env, regno, sizeof(void *));
6316 /* scalar. ensured by btf_check_kfunc_arg_match() */
6317 mark_btf_func_reg_size(env, regno, t->size);
6323 static bool signed_add_overflows(s64 a, s64 b)
6325 /* Do the add in u64, where overflow is well-defined */
6326 s64 res = (s64)((u64)a + (u64)b);
6333 static bool signed_add32_overflows(s32 a, s32 b)
6335 /* Do the add in u32, where overflow is well-defined */
6336 s32 res = (s32)((u32)a + (u32)b);
6343 static bool signed_sub_overflows(s64 a, s64 b)
6345 /* Do the sub in u64, where overflow is well-defined */
6346 s64 res = (s64)((u64)a - (u64)b);
6353 static bool signed_sub32_overflows(s32 a, s32 b)
6355 /* Do the sub in u32, where overflow is well-defined */
6356 s32 res = (s32)((u32)a - (u32)b);
6363 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6364 const struct bpf_reg_state *reg,
6365 enum bpf_reg_type type)
6367 bool known = tnum_is_const(reg->var_off);
6368 s64 val = reg->var_off.value;
6369 s64 smin = reg->smin_value;
6371 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6372 verbose(env, "math between %s pointer and %lld is not allowed\n",
6373 reg_type_str[type], val);
6377 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6378 verbose(env, "%s pointer offset %d is not allowed\n",
6379 reg_type_str[type], reg->off);
6383 if (smin == S64_MIN) {
6384 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6385 reg_type_str[type]);
6389 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6390 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6391 smin, reg_type_str[type]);
6398 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6400 return &env->insn_aux_data[env->insn_idx];
6411 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6412 u32 *alu_limit, bool mask_to_left)
6414 u32 max = 0, ptr_limit = 0;
6416 switch (ptr_reg->type) {
6418 /* Offset 0 is out-of-bounds, but acceptable start for the
6419 * left direction, see BPF_REG_FP. Also, unknown scalar
6420 * offset where we would need to deal with min/max bounds is
6421 * currently prohibited for unprivileged.
6423 max = MAX_BPF_STACK + mask_to_left;
6424 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6426 case PTR_TO_MAP_VALUE:
6427 max = ptr_reg->map_ptr->value_size;
6428 ptr_limit = (mask_to_left ?
6429 ptr_reg->smin_value :
6430 ptr_reg->umax_value) + ptr_reg->off;
6436 if (ptr_limit >= max)
6437 return REASON_LIMIT;
6438 *alu_limit = ptr_limit;
6442 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6443 const struct bpf_insn *insn)
6445 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6448 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6449 u32 alu_state, u32 alu_limit)
6451 /* If we arrived here from different branches with different
6452 * state or limits to sanitize, then this won't work.
6454 if (aux->alu_state &&
6455 (aux->alu_state != alu_state ||
6456 aux->alu_limit != alu_limit))
6457 return REASON_PATHS;
6459 /* Corresponding fixup done in do_misc_fixups(). */
6460 aux->alu_state = alu_state;
6461 aux->alu_limit = alu_limit;
6465 static int sanitize_val_alu(struct bpf_verifier_env *env,
6466 struct bpf_insn *insn)
6468 struct bpf_insn_aux_data *aux = cur_aux(env);
6470 if (can_skip_alu_sanitation(env, insn))
6473 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6476 static bool sanitize_needed(u8 opcode)
6478 return opcode == BPF_ADD || opcode == BPF_SUB;
6481 struct bpf_sanitize_info {
6482 struct bpf_insn_aux_data aux;
6486 static struct bpf_verifier_state *
6487 sanitize_speculative_path(struct bpf_verifier_env *env,
6488 const struct bpf_insn *insn,
6489 u32 next_idx, u32 curr_idx)
6491 struct bpf_verifier_state *branch;
6492 struct bpf_reg_state *regs;
6494 branch = push_stack(env, next_idx, curr_idx, true);
6495 if (branch && insn) {
6496 regs = branch->frame[branch->curframe]->regs;
6497 if (BPF_SRC(insn->code) == BPF_K) {
6498 mark_reg_unknown(env, regs, insn->dst_reg);
6499 } else if (BPF_SRC(insn->code) == BPF_X) {
6500 mark_reg_unknown(env, regs, insn->dst_reg);
6501 mark_reg_unknown(env, regs, insn->src_reg);
6507 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6508 struct bpf_insn *insn,
6509 const struct bpf_reg_state *ptr_reg,
6510 const struct bpf_reg_state *off_reg,
6511 struct bpf_reg_state *dst_reg,
6512 struct bpf_sanitize_info *info,
6513 const bool commit_window)
6515 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6516 struct bpf_verifier_state *vstate = env->cur_state;
6517 bool off_is_imm = tnum_is_const(off_reg->var_off);
6518 bool off_is_neg = off_reg->smin_value < 0;
6519 bool ptr_is_dst_reg = ptr_reg == dst_reg;
6520 u8 opcode = BPF_OP(insn->code);
6521 u32 alu_state, alu_limit;
6522 struct bpf_reg_state tmp;
6526 if (can_skip_alu_sanitation(env, insn))
6529 /* We already marked aux for masking from non-speculative
6530 * paths, thus we got here in the first place. We only care
6531 * to explore bad access from here.
6533 if (vstate->speculative)
6536 if (!commit_window) {
6537 if (!tnum_is_const(off_reg->var_off) &&
6538 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6539 return REASON_BOUNDS;
6541 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
6542 (opcode == BPF_SUB && !off_is_neg);
6545 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6549 if (commit_window) {
6550 /* In commit phase we narrow the masking window based on
6551 * the observed pointer move after the simulated operation.
6553 alu_state = info->aux.alu_state;
6554 alu_limit = abs(info->aux.alu_limit - alu_limit);
6556 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6557 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6558 alu_state |= ptr_is_dst_reg ?
6559 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6562 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6566 /* If we're in commit phase, we're done here given we already
6567 * pushed the truncated dst_reg into the speculative verification
6570 * Also, when register is a known constant, we rewrite register-based
6571 * operation to immediate-based, and thus do not need masking (and as
6572 * a consequence, do not need to simulate the zero-truncation either).
6574 if (commit_window || off_is_imm)
6577 /* Simulate and find potential out-of-bounds access under
6578 * speculative execution from truncation as a result of
6579 * masking when off was not within expected range. If off
6580 * sits in dst, then we temporarily need to move ptr there
6581 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6582 * for cases where we use K-based arithmetic in one direction
6583 * and truncated reg-based in the other in order to explore
6586 if (!ptr_is_dst_reg) {
6588 *dst_reg = *ptr_reg;
6590 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6592 if (!ptr_is_dst_reg && ret)
6594 return !ret ? REASON_STACK : 0;
6597 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6599 struct bpf_verifier_state *vstate = env->cur_state;
6601 /* If we simulate paths under speculation, we don't update the
6602 * insn as 'seen' such that when we verify unreachable paths in
6603 * the non-speculative domain, sanitize_dead_code() can still
6604 * rewrite/sanitize them.
6606 if (!vstate->speculative)
6607 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6610 static int sanitize_err(struct bpf_verifier_env *env,
6611 const struct bpf_insn *insn, int reason,
6612 const struct bpf_reg_state *off_reg,
6613 const struct bpf_reg_state *dst_reg)
6615 static const char *err = "pointer arithmetic with it prohibited for !root";
6616 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6617 u32 dst = insn->dst_reg, src = insn->src_reg;
6621 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6622 off_reg == dst_reg ? dst : src, err);
6625 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6626 off_reg == dst_reg ? src : dst, err);
6629 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6633 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6637 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6641 verbose(env, "verifier internal error: unknown reason (%d)\n",
6649 /* check that stack access falls within stack limits and that 'reg' doesn't
6650 * have a variable offset.
6652 * Variable offset is prohibited for unprivileged mode for simplicity since it
6653 * requires corresponding support in Spectre masking for stack ALU. See also
6654 * retrieve_ptr_limit().
6657 * 'off' includes 'reg->off'.
6659 static int check_stack_access_for_ptr_arithmetic(
6660 struct bpf_verifier_env *env,
6662 const struct bpf_reg_state *reg,
6665 if (!tnum_is_const(reg->var_off)) {
6668 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6669 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6670 regno, tn_buf, off);
6674 if (off >= 0 || off < -MAX_BPF_STACK) {
6675 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6676 "prohibited for !root; off=%d\n", regno, off);
6683 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6684 const struct bpf_insn *insn,
6685 const struct bpf_reg_state *dst_reg)
6687 u32 dst = insn->dst_reg;
6689 /* For unprivileged we require that resulting offset must be in bounds
6690 * in order to be able to sanitize access later on.
6692 if (env->bypass_spec_v1)
6695 switch (dst_reg->type) {
6697 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6698 dst_reg->off + dst_reg->var_off.value))
6701 case PTR_TO_MAP_VALUE:
6702 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6703 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6704 "prohibited for !root\n", dst);
6715 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6716 * Caller should also handle BPF_MOV case separately.
6717 * If we return -EACCES, caller may want to try again treating pointer as a
6718 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6720 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6721 struct bpf_insn *insn,
6722 const struct bpf_reg_state *ptr_reg,
6723 const struct bpf_reg_state *off_reg)
6725 struct bpf_verifier_state *vstate = env->cur_state;
6726 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6727 struct bpf_reg_state *regs = state->regs, *dst_reg;
6728 bool known = tnum_is_const(off_reg->var_off);
6729 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6730 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6731 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6732 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6733 struct bpf_sanitize_info info = {};
6734 u8 opcode = BPF_OP(insn->code);
6735 u32 dst = insn->dst_reg;
6738 dst_reg = ®s[dst];
6740 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6741 smin_val > smax_val || umin_val > umax_val) {
6742 /* Taint dst register if offset had invalid bounds derived from
6743 * e.g. dead branches.
6745 __mark_reg_unknown(env, dst_reg);
6749 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6750 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6751 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6752 __mark_reg_unknown(env, dst_reg);
6757 "R%d 32-bit pointer arithmetic prohibited\n",
6762 switch (ptr_reg->type) {
6763 case PTR_TO_MAP_VALUE_OR_NULL:
6764 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6765 dst, reg_type_str[ptr_reg->type]);
6767 case CONST_PTR_TO_MAP:
6768 /* smin_val represents the known value */
6769 if (known && smin_val == 0 && opcode == BPF_ADD)
6772 case PTR_TO_PACKET_END:
6774 case PTR_TO_SOCKET_OR_NULL:
6775 case PTR_TO_SOCK_COMMON:
6776 case PTR_TO_SOCK_COMMON_OR_NULL:
6777 case PTR_TO_TCP_SOCK:
6778 case PTR_TO_TCP_SOCK_OR_NULL:
6779 case PTR_TO_XDP_SOCK:
6780 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6781 dst, reg_type_str[ptr_reg->type]);
6787 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6788 * The id may be overwritten later if we create a new variable offset.
6790 dst_reg->type = ptr_reg->type;
6791 dst_reg->id = ptr_reg->id;
6793 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6794 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6797 /* pointer types do not carry 32-bit bounds at the moment. */
6798 __mark_reg32_unbounded(dst_reg);
6800 if (sanitize_needed(opcode)) {
6801 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6804 return sanitize_err(env, insn, ret, off_reg, dst_reg);
6809 /* We can take a fixed offset as long as it doesn't overflow
6810 * the s32 'off' field
6812 if (known && (ptr_reg->off + smin_val ==
6813 (s64)(s32)(ptr_reg->off + smin_val))) {
6814 /* pointer += K. Accumulate it into fixed offset */
6815 dst_reg->smin_value = smin_ptr;
6816 dst_reg->smax_value = smax_ptr;
6817 dst_reg->umin_value = umin_ptr;
6818 dst_reg->umax_value = umax_ptr;
6819 dst_reg->var_off = ptr_reg->var_off;
6820 dst_reg->off = ptr_reg->off + smin_val;
6821 dst_reg->raw = ptr_reg->raw;
6824 /* A new variable offset is created. Note that off_reg->off
6825 * == 0, since it's a scalar.
6826 * dst_reg gets the pointer type and since some positive
6827 * integer value was added to the pointer, give it a new 'id'
6828 * if it's a PTR_TO_PACKET.
6829 * this creates a new 'base' pointer, off_reg (variable) gets
6830 * added into the variable offset, and we copy the fixed offset
6833 if (signed_add_overflows(smin_ptr, smin_val) ||
6834 signed_add_overflows(smax_ptr, smax_val)) {
6835 dst_reg->smin_value = S64_MIN;
6836 dst_reg->smax_value = S64_MAX;
6838 dst_reg->smin_value = smin_ptr + smin_val;
6839 dst_reg->smax_value = smax_ptr + smax_val;
6841 if (umin_ptr + umin_val < umin_ptr ||
6842 umax_ptr + umax_val < umax_ptr) {
6843 dst_reg->umin_value = 0;
6844 dst_reg->umax_value = U64_MAX;
6846 dst_reg->umin_value = umin_ptr + umin_val;
6847 dst_reg->umax_value = umax_ptr + umax_val;
6849 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6850 dst_reg->off = ptr_reg->off;
6851 dst_reg->raw = ptr_reg->raw;
6852 if (reg_is_pkt_pointer(ptr_reg)) {
6853 dst_reg->id = ++env->id_gen;
6854 /* something was added to pkt_ptr, set range to zero */
6855 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6859 if (dst_reg == off_reg) {
6860 /* scalar -= pointer. Creates an unknown scalar */
6861 verbose(env, "R%d tried to subtract pointer from scalar\n",
6865 /* We don't allow subtraction from FP, because (according to
6866 * test_verifier.c test "invalid fp arithmetic", JITs might not
6867 * be able to deal with it.
6869 if (ptr_reg->type == PTR_TO_STACK) {
6870 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6874 if (known && (ptr_reg->off - smin_val ==
6875 (s64)(s32)(ptr_reg->off - smin_val))) {
6876 /* pointer -= K. Subtract it from fixed offset */
6877 dst_reg->smin_value = smin_ptr;
6878 dst_reg->smax_value = smax_ptr;
6879 dst_reg->umin_value = umin_ptr;
6880 dst_reg->umax_value = umax_ptr;
6881 dst_reg->var_off = ptr_reg->var_off;
6882 dst_reg->id = ptr_reg->id;
6883 dst_reg->off = ptr_reg->off - smin_val;
6884 dst_reg->raw = ptr_reg->raw;
6887 /* A new variable offset is created. If the subtrahend is known
6888 * nonnegative, then any reg->range we had before is still good.
6890 if (signed_sub_overflows(smin_ptr, smax_val) ||
6891 signed_sub_overflows(smax_ptr, smin_val)) {
6892 /* Overflow possible, we know nothing */
6893 dst_reg->smin_value = S64_MIN;
6894 dst_reg->smax_value = S64_MAX;
6896 dst_reg->smin_value = smin_ptr - smax_val;
6897 dst_reg->smax_value = smax_ptr - smin_val;
6899 if (umin_ptr < umax_val) {
6900 /* Overflow possible, we know nothing */
6901 dst_reg->umin_value = 0;
6902 dst_reg->umax_value = U64_MAX;
6904 /* Cannot overflow (as long as bounds are consistent) */
6905 dst_reg->umin_value = umin_ptr - umax_val;
6906 dst_reg->umax_value = umax_ptr - umin_val;
6908 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6909 dst_reg->off = ptr_reg->off;
6910 dst_reg->raw = ptr_reg->raw;
6911 if (reg_is_pkt_pointer(ptr_reg)) {
6912 dst_reg->id = ++env->id_gen;
6913 /* something was added to pkt_ptr, set range to zero */
6915 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6921 /* bitwise ops on pointers are troublesome, prohibit. */
6922 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6923 dst, bpf_alu_string[opcode >> 4]);
6926 /* other operators (e.g. MUL,LSH) produce non-pointer results */
6927 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6928 dst, bpf_alu_string[opcode >> 4]);
6932 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6935 __update_reg_bounds(dst_reg);
6936 __reg_deduce_bounds(dst_reg);
6937 __reg_bound_offset(dst_reg);
6939 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6941 if (sanitize_needed(opcode)) {
6942 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6945 return sanitize_err(env, insn, ret, off_reg, dst_reg);
6951 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6952 struct bpf_reg_state *src_reg)
6954 s32 smin_val = src_reg->s32_min_value;
6955 s32 smax_val = src_reg->s32_max_value;
6956 u32 umin_val = src_reg->u32_min_value;
6957 u32 umax_val = src_reg->u32_max_value;
6959 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6960 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6961 dst_reg->s32_min_value = S32_MIN;
6962 dst_reg->s32_max_value = S32_MAX;
6964 dst_reg->s32_min_value += smin_val;
6965 dst_reg->s32_max_value += smax_val;
6967 if (dst_reg->u32_min_value + umin_val < umin_val ||
6968 dst_reg->u32_max_value + umax_val < umax_val) {
6969 dst_reg->u32_min_value = 0;
6970 dst_reg->u32_max_value = U32_MAX;
6972 dst_reg->u32_min_value += umin_val;
6973 dst_reg->u32_max_value += umax_val;
6977 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6978 struct bpf_reg_state *src_reg)
6980 s64 smin_val = src_reg->smin_value;
6981 s64 smax_val = src_reg->smax_value;
6982 u64 umin_val = src_reg->umin_value;
6983 u64 umax_val = src_reg->umax_value;
6985 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6986 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6987 dst_reg->smin_value = S64_MIN;
6988 dst_reg->smax_value = S64_MAX;
6990 dst_reg->smin_value += smin_val;
6991 dst_reg->smax_value += smax_val;
6993 if (dst_reg->umin_value + umin_val < umin_val ||
6994 dst_reg->umax_value + umax_val < umax_val) {
6995 dst_reg->umin_value = 0;
6996 dst_reg->umax_value = U64_MAX;
6998 dst_reg->umin_value += umin_val;
6999 dst_reg->umax_value += umax_val;
7003 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7004 struct bpf_reg_state *src_reg)
7006 s32 smin_val = src_reg->s32_min_value;
7007 s32 smax_val = src_reg->s32_max_value;
7008 u32 umin_val = src_reg->u32_min_value;
7009 u32 umax_val = src_reg->u32_max_value;
7011 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7012 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7013 /* Overflow possible, we know nothing */
7014 dst_reg->s32_min_value = S32_MIN;
7015 dst_reg->s32_max_value = S32_MAX;
7017 dst_reg->s32_min_value -= smax_val;
7018 dst_reg->s32_max_value -= smin_val;
7020 if (dst_reg->u32_min_value < umax_val) {
7021 /* Overflow possible, we know nothing */
7022 dst_reg->u32_min_value = 0;
7023 dst_reg->u32_max_value = U32_MAX;
7025 /* Cannot overflow (as long as bounds are consistent) */
7026 dst_reg->u32_min_value -= umax_val;
7027 dst_reg->u32_max_value -= umin_val;
7031 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7032 struct bpf_reg_state *src_reg)
7034 s64 smin_val = src_reg->smin_value;
7035 s64 smax_val = src_reg->smax_value;
7036 u64 umin_val = src_reg->umin_value;
7037 u64 umax_val = src_reg->umax_value;
7039 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7040 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7041 /* Overflow possible, we know nothing */
7042 dst_reg->smin_value = S64_MIN;
7043 dst_reg->smax_value = S64_MAX;
7045 dst_reg->smin_value -= smax_val;
7046 dst_reg->smax_value -= smin_val;
7048 if (dst_reg->umin_value < umax_val) {
7049 /* Overflow possible, we know nothing */
7050 dst_reg->umin_value = 0;
7051 dst_reg->umax_value = U64_MAX;
7053 /* Cannot overflow (as long as bounds are consistent) */
7054 dst_reg->umin_value -= umax_val;
7055 dst_reg->umax_value -= umin_val;
7059 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7060 struct bpf_reg_state *src_reg)
7062 s32 smin_val = src_reg->s32_min_value;
7063 u32 umin_val = src_reg->u32_min_value;
7064 u32 umax_val = src_reg->u32_max_value;
7066 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7067 /* Ain't nobody got time to multiply that sign */
7068 __mark_reg32_unbounded(dst_reg);
7071 /* Both values are positive, so we can work with unsigned and
7072 * copy the result to signed (unless it exceeds S32_MAX).
7074 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7075 /* Potential overflow, we know nothing */
7076 __mark_reg32_unbounded(dst_reg);
7079 dst_reg->u32_min_value *= umin_val;
7080 dst_reg->u32_max_value *= umax_val;
7081 if (dst_reg->u32_max_value > S32_MAX) {
7082 /* Overflow possible, we know nothing */
7083 dst_reg->s32_min_value = S32_MIN;
7084 dst_reg->s32_max_value = S32_MAX;
7086 dst_reg->s32_min_value = dst_reg->u32_min_value;
7087 dst_reg->s32_max_value = dst_reg->u32_max_value;
7091 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7092 struct bpf_reg_state *src_reg)
7094 s64 smin_val = src_reg->smin_value;
7095 u64 umin_val = src_reg->umin_value;
7096 u64 umax_val = src_reg->umax_value;
7098 if (smin_val < 0 || dst_reg->smin_value < 0) {
7099 /* Ain't nobody got time to multiply that sign */
7100 __mark_reg64_unbounded(dst_reg);
7103 /* Both values are positive, so we can work with unsigned and
7104 * copy the result to signed (unless it exceeds S64_MAX).
7106 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7107 /* Potential overflow, we know nothing */
7108 __mark_reg64_unbounded(dst_reg);
7111 dst_reg->umin_value *= umin_val;
7112 dst_reg->umax_value *= umax_val;
7113 if (dst_reg->umax_value > S64_MAX) {
7114 /* Overflow possible, we know nothing */
7115 dst_reg->smin_value = S64_MIN;
7116 dst_reg->smax_value = S64_MAX;
7118 dst_reg->smin_value = dst_reg->umin_value;
7119 dst_reg->smax_value = dst_reg->umax_value;
7123 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7124 struct bpf_reg_state *src_reg)
7126 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7127 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7128 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7129 s32 smin_val = src_reg->s32_min_value;
7130 u32 umax_val = src_reg->u32_max_value;
7132 if (src_known && dst_known) {
7133 __mark_reg32_known(dst_reg, var32_off.value);
7137 /* We get our minimum from the var_off, since that's inherently
7138 * bitwise. Our maximum is the minimum of the operands' maxima.
7140 dst_reg->u32_min_value = var32_off.value;
7141 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7142 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7143 /* Lose signed bounds when ANDing negative numbers,
7144 * ain't nobody got time for that.
7146 dst_reg->s32_min_value = S32_MIN;
7147 dst_reg->s32_max_value = S32_MAX;
7149 /* ANDing two positives gives a positive, so safe to
7150 * cast result into s64.
7152 dst_reg->s32_min_value = dst_reg->u32_min_value;
7153 dst_reg->s32_max_value = dst_reg->u32_max_value;
7157 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7158 struct bpf_reg_state *src_reg)
7160 bool src_known = tnum_is_const(src_reg->var_off);
7161 bool dst_known = tnum_is_const(dst_reg->var_off);
7162 s64 smin_val = src_reg->smin_value;
7163 u64 umax_val = src_reg->umax_value;
7165 if (src_known && dst_known) {
7166 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7170 /* We get our minimum from the var_off, since that's inherently
7171 * bitwise. Our maximum is the minimum of the operands' maxima.
7173 dst_reg->umin_value = dst_reg->var_off.value;
7174 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7175 if (dst_reg->smin_value < 0 || smin_val < 0) {
7176 /* Lose signed bounds when ANDing negative numbers,
7177 * ain't nobody got time for that.
7179 dst_reg->smin_value = S64_MIN;
7180 dst_reg->smax_value = S64_MAX;
7182 /* ANDing two positives gives a positive, so safe to
7183 * cast result into s64.
7185 dst_reg->smin_value = dst_reg->umin_value;
7186 dst_reg->smax_value = dst_reg->umax_value;
7188 /* We may learn something more from the var_off */
7189 __update_reg_bounds(dst_reg);
7192 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7193 struct bpf_reg_state *src_reg)
7195 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7196 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7197 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7198 s32 smin_val = src_reg->s32_min_value;
7199 u32 umin_val = src_reg->u32_min_value;
7201 if (src_known && dst_known) {
7202 __mark_reg32_known(dst_reg, var32_off.value);
7206 /* We get our maximum from the var_off, and our minimum is the
7207 * maximum of the operands' minima
7209 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7210 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7211 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7212 /* Lose signed bounds when ORing negative numbers,
7213 * ain't nobody got time for that.
7215 dst_reg->s32_min_value = S32_MIN;
7216 dst_reg->s32_max_value = S32_MAX;
7218 /* ORing two positives gives a positive, so safe to
7219 * cast result into s64.
7221 dst_reg->s32_min_value = dst_reg->u32_min_value;
7222 dst_reg->s32_max_value = dst_reg->u32_max_value;
7226 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7227 struct bpf_reg_state *src_reg)
7229 bool src_known = tnum_is_const(src_reg->var_off);
7230 bool dst_known = tnum_is_const(dst_reg->var_off);
7231 s64 smin_val = src_reg->smin_value;
7232 u64 umin_val = src_reg->umin_value;
7234 if (src_known && dst_known) {
7235 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7239 /* We get our maximum from the var_off, and our minimum is the
7240 * maximum of the operands' minima
7242 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7243 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7244 if (dst_reg->smin_value < 0 || smin_val < 0) {
7245 /* Lose signed bounds when ORing negative numbers,
7246 * ain't nobody got time for that.
7248 dst_reg->smin_value = S64_MIN;
7249 dst_reg->smax_value = S64_MAX;
7251 /* ORing two positives gives a positive, so safe to
7252 * cast result into s64.
7254 dst_reg->smin_value = dst_reg->umin_value;
7255 dst_reg->smax_value = dst_reg->umax_value;
7257 /* We may learn something more from the var_off */
7258 __update_reg_bounds(dst_reg);
7261 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7262 struct bpf_reg_state *src_reg)
7264 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7265 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7266 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7267 s32 smin_val = src_reg->s32_min_value;
7269 if (src_known && dst_known) {
7270 __mark_reg32_known(dst_reg, var32_off.value);
7274 /* We get both minimum and maximum from the var32_off. */
7275 dst_reg->u32_min_value = var32_off.value;
7276 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7278 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7279 /* XORing two positive sign numbers gives a positive,
7280 * so safe to cast u32 result into s32.
7282 dst_reg->s32_min_value = dst_reg->u32_min_value;
7283 dst_reg->s32_max_value = dst_reg->u32_max_value;
7285 dst_reg->s32_min_value = S32_MIN;
7286 dst_reg->s32_max_value = S32_MAX;
7290 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7291 struct bpf_reg_state *src_reg)
7293 bool src_known = tnum_is_const(src_reg->var_off);
7294 bool dst_known = tnum_is_const(dst_reg->var_off);
7295 s64 smin_val = src_reg->smin_value;
7297 if (src_known && dst_known) {
7298 /* dst_reg->var_off.value has been updated earlier */
7299 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7303 /* We get both minimum and maximum from the var_off. */
7304 dst_reg->umin_value = dst_reg->var_off.value;
7305 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7307 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7308 /* XORing two positive sign numbers gives a positive,
7309 * so safe to cast u64 result into s64.
7311 dst_reg->smin_value = dst_reg->umin_value;
7312 dst_reg->smax_value = dst_reg->umax_value;
7314 dst_reg->smin_value = S64_MIN;
7315 dst_reg->smax_value = S64_MAX;
7318 __update_reg_bounds(dst_reg);
7321 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7322 u64 umin_val, u64 umax_val)
7324 /* We lose all sign bit information (except what we can pick
7327 dst_reg->s32_min_value = S32_MIN;
7328 dst_reg->s32_max_value = S32_MAX;
7329 /* If we might shift our top bit out, then we know nothing */
7330 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7331 dst_reg->u32_min_value = 0;
7332 dst_reg->u32_max_value = U32_MAX;
7334 dst_reg->u32_min_value <<= umin_val;
7335 dst_reg->u32_max_value <<= umax_val;
7339 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7340 struct bpf_reg_state *src_reg)
7342 u32 umax_val = src_reg->u32_max_value;
7343 u32 umin_val = src_reg->u32_min_value;
7344 /* u32 alu operation will zext upper bits */
7345 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7347 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7348 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7349 /* Not required but being careful mark reg64 bounds as unknown so
7350 * that we are forced to pick them up from tnum and zext later and
7351 * if some path skips this step we are still safe.
7353 __mark_reg64_unbounded(dst_reg);
7354 __update_reg32_bounds(dst_reg);
7357 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7358 u64 umin_val, u64 umax_val)
7360 /* Special case <<32 because it is a common compiler pattern to sign
7361 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7362 * positive we know this shift will also be positive so we can track
7363 * bounds correctly. Otherwise we lose all sign bit information except
7364 * what we can pick up from var_off. Perhaps we can generalize this
7365 * later to shifts of any length.
7367 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7368 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7370 dst_reg->smax_value = S64_MAX;
7372 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7373 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7375 dst_reg->smin_value = S64_MIN;
7377 /* If we might shift our top bit out, then we know nothing */
7378 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7379 dst_reg->umin_value = 0;
7380 dst_reg->umax_value = U64_MAX;
7382 dst_reg->umin_value <<= umin_val;
7383 dst_reg->umax_value <<= umax_val;
7387 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7388 struct bpf_reg_state *src_reg)
7390 u64 umax_val = src_reg->umax_value;
7391 u64 umin_val = src_reg->umin_value;
7393 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7394 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7395 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7397 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7398 /* We may learn something more from the var_off */
7399 __update_reg_bounds(dst_reg);
7402 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7403 struct bpf_reg_state *src_reg)
7405 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7406 u32 umax_val = src_reg->u32_max_value;
7407 u32 umin_val = src_reg->u32_min_value;
7409 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7410 * be negative, then either:
7411 * 1) src_reg might be zero, so the sign bit of the result is
7412 * unknown, so we lose our signed bounds
7413 * 2) it's known negative, thus the unsigned bounds capture the
7415 * 3) the signed bounds cross zero, so they tell us nothing
7417 * If the value in dst_reg is known nonnegative, then again the
7418 * unsigned bounds capture the signed bounds.
7419 * Thus, in all cases it suffices to blow away our signed bounds
7420 * and rely on inferring new ones from the unsigned bounds and
7421 * var_off of the result.
7423 dst_reg->s32_min_value = S32_MIN;
7424 dst_reg->s32_max_value = S32_MAX;
7426 dst_reg->var_off = tnum_rshift(subreg, umin_val);
7427 dst_reg->u32_min_value >>= umax_val;
7428 dst_reg->u32_max_value >>= umin_val;
7430 __mark_reg64_unbounded(dst_reg);
7431 __update_reg32_bounds(dst_reg);
7434 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7435 struct bpf_reg_state *src_reg)
7437 u64 umax_val = src_reg->umax_value;
7438 u64 umin_val = src_reg->umin_value;
7440 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7441 * be negative, then either:
7442 * 1) src_reg might be zero, so the sign bit of the result is
7443 * unknown, so we lose our signed bounds
7444 * 2) it's known negative, thus the unsigned bounds capture the
7446 * 3) the signed bounds cross zero, so they tell us nothing
7448 * If the value in dst_reg is known nonnegative, then again the
7449 * unsigned bounds capture the signed bounds.
7450 * Thus, in all cases it suffices to blow away our signed bounds
7451 * and rely on inferring new ones from the unsigned bounds and
7452 * var_off of the result.
7454 dst_reg->smin_value = S64_MIN;
7455 dst_reg->smax_value = S64_MAX;
7456 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7457 dst_reg->umin_value >>= umax_val;
7458 dst_reg->umax_value >>= umin_val;
7460 /* Its not easy to operate on alu32 bounds here because it depends
7461 * on bits being shifted in. Take easy way out and mark unbounded
7462 * so we can recalculate later from tnum.
7464 __mark_reg32_unbounded(dst_reg);
7465 __update_reg_bounds(dst_reg);
7468 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7469 struct bpf_reg_state *src_reg)
7471 u64 umin_val = src_reg->u32_min_value;
7473 /* Upon reaching here, src_known is true and
7474 * umax_val is equal to umin_val.
7476 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7477 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7479 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7481 /* blow away the dst_reg umin_value/umax_value and rely on
7482 * dst_reg var_off to refine the result.
7484 dst_reg->u32_min_value = 0;
7485 dst_reg->u32_max_value = U32_MAX;
7487 __mark_reg64_unbounded(dst_reg);
7488 __update_reg32_bounds(dst_reg);
7491 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7492 struct bpf_reg_state *src_reg)
7494 u64 umin_val = src_reg->umin_value;
7496 /* Upon reaching here, src_known is true and umax_val is equal
7499 dst_reg->smin_value >>= umin_val;
7500 dst_reg->smax_value >>= umin_val;
7502 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7504 /* blow away the dst_reg umin_value/umax_value and rely on
7505 * dst_reg var_off to refine the result.
7507 dst_reg->umin_value = 0;
7508 dst_reg->umax_value = U64_MAX;
7510 /* Its not easy to operate on alu32 bounds here because it depends
7511 * on bits being shifted in from upper 32-bits. Take easy way out
7512 * and mark unbounded so we can recalculate later from tnum.
7514 __mark_reg32_unbounded(dst_reg);
7515 __update_reg_bounds(dst_reg);
7518 /* WARNING: This function does calculations on 64-bit values, but the actual
7519 * execution may occur on 32-bit values. Therefore, things like bitshifts
7520 * need extra checks in the 32-bit case.
7522 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7523 struct bpf_insn *insn,
7524 struct bpf_reg_state *dst_reg,
7525 struct bpf_reg_state src_reg)
7527 struct bpf_reg_state *regs = cur_regs(env);
7528 u8 opcode = BPF_OP(insn->code);
7530 s64 smin_val, smax_val;
7531 u64 umin_val, umax_val;
7532 s32 s32_min_val, s32_max_val;
7533 u32 u32_min_val, u32_max_val;
7534 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7535 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7538 smin_val = src_reg.smin_value;
7539 smax_val = src_reg.smax_value;
7540 umin_val = src_reg.umin_value;
7541 umax_val = src_reg.umax_value;
7543 s32_min_val = src_reg.s32_min_value;
7544 s32_max_val = src_reg.s32_max_value;
7545 u32_min_val = src_reg.u32_min_value;
7546 u32_max_val = src_reg.u32_max_value;
7549 src_known = tnum_subreg_is_const(src_reg.var_off);
7551 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7552 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7553 /* Taint dst register if offset had invalid bounds
7554 * derived from e.g. dead branches.
7556 __mark_reg_unknown(env, dst_reg);
7560 src_known = tnum_is_const(src_reg.var_off);
7562 (smin_val != smax_val || umin_val != umax_val)) ||
7563 smin_val > smax_val || umin_val > umax_val) {
7564 /* Taint dst register if offset had invalid bounds
7565 * derived from e.g. dead branches.
7567 __mark_reg_unknown(env, dst_reg);
7573 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7574 __mark_reg_unknown(env, dst_reg);
7578 if (sanitize_needed(opcode)) {
7579 ret = sanitize_val_alu(env, insn);
7581 return sanitize_err(env, insn, ret, NULL, NULL);
7584 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7585 * There are two classes of instructions: The first class we track both
7586 * alu32 and alu64 sign/unsigned bounds independently this provides the
7587 * greatest amount of precision when alu operations are mixed with jmp32
7588 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7589 * and BPF_OR. This is possible because these ops have fairly easy to
7590 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7591 * See alu32 verifier tests for examples. The second class of
7592 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7593 * with regards to tracking sign/unsigned bounds because the bits may
7594 * cross subreg boundaries in the alu64 case. When this happens we mark
7595 * the reg unbounded in the subreg bound space and use the resulting
7596 * tnum to calculate an approximation of the sign/unsigned bounds.
7600 scalar32_min_max_add(dst_reg, &src_reg);
7601 scalar_min_max_add(dst_reg, &src_reg);
7602 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7605 scalar32_min_max_sub(dst_reg, &src_reg);
7606 scalar_min_max_sub(dst_reg, &src_reg);
7607 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7610 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7611 scalar32_min_max_mul(dst_reg, &src_reg);
7612 scalar_min_max_mul(dst_reg, &src_reg);
7615 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7616 scalar32_min_max_and(dst_reg, &src_reg);
7617 scalar_min_max_and(dst_reg, &src_reg);
7620 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7621 scalar32_min_max_or(dst_reg, &src_reg);
7622 scalar_min_max_or(dst_reg, &src_reg);
7625 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7626 scalar32_min_max_xor(dst_reg, &src_reg);
7627 scalar_min_max_xor(dst_reg, &src_reg);
7630 if (umax_val >= insn_bitness) {
7631 /* Shifts greater than 31 or 63 are undefined.
7632 * This includes shifts by a negative number.
7634 mark_reg_unknown(env, regs, insn->dst_reg);
7638 scalar32_min_max_lsh(dst_reg, &src_reg);
7640 scalar_min_max_lsh(dst_reg, &src_reg);
7643 if (umax_val >= insn_bitness) {
7644 /* Shifts greater than 31 or 63 are undefined.
7645 * This includes shifts by a negative number.
7647 mark_reg_unknown(env, regs, insn->dst_reg);
7651 scalar32_min_max_rsh(dst_reg, &src_reg);
7653 scalar_min_max_rsh(dst_reg, &src_reg);
7656 if (umax_val >= insn_bitness) {
7657 /* Shifts greater than 31 or 63 are undefined.
7658 * This includes shifts by a negative number.
7660 mark_reg_unknown(env, regs, insn->dst_reg);
7664 scalar32_min_max_arsh(dst_reg, &src_reg);
7666 scalar_min_max_arsh(dst_reg, &src_reg);
7669 mark_reg_unknown(env, regs, insn->dst_reg);
7673 /* ALU32 ops are zero extended into 64bit register */
7675 zext_32_to_64(dst_reg);
7677 __update_reg_bounds(dst_reg);
7678 __reg_deduce_bounds(dst_reg);
7679 __reg_bound_offset(dst_reg);
7683 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7686 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7687 struct bpf_insn *insn)
7689 struct bpf_verifier_state *vstate = env->cur_state;
7690 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7691 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7692 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7693 u8 opcode = BPF_OP(insn->code);
7696 dst_reg = ®s[insn->dst_reg];
7698 if (dst_reg->type != SCALAR_VALUE)
7701 /* Make sure ID is cleared otherwise dst_reg min/max could be
7702 * incorrectly propagated into other registers by find_equal_scalars()
7705 if (BPF_SRC(insn->code) == BPF_X) {
7706 src_reg = ®s[insn->src_reg];
7707 if (src_reg->type != SCALAR_VALUE) {
7708 if (dst_reg->type != SCALAR_VALUE) {
7709 /* Combining two pointers by any ALU op yields
7710 * an arbitrary scalar. Disallow all math except
7711 * pointer subtraction
7713 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7714 mark_reg_unknown(env, regs, insn->dst_reg);
7717 verbose(env, "R%d pointer %s pointer prohibited\n",
7719 bpf_alu_string[opcode >> 4]);
7722 /* scalar += pointer
7723 * This is legal, but we have to reverse our
7724 * src/dest handling in computing the range
7726 err = mark_chain_precision(env, insn->dst_reg);
7729 return adjust_ptr_min_max_vals(env, insn,
7732 } else if (ptr_reg) {
7733 /* pointer += scalar */
7734 err = mark_chain_precision(env, insn->src_reg);
7737 return adjust_ptr_min_max_vals(env, insn,
7741 /* Pretend the src is a reg with a known value, since we only
7742 * need to be able to read from this state.
7744 off_reg.type = SCALAR_VALUE;
7745 __mark_reg_known(&off_reg, insn->imm);
7747 if (ptr_reg) /* pointer += K */
7748 return adjust_ptr_min_max_vals(env, insn,
7752 /* Got here implies adding two SCALAR_VALUEs */
7753 if (WARN_ON_ONCE(ptr_reg)) {
7754 print_verifier_state(env, state);
7755 verbose(env, "verifier internal error: unexpected ptr_reg\n");
7758 if (WARN_ON(!src_reg)) {
7759 print_verifier_state(env, state);
7760 verbose(env, "verifier internal error: no src_reg\n");
7763 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7766 /* check validity of 32-bit and 64-bit arithmetic operations */
7767 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7769 struct bpf_reg_state *regs = cur_regs(env);
7770 u8 opcode = BPF_OP(insn->code);
7773 if (opcode == BPF_END || opcode == BPF_NEG) {
7774 if (opcode == BPF_NEG) {
7775 if (BPF_SRC(insn->code) != 0 ||
7776 insn->src_reg != BPF_REG_0 ||
7777 insn->off != 0 || insn->imm != 0) {
7778 verbose(env, "BPF_NEG uses reserved fields\n");
7782 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7783 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7784 BPF_CLASS(insn->code) == BPF_ALU64) {
7785 verbose(env, "BPF_END uses reserved fields\n");
7790 /* check src operand */
7791 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7795 if (is_pointer_value(env, insn->dst_reg)) {
7796 verbose(env, "R%d pointer arithmetic prohibited\n",
7801 /* check dest operand */
7802 err = check_reg_arg(env, insn->dst_reg, DST_OP);
7806 } else if (opcode == BPF_MOV) {
7808 if (BPF_SRC(insn->code) == BPF_X) {
7809 if (insn->imm != 0 || insn->off != 0) {
7810 verbose(env, "BPF_MOV uses reserved fields\n");
7814 /* check src operand */
7815 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7819 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7820 verbose(env, "BPF_MOV uses reserved fields\n");
7825 /* check dest operand, mark as required later */
7826 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7830 if (BPF_SRC(insn->code) == BPF_X) {
7831 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7832 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7834 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7836 * copy register state to dest reg
7838 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7839 /* Assign src and dst registers the same ID
7840 * that will be used by find_equal_scalars()
7841 * to propagate min/max range.
7843 src_reg->id = ++env->id_gen;
7844 *dst_reg = *src_reg;
7845 dst_reg->live |= REG_LIVE_WRITTEN;
7846 dst_reg->subreg_def = DEF_NOT_SUBREG;
7849 if (is_pointer_value(env, insn->src_reg)) {
7851 "R%d partial copy of pointer\n",
7854 } else if (src_reg->type == SCALAR_VALUE) {
7855 *dst_reg = *src_reg;
7856 /* Make sure ID is cleared otherwise
7857 * dst_reg min/max could be incorrectly
7858 * propagated into src_reg by find_equal_scalars()
7861 dst_reg->live |= REG_LIVE_WRITTEN;
7862 dst_reg->subreg_def = env->insn_idx + 1;
7864 mark_reg_unknown(env, regs,
7867 zext_32_to_64(dst_reg);
7871 * remember the value we stored into this reg
7873 /* clear any state __mark_reg_known doesn't set */
7874 mark_reg_unknown(env, regs, insn->dst_reg);
7875 regs[insn->dst_reg].type = SCALAR_VALUE;
7876 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7877 __mark_reg_known(regs + insn->dst_reg,
7880 __mark_reg_known(regs + insn->dst_reg,
7885 } else if (opcode > BPF_END) {
7886 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7889 } else { /* all other ALU ops: and, sub, xor, add, ... */
7891 if (BPF_SRC(insn->code) == BPF_X) {
7892 if (insn->imm != 0 || insn->off != 0) {
7893 verbose(env, "BPF_ALU uses reserved fields\n");
7896 /* check src1 operand */
7897 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7901 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7902 verbose(env, "BPF_ALU uses reserved fields\n");
7907 /* check src2 operand */
7908 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7912 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7913 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7914 verbose(env, "div by zero\n");
7918 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7919 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7920 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7922 if (insn->imm < 0 || insn->imm >= size) {
7923 verbose(env, "invalid shift %d\n", insn->imm);
7928 /* check dest operand */
7929 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7933 return adjust_reg_min_max_vals(env, insn);
7939 static void __find_good_pkt_pointers(struct bpf_func_state *state,
7940 struct bpf_reg_state *dst_reg,
7941 enum bpf_reg_type type, int new_range)
7943 struct bpf_reg_state *reg;
7946 for (i = 0; i < MAX_BPF_REG; i++) {
7947 reg = &state->regs[i];
7948 if (reg->type == type && reg->id == dst_reg->id)
7949 /* keep the maximum range already checked */
7950 reg->range = max(reg->range, new_range);
7953 bpf_for_each_spilled_reg(i, state, reg) {
7956 if (reg->type == type && reg->id == dst_reg->id)
7957 reg->range = max(reg->range, new_range);
7961 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7962 struct bpf_reg_state *dst_reg,
7963 enum bpf_reg_type type,
7964 bool range_right_open)
7968 if (dst_reg->off < 0 ||
7969 (dst_reg->off == 0 && range_right_open))
7970 /* This doesn't give us any range */
7973 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7974 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7975 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7976 * than pkt_end, but that's because it's also less than pkt.
7980 new_range = dst_reg->off;
7981 if (range_right_open)
7984 /* Examples for register markings:
7986 * pkt_data in dst register:
7990 * if (r2 > pkt_end) goto <handle exception>
7995 * if (r2 < pkt_end) goto <access okay>
7996 * <handle exception>
7999 * r2 == dst_reg, pkt_end == src_reg
8000 * r2=pkt(id=n,off=8,r=0)
8001 * r3=pkt(id=n,off=0,r=0)
8003 * pkt_data in src register:
8007 * if (pkt_end >= r2) goto <access okay>
8008 * <handle exception>
8012 * if (pkt_end <= r2) goto <handle exception>
8016 * pkt_end == dst_reg, r2 == src_reg
8017 * r2=pkt(id=n,off=8,r=0)
8018 * r3=pkt(id=n,off=0,r=0)
8020 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8021 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8022 * and [r3, r3 + 8-1) respectively is safe to access depending on
8026 /* If our ids match, then we must have the same max_value. And we
8027 * don't care about the other reg's fixed offset, since if it's too big
8028 * the range won't allow anything.
8029 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8031 for (i = 0; i <= vstate->curframe; i++)
8032 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8036 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8038 struct tnum subreg = tnum_subreg(reg->var_off);
8039 s32 sval = (s32)val;
8043 if (tnum_is_const(subreg))
8044 return !!tnum_equals_const(subreg, val);
8047 if (tnum_is_const(subreg))
8048 return !tnum_equals_const(subreg, val);
8051 if ((~subreg.mask & subreg.value) & val)
8053 if (!((subreg.mask | subreg.value) & val))
8057 if (reg->u32_min_value > val)
8059 else if (reg->u32_max_value <= val)
8063 if (reg->s32_min_value > sval)
8065 else if (reg->s32_max_value <= sval)
8069 if (reg->u32_max_value < val)
8071 else if (reg->u32_min_value >= val)
8075 if (reg->s32_max_value < sval)
8077 else if (reg->s32_min_value >= sval)
8081 if (reg->u32_min_value >= val)
8083 else if (reg->u32_max_value < val)
8087 if (reg->s32_min_value >= sval)
8089 else if (reg->s32_max_value < sval)
8093 if (reg->u32_max_value <= val)
8095 else if (reg->u32_min_value > val)
8099 if (reg->s32_max_value <= sval)
8101 else if (reg->s32_min_value > sval)
8110 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8112 s64 sval = (s64)val;
8116 if (tnum_is_const(reg->var_off))
8117 return !!tnum_equals_const(reg->var_off, val);
8120 if (tnum_is_const(reg->var_off))
8121 return !tnum_equals_const(reg->var_off, val);
8124 if ((~reg->var_off.mask & reg->var_off.value) & val)
8126 if (!((reg->var_off.mask | reg->var_off.value) & val))
8130 if (reg->umin_value > val)
8132 else if (reg->umax_value <= val)
8136 if (reg->smin_value > sval)
8138 else if (reg->smax_value <= sval)
8142 if (reg->umax_value < val)
8144 else if (reg->umin_value >= val)
8148 if (reg->smax_value < sval)
8150 else if (reg->smin_value >= sval)
8154 if (reg->umin_value >= val)
8156 else if (reg->umax_value < val)
8160 if (reg->smin_value >= sval)
8162 else if (reg->smax_value < sval)
8166 if (reg->umax_value <= val)
8168 else if (reg->umin_value > val)
8172 if (reg->smax_value <= sval)
8174 else if (reg->smin_value > sval)
8182 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8184 * 1 - branch will be taken and "goto target" will be executed
8185 * 0 - branch will not be taken and fall-through to next insn
8186 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8189 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8192 if (__is_pointer_value(false, reg)) {
8193 if (!reg_type_not_null(reg->type))
8196 /* If pointer is valid tests against zero will fail so we can
8197 * use this to direct branch taken.
8213 return is_branch32_taken(reg, val, opcode);
8214 return is_branch64_taken(reg, val, opcode);
8217 static int flip_opcode(u32 opcode)
8219 /* How can we transform "a <op> b" into "b <op> a"? */
8220 static const u8 opcode_flip[16] = {
8221 /* these stay the same */
8222 [BPF_JEQ >> 4] = BPF_JEQ,
8223 [BPF_JNE >> 4] = BPF_JNE,
8224 [BPF_JSET >> 4] = BPF_JSET,
8225 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8226 [BPF_JGE >> 4] = BPF_JLE,
8227 [BPF_JGT >> 4] = BPF_JLT,
8228 [BPF_JLE >> 4] = BPF_JGE,
8229 [BPF_JLT >> 4] = BPF_JGT,
8230 [BPF_JSGE >> 4] = BPF_JSLE,
8231 [BPF_JSGT >> 4] = BPF_JSLT,
8232 [BPF_JSLE >> 4] = BPF_JSGE,
8233 [BPF_JSLT >> 4] = BPF_JSGT
8235 return opcode_flip[opcode >> 4];
8238 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8239 struct bpf_reg_state *src_reg,
8242 struct bpf_reg_state *pkt;
8244 if (src_reg->type == PTR_TO_PACKET_END) {
8246 } else if (dst_reg->type == PTR_TO_PACKET_END) {
8248 opcode = flip_opcode(opcode);
8253 if (pkt->range >= 0)
8258 /* pkt <= pkt_end */
8262 if (pkt->range == BEYOND_PKT_END)
8263 /* pkt has at last one extra byte beyond pkt_end */
8264 return opcode == BPF_JGT;
8270 /* pkt >= pkt_end */
8271 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8272 return opcode == BPF_JGE;
8278 /* Adjusts the register min/max values in the case that the dst_reg is the
8279 * variable register that we are working on, and src_reg is a constant or we're
8280 * simply doing a BPF_K check.
8281 * In JEQ/JNE cases we also adjust the var_off values.
8283 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8284 struct bpf_reg_state *false_reg,
8286 u8 opcode, bool is_jmp32)
8288 struct tnum false_32off = tnum_subreg(false_reg->var_off);
8289 struct tnum false_64off = false_reg->var_off;
8290 struct tnum true_32off = tnum_subreg(true_reg->var_off);
8291 struct tnum true_64off = true_reg->var_off;
8292 s64 sval = (s64)val;
8293 s32 sval32 = (s32)val32;
8295 /* If the dst_reg is a pointer, we can't learn anything about its
8296 * variable offset from the compare (unless src_reg were a pointer into
8297 * the same object, but we don't bother with that.
8298 * Since false_reg and true_reg have the same type by construction, we
8299 * only need to check one of them for pointerness.
8301 if (__is_pointer_value(false, false_reg))
8308 struct bpf_reg_state *reg =
8309 opcode == BPF_JEQ ? true_reg : false_reg;
8311 /* JEQ/JNE comparison doesn't change the register equivalence.
8313 * if (r1 == 42) goto label;
8315 * label: // here both r1 and r2 are known to be 42.
8317 * Hence when marking register as known preserve it's ID.
8320 __mark_reg32_known(reg, val32);
8322 ___mark_reg_known(reg, val);
8327 false_32off = tnum_and(false_32off, tnum_const(~val32));
8328 if (is_power_of_2(val32))
8329 true_32off = tnum_or(true_32off,
8332 false_64off = tnum_and(false_64off, tnum_const(~val));
8333 if (is_power_of_2(val))
8334 true_64off = tnum_or(true_64off,
8342 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
8343 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8345 false_reg->u32_max_value = min(false_reg->u32_max_value,
8347 true_reg->u32_min_value = max(true_reg->u32_min_value,
8350 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
8351 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8353 false_reg->umax_value = min(false_reg->umax_value, false_umax);
8354 true_reg->umin_value = max(true_reg->umin_value, true_umin);
8362 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
8363 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8365 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8366 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8368 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
8369 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8371 false_reg->smax_value = min(false_reg->smax_value, false_smax);
8372 true_reg->smin_value = max(true_reg->smin_value, true_smin);
8380 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
8381 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8383 false_reg->u32_min_value = max(false_reg->u32_min_value,
8385 true_reg->u32_max_value = min(true_reg->u32_max_value,
8388 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
8389 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8391 false_reg->umin_value = max(false_reg->umin_value, false_umin);
8392 true_reg->umax_value = min(true_reg->umax_value, true_umax);
8400 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
8401 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8403 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8404 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8406 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
8407 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8409 false_reg->smin_value = max(false_reg->smin_value, false_smin);
8410 true_reg->smax_value = min(true_reg->smax_value, true_smax);
8419 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8420 tnum_subreg(false_32off));
8421 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8422 tnum_subreg(true_32off));
8423 __reg_combine_32_into_64(false_reg);
8424 __reg_combine_32_into_64(true_reg);
8426 false_reg->var_off = false_64off;
8427 true_reg->var_off = true_64off;
8428 __reg_combine_64_into_32(false_reg);
8429 __reg_combine_64_into_32(true_reg);
8433 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8436 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8437 struct bpf_reg_state *false_reg,
8439 u8 opcode, bool is_jmp32)
8441 opcode = flip_opcode(opcode);
8442 /* This uses zero as "not present in table"; luckily the zero opcode,
8443 * BPF_JA, can't get here.
8446 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8449 /* Regs are known to be equal, so intersect their min/max/var_off */
8450 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8451 struct bpf_reg_state *dst_reg)
8453 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8454 dst_reg->umin_value);
8455 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8456 dst_reg->umax_value);
8457 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8458 dst_reg->smin_value);
8459 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8460 dst_reg->smax_value);
8461 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8463 /* We might have learned new bounds from the var_off. */
8464 __update_reg_bounds(src_reg);
8465 __update_reg_bounds(dst_reg);
8466 /* We might have learned something about the sign bit. */
8467 __reg_deduce_bounds(src_reg);
8468 __reg_deduce_bounds(dst_reg);
8469 /* We might have learned some bits from the bounds. */
8470 __reg_bound_offset(src_reg);
8471 __reg_bound_offset(dst_reg);
8472 /* Intersecting with the old var_off might have improved our bounds
8473 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8474 * then new var_off is (0; 0x7f...fc) which improves our umax.
8476 __update_reg_bounds(src_reg);
8477 __update_reg_bounds(dst_reg);
8480 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8481 struct bpf_reg_state *true_dst,
8482 struct bpf_reg_state *false_src,
8483 struct bpf_reg_state *false_dst,
8488 __reg_combine_min_max(true_src, true_dst);
8491 __reg_combine_min_max(false_src, false_dst);
8496 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8497 struct bpf_reg_state *reg, u32 id,
8500 if (reg_type_may_be_null(reg->type) && reg->id == id &&
8501 !WARN_ON_ONCE(!reg->id)) {
8502 /* Old offset (both fixed and variable parts) should
8503 * have been known-zero, because we don't allow pointer
8504 * arithmetic on pointers that might be NULL.
8506 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8507 !tnum_equals_const(reg->var_off, 0) ||
8509 __mark_reg_known_zero(reg);
8513 reg->type = SCALAR_VALUE;
8514 /* We don't need id and ref_obj_id from this point
8515 * onwards anymore, thus we should better reset it,
8516 * so that state pruning has chances to take effect.
8519 reg->ref_obj_id = 0;
8524 mark_ptr_not_null_reg(reg);
8526 if (!reg_may_point_to_spin_lock(reg)) {
8527 /* For not-NULL ptr, reg->ref_obj_id will be reset
8528 * in release_reg_references().
8530 * reg->id is still used by spin_lock ptr. Other
8531 * than spin_lock ptr type, reg->id can be reset.
8538 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8541 struct bpf_reg_state *reg;
8544 for (i = 0; i < MAX_BPF_REG; i++)
8545 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8547 bpf_for_each_spilled_reg(i, state, reg) {
8550 mark_ptr_or_null_reg(state, reg, id, is_null);
8554 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8555 * be folded together at some point.
8557 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8560 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8561 struct bpf_reg_state *regs = state->regs;
8562 u32 ref_obj_id = regs[regno].ref_obj_id;
8563 u32 id = regs[regno].id;
8566 if (ref_obj_id && ref_obj_id == id && is_null)
8567 /* regs[regno] is in the " == NULL" branch.
8568 * No one could have freed the reference state before
8569 * doing the NULL check.
8571 WARN_ON_ONCE(release_reference_state(state, id));
8573 for (i = 0; i <= vstate->curframe; i++)
8574 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
8577 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8578 struct bpf_reg_state *dst_reg,
8579 struct bpf_reg_state *src_reg,
8580 struct bpf_verifier_state *this_branch,
8581 struct bpf_verifier_state *other_branch)
8583 if (BPF_SRC(insn->code) != BPF_X)
8586 /* Pointers are always 64-bit. */
8587 if (BPF_CLASS(insn->code) == BPF_JMP32)
8590 switch (BPF_OP(insn->code)) {
8592 if ((dst_reg->type == PTR_TO_PACKET &&
8593 src_reg->type == PTR_TO_PACKET_END) ||
8594 (dst_reg->type == PTR_TO_PACKET_META &&
8595 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8596 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8597 find_good_pkt_pointers(this_branch, dst_reg,
8598 dst_reg->type, false);
8599 mark_pkt_end(other_branch, insn->dst_reg, true);
8600 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8601 src_reg->type == PTR_TO_PACKET) ||
8602 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8603 src_reg->type == PTR_TO_PACKET_META)) {
8604 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8605 find_good_pkt_pointers(other_branch, src_reg,
8606 src_reg->type, true);
8607 mark_pkt_end(this_branch, insn->src_reg, false);
8613 if ((dst_reg->type == PTR_TO_PACKET &&
8614 src_reg->type == PTR_TO_PACKET_END) ||
8615 (dst_reg->type == PTR_TO_PACKET_META &&
8616 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8617 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8618 find_good_pkt_pointers(other_branch, dst_reg,
8619 dst_reg->type, true);
8620 mark_pkt_end(this_branch, insn->dst_reg, false);
8621 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8622 src_reg->type == PTR_TO_PACKET) ||
8623 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8624 src_reg->type == PTR_TO_PACKET_META)) {
8625 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8626 find_good_pkt_pointers(this_branch, src_reg,
8627 src_reg->type, false);
8628 mark_pkt_end(other_branch, insn->src_reg, true);
8634 if ((dst_reg->type == PTR_TO_PACKET &&
8635 src_reg->type == PTR_TO_PACKET_END) ||
8636 (dst_reg->type == PTR_TO_PACKET_META &&
8637 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8638 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8639 find_good_pkt_pointers(this_branch, dst_reg,
8640 dst_reg->type, true);
8641 mark_pkt_end(other_branch, insn->dst_reg, false);
8642 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8643 src_reg->type == PTR_TO_PACKET) ||
8644 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8645 src_reg->type == PTR_TO_PACKET_META)) {
8646 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8647 find_good_pkt_pointers(other_branch, src_reg,
8648 src_reg->type, false);
8649 mark_pkt_end(this_branch, insn->src_reg, true);
8655 if ((dst_reg->type == PTR_TO_PACKET &&
8656 src_reg->type == PTR_TO_PACKET_END) ||
8657 (dst_reg->type == PTR_TO_PACKET_META &&
8658 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8659 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8660 find_good_pkt_pointers(other_branch, dst_reg,
8661 dst_reg->type, false);
8662 mark_pkt_end(this_branch, insn->dst_reg, true);
8663 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8664 src_reg->type == PTR_TO_PACKET) ||
8665 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8666 src_reg->type == PTR_TO_PACKET_META)) {
8667 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8668 find_good_pkt_pointers(this_branch, src_reg,
8669 src_reg->type, true);
8670 mark_pkt_end(other_branch, insn->src_reg, false);
8682 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8683 struct bpf_reg_state *known_reg)
8685 struct bpf_func_state *state;
8686 struct bpf_reg_state *reg;
8689 for (i = 0; i <= vstate->curframe; i++) {
8690 state = vstate->frame[i];
8691 for (j = 0; j < MAX_BPF_REG; j++) {
8692 reg = &state->regs[j];
8693 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8697 bpf_for_each_spilled_reg(j, state, reg) {
8700 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8706 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8707 struct bpf_insn *insn, int *insn_idx)
8709 struct bpf_verifier_state *this_branch = env->cur_state;
8710 struct bpf_verifier_state *other_branch;
8711 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8712 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8713 u8 opcode = BPF_OP(insn->code);
8718 /* Only conditional jumps are expected to reach here. */
8719 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8720 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8724 if (BPF_SRC(insn->code) == BPF_X) {
8725 if (insn->imm != 0) {
8726 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8730 /* check src1 operand */
8731 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8735 if (is_pointer_value(env, insn->src_reg)) {
8736 verbose(env, "R%d pointer comparison prohibited\n",
8740 src_reg = ®s[insn->src_reg];
8742 if (insn->src_reg != BPF_REG_0) {
8743 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8748 /* check src2 operand */
8749 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8753 dst_reg = ®s[insn->dst_reg];
8754 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8756 if (BPF_SRC(insn->code) == BPF_K) {
8757 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8758 } else if (src_reg->type == SCALAR_VALUE &&
8759 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8760 pred = is_branch_taken(dst_reg,
8761 tnum_subreg(src_reg->var_off).value,
8764 } else if (src_reg->type == SCALAR_VALUE &&
8765 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8766 pred = is_branch_taken(dst_reg,
8767 src_reg->var_off.value,
8770 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8771 reg_is_pkt_pointer_any(src_reg) &&
8773 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8777 /* If we get here with a dst_reg pointer type it is because
8778 * above is_branch_taken() special cased the 0 comparison.
8780 if (!__is_pointer_value(false, dst_reg))
8781 err = mark_chain_precision(env, insn->dst_reg);
8782 if (BPF_SRC(insn->code) == BPF_X && !err &&
8783 !__is_pointer_value(false, src_reg))
8784 err = mark_chain_precision(env, insn->src_reg);
8790 /* Only follow the goto, ignore fall-through. If needed, push
8791 * the fall-through branch for simulation under speculative
8794 if (!env->bypass_spec_v1 &&
8795 !sanitize_speculative_path(env, insn, *insn_idx + 1,
8798 *insn_idx += insn->off;
8800 } else if (pred == 0) {
8801 /* Only follow the fall-through branch, since that's where the
8802 * program will go. If needed, push the goto branch for
8803 * simulation under speculative execution.
8805 if (!env->bypass_spec_v1 &&
8806 !sanitize_speculative_path(env, insn,
8807 *insn_idx + insn->off + 1,
8813 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8817 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8819 /* detect if we are comparing against a constant value so we can adjust
8820 * our min/max values for our dst register.
8821 * this is only legit if both are scalars (or pointers to the same
8822 * object, I suppose, but we don't support that right now), because
8823 * otherwise the different base pointers mean the offsets aren't
8826 if (BPF_SRC(insn->code) == BPF_X) {
8827 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
8829 if (dst_reg->type == SCALAR_VALUE &&
8830 src_reg->type == SCALAR_VALUE) {
8831 if (tnum_is_const(src_reg->var_off) ||
8833 tnum_is_const(tnum_subreg(src_reg->var_off))))
8834 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8836 src_reg->var_off.value,
8837 tnum_subreg(src_reg->var_off).value,
8839 else if (tnum_is_const(dst_reg->var_off) ||
8841 tnum_is_const(tnum_subreg(dst_reg->var_off))))
8842 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8844 dst_reg->var_off.value,
8845 tnum_subreg(dst_reg->var_off).value,
8847 else if (!is_jmp32 &&
8848 (opcode == BPF_JEQ || opcode == BPF_JNE))
8849 /* Comparing for equality, we can combine knowledge */
8850 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8851 &other_branch_regs[insn->dst_reg],
8852 src_reg, dst_reg, opcode);
8854 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8855 find_equal_scalars(this_branch, src_reg);
8856 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8860 } else if (dst_reg->type == SCALAR_VALUE) {
8861 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8862 dst_reg, insn->imm, (u32)insn->imm,
8866 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8867 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8868 find_equal_scalars(this_branch, dst_reg);
8869 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8872 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8873 * NOTE: these optimizations below are related with pointer comparison
8874 * which will never be JMP32.
8876 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8877 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8878 reg_type_may_be_null(dst_reg->type)) {
8879 /* Mark all identical registers in each branch as either
8880 * safe or unknown depending R == 0 or R != 0 conditional.
8882 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8884 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8886 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
8887 this_branch, other_branch) &&
8888 is_pointer_value(env, insn->dst_reg)) {
8889 verbose(env, "R%d pointer comparison prohibited\n",
8893 if (env->log.level & BPF_LOG_LEVEL)
8894 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8898 /* verify BPF_LD_IMM64 instruction */
8899 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8901 struct bpf_insn_aux_data *aux = cur_aux(env);
8902 struct bpf_reg_state *regs = cur_regs(env);
8903 struct bpf_reg_state *dst_reg;
8904 struct bpf_map *map;
8907 if (BPF_SIZE(insn->code) != BPF_DW) {
8908 verbose(env, "invalid BPF_LD_IMM insn\n");
8911 if (insn->off != 0) {
8912 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8916 err = check_reg_arg(env, insn->dst_reg, DST_OP);
8920 dst_reg = ®s[insn->dst_reg];
8921 if (insn->src_reg == 0) {
8922 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8924 dst_reg->type = SCALAR_VALUE;
8925 __mark_reg_known(®s[insn->dst_reg], imm);
8929 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8930 mark_reg_known_zero(env, regs, insn->dst_reg);
8932 dst_reg->type = aux->btf_var.reg_type;
8933 switch (dst_reg->type) {
8935 dst_reg->mem_size = aux->btf_var.mem_size;
8938 case PTR_TO_PERCPU_BTF_ID:
8939 dst_reg->btf = aux->btf_var.btf;
8940 dst_reg->btf_id = aux->btf_var.btf_id;
8943 verbose(env, "bpf verifier is misconfigured\n");
8949 if (insn->src_reg == BPF_PSEUDO_FUNC) {
8950 struct bpf_prog_aux *aux = env->prog->aux;
8951 u32 subprogno = insn[1].imm;
8953 if (!aux->func_info) {
8954 verbose(env, "missing btf func_info\n");
8957 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8958 verbose(env, "callback function not static\n");
8962 dst_reg->type = PTR_TO_FUNC;
8963 dst_reg->subprogno = subprogno;
8967 map = env->used_maps[aux->map_index];
8968 mark_reg_known_zero(env, regs, insn->dst_reg);
8969 dst_reg->map_ptr = map;
8971 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8972 dst_reg->type = PTR_TO_MAP_VALUE;
8973 dst_reg->off = aux->map_off;
8974 if (map_value_has_spin_lock(map))
8975 dst_reg->id = ++env->id_gen;
8976 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8977 dst_reg->type = CONST_PTR_TO_MAP;
8979 verbose(env, "bpf verifier is misconfigured\n");
8986 static bool may_access_skb(enum bpf_prog_type type)
8989 case BPF_PROG_TYPE_SOCKET_FILTER:
8990 case BPF_PROG_TYPE_SCHED_CLS:
8991 case BPF_PROG_TYPE_SCHED_ACT:
8998 /* verify safety of LD_ABS|LD_IND instructions:
8999 * - they can only appear in the programs where ctx == skb
9000 * - since they are wrappers of function calls, they scratch R1-R5 registers,
9001 * preserve R6-R9, and store return value into R0
9004 * ctx == skb == R6 == CTX
9007 * SRC == any register
9008 * IMM == 32-bit immediate
9011 * R0 - 8/16/32-bit skb data converted to cpu endianness
9013 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9015 struct bpf_reg_state *regs = cur_regs(env);
9016 static const int ctx_reg = BPF_REG_6;
9017 u8 mode = BPF_MODE(insn->code);
9020 if (!may_access_skb(resolve_prog_type(env->prog))) {
9021 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9025 if (!env->ops->gen_ld_abs) {
9026 verbose(env, "bpf verifier is misconfigured\n");
9030 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9031 BPF_SIZE(insn->code) == BPF_DW ||
9032 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9033 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9037 /* check whether implicit source operand (register R6) is readable */
9038 err = check_reg_arg(env, ctx_reg, SRC_OP);
9042 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9043 * gen_ld_abs() may terminate the program at runtime, leading to
9046 err = check_reference_leak(env);
9048 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9052 if (env->cur_state->active_spin_lock) {
9053 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9057 if (regs[ctx_reg].type != PTR_TO_CTX) {
9059 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9063 if (mode == BPF_IND) {
9064 /* check explicit source operand */
9065 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9070 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg);
9074 /* reset caller saved regs to unreadable */
9075 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9076 mark_reg_not_init(env, regs, caller_saved[i]);
9077 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9080 /* mark destination R0 register as readable, since it contains
9081 * the value fetched from the packet.
9082 * Already marked as written above.
9084 mark_reg_unknown(env, regs, BPF_REG_0);
9085 /* ld_abs load up to 32-bit skb data. */
9086 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9090 static int check_return_code(struct bpf_verifier_env *env)
9092 struct tnum enforce_attach_type_range = tnum_unknown;
9093 const struct bpf_prog *prog = env->prog;
9094 struct bpf_reg_state *reg;
9095 struct tnum range = tnum_range(0, 1);
9096 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9098 const bool is_subprog = env->cur_state->frame[0]->subprogno;
9100 /* LSM and struct_ops func-ptr's return type could be "void" */
9102 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9103 prog_type == BPF_PROG_TYPE_LSM) &&
9104 !prog->aux->attach_func_proto->type)
9107 /* eBPF calling convetion is such that R0 is used
9108 * to return the value from eBPF program.
9109 * Make sure that it's readable at this time
9110 * of bpf_exit, which means that program wrote
9111 * something into it earlier
9113 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9117 if (is_pointer_value(env, BPF_REG_0)) {
9118 verbose(env, "R0 leaks addr as return value\n");
9122 reg = cur_regs(env) + BPF_REG_0;
9124 if (reg->type != SCALAR_VALUE) {
9125 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9126 reg_type_str[reg->type]);
9132 switch (prog_type) {
9133 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9134 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9135 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9136 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9137 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9138 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9139 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9140 range = tnum_range(1, 1);
9141 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9142 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9143 range = tnum_range(0, 3);
9145 case BPF_PROG_TYPE_CGROUP_SKB:
9146 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9147 range = tnum_range(0, 3);
9148 enforce_attach_type_range = tnum_range(2, 3);
9151 case BPF_PROG_TYPE_CGROUP_SOCK:
9152 case BPF_PROG_TYPE_SOCK_OPS:
9153 case BPF_PROG_TYPE_CGROUP_DEVICE:
9154 case BPF_PROG_TYPE_CGROUP_SYSCTL:
9155 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9157 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9158 if (!env->prog->aux->attach_btf_id)
9160 range = tnum_const(0);
9162 case BPF_PROG_TYPE_TRACING:
9163 switch (env->prog->expected_attach_type) {
9164 case BPF_TRACE_FENTRY:
9165 case BPF_TRACE_FEXIT:
9166 range = tnum_const(0);
9168 case BPF_TRACE_RAW_TP:
9169 case BPF_MODIFY_RETURN:
9171 case BPF_TRACE_ITER:
9177 case BPF_PROG_TYPE_SK_LOOKUP:
9178 range = tnum_range(SK_DROP, SK_PASS);
9180 case BPF_PROG_TYPE_EXT:
9181 /* freplace program can return anything as its return value
9182 * depends on the to-be-replaced kernel func or bpf program.
9188 if (reg->type != SCALAR_VALUE) {
9189 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9190 reg_type_str[reg->type]);
9194 if (!tnum_in(range, reg->var_off)) {
9195 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9199 if (!tnum_is_unknown(enforce_attach_type_range) &&
9200 tnum_in(enforce_attach_type_range, reg->var_off))
9201 env->prog->enforce_expected_attach_type = 1;
9205 /* non-recursive DFS pseudo code
9206 * 1 procedure DFS-iterative(G,v):
9207 * 2 label v as discovered
9208 * 3 let S be a stack
9210 * 5 while S is not empty
9212 * 7 if t is what we're looking for:
9214 * 9 for all edges e in G.adjacentEdges(t) do
9215 * 10 if edge e is already labelled
9216 * 11 continue with the next edge
9217 * 12 w <- G.adjacentVertex(t,e)
9218 * 13 if vertex w is not discovered and not explored
9219 * 14 label e as tree-edge
9220 * 15 label w as discovered
9223 * 18 else if vertex w is discovered
9224 * 19 label e as back-edge
9226 * 21 // vertex w is explored
9227 * 22 label e as forward- or cross-edge
9228 * 23 label t as explored
9233 * 0x11 - discovered and fall-through edge labelled
9234 * 0x12 - discovered and fall-through and branch edges labelled
9245 static u32 state_htab_size(struct bpf_verifier_env *env)
9247 return env->prog->len;
9250 static struct bpf_verifier_state_list **explored_state(
9251 struct bpf_verifier_env *env,
9254 struct bpf_verifier_state *cur = env->cur_state;
9255 struct bpf_func_state *state = cur->frame[cur->curframe];
9257 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9260 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9262 env->insn_aux_data[idx].prune_point = true;
9270 /* t, w, e - match pseudo-code above:
9271 * t - index of current instruction
9272 * w - next instruction
9275 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9278 int *insn_stack = env->cfg.insn_stack;
9279 int *insn_state = env->cfg.insn_state;
9281 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9282 return DONE_EXPLORING;
9284 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9285 return DONE_EXPLORING;
9287 if (w < 0 || w >= env->prog->len) {
9288 verbose_linfo(env, t, "%d: ", t);
9289 verbose(env, "jump out of range from insn %d to %d\n", t, w);
9294 /* mark branch target for state pruning */
9295 init_explored_state(env, w);
9297 if (insn_state[w] == 0) {
9299 insn_state[t] = DISCOVERED | e;
9300 insn_state[w] = DISCOVERED;
9301 if (env->cfg.cur_stack >= env->prog->len)
9303 insn_stack[env->cfg.cur_stack++] = w;
9304 return KEEP_EXPLORING;
9305 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9306 if (loop_ok && env->bpf_capable)
9307 return DONE_EXPLORING;
9308 verbose_linfo(env, t, "%d: ", t);
9309 verbose_linfo(env, w, "%d: ", w);
9310 verbose(env, "back-edge from insn %d to %d\n", t, w);
9312 } else if (insn_state[w] == EXPLORED) {
9313 /* forward- or cross-edge */
9314 insn_state[t] = DISCOVERED | e;
9316 verbose(env, "insn state internal bug\n");
9319 return DONE_EXPLORING;
9322 static int visit_func_call_insn(int t, int insn_cnt,
9323 struct bpf_insn *insns,
9324 struct bpf_verifier_env *env,
9329 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9333 if (t + 1 < insn_cnt)
9334 init_explored_state(env, t + 1);
9336 init_explored_state(env, t);
9337 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
9343 /* Visits the instruction at index t and returns one of the following:
9344 * < 0 - an error occurred
9345 * DONE_EXPLORING - the instruction was fully explored
9346 * KEEP_EXPLORING - there is still work to be done before it is fully explored
9348 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9350 struct bpf_insn *insns = env->prog->insnsi;
9353 if (bpf_pseudo_func(insns + t))
9354 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9356 /* All non-branch instructions have a single fall-through edge. */
9357 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9358 BPF_CLASS(insns[t].code) != BPF_JMP32)
9359 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9361 switch (BPF_OP(insns[t].code)) {
9363 return DONE_EXPLORING;
9366 return visit_func_call_insn(t, insn_cnt, insns, env,
9367 insns[t].src_reg == BPF_PSEUDO_CALL);
9370 if (BPF_SRC(insns[t].code) != BPF_K)
9373 /* unconditional jump with single edge */
9374 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9379 /* unconditional jmp is not a good pruning point,
9380 * but it's marked, since backtracking needs
9381 * to record jmp history in is_state_visited().
9383 init_explored_state(env, t + insns[t].off + 1);
9384 /* tell verifier to check for equivalent states
9385 * after every call and jump
9387 if (t + 1 < insn_cnt)
9388 init_explored_state(env, t + 1);
9393 /* conditional jump with two edges */
9394 init_explored_state(env, t);
9395 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9399 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9403 /* non-recursive depth-first-search to detect loops in BPF program
9404 * loop == back-edge in directed graph
9406 static int check_cfg(struct bpf_verifier_env *env)
9408 int insn_cnt = env->prog->len;
9409 int *insn_stack, *insn_state;
9413 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9417 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9423 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9424 insn_stack[0] = 0; /* 0 is the first instruction */
9425 env->cfg.cur_stack = 1;
9427 while (env->cfg.cur_stack > 0) {
9428 int t = insn_stack[env->cfg.cur_stack - 1];
9430 ret = visit_insn(t, insn_cnt, env);
9432 case DONE_EXPLORING:
9433 insn_state[t] = EXPLORED;
9434 env->cfg.cur_stack--;
9436 case KEEP_EXPLORING:
9440 verbose(env, "visit_insn internal bug\n");
9447 if (env->cfg.cur_stack < 0) {
9448 verbose(env, "pop stack internal bug\n");
9453 for (i = 0; i < insn_cnt; i++) {
9454 if (insn_state[i] != EXPLORED) {
9455 verbose(env, "unreachable insn %d\n", i);
9460 ret = 0; /* cfg looks good */
9465 env->cfg.insn_state = env->cfg.insn_stack = NULL;
9469 static int check_abnormal_return(struct bpf_verifier_env *env)
9473 for (i = 1; i < env->subprog_cnt; i++) {
9474 if (env->subprog_info[i].has_ld_abs) {
9475 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9478 if (env->subprog_info[i].has_tail_call) {
9479 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9486 /* The minimum supported BTF func info size */
9487 #define MIN_BPF_FUNCINFO_SIZE 8
9488 #define MAX_FUNCINFO_REC_SIZE 252
9490 static int check_btf_func(struct bpf_verifier_env *env,
9491 const union bpf_attr *attr,
9492 union bpf_attr __user *uattr)
9494 const struct btf_type *type, *func_proto, *ret_type;
9495 u32 i, nfuncs, urec_size, min_size;
9496 u32 krec_size = sizeof(struct bpf_func_info);
9497 struct bpf_func_info *krecord;
9498 struct bpf_func_info_aux *info_aux = NULL;
9499 struct bpf_prog *prog;
9500 const struct btf *btf;
9501 void __user *urecord;
9502 u32 prev_offset = 0;
9506 nfuncs = attr->func_info_cnt;
9508 if (check_abnormal_return(env))
9513 if (nfuncs != env->subprog_cnt) {
9514 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9518 urec_size = attr->func_info_rec_size;
9519 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9520 urec_size > MAX_FUNCINFO_REC_SIZE ||
9521 urec_size % sizeof(u32)) {
9522 verbose(env, "invalid func info rec size %u\n", urec_size);
9527 btf = prog->aux->btf;
9529 urecord = u64_to_user_ptr(attr->func_info);
9530 min_size = min_t(u32, krec_size, urec_size);
9532 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9535 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9539 for (i = 0; i < nfuncs; i++) {
9540 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9542 if (ret == -E2BIG) {
9543 verbose(env, "nonzero tailing record in func info");
9544 /* set the size kernel expects so loader can zero
9545 * out the rest of the record.
9547 if (put_user(min_size, &uattr->func_info_rec_size))
9553 if (copy_from_user(&krecord[i], urecord, min_size)) {
9558 /* check insn_off */
9561 if (krecord[i].insn_off) {
9563 "nonzero insn_off %u for the first func info record",
9564 krecord[i].insn_off);
9567 } else if (krecord[i].insn_off <= prev_offset) {
9569 "same or smaller insn offset (%u) than previous func info record (%u)",
9570 krecord[i].insn_off, prev_offset);
9574 if (env->subprog_info[i].start != krecord[i].insn_off) {
9575 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9580 type = btf_type_by_id(btf, krecord[i].type_id);
9581 if (!type || !btf_type_is_func(type)) {
9582 verbose(env, "invalid type id %d in func info",
9583 krecord[i].type_id);
9586 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9588 func_proto = btf_type_by_id(btf, type->type);
9589 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9590 /* btf_func_check() already verified it during BTF load */
9592 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9594 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9595 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9596 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9599 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9600 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9604 prev_offset = krecord[i].insn_off;
9605 urecord += urec_size;
9608 prog->aux->func_info = krecord;
9609 prog->aux->func_info_cnt = nfuncs;
9610 prog->aux->func_info_aux = info_aux;
9619 static void adjust_btf_func(struct bpf_verifier_env *env)
9621 struct bpf_prog_aux *aux = env->prog->aux;
9624 if (!aux->func_info)
9627 for (i = 0; i < env->subprog_cnt; i++)
9628 aux->func_info[i].insn_off = env->subprog_info[i].start;
9631 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9632 sizeof(((struct bpf_line_info *)(0))->line_col))
9633 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9635 static int check_btf_line(struct bpf_verifier_env *env,
9636 const union bpf_attr *attr,
9637 union bpf_attr __user *uattr)
9639 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9640 struct bpf_subprog_info *sub;
9641 struct bpf_line_info *linfo;
9642 struct bpf_prog *prog;
9643 const struct btf *btf;
9644 void __user *ulinfo;
9647 nr_linfo = attr->line_info_cnt;
9651 rec_size = attr->line_info_rec_size;
9652 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9653 rec_size > MAX_LINEINFO_REC_SIZE ||
9654 rec_size & (sizeof(u32) - 1))
9657 /* Need to zero it in case the userspace may
9658 * pass in a smaller bpf_line_info object.
9660 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9661 GFP_KERNEL | __GFP_NOWARN);
9666 btf = prog->aux->btf;
9669 sub = env->subprog_info;
9670 ulinfo = u64_to_user_ptr(attr->line_info);
9671 expected_size = sizeof(struct bpf_line_info);
9672 ncopy = min_t(u32, expected_size, rec_size);
9673 for (i = 0; i < nr_linfo; i++) {
9674 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9676 if (err == -E2BIG) {
9677 verbose(env, "nonzero tailing record in line_info");
9678 if (put_user(expected_size,
9679 &uattr->line_info_rec_size))
9685 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9691 * Check insn_off to ensure
9692 * 1) strictly increasing AND
9693 * 2) bounded by prog->len
9695 * The linfo[0].insn_off == 0 check logically falls into
9696 * the later "missing bpf_line_info for func..." case
9697 * because the first linfo[0].insn_off must be the
9698 * first sub also and the first sub must have
9699 * subprog_info[0].start == 0.
9701 if ((i && linfo[i].insn_off <= prev_offset) ||
9702 linfo[i].insn_off >= prog->len) {
9703 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9704 i, linfo[i].insn_off, prev_offset,
9710 if (!prog->insnsi[linfo[i].insn_off].code) {
9712 "Invalid insn code at line_info[%u].insn_off\n",
9718 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9719 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9720 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9725 if (s != env->subprog_cnt) {
9726 if (linfo[i].insn_off == sub[s].start) {
9727 sub[s].linfo_idx = i;
9729 } else if (sub[s].start < linfo[i].insn_off) {
9730 verbose(env, "missing bpf_line_info for func#%u\n", s);
9736 prev_offset = linfo[i].insn_off;
9740 if (s != env->subprog_cnt) {
9741 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9742 env->subprog_cnt - s, s);
9747 prog->aux->linfo = linfo;
9748 prog->aux->nr_linfo = nr_linfo;
9757 static int check_btf_info(struct bpf_verifier_env *env,
9758 const union bpf_attr *attr,
9759 union bpf_attr __user *uattr)
9764 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9765 if (check_abnormal_return(env))
9770 btf = btf_get_by_fd(attr->prog_btf_fd);
9772 return PTR_ERR(btf);
9773 if (btf_is_kernel(btf)) {
9777 env->prog->aux->btf = btf;
9779 err = check_btf_func(env, attr, uattr);
9783 err = check_btf_line(env, attr, uattr);
9790 /* check %cur's range satisfies %old's */
9791 static bool range_within(struct bpf_reg_state *old,
9792 struct bpf_reg_state *cur)
9794 return old->umin_value <= cur->umin_value &&
9795 old->umax_value >= cur->umax_value &&
9796 old->smin_value <= cur->smin_value &&
9797 old->smax_value >= cur->smax_value &&
9798 old->u32_min_value <= cur->u32_min_value &&
9799 old->u32_max_value >= cur->u32_max_value &&
9800 old->s32_min_value <= cur->s32_min_value &&
9801 old->s32_max_value >= cur->s32_max_value;
9804 /* Maximum number of register states that can exist at once */
9805 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9811 /* If in the old state two registers had the same id, then they need to have
9812 * the same id in the new state as well. But that id could be different from
9813 * the old state, so we need to track the mapping from old to new ids.
9814 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9815 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9816 * regs with a different old id could still have new id 9, we don't care about
9818 * So we look through our idmap to see if this old id has been seen before. If
9819 * so, we require the new id to match; otherwise, we add the id pair to the map.
9821 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
9825 for (i = 0; i < ID_MAP_SIZE; i++) {
9826 if (!idmap[i].old) {
9827 /* Reached an empty slot; haven't seen this id before */
9828 idmap[i].old = old_id;
9829 idmap[i].cur = cur_id;
9832 if (idmap[i].old == old_id)
9833 return idmap[i].cur == cur_id;
9835 /* We ran out of idmap slots, which should be impossible */
9840 static void clean_func_state(struct bpf_verifier_env *env,
9841 struct bpf_func_state *st)
9843 enum bpf_reg_liveness live;
9846 for (i = 0; i < BPF_REG_FP; i++) {
9847 live = st->regs[i].live;
9848 /* liveness must not touch this register anymore */
9849 st->regs[i].live |= REG_LIVE_DONE;
9850 if (!(live & REG_LIVE_READ))
9851 /* since the register is unused, clear its state
9852 * to make further comparison simpler
9854 __mark_reg_not_init(env, &st->regs[i]);
9857 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9858 live = st->stack[i].spilled_ptr.live;
9859 /* liveness must not touch this stack slot anymore */
9860 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9861 if (!(live & REG_LIVE_READ)) {
9862 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9863 for (j = 0; j < BPF_REG_SIZE; j++)
9864 st->stack[i].slot_type[j] = STACK_INVALID;
9869 static void clean_verifier_state(struct bpf_verifier_env *env,
9870 struct bpf_verifier_state *st)
9874 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9875 /* all regs in this state in all frames were already marked */
9878 for (i = 0; i <= st->curframe; i++)
9879 clean_func_state(env, st->frame[i]);
9882 /* the parentage chains form a tree.
9883 * the verifier states are added to state lists at given insn and
9884 * pushed into state stack for future exploration.
9885 * when the verifier reaches bpf_exit insn some of the verifer states
9886 * stored in the state lists have their final liveness state already,
9887 * but a lot of states will get revised from liveness point of view when
9888 * the verifier explores other branches.
9891 * 2: if r1 == 100 goto pc+1
9894 * when the verifier reaches exit insn the register r0 in the state list of
9895 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9896 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9897 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9899 * Since the verifier pushes the branch states as it sees them while exploring
9900 * the program the condition of walking the branch instruction for the second
9901 * time means that all states below this branch were already explored and
9902 * their final liveness markes are already propagated.
9903 * Hence when the verifier completes the search of state list in is_state_visited()
9904 * we can call this clean_live_states() function to mark all liveness states
9905 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9907 * This function also clears the registers and stack for states that !READ
9908 * to simplify state merging.
9910 * Important note here that walking the same branch instruction in the callee
9911 * doesn't meant that the states are DONE. The verifier has to compare
9914 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9915 struct bpf_verifier_state *cur)
9917 struct bpf_verifier_state_list *sl;
9920 sl = *explored_state(env, insn);
9922 if (sl->state.branches)
9924 if (sl->state.insn_idx != insn ||
9925 sl->state.curframe != cur->curframe)
9927 for (i = 0; i <= cur->curframe; i++)
9928 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9930 clean_verifier_state(env, &sl->state);
9936 /* Returns true if (rold safe implies rcur safe) */
9937 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9938 struct idpair *idmap)
9942 if (!(rold->live & REG_LIVE_READ))
9943 /* explored state didn't use this */
9946 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9948 if (rold->type == PTR_TO_STACK)
9949 /* two stack pointers are equal only if they're pointing to
9950 * the same stack frame, since fp-8 in foo != fp-8 in bar
9952 return equal && rold->frameno == rcur->frameno;
9957 if (rold->type == NOT_INIT)
9958 /* explored state can't have used this */
9960 if (rcur->type == NOT_INIT)
9962 switch (rold->type) {
9964 if (rcur->type == SCALAR_VALUE) {
9965 if (!rold->precise && !rcur->precise)
9967 /* new val must satisfy old val knowledge */
9968 return range_within(rold, rcur) &&
9969 tnum_in(rold->var_off, rcur->var_off);
9971 /* We're trying to use a pointer in place of a scalar.
9972 * Even if the scalar was unbounded, this could lead to
9973 * pointer leaks because scalars are allowed to leak
9974 * while pointers are not. We could make this safe in
9975 * special cases if root is calling us, but it's
9976 * probably not worth the hassle.
9980 case PTR_TO_MAP_KEY:
9981 case PTR_TO_MAP_VALUE:
9982 /* If the new min/max/var_off satisfy the old ones and
9983 * everything else matches, we are OK.
9984 * 'id' is not compared, since it's only used for maps with
9985 * bpf_spin_lock inside map element and in such cases if
9986 * the rest of the prog is valid for one map element then
9987 * it's valid for all map elements regardless of the key
9988 * used in bpf_map_lookup()
9990 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9991 range_within(rold, rcur) &&
9992 tnum_in(rold->var_off, rcur->var_off);
9993 case PTR_TO_MAP_VALUE_OR_NULL:
9994 /* a PTR_TO_MAP_VALUE could be safe to use as a
9995 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9996 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9997 * checked, doing so could have affected others with the same
9998 * id, and we can't check for that because we lost the id when
9999 * we converted to a PTR_TO_MAP_VALUE.
10001 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
10003 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10005 /* Check our ids match any regs they're supposed to */
10006 return check_ids(rold->id, rcur->id, idmap);
10007 case PTR_TO_PACKET_META:
10008 case PTR_TO_PACKET:
10009 if (rcur->type != rold->type)
10011 /* We must have at least as much range as the old ptr
10012 * did, so that any accesses which were safe before are
10013 * still safe. This is true even if old range < old off,
10014 * since someone could have accessed through (ptr - k), or
10015 * even done ptr -= k in a register, to get a safe access.
10017 if (rold->range > rcur->range)
10019 /* If the offsets don't match, we can't trust our alignment;
10020 * nor can we be sure that we won't fall out of range.
10022 if (rold->off != rcur->off)
10024 /* id relations must be preserved */
10025 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10027 /* new val must satisfy old val knowledge */
10028 return range_within(rold, rcur) &&
10029 tnum_in(rold->var_off, rcur->var_off);
10031 case CONST_PTR_TO_MAP:
10032 case PTR_TO_PACKET_END:
10033 case PTR_TO_FLOW_KEYS:
10034 case PTR_TO_SOCKET:
10035 case PTR_TO_SOCKET_OR_NULL:
10036 case PTR_TO_SOCK_COMMON:
10037 case PTR_TO_SOCK_COMMON_OR_NULL:
10038 case PTR_TO_TCP_SOCK:
10039 case PTR_TO_TCP_SOCK_OR_NULL:
10040 case PTR_TO_XDP_SOCK:
10041 /* Only valid matches are exact, which memcmp() above
10042 * would have accepted
10045 /* Don't know what's going on, just say it's not safe */
10049 /* Shouldn't get here; if we do, say it's not safe */
10054 static bool stacksafe(struct bpf_func_state *old,
10055 struct bpf_func_state *cur,
10056 struct idpair *idmap)
10060 /* walk slots of the explored stack and ignore any additional
10061 * slots in the current stack, since explored(safe) state
10064 for (i = 0; i < old->allocated_stack; i++) {
10065 spi = i / BPF_REG_SIZE;
10067 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10068 i += BPF_REG_SIZE - 1;
10069 /* explored state didn't use this */
10073 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10076 /* explored stack has more populated slots than current stack
10077 * and these slots were used
10079 if (i >= cur->allocated_stack)
10082 /* if old state was safe with misc data in the stack
10083 * it will be safe with zero-initialized stack.
10084 * The opposite is not true
10086 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10087 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10089 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10090 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10091 /* Ex: old explored (safe) state has STACK_SPILL in
10092 * this stack slot, but current has STACK_MISC ->
10093 * this verifier states are not equivalent,
10094 * return false to continue verification of this path
10097 if (i % BPF_REG_SIZE)
10099 if (old->stack[spi].slot_type[0] != STACK_SPILL)
10101 if (!regsafe(&old->stack[spi].spilled_ptr,
10102 &cur->stack[spi].spilled_ptr,
10104 /* when explored and current stack slot are both storing
10105 * spilled registers, check that stored pointers types
10106 * are the same as well.
10107 * Ex: explored safe path could have stored
10108 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10109 * but current path has stored:
10110 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10111 * such verifier states are not equivalent.
10112 * return false to continue verification of this path
10119 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10121 if (old->acquired_refs != cur->acquired_refs)
10123 return !memcmp(old->refs, cur->refs,
10124 sizeof(*old->refs) * old->acquired_refs);
10127 /* compare two verifier states
10129 * all states stored in state_list are known to be valid, since
10130 * verifier reached 'bpf_exit' instruction through them
10132 * this function is called when verifier exploring different branches of
10133 * execution popped from the state stack. If it sees an old state that has
10134 * more strict register state and more strict stack state then this execution
10135 * branch doesn't need to be explored further, since verifier already
10136 * concluded that more strict state leads to valid finish.
10138 * Therefore two states are equivalent if register state is more conservative
10139 * and explored stack state is more conservative than the current one.
10142 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10143 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10145 * In other words if current stack state (one being explored) has more
10146 * valid slots than old one that already passed validation, it means
10147 * the verifier can stop exploring and conclude that current state is valid too
10149 * Similarly with registers. If explored state has register type as invalid
10150 * whereas register type in current state is meaningful, it means that
10151 * the current state will reach 'bpf_exit' instruction safely
10153 static bool func_states_equal(struct bpf_func_state *old,
10154 struct bpf_func_state *cur)
10156 struct idpair *idmap;
10160 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
10161 /* If we failed to allocate the idmap, just say it's not safe */
10165 for (i = 0; i < MAX_BPF_REG; i++) {
10166 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
10170 if (!stacksafe(old, cur, idmap))
10173 if (!refsafe(old, cur))
10181 static bool states_equal(struct bpf_verifier_env *env,
10182 struct bpf_verifier_state *old,
10183 struct bpf_verifier_state *cur)
10187 if (old->curframe != cur->curframe)
10190 /* Verification state from speculative execution simulation
10191 * must never prune a non-speculative execution one.
10193 if (old->speculative && !cur->speculative)
10196 if (old->active_spin_lock != cur->active_spin_lock)
10199 /* for states to be equal callsites have to be the same
10200 * and all frame states need to be equivalent
10202 for (i = 0; i <= old->curframe; i++) {
10203 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10205 if (!func_states_equal(old->frame[i], cur->frame[i]))
10211 /* Return 0 if no propagation happened. Return negative error code if error
10212 * happened. Otherwise, return the propagated bit.
10214 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10215 struct bpf_reg_state *reg,
10216 struct bpf_reg_state *parent_reg)
10218 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10219 u8 flag = reg->live & REG_LIVE_READ;
10222 /* When comes here, read flags of PARENT_REG or REG could be any of
10223 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10224 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10226 if (parent_flag == REG_LIVE_READ64 ||
10227 /* Or if there is no read flag from REG. */
10229 /* Or if the read flag from REG is the same as PARENT_REG. */
10230 parent_flag == flag)
10233 err = mark_reg_read(env, reg, parent_reg, flag);
10240 /* A write screens off any subsequent reads; but write marks come from the
10241 * straight-line code between a state and its parent. When we arrive at an
10242 * equivalent state (jump target or such) we didn't arrive by the straight-line
10243 * code, so read marks in the state must propagate to the parent regardless
10244 * of the state's write marks. That's what 'parent == state->parent' comparison
10245 * in mark_reg_read() is for.
10247 static int propagate_liveness(struct bpf_verifier_env *env,
10248 const struct bpf_verifier_state *vstate,
10249 struct bpf_verifier_state *vparent)
10251 struct bpf_reg_state *state_reg, *parent_reg;
10252 struct bpf_func_state *state, *parent;
10253 int i, frame, err = 0;
10255 if (vparent->curframe != vstate->curframe) {
10256 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10257 vparent->curframe, vstate->curframe);
10260 /* Propagate read liveness of registers... */
10261 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10262 for (frame = 0; frame <= vstate->curframe; frame++) {
10263 parent = vparent->frame[frame];
10264 state = vstate->frame[frame];
10265 parent_reg = parent->regs;
10266 state_reg = state->regs;
10267 /* We don't need to worry about FP liveness, it's read-only */
10268 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10269 err = propagate_liveness_reg(env, &state_reg[i],
10273 if (err == REG_LIVE_READ64)
10274 mark_insn_zext(env, &parent_reg[i]);
10277 /* Propagate stack slots. */
10278 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10279 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10280 parent_reg = &parent->stack[i].spilled_ptr;
10281 state_reg = &state->stack[i].spilled_ptr;
10282 err = propagate_liveness_reg(env, state_reg,
10291 /* find precise scalars in the previous equivalent state and
10292 * propagate them into the current state
10294 static int propagate_precision(struct bpf_verifier_env *env,
10295 const struct bpf_verifier_state *old)
10297 struct bpf_reg_state *state_reg;
10298 struct bpf_func_state *state;
10301 state = old->frame[old->curframe];
10302 state_reg = state->regs;
10303 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10304 if (state_reg->type != SCALAR_VALUE ||
10305 !state_reg->precise)
10307 if (env->log.level & BPF_LOG_LEVEL2)
10308 verbose(env, "propagating r%d\n", i);
10309 err = mark_chain_precision(env, i);
10314 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10315 if (state->stack[i].slot_type[0] != STACK_SPILL)
10317 state_reg = &state->stack[i].spilled_ptr;
10318 if (state_reg->type != SCALAR_VALUE ||
10319 !state_reg->precise)
10321 if (env->log.level & BPF_LOG_LEVEL2)
10322 verbose(env, "propagating fp%d\n",
10323 (-i - 1) * BPF_REG_SIZE);
10324 err = mark_chain_precision_stack(env, i);
10331 static bool states_maybe_looping(struct bpf_verifier_state *old,
10332 struct bpf_verifier_state *cur)
10334 struct bpf_func_state *fold, *fcur;
10335 int i, fr = cur->curframe;
10337 if (old->curframe != fr)
10340 fold = old->frame[fr];
10341 fcur = cur->frame[fr];
10342 for (i = 0; i < MAX_BPF_REG; i++)
10343 if (memcmp(&fold->regs[i], &fcur->regs[i],
10344 offsetof(struct bpf_reg_state, parent)))
10350 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10352 struct bpf_verifier_state_list *new_sl;
10353 struct bpf_verifier_state_list *sl, **pprev;
10354 struct bpf_verifier_state *cur = env->cur_state, *new;
10355 int i, j, err, states_cnt = 0;
10356 bool add_new_state = env->test_state_freq ? true : false;
10358 cur->last_insn_idx = env->prev_insn_idx;
10359 if (!env->insn_aux_data[insn_idx].prune_point)
10360 /* this 'insn_idx' instruction wasn't marked, so we will not
10361 * be doing state search here
10365 /* bpf progs typically have pruning point every 4 instructions
10366 * http://vger.kernel.org/bpfconf2019.html#session-1
10367 * Do not add new state for future pruning if the verifier hasn't seen
10368 * at least 2 jumps and at least 8 instructions.
10369 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10370 * In tests that amounts to up to 50% reduction into total verifier
10371 * memory consumption and 20% verifier time speedup.
10373 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10374 env->insn_processed - env->prev_insn_processed >= 8)
10375 add_new_state = true;
10377 pprev = explored_state(env, insn_idx);
10380 clean_live_states(env, insn_idx, cur);
10384 if (sl->state.insn_idx != insn_idx)
10386 if (sl->state.branches) {
10387 if (states_maybe_looping(&sl->state, cur) &&
10388 states_equal(env, &sl->state, cur)) {
10389 verbose_linfo(env, insn_idx, "; ");
10390 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10393 /* if the verifier is processing a loop, avoid adding new state
10394 * too often, since different loop iterations have distinct
10395 * states and may not help future pruning.
10396 * This threshold shouldn't be too low to make sure that
10397 * a loop with large bound will be rejected quickly.
10398 * The most abusive loop will be:
10400 * if r1 < 1000000 goto pc-2
10401 * 1M insn_procssed limit / 100 == 10k peak states.
10402 * This threshold shouldn't be too high either, since states
10403 * at the end of the loop are likely to be useful in pruning.
10405 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10406 env->insn_processed - env->prev_insn_processed < 100)
10407 add_new_state = false;
10410 if (states_equal(env, &sl->state, cur)) {
10412 /* reached equivalent register/stack state,
10413 * prune the search.
10414 * Registers read by the continuation are read by us.
10415 * If we have any write marks in env->cur_state, they
10416 * will prevent corresponding reads in the continuation
10417 * from reaching our parent (an explored_state). Our
10418 * own state will get the read marks recorded, but
10419 * they'll be immediately forgotten as we're pruning
10420 * this state and will pop a new one.
10422 err = propagate_liveness(env, &sl->state, cur);
10424 /* if previous state reached the exit with precision and
10425 * current state is equivalent to it (except precsion marks)
10426 * the precision needs to be propagated back in
10427 * the current state.
10429 err = err ? : push_jmp_history(env, cur);
10430 err = err ? : propagate_precision(env, &sl->state);
10436 /* when new state is not going to be added do not increase miss count.
10437 * Otherwise several loop iterations will remove the state
10438 * recorded earlier. The goal of these heuristics is to have
10439 * states from some iterations of the loop (some in the beginning
10440 * and some at the end) to help pruning.
10444 /* heuristic to determine whether this state is beneficial
10445 * to keep checking from state equivalence point of view.
10446 * Higher numbers increase max_states_per_insn and verification time,
10447 * but do not meaningfully decrease insn_processed.
10449 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10450 /* the state is unlikely to be useful. Remove it to
10451 * speed up verification
10454 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10455 u32 br = sl->state.branches;
10458 "BUG live_done but branches_to_explore %d\n",
10460 free_verifier_state(&sl->state, false);
10462 env->peak_states--;
10464 /* cannot free this state, since parentage chain may
10465 * walk it later. Add it for free_list instead to
10466 * be freed at the end of verification
10468 sl->next = env->free_list;
10469 env->free_list = sl;
10479 if (env->max_states_per_insn < states_cnt)
10480 env->max_states_per_insn = states_cnt;
10482 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
10483 return push_jmp_history(env, cur);
10485 if (!add_new_state)
10486 return push_jmp_history(env, cur);
10488 /* There were no equivalent states, remember the current one.
10489 * Technically the current state is not proven to be safe yet,
10490 * but it will either reach outer most bpf_exit (which means it's safe)
10491 * or it will be rejected. When there are no loops the verifier won't be
10492 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
10493 * again on the way to bpf_exit.
10494 * When looping the sl->state.branches will be > 0 and this state
10495 * will not be considered for equivalence until branches == 0.
10497 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
10500 env->total_states++;
10501 env->peak_states++;
10502 env->prev_jmps_processed = env->jmps_processed;
10503 env->prev_insn_processed = env->insn_processed;
10505 /* add new state to the head of linked list */
10506 new = &new_sl->state;
10507 err = copy_verifier_state(new, cur);
10509 free_verifier_state(new, false);
10513 new->insn_idx = insn_idx;
10514 WARN_ONCE(new->branches != 1,
10515 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
10518 cur->first_insn_idx = insn_idx;
10519 clear_jmp_history(cur);
10520 new_sl->next = *explored_state(env, insn_idx);
10521 *explored_state(env, insn_idx) = new_sl;
10522 /* connect new state to parentage chain. Current frame needs all
10523 * registers connected. Only r6 - r9 of the callers are alive (pushed
10524 * to the stack implicitly by JITs) so in callers' frames connect just
10525 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10526 * the state of the call instruction (with WRITTEN set), and r0 comes
10527 * from callee with its full parentage chain, anyway.
10529 /* clear write marks in current state: the writes we did are not writes
10530 * our child did, so they don't screen off its reads from us.
10531 * (There are no read marks in current state, because reads always mark
10532 * their parent and current state never has children yet. Only
10533 * explored_states can get read marks.)
10535 for (j = 0; j <= cur->curframe; j++) {
10536 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10537 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10538 for (i = 0; i < BPF_REG_FP; i++)
10539 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10542 /* all stack frames are accessible from callee, clear them all */
10543 for (j = 0; j <= cur->curframe; j++) {
10544 struct bpf_func_state *frame = cur->frame[j];
10545 struct bpf_func_state *newframe = new->frame[j];
10547 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10548 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10549 frame->stack[i].spilled_ptr.parent =
10550 &newframe->stack[i].spilled_ptr;
10556 /* Return true if it's OK to have the same insn return a different type. */
10557 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10561 case PTR_TO_SOCKET:
10562 case PTR_TO_SOCKET_OR_NULL:
10563 case PTR_TO_SOCK_COMMON:
10564 case PTR_TO_SOCK_COMMON_OR_NULL:
10565 case PTR_TO_TCP_SOCK:
10566 case PTR_TO_TCP_SOCK_OR_NULL:
10567 case PTR_TO_XDP_SOCK:
10568 case PTR_TO_BTF_ID:
10569 case PTR_TO_BTF_ID_OR_NULL:
10576 /* If an instruction was previously used with particular pointer types, then we
10577 * need to be careful to avoid cases such as the below, where it may be ok
10578 * for one branch accessing the pointer, but not ok for the other branch:
10583 * R1 = some_other_valid_ptr;
10586 * R2 = *(u32 *)(R1 + 0);
10588 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10590 return src != prev && (!reg_type_mismatch_ok(src) ||
10591 !reg_type_mismatch_ok(prev));
10594 static int do_check(struct bpf_verifier_env *env)
10596 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10597 struct bpf_verifier_state *state = env->cur_state;
10598 struct bpf_insn *insns = env->prog->insnsi;
10599 struct bpf_reg_state *regs;
10600 int insn_cnt = env->prog->len;
10601 bool do_print_state = false;
10602 int prev_insn_idx = -1;
10605 struct bpf_insn *insn;
10609 env->prev_insn_idx = prev_insn_idx;
10610 if (env->insn_idx >= insn_cnt) {
10611 verbose(env, "invalid insn idx %d insn_cnt %d\n",
10612 env->insn_idx, insn_cnt);
10616 insn = &insns[env->insn_idx];
10617 class = BPF_CLASS(insn->code);
10619 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10621 "BPF program is too large. Processed %d insn\n",
10622 env->insn_processed);
10626 err = is_state_visited(env, env->insn_idx);
10630 /* found equivalent state, can prune the search */
10631 if (env->log.level & BPF_LOG_LEVEL) {
10632 if (do_print_state)
10633 verbose(env, "\nfrom %d to %d%s: safe\n",
10634 env->prev_insn_idx, env->insn_idx,
10635 env->cur_state->speculative ?
10636 " (speculative execution)" : "");
10638 verbose(env, "%d: safe\n", env->insn_idx);
10640 goto process_bpf_exit;
10643 if (signal_pending(current))
10646 if (need_resched())
10649 if (env->log.level & BPF_LOG_LEVEL2 ||
10650 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10651 if (env->log.level & BPF_LOG_LEVEL2)
10652 verbose(env, "%d:", env->insn_idx);
10654 verbose(env, "\nfrom %d to %d%s:",
10655 env->prev_insn_idx, env->insn_idx,
10656 env->cur_state->speculative ?
10657 " (speculative execution)" : "");
10658 print_verifier_state(env, state->frame[state->curframe]);
10659 do_print_state = false;
10662 if (env->log.level & BPF_LOG_LEVEL) {
10663 const struct bpf_insn_cbs cbs = {
10664 .cb_call = disasm_kfunc_name,
10665 .cb_print = verbose,
10666 .private_data = env,
10669 verbose_linfo(env, env->insn_idx, "; ");
10670 verbose(env, "%d: ", env->insn_idx);
10671 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10674 if (bpf_prog_is_dev_bound(env->prog->aux)) {
10675 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10676 env->prev_insn_idx);
10681 regs = cur_regs(env);
10682 sanitize_mark_insn_seen(env);
10683 prev_insn_idx = env->insn_idx;
10685 if (class == BPF_ALU || class == BPF_ALU64) {
10686 err = check_alu_op(env, insn);
10690 } else if (class == BPF_LDX) {
10691 enum bpf_reg_type *prev_src_type, src_reg_type;
10693 /* check for reserved fields is already done */
10695 /* check src operand */
10696 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10700 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10704 src_reg_type = regs[insn->src_reg].type;
10706 /* check that memory (src_reg + off) is readable,
10707 * the state of dst_reg will be updated by this func
10709 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10710 insn->off, BPF_SIZE(insn->code),
10711 BPF_READ, insn->dst_reg, false);
10715 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10717 if (*prev_src_type == NOT_INIT) {
10718 /* saw a valid insn
10719 * dst_reg = *(u32 *)(src_reg + off)
10720 * save type to validate intersecting paths
10722 *prev_src_type = src_reg_type;
10724 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10725 /* ABuser program is trying to use the same insn
10726 * dst_reg = *(u32*) (src_reg + off)
10727 * with different pointer types:
10728 * src_reg == ctx in one branch and
10729 * src_reg == stack|map in some other branch.
10732 verbose(env, "same insn cannot be used with different pointers\n");
10736 } else if (class == BPF_STX) {
10737 enum bpf_reg_type *prev_dst_type, dst_reg_type;
10739 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10740 err = check_atomic(env, env->insn_idx, insn);
10747 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10748 verbose(env, "BPF_STX uses reserved fields\n");
10752 /* check src1 operand */
10753 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10756 /* check src2 operand */
10757 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10761 dst_reg_type = regs[insn->dst_reg].type;
10763 /* check that memory (dst_reg + off) is writeable */
10764 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10765 insn->off, BPF_SIZE(insn->code),
10766 BPF_WRITE, insn->src_reg, false);
10770 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10772 if (*prev_dst_type == NOT_INIT) {
10773 *prev_dst_type = dst_reg_type;
10774 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10775 verbose(env, "same insn cannot be used with different pointers\n");
10779 } else if (class == BPF_ST) {
10780 if (BPF_MODE(insn->code) != BPF_MEM ||
10781 insn->src_reg != BPF_REG_0) {
10782 verbose(env, "BPF_ST uses reserved fields\n");
10785 /* check src operand */
10786 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10790 if (is_ctx_reg(env, insn->dst_reg)) {
10791 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10793 reg_type_str[reg_state(env, insn->dst_reg)->type]);
10797 /* check that memory (dst_reg + off) is writeable */
10798 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10799 insn->off, BPF_SIZE(insn->code),
10800 BPF_WRITE, -1, false);
10804 } else if (class == BPF_JMP || class == BPF_JMP32) {
10805 u8 opcode = BPF_OP(insn->code);
10807 env->jmps_processed++;
10808 if (opcode == BPF_CALL) {
10809 if (BPF_SRC(insn->code) != BPF_K ||
10811 (insn->src_reg != BPF_REG_0 &&
10812 insn->src_reg != BPF_PSEUDO_CALL &&
10813 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
10814 insn->dst_reg != BPF_REG_0 ||
10815 class == BPF_JMP32) {
10816 verbose(env, "BPF_CALL uses reserved fields\n");
10820 if (env->cur_state->active_spin_lock &&
10821 (insn->src_reg == BPF_PSEUDO_CALL ||
10822 insn->imm != BPF_FUNC_spin_unlock)) {
10823 verbose(env, "function calls are not allowed while holding a lock\n");
10826 if (insn->src_reg == BPF_PSEUDO_CALL)
10827 err = check_func_call(env, insn, &env->insn_idx);
10828 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
10829 err = check_kfunc_call(env, insn);
10831 err = check_helper_call(env, insn, &env->insn_idx);
10834 } else if (opcode == BPF_JA) {
10835 if (BPF_SRC(insn->code) != BPF_K ||
10837 insn->src_reg != BPF_REG_0 ||
10838 insn->dst_reg != BPF_REG_0 ||
10839 class == BPF_JMP32) {
10840 verbose(env, "BPF_JA uses reserved fields\n");
10844 env->insn_idx += insn->off + 1;
10847 } else if (opcode == BPF_EXIT) {
10848 if (BPF_SRC(insn->code) != BPF_K ||
10850 insn->src_reg != BPF_REG_0 ||
10851 insn->dst_reg != BPF_REG_0 ||
10852 class == BPF_JMP32) {
10853 verbose(env, "BPF_EXIT uses reserved fields\n");
10857 if (env->cur_state->active_spin_lock) {
10858 verbose(env, "bpf_spin_unlock is missing\n");
10862 if (state->curframe) {
10863 /* exit from nested function */
10864 err = prepare_func_exit(env, &env->insn_idx);
10867 do_print_state = true;
10871 err = check_reference_leak(env);
10875 err = check_return_code(env);
10879 update_branch_counts(env, env->cur_state);
10880 err = pop_stack(env, &prev_insn_idx,
10881 &env->insn_idx, pop_log);
10883 if (err != -ENOENT)
10887 do_print_state = true;
10891 err = check_cond_jmp_op(env, insn, &env->insn_idx);
10895 } else if (class == BPF_LD) {
10896 u8 mode = BPF_MODE(insn->code);
10898 if (mode == BPF_ABS || mode == BPF_IND) {
10899 err = check_ld_abs(env, insn);
10903 } else if (mode == BPF_IMM) {
10904 err = check_ld_imm(env, insn);
10909 sanitize_mark_insn_seen(env);
10911 verbose(env, "invalid BPF_LD mode\n");
10915 verbose(env, "unknown insn class %d\n", class);
10925 static int find_btf_percpu_datasec(struct btf *btf)
10927 const struct btf_type *t;
10932 * Both vmlinux and module each have their own ".data..percpu"
10933 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10934 * types to look at only module's own BTF types.
10936 n = btf_nr_types(btf);
10937 if (btf_is_module(btf))
10938 i = btf_nr_types(btf_vmlinux);
10942 for(; i < n; i++) {
10943 t = btf_type_by_id(btf, i);
10944 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10947 tname = btf_name_by_offset(btf, t->name_off);
10948 if (!strcmp(tname, ".data..percpu"))
10955 /* replace pseudo btf_id with kernel symbol address */
10956 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10957 struct bpf_insn *insn,
10958 struct bpf_insn_aux_data *aux)
10960 const struct btf_var_secinfo *vsi;
10961 const struct btf_type *datasec;
10962 struct btf_mod_pair *btf_mod;
10963 const struct btf_type *t;
10964 const char *sym_name;
10965 bool percpu = false;
10966 u32 type, id = insn->imm;
10970 int i, btf_fd, err;
10972 btf_fd = insn[1].imm;
10974 btf = btf_get_by_fd(btf_fd);
10976 verbose(env, "invalid module BTF object FD specified.\n");
10980 if (!btf_vmlinux) {
10981 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10988 t = btf_type_by_id(btf, id);
10990 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10995 if (!btf_type_is_var(t)) {
10996 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11001 sym_name = btf_name_by_offset(btf, t->name_off);
11002 addr = kallsyms_lookup_name(sym_name);
11004 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11010 datasec_id = find_btf_percpu_datasec(btf);
11011 if (datasec_id > 0) {
11012 datasec = btf_type_by_id(btf, datasec_id);
11013 for_each_vsi(i, datasec, vsi) {
11014 if (vsi->type == id) {
11021 insn[0].imm = (u32)addr;
11022 insn[1].imm = addr >> 32;
11025 t = btf_type_skip_modifiers(btf, type, NULL);
11027 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11028 aux->btf_var.btf = btf;
11029 aux->btf_var.btf_id = type;
11030 } else if (!btf_type_is_struct(t)) {
11031 const struct btf_type *ret;
11035 /* resolve the type size of ksym. */
11036 ret = btf_resolve_size(btf, t, &tsize);
11038 tname = btf_name_by_offset(btf, t->name_off);
11039 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11040 tname, PTR_ERR(ret));
11044 aux->btf_var.reg_type = PTR_TO_MEM;
11045 aux->btf_var.mem_size = tsize;
11047 aux->btf_var.reg_type = PTR_TO_BTF_ID;
11048 aux->btf_var.btf = btf;
11049 aux->btf_var.btf_id = type;
11052 /* check whether we recorded this BTF (and maybe module) already */
11053 for (i = 0; i < env->used_btf_cnt; i++) {
11054 if (env->used_btfs[i].btf == btf) {
11060 if (env->used_btf_cnt >= MAX_USED_BTFS) {
11065 btf_mod = &env->used_btfs[env->used_btf_cnt];
11066 btf_mod->btf = btf;
11067 btf_mod->module = NULL;
11069 /* if we reference variables from kernel module, bump its refcount */
11070 if (btf_is_module(btf)) {
11071 btf_mod->module = btf_try_get_module(btf);
11072 if (!btf_mod->module) {
11078 env->used_btf_cnt++;
11086 static int check_map_prealloc(struct bpf_map *map)
11088 return (map->map_type != BPF_MAP_TYPE_HASH &&
11089 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11090 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11091 !(map->map_flags & BPF_F_NO_PREALLOC);
11094 static bool is_tracing_prog_type(enum bpf_prog_type type)
11097 case BPF_PROG_TYPE_KPROBE:
11098 case BPF_PROG_TYPE_TRACEPOINT:
11099 case BPF_PROG_TYPE_PERF_EVENT:
11100 case BPF_PROG_TYPE_RAW_TRACEPOINT:
11107 static bool is_preallocated_map(struct bpf_map *map)
11109 if (!check_map_prealloc(map))
11111 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11116 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11117 struct bpf_map *map,
11118 struct bpf_prog *prog)
11121 enum bpf_prog_type prog_type = resolve_prog_type(prog);
11123 * Validate that trace type programs use preallocated hash maps.
11125 * For programs attached to PERF events this is mandatory as the
11126 * perf NMI can hit any arbitrary code sequence.
11128 * All other trace types using preallocated hash maps are unsafe as
11129 * well because tracepoint or kprobes can be inside locked regions
11130 * of the memory allocator or at a place where a recursion into the
11131 * memory allocator would see inconsistent state.
11133 * On RT enabled kernels run-time allocation of all trace type
11134 * programs is strictly prohibited due to lock type constraints. On
11135 * !RT kernels it is allowed for backwards compatibility reasons for
11136 * now, but warnings are emitted so developers are made aware of
11137 * the unsafety and can fix their programs before this is enforced.
11139 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11140 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11141 verbose(env, "perf_event programs can only use preallocated hash map\n");
11144 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11145 verbose(env, "trace type programs can only use preallocated hash map\n");
11148 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11149 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11152 if (map_value_has_spin_lock(map)) {
11153 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11154 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11158 if (is_tracing_prog_type(prog_type)) {
11159 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11163 if (prog->aux->sleepable) {
11164 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11169 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11170 !bpf_offload_prog_map_match(prog, map)) {
11171 verbose(env, "offload device mismatch between prog and map\n");
11175 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11176 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11180 if (prog->aux->sleepable)
11181 switch (map->map_type) {
11182 case BPF_MAP_TYPE_HASH:
11183 case BPF_MAP_TYPE_LRU_HASH:
11184 case BPF_MAP_TYPE_ARRAY:
11185 case BPF_MAP_TYPE_PERCPU_HASH:
11186 case BPF_MAP_TYPE_PERCPU_ARRAY:
11187 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11188 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11189 case BPF_MAP_TYPE_HASH_OF_MAPS:
11190 if (!is_preallocated_map(map)) {
11192 "Sleepable programs can only use preallocated maps\n");
11196 case BPF_MAP_TYPE_RINGBUF:
11200 "Sleepable programs can only use array, hash, and ringbuf maps\n");
11207 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11209 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11210 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11213 /* find and rewrite pseudo imm in ld_imm64 instructions:
11215 * 1. if it accesses map FD, replace it with actual map pointer.
11216 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11218 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11220 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11222 struct bpf_insn *insn = env->prog->insnsi;
11223 int insn_cnt = env->prog->len;
11226 err = bpf_prog_calc_tag(env->prog);
11230 for (i = 0; i < insn_cnt; i++, insn++) {
11231 if (BPF_CLASS(insn->code) == BPF_LDX &&
11232 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11233 verbose(env, "BPF_LDX uses reserved fields\n");
11237 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11238 struct bpf_insn_aux_data *aux;
11239 struct bpf_map *map;
11243 if (i == insn_cnt - 1 || insn[1].code != 0 ||
11244 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11245 insn[1].off != 0) {
11246 verbose(env, "invalid bpf_ld_imm64 insn\n");
11250 if (insn[0].src_reg == 0)
11251 /* valid generic load 64-bit imm */
11254 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11255 aux = &env->insn_aux_data[i];
11256 err = check_pseudo_btf_id(env, insn, aux);
11262 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11263 aux = &env->insn_aux_data[i];
11264 aux->ptr_type = PTR_TO_FUNC;
11268 /* In final convert_pseudo_ld_imm64() step, this is
11269 * converted into regular 64-bit imm load insn.
11271 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
11272 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
11273 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
11274 insn[1].imm != 0)) {
11276 "unrecognized bpf_ld_imm64 insn\n");
11280 f = fdget(insn[0].imm);
11281 map = __bpf_map_get(f);
11283 verbose(env, "fd %d is not pointing to valid bpf_map\n",
11285 return PTR_ERR(map);
11288 err = check_map_prog_compatibility(env, map, env->prog);
11294 aux = &env->insn_aux_data[i];
11295 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
11296 addr = (unsigned long)map;
11298 u32 off = insn[1].imm;
11300 if (off >= BPF_MAX_VAR_OFF) {
11301 verbose(env, "direct value offset of %u is not allowed\n", off);
11306 if (!map->ops->map_direct_value_addr) {
11307 verbose(env, "no direct value access support for this map type\n");
11312 err = map->ops->map_direct_value_addr(map, &addr, off);
11314 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11315 map->value_size, off);
11320 aux->map_off = off;
11324 insn[0].imm = (u32)addr;
11325 insn[1].imm = addr >> 32;
11327 /* check whether we recorded this map already */
11328 for (j = 0; j < env->used_map_cnt; j++) {
11329 if (env->used_maps[j] == map) {
11330 aux->map_index = j;
11336 if (env->used_map_cnt >= MAX_USED_MAPS) {
11341 /* hold the map. If the program is rejected by verifier,
11342 * the map will be released by release_maps() or it
11343 * will be used by the valid program until it's unloaded
11344 * and all maps are released in free_used_maps()
11348 aux->map_index = env->used_map_cnt;
11349 env->used_maps[env->used_map_cnt++] = map;
11351 if (bpf_map_is_cgroup_storage(map) &&
11352 bpf_cgroup_storage_assign(env->prog->aux, map)) {
11353 verbose(env, "only one cgroup storage of each type is allowed\n");
11365 /* Basic sanity check before we invest more work here. */
11366 if (!bpf_opcode_in_insntable(insn->code)) {
11367 verbose(env, "unknown opcode %02x\n", insn->code);
11372 /* now all pseudo BPF_LD_IMM64 instructions load valid
11373 * 'struct bpf_map *' into a register instead of user map_fd.
11374 * These pointers will be used later by verifier to validate map access.
11379 /* drop refcnt of maps used by the rejected program */
11380 static void release_maps(struct bpf_verifier_env *env)
11382 __bpf_free_used_maps(env->prog->aux, env->used_maps,
11383 env->used_map_cnt);
11386 /* drop refcnt of maps used by the rejected program */
11387 static void release_btfs(struct bpf_verifier_env *env)
11389 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11390 env->used_btf_cnt);
11393 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
11394 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11396 struct bpf_insn *insn = env->prog->insnsi;
11397 int insn_cnt = env->prog->len;
11400 for (i = 0; i < insn_cnt; i++, insn++) {
11401 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11403 if (insn->src_reg == BPF_PSEUDO_FUNC)
11409 /* single env->prog->insni[off] instruction was replaced with the range
11410 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
11411 * [0, off) and [off, end) to new locations, so the patched range stays zero
11413 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
11414 struct bpf_prog *new_prog, u32 off, u32 cnt)
11416 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
11417 struct bpf_insn *insn = new_prog->insnsi;
11418 u32 old_seen = old_data[off].seen;
11422 /* aux info at OFF always needs adjustment, no matter fast path
11423 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11424 * original insn at old prog.
11426 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11430 prog_len = new_prog->len;
11431 new_data = vzalloc(array_size(prog_len,
11432 sizeof(struct bpf_insn_aux_data)));
11435 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11436 memcpy(new_data + off + cnt - 1, old_data + off,
11437 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11438 for (i = off; i < off + cnt - 1; i++) {
11439 /* Expand insni[off]'s seen count to the patched range. */
11440 new_data[i].seen = old_seen;
11441 new_data[i].zext_dst = insn_has_def32(env, insn + i);
11443 env->insn_aux_data = new_data;
11448 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11454 /* NOTE: fake 'exit' subprog should be updated as well. */
11455 for (i = 0; i <= env->subprog_cnt; i++) {
11456 if (env->subprog_info[i].start <= off)
11458 env->subprog_info[i].start += len - 1;
11462 static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
11464 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11465 int i, sz = prog->aux->size_poke_tab;
11466 struct bpf_jit_poke_descriptor *desc;
11468 for (i = 0; i < sz; i++) {
11470 desc->insn_idx += len - 1;
11474 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11475 const struct bpf_insn *patch, u32 len)
11477 struct bpf_prog *new_prog;
11479 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
11480 if (IS_ERR(new_prog)) {
11481 if (PTR_ERR(new_prog) == -ERANGE)
11483 "insn %d cannot be patched due to 16-bit range\n",
11484 env->insn_aux_data[off].orig_idx);
11487 if (adjust_insn_aux_data(env, new_prog, off, len))
11489 adjust_subprog_starts(env, off, len);
11490 adjust_poke_descs(new_prog, len);
11494 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11499 /* find first prog starting at or after off (first to remove) */
11500 for (i = 0; i < env->subprog_cnt; i++)
11501 if (env->subprog_info[i].start >= off)
11503 /* find first prog starting at or after off + cnt (first to stay) */
11504 for (j = i; j < env->subprog_cnt; j++)
11505 if (env->subprog_info[j].start >= off + cnt)
11507 /* if j doesn't start exactly at off + cnt, we are just removing
11508 * the front of previous prog
11510 if (env->subprog_info[j].start != off + cnt)
11514 struct bpf_prog_aux *aux = env->prog->aux;
11517 /* move fake 'exit' subprog as well */
11518 move = env->subprog_cnt + 1 - j;
11520 memmove(env->subprog_info + i,
11521 env->subprog_info + j,
11522 sizeof(*env->subprog_info) * move);
11523 env->subprog_cnt -= j - i;
11525 /* remove func_info */
11526 if (aux->func_info) {
11527 move = aux->func_info_cnt - j;
11529 memmove(aux->func_info + i,
11530 aux->func_info + j,
11531 sizeof(*aux->func_info) * move);
11532 aux->func_info_cnt -= j - i;
11533 /* func_info->insn_off is set after all code rewrites,
11534 * in adjust_btf_func() - no need to adjust
11538 /* convert i from "first prog to remove" to "first to adjust" */
11539 if (env->subprog_info[i].start == off)
11543 /* update fake 'exit' subprog as well */
11544 for (; i <= env->subprog_cnt; i++)
11545 env->subprog_info[i].start -= cnt;
11550 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11553 struct bpf_prog *prog = env->prog;
11554 u32 i, l_off, l_cnt, nr_linfo;
11555 struct bpf_line_info *linfo;
11557 nr_linfo = prog->aux->nr_linfo;
11561 linfo = prog->aux->linfo;
11563 /* find first line info to remove, count lines to be removed */
11564 for (i = 0; i < nr_linfo; i++)
11565 if (linfo[i].insn_off >= off)
11570 for (; i < nr_linfo; i++)
11571 if (linfo[i].insn_off < off + cnt)
11576 /* First live insn doesn't match first live linfo, it needs to "inherit"
11577 * last removed linfo. prog is already modified, so prog->len == off
11578 * means no live instructions after (tail of the program was removed).
11580 if (prog->len != off && l_cnt &&
11581 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11583 linfo[--i].insn_off = off + cnt;
11586 /* remove the line info which refer to the removed instructions */
11588 memmove(linfo + l_off, linfo + i,
11589 sizeof(*linfo) * (nr_linfo - i));
11591 prog->aux->nr_linfo -= l_cnt;
11592 nr_linfo = prog->aux->nr_linfo;
11595 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11596 for (i = l_off; i < nr_linfo; i++)
11597 linfo[i].insn_off -= cnt;
11599 /* fix up all subprogs (incl. 'exit') which start >= off */
11600 for (i = 0; i <= env->subprog_cnt; i++)
11601 if (env->subprog_info[i].linfo_idx > l_off) {
11602 /* program may have started in the removed region but
11603 * may not be fully removed
11605 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11606 env->subprog_info[i].linfo_idx -= l_cnt;
11608 env->subprog_info[i].linfo_idx = l_off;
11614 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11616 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11617 unsigned int orig_prog_len = env->prog->len;
11620 if (bpf_prog_is_dev_bound(env->prog->aux))
11621 bpf_prog_offload_remove_insns(env, off, cnt);
11623 err = bpf_remove_insns(env->prog, off, cnt);
11627 err = adjust_subprog_starts_after_remove(env, off, cnt);
11631 err = bpf_adj_linfo_after_remove(env, off, cnt);
11635 memmove(aux_data + off, aux_data + off + cnt,
11636 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11641 /* The verifier does more data flow analysis than llvm and will not
11642 * explore branches that are dead at run time. Malicious programs can
11643 * have dead code too. Therefore replace all dead at-run-time code
11646 * Just nops are not optimal, e.g. if they would sit at the end of the
11647 * program and through another bug we would manage to jump there, then
11648 * we'd execute beyond program memory otherwise. Returning exception
11649 * code also wouldn't work since we can have subprogs where the dead
11650 * code could be located.
11652 static void sanitize_dead_code(struct bpf_verifier_env *env)
11654 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11655 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
11656 struct bpf_insn *insn = env->prog->insnsi;
11657 const int insn_cnt = env->prog->len;
11660 for (i = 0; i < insn_cnt; i++) {
11661 if (aux_data[i].seen)
11663 memcpy(insn + i, &trap, sizeof(trap));
11667 static bool insn_is_cond_jump(u8 code)
11671 if (BPF_CLASS(code) == BPF_JMP32)
11674 if (BPF_CLASS(code) != BPF_JMP)
11678 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11681 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11683 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11684 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11685 struct bpf_insn *insn = env->prog->insnsi;
11686 const int insn_cnt = env->prog->len;
11689 for (i = 0; i < insn_cnt; i++, insn++) {
11690 if (!insn_is_cond_jump(insn->code))
11693 if (!aux_data[i + 1].seen)
11694 ja.off = insn->off;
11695 else if (!aux_data[i + 1 + insn->off].seen)
11700 if (bpf_prog_is_dev_bound(env->prog->aux))
11701 bpf_prog_offload_replace_insn(env, i, &ja);
11703 memcpy(insn, &ja, sizeof(ja));
11707 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11709 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11710 int insn_cnt = env->prog->len;
11713 for (i = 0; i < insn_cnt; i++) {
11717 while (i + j < insn_cnt && !aux_data[i + j].seen)
11722 err = verifier_remove_insns(env, i, j);
11725 insn_cnt = env->prog->len;
11731 static int opt_remove_nops(struct bpf_verifier_env *env)
11733 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11734 struct bpf_insn *insn = env->prog->insnsi;
11735 int insn_cnt = env->prog->len;
11738 for (i = 0; i < insn_cnt; i++) {
11739 if (memcmp(&insn[i], &ja, sizeof(ja)))
11742 err = verifier_remove_insns(env, i, 1);
11752 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11753 const union bpf_attr *attr)
11755 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
11756 struct bpf_insn_aux_data *aux = env->insn_aux_data;
11757 int i, patch_len, delta = 0, len = env->prog->len;
11758 struct bpf_insn *insns = env->prog->insnsi;
11759 struct bpf_prog *new_prog;
11762 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11763 zext_patch[1] = BPF_ZEXT_REG(0);
11764 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11765 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11766 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11767 for (i = 0; i < len; i++) {
11768 int adj_idx = i + delta;
11769 struct bpf_insn insn;
11772 insn = insns[adj_idx];
11773 load_reg = insn_def_regno(&insn);
11774 if (!aux[adj_idx].zext_dst) {
11782 class = BPF_CLASS(code);
11783 if (load_reg == -1)
11786 /* NOTE: arg "reg" (the fourth one) is only used for
11787 * BPF_STX + SRC_OP, so it is safe to pass NULL
11790 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
11791 if (class == BPF_LD &&
11792 BPF_MODE(code) == BPF_IMM)
11797 /* ctx load could be transformed into wider load. */
11798 if (class == BPF_LDX &&
11799 aux[adj_idx].ptr_type == PTR_TO_CTX)
11802 imm_rnd = get_random_int();
11803 rnd_hi32_patch[0] = insn;
11804 rnd_hi32_patch[1].imm = imm_rnd;
11805 rnd_hi32_patch[3].dst_reg = load_reg;
11806 patch = rnd_hi32_patch;
11808 goto apply_patch_buffer;
11811 /* Add in an zero-extend instruction if a) the JIT has requested
11812 * it or b) it's a CMPXCHG.
11814 * The latter is because: BPF_CMPXCHG always loads a value into
11815 * R0, therefore always zero-extends. However some archs'
11816 * equivalent instruction only does this load when the
11817 * comparison is successful. This detail of CMPXCHG is
11818 * orthogonal to the general zero-extension behaviour of the
11819 * CPU, so it's treated independently of bpf_jit_needs_zext.
11821 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
11824 if (WARN_ON(load_reg == -1)) {
11825 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11829 zext_patch[0] = insn;
11830 zext_patch[1].dst_reg = load_reg;
11831 zext_patch[1].src_reg = load_reg;
11832 patch = zext_patch;
11834 apply_patch_buffer:
11835 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11838 env->prog = new_prog;
11839 insns = new_prog->insnsi;
11840 aux = env->insn_aux_data;
11841 delta += patch_len - 1;
11847 /* convert load instructions that access fields of a context type into a
11848 * sequence of instructions that access fields of the underlying structure:
11849 * struct __sk_buff -> struct sk_buff
11850 * struct bpf_sock_ops -> struct sock
11852 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11854 const struct bpf_verifier_ops *ops = env->ops;
11855 int i, cnt, size, ctx_field_size, delta = 0;
11856 const int insn_cnt = env->prog->len;
11857 struct bpf_insn insn_buf[16], *insn;
11858 u32 target_size, size_default, off;
11859 struct bpf_prog *new_prog;
11860 enum bpf_access_type type;
11861 bool is_narrower_load;
11863 if (ops->gen_prologue || env->seen_direct_write) {
11864 if (!ops->gen_prologue) {
11865 verbose(env, "bpf verifier is misconfigured\n");
11868 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11870 if (cnt >= ARRAY_SIZE(insn_buf)) {
11871 verbose(env, "bpf verifier is misconfigured\n");
11874 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11878 env->prog = new_prog;
11883 if (bpf_prog_is_dev_bound(env->prog->aux))
11886 insn = env->prog->insnsi + delta;
11888 for (i = 0; i < insn_cnt; i++, insn++) {
11889 bpf_convert_ctx_access_t convert_ctx_access;
11891 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11892 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11893 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11894 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
11896 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11897 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11898 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11899 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
11904 if (type == BPF_WRITE &&
11905 env->insn_aux_data[i + delta].sanitize_stack_off) {
11906 struct bpf_insn patch[] = {
11907 /* Sanitize suspicious stack slot with zero.
11908 * There are no memory dependencies for this store,
11909 * since it's only using frame pointer and immediate
11912 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11913 env->insn_aux_data[i + delta].sanitize_stack_off,
11915 /* the original STX instruction will immediately
11916 * overwrite the same stack slot with appropriate value
11921 cnt = ARRAY_SIZE(patch);
11922 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11927 env->prog = new_prog;
11928 insn = new_prog->insnsi + i + delta;
11932 switch (env->insn_aux_data[i + delta].ptr_type) {
11934 if (!ops->convert_ctx_access)
11936 convert_ctx_access = ops->convert_ctx_access;
11938 case PTR_TO_SOCKET:
11939 case PTR_TO_SOCK_COMMON:
11940 convert_ctx_access = bpf_sock_convert_ctx_access;
11942 case PTR_TO_TCP_SOCK:
11943 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11945 case PTR_TO_XDP_SOCK:
11946 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11948 case PTR_TO_BTF_ID:
11949 if (type == BPF_READ) {
11950 insn->code = BPF_LDX | BPF_PROBE_MEM |
11951 BPF_SIZE((insn)->code);
11952 env->prog->aux->num_exentries++;
11953 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11954 verbose(env, "Writes through BTF pointers are not allowed\n");
11962 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11963 size = BPF_LDST_BYTES(insn);
11965 /* If the read access is a narrower load of the field,
11966 * convert to a 4/8-byte load, to minimum program type specific
11967 * convert_ctx_access changes. If conversion is successful,
11968 * we will apply proper mask to the result.
11970 is_narrower_load = size < ctx_field_size;
11971 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11973 if (is_narrower_load) {
11976 if (type == BPF_WRITE) {
11977 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11982 if (ctx_field_size == 4)
11984 else if (ctx_field_size == 8)
11985 size_code = BPF_DW;
11987 insn->off = off & ~(size_default - 1);
11988 insn->code = BPF_LDX | BPF_MEM | size_code;
11992 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11994 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11995 (ctx_field_size && !target_size)) {
11996 verbose(env, "bpf verifier is misconfigured\n");
12000 if (is_narrower_load && size < target_size) {
12001 u8 shift = bpf_ctx_narrow_access_offset(
12002 off, size, size_default) * 8;
12003 if (ctx_field_size <= 4) {
12005 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12008 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12009 (1 << size * 8) - 1);
12012 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12015 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
12016 (1ULL << size * 8) - 1);
12020 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12026 /* keep walking new program and skip insns we just inserted */
12027 env->prog = new_prog;
12028 insn = new_prog->insnsi + i + delta;
12034 static int jit_subprogs(struct bpf_verifier_env *env)
12036 struct bpf_prog *prog = env->prog, **func, *tmp;
12037 int i, j, subprog_start, subprog_end = 0, len, subprog;
12038 struct bpf_map *map_ptr;
12039 struct bpf_insn *insn;
12040 void *old_bpf_func;
12041 int err, num_exentries;
12043 if (env->subprog_cnt <= 1)
12046 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12047 if (bpf_pseudo_func(insn)) {
12048 env->insn_aux_data[i].call_imm = insn->imm;
12049 /* subprog is encoded in insn[1].imm */
12053 if (!bpf_pseudo_call(insn))
12055 /* Upon error here we cannot fall back to interpreter but
12056 * need a hard reject of the program. Thus -EFAULT is
12057 * propagated in any case.
12059 subprog = find_subprog(env, i + insn->imm + 1);
12061 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12062 i + insn->imm + 1);
12065 /* temporarily remember subprog id inside insn instead of
12066 * aux_data, since next loop will split up all insns into funcs
12068 insn->off = subprog;
12069 /* remember original imm in case JIT fails and fallback
12070 * to interpreter will be needed
12072 env->insn_aux_data[i].call_imm = insn->imm;
12073 /* point imm to __bpf_call_base+1 from JITs point of view */
12077 err = bpf_prog_alloc_jited_linfo(prog);
12079 goto out_undo_insn;
12082 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12084 goto out_undo_insn;
12086 for (i = 0; i < env->subprog_cnt; i++) {
12087 subprog_start = subprog_end;
12088 subprog_end = env->subprog_info[i + 1].start;
12090 len = subprog_end - subprog_start;
12091 /* BPF_PROG_RUN doesn't call subprogs directly,
12092 * hence main prog stats include the runtime of subprogs.
12093 * subprogs don't have IDs and not reachable via prog_get_next_id
12094 * func[i]->stats will never be accessed and stays NULL
12096 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12099 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12100 len * sizeof(struct bpf_insn));
12101 func[i]->type = prog->type;
12102 func[i]->len = len;
12103 if (bpf_prog_calc_tag(func[i]))
12105 func[i]->is_func = 1;
12106 func[i]->aux->func_idx = i;
12107 /* the btf and func_info will be freed only at prog->aux */
12108 func[i]->aux->btf = prog->aux->btf;
12109 func[i]->aux->func_info = prog->aux->func_info;
12111 for (j = 0; j < prog->aux->size_poke_tab; j++) {
12112 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
12115 if (!(insn_idx >= subprog_start &&
12116 insn_idx <= subprog_end))
12119 ret = bpf_jit_add_poke_descriptor(func[i],
12120 &prog->aux->poke_tab[j]);
12122 verbose(env, "adding tail call poke descriptor failed\n");
12126 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
12128 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
12129 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
12131 verbose(env, "tracking tail call prog failed\n");
12136 /* Use bpf_prog_F_tag to indicate functions in stack traces.
12137 * Long term would need debug info to populate names
12139 func[i]->aux->name[0] = 'F';
12140 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12141 func[i]->jit_requested = 1;
12142 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12143 func[i]->aux->linfo = prog->aux->linfo;
12144 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12145 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12146 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12148 insn = func[i]->insnsi;
12149 for (j = 0; j < func[i]->len; j++, insn++) {
12150 if (BPF_CLASS(insn->code) == BPF_LDX &&
12151 BPF_MODE(insn->code) == BPF_PROBE_MEM)
12154 func[i]->aux->num_exentries = num_exentries;
12155 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12156 func[i] = bpf_int_jit_compile(func[i]);
12157 if (!func[i]->jited) {
12164 /* Untrack main program's aux structs so that during map_poke_run()
12165 * we will not stumble upon the unfilled poke descriptors; each
12166 * of the main program's poke descs got distributed across subprogs
12167 * and got tracked onto map, so we are sure that none of them will
12168 * be missed after the operation below
12170 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12171 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12173 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12176 /* at this point all bpf functions were successfully JITed
12177 * now populate all bpf_calls with correct addresses and
12178 * run last pass of JIT
12180 for (i = 0; i < env->subprog_cnt; i++) {
12181 insn = func[i]->insnsi;
12182 for (j = 0; j < func[i]->len; j++, insn++) {
12183 if (bpf_pseudo_func(insn)) {
12184 subprog = insn[1].imm;
12185 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12186 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12189 if (!bpf_pseudo_call(insn))
12191 subprog = insn->off;
12192 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12196 /* we use the aux data to keep a list of the start addresses
12197 * of the JITed images for each function in the program
12199 * for some architectures, such as powerpc64, the imm field
12200 * might not be large enough to hold the offset of the start
12201 * address of the callee's JITed image from __bpf_call_base
12203 * in such cases, we can lookup the start address of a callee
12204 * by using its subprog id, available from the off field of
12205 * the call instruction, as an index for this list
12207 func[i]->aux->func = func;
12208 func[i]->aux->func_cnt = env->subprog_cnt;
12210 for (i = 0; i < env->subprog_cnt; i++) {
12211 old_bpf_func = func[i]->bpf_func;
12212 tmp = bpf_int_jit_compile(func[i]);
12213 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12214 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12221 /* finally lock prog and jit images for all functions and
12222 * populate kallsysm
12224 for (i = 0; i < env->subprog_cnt; i++) {
12225 bpf_prog_lock_ro(func[i]);
12226 bpf_prog_kallsyms_add(func[i]);
12229 /* Last step: make now unused interpreter insns from main
12230 * prog consistent for later dump requests, so they can
12231 * later look the same as if they were interpreted only.
12233 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12234 if (bpf_pseudo_func(insn)) {
12235 insn[0].imm = env->insn_aux_data[i].call_imm;
12236 insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12239 if (!bpf_pseudo_call(insn))
12241 insn->off = env->insn_aux_data[i].call_imm;
12242 subprog = find_subprog(env, i + insn->off + 1);
12243 insn->imm = subprog;
12247 prog->bpf_func = func[0]->bpf_func;
12248 prog->aux->func = func;
12249 prog->aux->func_cnt = env->subprog_cnt;
12250 bpf_prog_jit_attempt_done(prog);
12253 for (i = 0; i < env->subprog_cnt; i++) {
12257 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
12258 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
12259 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
12261 bpf_jit_free(func[i]);
12265 /* cleanup main prog to be interpreted */
12266 prog->jit_requested = 0;
12267 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12268 if (!bpf_pseudo_call(insn))
12271 insn->imm = env->insn_aux_data[i].call_imm;
12273 bpf_prog_jit_attempt_done(prog);
12277 static int fixup_call_args(struct bpf_verifier_env *env)
12279 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12280 struct bpf_prog *prog = env->prog;
12281 struct bpf_insn *insn = prog->insnsi;
12282 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12287 if (env->prog->jit_requested &&
12288 !bpf_prog_is_dev_bound(env->prog->aux)) {
12289 err = jit_subprogs(env);
12292 if (err == -EFAULT)
12295 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12296 if (has_kfunc_call) {
12297 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12300 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12301 /* When JIT fails the progs with bpf2bpf calls and tail_calls
12302 * have to be rejected, since interpreter doesn't support them yet.
12304 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12307 for (i = 0; i < prog->len; i++, insn++) {
12308 if (bpf_pseudo_func(insn)) {
12309 /* When JIT fails the progs with callback calls
12310 * have to be rejected, since interpreter doesn't support them yet.
12312 verbose(env, "callbacks are not allowed in non-JITed programs\n");
12316 if (!bpf_pseudo_call(insn))
12318 depth = get_callee_stack_depth(env, insn, i);
12321 bpf_patch_call_args(insn, depth);
12328 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12329 struct bpf_insn *insn)
12331 const struct bpf_kfunc_desc *desc;
12333 /* insn->imm has the btf func_id. Replace it with
12334 * an address (relative to __bpf_base_call).
12336 desc = find_kfunc_desc(env->prog, insn->imm);
12338 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12343 insn->imm = desc->imm;
12348 /* Do various post-verification rewrites in a single program pass.
12349 * These rewrites simplify JIT and interpreter implementations.
12351 static int do_misc_fixups(struct bpf_verifier_env *env)
12353 struct bpf_prog *prog = env->prog;
12354 bool expect_blinding = bpf_jit_blinding_enabled(prog);
12355 struct bpf_insn *insn = prog->insnsi;
12356 const struct bpf_func_proto *fn;
12357 const int insn_cnt = prog->len;
12358 const struct bpf_map_ops *ops;
12359 struct bpf_insn_aux_data *aux;
12360 struct bpf_insn insn_buf[16];
12361 struct bpf_prog *new_prog;
12362 struct bpf_map *map_ptr;
12363 int i, ret, cnt, delta = 0;
12365 for (i = 0; i < insn_cnt; i++, insn++) {
12366 /* Make divide-by-zero exceptions impossible. */
12367 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12368 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12369 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12370 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12371 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12372 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12373 struct bpf_insn *patchlet;
12374 struct bpf_insn chk_and_div[] = {
12375 /* [R,W]x div 0 -> 0 */
12376 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12377 BPF_JNE | BPF_K, insn->src_reg,
12379 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12380 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12383 struct bpf_insn chk_and_mod[] = {
12384 /* [R,W]x mod 0 -> [R,W]x */
12385 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12386 BPF_JEQ | BPF_K, insn->src_reg,
12387 0, 1 + (is64 ? 0 : 1), 0),
12389 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12390 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12393 patchlet = isdiv ? chk_and_div : chk_and_mod;
12394 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12395 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12397 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12402 env->prog = prog = new_prog;
12403 insn = new_prog->insnsi + i + delta;
12407 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12408 if (BPF_CLASS(insn->code) == BPF_LD &&
12409 (BPF_MODE(insn->code) == BPF_ABS ||
12410 BPF_MODE(insn->code) == BPF_IND)) {
12411 cnt = env->ops->gen_ld_abs(insn, insn_buf);
12412 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12413 verbose(env, "bpf verifier is misconfigured\n");
12417 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12422 env->prog = prog = new_prog;
12423 insn = new_prog->insnsi + i + delta;
12427 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
12428 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12429 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12430 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12431 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12432 struct bpf_insn *patch = &insn_buf[0];
12433 bool issrc, isneg, isimm;
12436 aux = &env->insn_aux_data[i + delta];
12437 if (!aux->alu_state ||
12438 aux->alu_state == BPF_ALU_NON_POINTER)
12441 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12442 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12443 BPF_ALU_SANITIZE_SRC;
12444 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
12446 off_reg = issrc ? insn->src_reg : insn->dst_reg;
12448 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12451 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12452 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12453 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12454 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12455 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12456 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12457 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12460 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12461 insn->src_reg = BPF_REG_AX;
12463 insn->code = insn->code == code_add ?
12464 code_sub : code_add;
12466 if (issrc && isneg && !isimm)
12467 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12468 cnt = patch - insn_buf;
12470 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12475 env->prog = prog = new_prog;
12476 insn = new_prog->insnsi + i + delta;
12480 if (insn->code != (BPF_JMP | BPF_CALL))
12482 if (insn->src_reg == BPF_PSEUDO_CALL)
12484 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12485 ret = fixup_kfunc_call(env, insn);
12491 if (insn->imm == BPF_FUNC_get_route_realm)
12492 prog->dst_needed = 1;
12493 if (insn->imm == BPF_FUNC_get_prandom_u32)
12494 bpf_user_rnd_init_once();
12495 if (insn->imm == BPF_FUNC_override_return)
12496 prog->kprobe_override = 1;
12497 if (insn->imm == BPF_FUNC_tail_call) {
12498 /* If we tail call into other programs, we
12499 * cannot make any assumptions since they can
12500 * be replaced dynamically during runtime in
12501 * the program array.
12503 prog->cb_access = 1;
12504 if (!allow_tail_call_in_subprogs(env))
12505 prog->aux->stack_depth = MAX_BPF_STACK;
12506 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
12508 /* mark bpf_tail_call as different opcode to avoid
12509 * conditional branch in the interpeter for every normal
12510 * call and to prevent accidental JITing by JIT compiler
12511 * that doesn't support bpf_tail_call yet
12514 insn->code = BPF_JMP | BPF_TAIL_CALL;
12516 aux = &env->insn_aux_data[i + delta];
12517 if (env->bpf_capable && !expect_blinding &&
12518 prog->jit_requested &&
12519 !bpf_map_key_poisoned(aux) &&
12520 !bpf_map_ptr_poisoned(aux) &&
12521 !bpf_map_ptr_unpriv(aux)) {
12522 struct bpf_jit_poke_descriptor desc = {
12523 .reason = BPF_POKE_REASON_TAIL_CALL,
12524 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12525 .tail_call.key = bpf_map_key_immediate(aux),
12526 .insn_idx = i + delta,
12529 ret = bpf_jit_add_poke_descriptor(prog, &desc);
12531 verbose(env, "adding tail call poke descriptor failed\n");
12535 insn->imm = ret + 1;
12539 if (!bpf_map_ptr_unpriv(aux))
12542 /* instead of changing every JIT dealing with tail_call
12543 * emit two extra insns:
12544 * if (index >= max_entries) goto out;
12545 * index &= array->index_mask;
12546 * to avoid out-of-bounds cpu speculation
12548 if (bpf_map_ptr_poisoned(aux)) {
12549 verbose(env, "tail_call abusing map_ptr\n");
12553 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12554 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12555 map_ptr->max_entries, 2);
12556 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12557 container_of(map_ptr,
12560 insn_buf[2] = *insn;
12562 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12567 env->prog = prog = new_prog;
12568 insn = new_prog->insnsi + i + delta;
12572 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
12573 * and other inlining handlers are currently limited to 64 bit
12576 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12577 (insn->imm == BPF_FUNC_map_lookup_elem ||
12578 insn->imm == BPF_FUNC_map_update_elem ||
12579 insn->imm == BPF_FUNC_map_delete_elem ||
12580 insn->imm == BPF_FUNC_map_push_elem ||
12581 insn->imm == BPF_FUNC_map_pop_elem ||
12582 insn->imm == BPF_FUNC_map_peek_elem ||
12583 insn->imm == BPF_FUNC_redirect_map)) {
12584 aux = &env->insn_aux_data[i + delta];
12585 if (bpf_map_ptr_poisoned(aux))
12586 goto patch_call_imm;
12588 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12589 ops = map_ptr->ops;
12590 if (insn->imm == BPF_FUNC_map_lookup_elem &&
12591 ops->map_gen_lookup) {
12592 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
12593 if (cnt == -EOPNOTSUPP)
12594 goto patch_map_ops_generic;
12595 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12596 verbose(env, "bpf verifier is misconfigured\n");
12600 new_prog = bpf_patch_insn_data(env, i + delta,
12606 env->prog = prog = new_prog;
12607 insn = new_prog->insnsi + i + delta;
12611 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12612 (void *(*)(struct bpf_map *map, void *key))NULL));
12613 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12614 (int (*)(struct bpf_map *map, void *key))NULL));
12615 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12616 (int (*)(struct bpf_map *map, void *key, void *value,
12618 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12619 (int (*)(struct bpf_map *map, void *value,
12621 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12622 (int (*)(struct bpf_map *map, void *value))NULL));
12623 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12624 (int (*)(struct bpf_map *map, void *value))NULL));
12625 BUILD_BUG_ON(!__same_type(ops->map_redirect,
12626 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12628 patch_map_ops_generic:
12629 switch (insn->imm) {
12630 case BPF_FUNC_map_lookup_elem:
12631 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12634 case BPF_FUNC_map_update_elem:
12635 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12638 case BPF_FUNC_map_delete_elem:
12639 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12642 case BPF_FUNC_map_push_elem:
12643 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12646 case BPF_FUNC_map_pop_elem:
12647 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12650 case BPF_FUNC_map_peek_elem:
12651 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12654 case BPF_FUNC_redirect_map:
12655 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12660 goto patch_call_imm;
12663 /* Implement bpf_jiffies64 inline. */
12664 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12665 insn->imm == BPF_FUNC_jiffies64) {
12666 struct bpf_insn ld_jiffies_addr[2] = {
12667 BPF_LD_IMM64(BPF_REG_0,
12668 (unsigned long)&jiffies),
12671 insn_buf[0] = ld_jiffies_addr[0];
12672 insn_buf[1] = ld_jiffies_addr[1];
12673 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12677 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12683 env->prog = prog = new_prog;
12684 insn = new_prog->insnsi + i + delta;
12689 fn = env->ops->get_func_proto(insn->imm, env->prog);
12690 /* all functions that have prototype and verifier allowed
12691 * programs to call them, must be real in-kernel functions
12695 "kernel subsystem misconfigured func %s#%d\n",
12696 func_id_name(insn->imm), insn->imm);
12699 insn->imm = fn->func - __bpf_call_base;
12702 /* Since poke tab is now finalized, publish aux to tracker. */
12703 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12704 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12705 if (!map_ptr->ops->map_poke_track ||
12706 !map_ptr->ops->map_poke_untrack ||
12707 !map_ptr->ops->map_poke_run) {
12708 verbose(env, "bpf verifier is misconfigured\n");
12712 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12714 verbose(env, "tracking tail call prog failed\n");
12719 sort_kfunc_descs_by_imm(env->prog);
12724 static void free_states(struct bpf_verifier_env *env)
12726 struct bpf_verifier_state_list *sl, *sln;
12729 sl = env->free_list;
12732 free_verifier_state(&sl->state, false);
12736 env->free_list = NULL;
12738 if (!env->explored_states)
12741 for (i = 0; i < state_htab_size(env); i++) {
12742 sl = env->explored_states[i];
12746 free_verifier_state(&sl->state, false);
12750 env->explored_states[i] = NULL;
12754 /* The verifier is using insn_aux_data[] to store temporary data during
12755 * verification and to store information for passes that run after the
12756 * verification like dead code sanitization. do_check_common() for subprogram N
12757 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
12758 * temporary data after do_check_common() finds that subprogram N cannot be
12759 * verified independently. pass_cnt counts the number of times
12760 * do_check_common() was run and insn->aux->seen tells the pass number
12761 * insn_aux_data was touched. These variables are compared to clear temporary
12762 * data from failed pass. For testing and experiments do_check_common() can be
12763 * run multiple times even when prior attempt to verify is unsuccessful.
12765 * Note that special handling is needed on !env->bypass_spec_v1 if this is
12766 * ever called outside of error path with subsequent program rejection.
12768 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
12770 struct bpf_insn *insn = env->prog->insnsi;
12771 struct bpf_insn_aux_data *aux;
12774 for (i = 0; i < env->prog->len; i++) {
12775 class = BPF_CLASS(insn[i].code);
12776 if (class != BPF_LDX && class != BPF_STX)
12778 aux = &env->insn_aux_data[i];
12779 if (aux->seen != env->pass_cnt)
12781 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
12785 static int do_check_common(struct bpf_verifier_env *env, int subprog)
12787 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12788 struct bpf_verifier_state *state;
12789 struct bpf_reg_state *regs;
12792 env->prev_linfo = NULL;
12795 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12798 state->curframe = 0;
12799 state->speculative = false;
12800 state->branches = 1;
12801 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12802 if (!state->frame[0]) {
12806 env->cur_state = state;
12807 init_func_state(env, state->frame[0],
12808 BPF_MAIN_FUNC /* callsite */,
12812 regs = state->frame[state->curframe]->regs;
12813 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
12814 ret = btf_prepare_func_args(env, subprog, regs);
12817 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12818 if (regs[i].type == PTR_TO_CTX)
12819 mark_reg_known_zero(env, regs, i);
12820 else if (regs[i].type == SCALAR_VALUE)
12821 mark_reg_unknown(env, regs, i);
12822 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12823 const u32 mem_size = regs[i].mem_size;
12825 mark_reg_known_zero(env, regs, i);
12826 regs[i].mem_size = mem_size;
12827 regs[i].id = ++env->id_gen;
12831 /* 1st arg to a function */
12832 regs[BPF_REG_1].type = PTR_TO_CTX;
12833 mark_reg_known_zero(env, regs, BPF_REG_1);
12834 ret = btf_check_subprog_arg_match(env, subprog, regs);
12835 if (ret == -EFAULT)
12836 /* unlikely verifier bug. abort.
12837 * ret == 0 and ret < 0 are sadly acceptable for
12838 * main() function due to backward compatibility.
12839 * Like socket filter program may be written as:
12840 * int bpf_prog(struct pt_regs *ctx)
12841 * and never dereference that ctx in the program.
12842 * 'struct pt_regs' is a type mismatch for socket
12843 * filter that should be using 'struct __sk_buff'.
12848 ret = do_check(env);
12850 /* check for NULL is necessary, since cur_state can be freed inside
12851 * do_check() under memory pressure.
12853 if (env->cur_state) {
12854 free_verifier_state(env->cur_state, true);
12855 env->cur_state = NULL;
12857 while (!pop_stack(env, NULL, NULL, false));
12858 if (!ret && pop_log)
12859 bpf_vlog_reset(&env->log, 0);
12862 /* clean aux data in case subprog was rejected */
12863 sanitize_insn_aux_data(env);
12867 /* Verify all global functions in a BPF program one by one based on their BTF.
12868 * All global functions must pass verification. Otherwise the whole program is rejected.
12879 * foo() will be verified first for R1=any_scalar_value. During verification it
12880 * will be assumed that bar() already verified successfully and call to bar()
12881 * from foo() will be checked for type match only. Later bar() will be verified
12882 * independently to check that it's safe for R1=any_scalar_value.
12884 static int do_check_subprogs(struct bpf_verifier_env *env)
12886 struct bpf_prog_aux *aux = env->prog->aux;
12889 if (!aux->func_info)
12892 for (i = 1; i < env->subprog_cnt; i++) {
12893 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12895 env->insn_idx = env->subprog_info[i].start;
12896 WARN_ON_ONCE(env->insn_idx == 0);
12897 ret = do_check_common(env, i);
12900 } else if (env->log.level & BPF_LOG_LEVEL) {
12902 "Func#%d is safe for any args that match its prototype\n",
12909 static int do_check_main(struct bpf_verifier_env *env)
12914 ret = do_check_common(env, 0);
12916 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12921 static void print_verification_stats(struct bpf_verifier_env *env)
12925 if (env->log.level & BPF_LOG_STATS) {
12926 verbose(env, "verification time %lld usec\n",
12927 div_u64(env->verification_time, 1000));
12928 verbose(env, "stack depth ");
12929 for (i = 0; i < env->subprog_cnt; i++) {
12930 u32 depth = env->subprog_info[i].stack_depth;
12932 verbose(env, "%d", depth);
12933 if (i + 1 < env->subprog_cnt)
12936 verbose(env, "\n");
12938 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12939 "total_states %d peak_states %d mark_read %d\n",
12940 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12941 env->max_states_per_insn, env->total_states,
12942 env->peak_states, env->longest_mark_read_walk);
12945 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12947 const struct btf_type *t, *func_proto;
12948 const struct bpf_struct_ops *st_ops;
12949 const struct btf_member *member;
12950 struct bpf_prog *prog = env->prog;
12951 u32 btf_id, member_idx;
12954 if (!prog->gpl_compatible) {
12955 verbose(env, "struct ops programs must have a GPL compatible license\n");
12959 btf_id = prog->aux->attach_btf_id;
12960 st_ops = bpf_struct_ops_find(btf_id);
12962 verbose(env, "attach_btf_id %u is not a supported struct\n",
12968 member_idx = prog->expected_attach_type;
12969 if (member_idx >= btf_type_vlen(t)) {
12970 verbose(env, "attach to invalid member idx %u of struct %s\n",
12971 member_idx, st_ops->name);
12975 member = &btf_type_member(t)[member_idx];
12976 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12977 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12980 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12981 mname, member_idx, st_ops->name);
12985 if (st_ops->check_member) {
12986 int err = st_ops->check_member(t, member);
12989 verbose(env, "attach to unsupported member %s of struct %s\n",
12990 mname, st_ops->name);
12995 prog->aux->attach_func_proto = func_proto;
12996 prog->aux->attach_func_name = mname;
12997 env->ops = st_ops->verifier_ops;
13001 #define SECURITY_PREFIX "security_"
13003 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13005 if (within_error_injection_list(addr) ||
13006 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13012 /* list of non-sleepable functions that are otherwise on
13013 * ALLOW_ERROR_INJECTION list
13015 BTF_SET_START(btf_non_sleepable_error_inject)
13016 /* Three functions below can be called from sleepable and non-sleepable context.
13017 * Assume non-sleepable from bpf safety point of view.
13019 BTF_ID(func, __add_to_page_cache_locked)
13020 BTF_ID(func, should_fail_alloc_page)
13021 BTF_ID(func, should_failslab)
13022 BTF_SET_END(btf_non_sleepable_error_inject)
13024 static int check_non_sleepable_error_inject(u32 btf_id)
13026 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13029 int bpf_check_attach_target(struct bpf_verifier_log *log,
13030 const struct bpf_prog *prog,
13031 const struct bpf_prog *tgt_prog,
13033 struct bpf_attach_target_info *tgt_info)
13035 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13036 const char prefix[] = "btf_trace_";
13037 int ret = 0, subprog = -1, i;
13038 const struct btf_type *t;
13039 bool conservative = true;
13045 bpf_log(log, "Tracing programs must provide btf_id\n");
13048 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13051 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13054 t = btf_type_by_id(btf, btf_id);
13056 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13059 tname = btf_name_by_offset(btf, t->name_off);
13061 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13065 struct bpf_prog_aux *aux = tgt_prog->aux;
13067 for (i = 0; i < aux->func_info_cnt; i++)
13068 if (aux->func_info[i].type_id == btf_id) {
13072 if (subprog == -1) {
13073 bpf_log(log, "Subprog %s doesn't exist\n", tname);
13076 conservative = aux->func_info_aux[subprog].unreliable;
13077 if (prog_extension) {
13078 if (conservative) {
13080 "Cannot replace static functions\n");
13083 if (!prog->jit_requested) {
13085 "Extension programs should be JITed\n");
13089 if (!tgt_prog->jited) {
13090 bpf_log(log, "Can attach to only JITed progs\n");
13093 if (tgt_prog->type == prog->type) {
13094 /* Cannot fentry/fexit another fentry/fexit program.
13095 * Cannot attach program extension to another extension.
13096 * It's ok to attach fentry/fexit to extension program.
13098 bpf_log(log, "Cannot recursively attach\n");
13101 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13103 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13104 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13105 /* Program extensions can extend all program types
13106 * except fentry/fexit. The reason is the following.
13107 * The fentry/fexit programs are used for performance
13108 * analysis, stats and can be attached to any program
13109 * type except themselves. When extension program is
13110 * replacing XDP function it is necessary to allow
13111 * performance analysis of all functions. Both original
13112 * XDP program and its program extension. Hence
13113 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13114 * allowed. If extending of fentry/fexit was allowed it
13115 * would be possible to create long call chain
13116 * fentry->extension->fentry->extension beyond
13117 * reasonable stack size. Hence extending fentry is not
13120 bpf_log(log, "Cannot extend fentry/fexit\n");
13124 if (prog_extension) {
13125 bpf_log(log, "Cannot replace kernel functions\n");
13130 switch (prog->expected_attach_type) {
13131 case BPF_TRACE_RAW_TP:
13134 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13137 if (!btf_type_is_typedef(t)) {
13138 bpf_log(log, "attach_btf_id %u is not a typedef\n",
13142 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13143 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13147 tname += sizeof(prefix) - 1;
13148 t = btf_type_by_id(btf, t->type);
13149 if (!btf_type_is_ptr(t))
13150 /* should never happen in valid vmlinux build */
13152 t = btf_type_by_id(btf, t->type);
13153 if (!btf_type_is_func_proto(t))
13154 /* should never happen in valid vmlinux build */
13158 case BPF_TRACE_ITER:
13159 if (!btf_type_is_func(t)) {
13160 bpf_log(log, "attach_btf_id %u is not a function\n",
13164 t = btf_type_by_id(btf, t->type);
13165 if (!btf_type_is_func_proto(t))
13167 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13172 if (!prog_extension)
13175 case BPF_MODIFY_RETURN:
13177 case BPF_TRACE_FENTRY:
13178 case BPF_TRACE_FEXIT:
13179 if (!btf_type_is_func(t)) {
13180 bpf_log(log, "attach_btf_id %u is not a function\n",
13184 if (prog_extension &&
13185 btf_check_type_match(log, prog, btf, t))
13187 t = btf_type_by_id(btf, t->type);
13188 if (!btf_type_is_func_proto(t))
13191 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13192 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13193 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13196 if (tgt_prog && conservative)
13199 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13205 addr = (long) tgt_prog->bpf_func;
13207 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13209 addr = kallsyms_lookup_name(tname);
13212 "The address of function %s cannot be found\n",
13218 if (prog->aux->sleepable) {
13220 switch (prog->type) {
13221 case BPF_PROG_TYPE_TRACING:
13222 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
13223 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13225 if (!check_non_sleepable_error_inject(btf_id) &&
13226 within_error_injection_list(addr))
13229 case BPF_PROG_TYPE_LSM:
13230 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
13231 * Only some of them are sleepable.
13233 if (bpf_lsm_is_sleepable_hook(btf_id))
13240 bpf_log(log, "%s is not sleepable\n", tname);
13243 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13245 bpf_log(log, "can't modify return codes of BPF programs\n");
13248 ret = check_attach_modify_return(addr, tname);
13250 bpf_log(log, "%s() is not modifiable\n", tname);
13257 tgt_info->tgt_addr = addr;
13258 tgt_info->tgt_name = tname;
13259 tgt_info->tgt_type = t;
13263 BTF_SET_START(btf_id_deny)
13266 BTF_ID(func, migrate_disable)
13267 BTF_ID(func, migrate_enable)
13269 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13270 BTF_ID(func, rcu_read_unlock_strict)
13272 BTF_SET_END(btf_id_deny)
13274 static int check_attach_btf_id(struct bpf_verifier_env *env)
13276 struct bpf_prog *prog = env->prog;
13277 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13278 struct bpf_attach_target_info tgt_info = {};
13279 u32 btf_id = prog->aux->attach_btf_id;
13280 struct bpf_trampoline *tr;
13284 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13285 prog->type != BPF_PROG_TYPE_LSM) {
13286 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13290 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13291 return check_struct_ops_btf_id(env);
13293 if (prog->type != BPF_PROG_TYPE_TRACING &&
13294 prog->type != BPF_PROG_TYPE_LSM &&
13295 prog->type != BPF_PROG_TYPE_EXT)
13298 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13302 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13303 /* to make freplace equivalent to their targets, they need to
13304 * inherit env->ops and expected_attach_type for the rest of the
13307 env->ops = bpf_verifier_ops[tgt_prog->type];
13308 prog->expected_attach_type = tgt_prog->expected_attach_type;
13311 /* store info about the attachment target that will be used later */
13312 prog->aux->attach_func_proto = tgt_info.tgt_type;
13313 prog->aux->attach_func_name = tgt_info.tgt_name;
13316 prog->aux->saved_dst_prog_type = tgt_prog->type;
13317 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13320 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13321 prog->aux->attach_btf_trace = true;
13323 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13324 if (!bpf_iter_prog_supported(prog))
13329 if (prog->type == BPF_PROG_TYPE_LSM) {
13330 ret = bpf_lsm_verify_prog(&env->log, prog);
13333 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
13334 btf_id_set_contains(&btf_id_deny, btf_id)) {
13338 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13339 tr = bpf_trampoline_get(key, &tgt_info);
13343 prog->aux->dst_trampoline = tr;
13347 struct btf *bpf_get_btf_vmlinux(void)
13349 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13350 mutex_lock(&bpf_verifier_lock);
13352 btf_vmlinux = btf_parse_vmlinux();
13353 mutex_unlock(&bpf_verifier_lock);
13355 return btf_vmlinux;
13358 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
13359 union bpf_attr __user *uattr)
13361 u64 start_time = ktime_get_ns();
13362 struct bpf_verifier_env *env;
13363 struct bpf_verifier_log *log;
13364 int i, len, ret = -EINVAL;
13367 /* no program is valid */
13368 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13371 /* 'struct bpf_verifier_env' can be global, but since it's not small,
13372 * allocate/free it every time bpf_check() is called
13374 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13379 len = (*prog)->len;
13380 env->insn_aux_data =
13381 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13383 if (!env->insn_aux_data)
13385 for (i = 0; i < len; i++)
13386 env->insn_aux_data[i].orig_idx = i;
13388 env->ops = bpf_verifier_ops[env->prog->type];
13389 is_priv = bpf_capable();
13391 bpf_get_btf_vmlinux();
13393 /* grab the mutex to protect few globals used by verifier */
13395 mutex_lock(&bpf_verifier_lock);
13397 if (attr->log_level || attr->log_buf || attr->log_size) {
13398 /* user requested verbose verifier output
13399 * and supplied buffer to store the verification trace
13401 log->level = attr->log_level;
13402 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13403 log->len_total = attr->log_size;
13406 /* log attributes have to be sane */
13407 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
13408 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
13412 if (IS_ERR(btf_vmlinux)) {
13413 /* Either gcc or pahole or kernel are broken. */
13414 verbose(env, "in-kernel BTF is malformed\n");
13415 ret = PTR_ERR(btf_vmlinux);
13416 goto skip_full_check;
13419 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13420 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
13421 env->strict_alignment = true;
13422 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13423 env->strict_alignment = false;
13425 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
13426 env->allow_uninit_stack = bpf_allow_uninit_stack();
13427 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
13428 env->bypass_spec_v1 = bpf_bypass_spec_v1();
13429 env->bypass_spec_v4 = bpf_bypass_spec_v4();
13430 env->bpf_capable = bpf_capable();
13433 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13435 env->explored_states = kvcalloc(state_htab_size(env),
13436 sizeof(struct bpf_verifier_state_list *),
13439 if (!env->explored_states)
13440 goto skip_full_check;
13442 ret = add_subprog_and_kfunc(env);
13444 goto skip_full_check;
13446 ret = check_subprogs(env);
13448 goto skip_full_check;
13450 ret = check_btf_info(env, attr, uattr);
13452 goto skip_full_check;
13454 ret = check_attach_btf_id(env);
13456 goto skip_full_check;
13458 ret = resolve_pseudo_ldimm64(env);
13460 goto skip_full_check;
13462 if (bpf_prog_is_dev_bound(env->prog->aux)) {
13463 ret = bpf_prog_offload_verifier_prep(env->prog);
13465 goto skip_full_check;
13468 ret = check_cfg(env);
13470 goto skip_full_check;
13472 ret = do_check_subprogs(env);
13473 ret = ret ?: do_check_main(env);
13475 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13476 ret = bpf_prog_offload_finalize(env);
13479 kvfree(env->explored_states);
13482 ret = check_max_stack_depth(env);
13484 /* instruction rewrites happen after this point */
13487 opt_hard_wire_dead_code_branches(env);
13489 ret = opt_remove_dead_code(env);
13491 ret = opt_remove_nops(env);
13494 sanitize_dead_code(env);
13498 /* program is valid, convert *(u32*)(ctx + off) accesses */
13499 ret = convert_ctx_accesses(env);
13502 ret = do_misc_fixups(env);
13504 /* do 32-bit optimization after insn patching has done so those patched
13505 * insns could be handled correctly.
13507 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13508 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13509 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13514 ret = fixup_call_args(env);
13516 env->verification_time = ktime_get_ns() - start_time;
13517 print_verification_stats(env);
13519 if (log->level && bpf_verifier_log_full(log))
13521 if (log->level && !log->ubuf) {
13523 goto err_release_maps;
13527 goto err_release_maps;
13529 if (env->used_map_cnt) {
13530 /* if program passed verifier, update used_maps in bpf_prog_info */
13531 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13532 sizeof(env->used_maps[0]),
13535 if (!env->prog->aux->used_maps) {
13537 goto err_release_maps;
13540 memcpy(env->prog->aux->used_maps, env->used_maps,
13541 sizeof(env->used_maps[0]) * env->used_map_cnt);
13542 env->prog->aux->used_map_cnt = env->used_map_cnt;
13544 if (env->used_btf_cnt) {
13545 /* if program passed verifier, update used_btfs in bpf_prog_aux */
13546 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13547 sizeof(env->used_btfs[0]),
13549 if (!env->prog->aux->used_btfs) {
13551 goto err_release_maps;
13554 memcpy(env->prog->aux->used_btfs, env->used_btfs,
13555 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13556 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13558 if (env->used_map_cnt || env->used_btf_cnt) {
13559 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
13560 * bpf_ld_imm64 instructions
13562 convert_pseudo_ld_imm64(env);
13565 adjust_btf_func(env);
13568 if (!env->prog->aux->used_maps)
13569 /* if we didn't copy map pointers into bpf_prog_info, release
13570 * them now. Otherwise free_used_maps() will release them.
13573 if (!env->prog->aux->used_btfs)
13576 /* extension progs temporarily inherit the attach_type of their targets
13577 for verification purposes, so set it back to zero before returning
13579 if (env->prog->type == BPF_PROG_TYPE_EXT)
13580 env->prog->expected_attach_type = 0;
13585 mutex_unlock(&bpf_verifier_lock);
13586 vfree(env->insn_aux_data);