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_func(const struct bpf_insn *insn)
239 return insn->code == (BPF_LD | BPF_IMM | BPF_DW) &&
240 insn->src_reg == BPF_PSEUDO_FUNC;
243 struct bpf_call_arg_meta {
244 struct bpf_map *map_ptr;
260 struct btf *btf_vmlinux;
262 static DEFINE_MUTEX(bpf_verifier_lock);
264 static const struct bpf_line_info *
265 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
267 const struct bpf_line_info *linfo;
268 const struct bpf_prog *prog;
272 nr_linfo = prog->aux->nr_linfo;
274 if (!nr_linfo || insn_off >= prog->len)
277 linfo = prog->aux->linfo;
278 for (i = 1; i < nr_linfo; i++)
279 if (insn_off < linfo[i].insn_off)
282 return &linfo[i - 1];
285 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
290 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
292 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
293 "verifier log line truncated - local buffer too short\n");
295 n = min(log->len_total - log->len_used - 1, n);
298 if (log->level == BPF_LOG_KERNEL) {
299 pr_err("BPF:%s\n", log->kbuf);
302 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
308 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
312 if (!bpf_verifier_log_needed(log))
315 log->len_used = new_pos;
316 if (put_user(zero, log->ubuf + new_pos))
320 /* log_level controls verbosity level of eBPF verifier.
321 * bpf_verifier_log_write() is used to dump the verification trace to the log,
322 * so the user can figure out what's wrong with the program
324 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
325 const char *fmt, ...)
329 if (!bpf_verifier_log_needed(&env->log))
333 bpf_verifier_vlog(&env->log, fmt, args);
336 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
338 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
340 struct bpf_verifier_env *env = private_data;
343 if (!bpf_verifier_log_needed(&env->log))
347 bpf_verifier_vlog(&env->log, fmt, args);
351 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
352 const char *fmt, ...)
356 if (!bpf_verifier_log_needed(log))
360 bpf_verifier_vlog(log, fmt, args);
364 static const char *ltrim(const char *s)
372 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
374 const char *prefix_fmt, ...)
376 const struct bpf_line_info *linfo;
378 if (!bpf_verifier_log_needed(&env->log))
381 linfo = find_linfo(env, insn_off);
382 if (!linfo || linfo == env->prev_linfo)
388 va_start(args, prefix_fmt);
389 bpf_verifier_vlog(&env->log, prefix_fmt, args);
394 ltrim(btf_name_by_offset(env->prog->aux->btf,
397 env->prev_linfo = linfo;
400 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
401 struct bpf_reg_state *reg,
402 struct tnum *range, const char *ctx,
403 const char *reg_name)
407 verbose(env, "At %s the register %s ", ctx, reg_name);
408 if (!tnum_is_unknown(reg->var_off)) {
409 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
410 verbose(env, "has value %s", tn_buf);
412 verbose(env, "has unknown scalar value");
414 tnum_strn(tn_buf, sizeof(tn_buf), *range);
415 verbose(env, " should have been in %s\n", tn_buf);
418 static bool type_is_pkt_pointer(enum bpf_reg_type type)
420 return type == PTR_TO_PACKET ||
421 type == PTR_TO_PACKET_META;
424 static bool type_is_sk_pointer(enum bpf_reg_type type)
426 return type == PTR_TO_SOCKET ||
427 type == PTR_TO_SOCK_COMMON ||
428 type == PTR_TO_TCP_SOCK ||
429 type == PTR_TO_XDP_SOCK;
432 static bool reg_type_not_null(enum bpf_reg_type type)
434 return type == PTR_TO_SOCKET ||
435 type == PTR_TO_TCP_SOCK ||
436 type == PTR_TO_MAP_VALUE ||
437 type == PTR_TO_MAP_KEY ||
438 type == PTR_TO_SOCK_COMMON;
441 static bool reg_type_may_be_null(enum bpf_reg_type type)
443 return type == PTR_TO_MAP_VALUE_OR_NULL ||
444 type == PTR_TO_SOCKET_OR_NULL ||
445 type == PTR_TO_SOCK_COMMON_OR_NULL ||
446 type == PTR_TO_TCP_SOCK_OR_NULL ||
447 type == PTR_TO_BTF_ID_OR_NULL ||
448 type == PTR_TO_MEM_OR_NULL ||
449 type == PTR_TO_RDONLY_BUF_OR_NULL ||
450 type == PTR_TO_RDWR_BUF_OR_NULL;
453 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
455 return reg->type == PTR_TO_MAP_VALUE &&
456 map_value_has_spin_lock(reg->map_ptr);
459 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
461 return type == PTR_TO_SOCKET ||
462 type == PTR_TO_SOCKET_OR_NULL ||
463 type == PTR_TO_TCP_SOCK ||
464 type == PTR_TO_TCP_SOCK_OR_NULL ||
465 type == PTR_TO_MEM ||
466 type == PTR_TO_MEM_OR_NULL;
469 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
471 return type == ARG_PTR_TO_SOCK_COMMON;
474 static bool arg_type_may_be_null(enum bpf_arg_type type)
476 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
477 type == ARG_PTR_TO_MEM_OR_NULL ||
478 type == ARG_PTR_TO_CTX_OR_NULL ||
479 type == ARG_PTR_TO_SOCKET_OR_NULL ||
480 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
481 type == ARG_PTR_TO_STACK_OR_NULL;
484 /* Determine whether the function releases some resources allocated by another
485 * function call. The first reference type argument will be assumed to be
486 * released by release_reference().
488 static bool is_release_function(enum bpf_func_id func_id)
490 return func_id == BPF_FUNC_sk_release ||
491 func_id == BPF_FUNC_ringbuf_submit ||
492 func_id == BPF_FUNC_ringbuf_discard;
495 static bool may_be_acquire_function(enum bpf_func_id func_id)
497 return func_id == BPF_FUNC_sk_lookup_tcp ||
498 func_id == BPF_FUNC_sk_lookup_udp ||
499 func_id == BPF_FUNC_skc_lookup_tcp ||
500 func_id == BPF_FUNC_map_lookup_elem ||
501 func_id == BPF_FUNC_ringbuf_reserve;
504 static bool is_acquire_function(enum bpf_func_id func_id,
505 const struct bpf_map *map)
507 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
509 if (func_id == BPF_FUNC_sk_lookup_tcp ||
510 func_id == BPF_FUNC_sk_lookup_udp ||
511 func_id == BPF_FUNC_skc_lookup_tcp ||
512 func_id == BPF_FUNC_ringbuf_reserve)
515 if (func_id == BPF_FUNC_map_lookup_elem &&
516 (map_type == BPF_MAP_TYPE_SOCKMAP ||
517 map_type == BPF_MAP_TYPE_SOCKHASH))
523 static bool is_ptr_cast_function(enum bpf_func_id func_id)
525 return func_id == BPF_FUNC_tcp_sock ||
526 func_id == BPF_FUNC_sk_fullsock ||
527 func_id == BPF_FUNC_skc_to_tcp_sock ||
528 func_id == BPF_FUNC_skc_to_tcp6_sock ||
529 func_id == BPF_FUNC_skc_to_udp6_sock ||
530 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
531 func_id == BPF_FUNC_skc_to_tcp_request_sock;
534 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
536 return BPF_CLASS(insn->code) == BPF_STX &&
537 BPF_MODE(insn->code) == BPF_ATOMIC &&
538 insn->imm == BPF_CMPXCHG;
541 /* string representation of 'enum bpf_reg_type' */
542 static const char * const reg_type_str[] = {
544 [SCALAR_VALUE] = "inv",
545 [PTR_TO_CTX] = "ctx",
546 [CONST_PTR_TO_MAP] = "map_ptr",
547 [PTR_TO_MAP_VALUE] = "map_value",
548 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
549 [PTR_TO_STACK] = "fp",
550 [PTR_TO_PACKET] = "pkt",
551 [PTR_TO_PACKET_META] = "pkt_meta",
552 [PTR_TO_PACKET_END] = "pkt_end",
553 [PTR_TO_FLOW_KEYS] = "flow_keys",
554 [PTR_TO_SOCKET] = "sock",
555 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
556 [PTR_TO_SOCK_COMMON] = "sock_common",
557 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
558 [PTR_TO_TCP_SOCK] = "tcp_sock",
559 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
560 [PTR_TO_TP_BUFFER] = "tp_buffer",
561 [PTR_TO_XDP_SOCK] = "xdp_sock",
562 [PTR_TO_BTF_ID] = "ptr_",
563 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
564 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
565 [PTR_TO_MEM] = "mem",
566 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
567 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
568 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
569 [PTR_TO_RDWR_BUF] = "rdwr_buf",
570 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
571 [PTR_TO_FUNC] = "func",
572 [PTR_TO_MAP_KEY] = "map_key",
575 static char slot_type_char[] = {
576 [STACK_INVALID] = '?',
582 static void print_liveness(struct bpf_verifier_env *env,
583 enum bpf_reg_liveness live)
585 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
587 if (live & REG_LIVE_READ)
589 if (live & REG_LIVE_WRITTEN)
591 if (live & REG_LIVE_DONE)
595 static struct bpf_func_state *func(struct bpf_verifier_env *env,
596 const struct bpf_reg_state *reg)
598 struct bpf_verifier_state *cur = env->cur_state;
600 return cur->frame[reg->frameno];
603 static const char *kernel_type_name(const struct btf* btf, u32 id)
605 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
608 static void print_verifier_state(struct bpf_verifier_env *env,
609 const struct bpf_func_state *state)
611 const struct bpf_reg_state *reg;
616 verbose(env, " frame%d:", state->frameno);
617 for (i = 0; i < MAX_BPF_REG; i++) {
618 reg = &state->regs[i];
622 verbose(env, " R%d", i);
623 print_liveness(env, reg->live);
624 verbose(env, "=%s", reg_type_str[t]);
625 if (t == SCALAR_VALUE && reg->precise)
627 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
628 tnum_is_const(reg->var_off)) {
629 /* reg->off should be 0 for SCALAR_VALUE */
630 verbose(env, "%lld", reg->var_off.value + reg->off);
632 if (t == PTR_TO_BTF_ID ||
633 t == PTR_TO_BTF_ID_OR_NULL ||
634 t == PTR_TO_PERCPU_BTF_ID)
635 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
636 verbose(env, "(id=%d", reg->id);
637 if (reg_type_may_be_refcounted_or_null(t))
638 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
639 if (t != SCALAR_VALUE)
640 verbose(env, ",off=%d", reg->off);
641 if (type_is_pkt_pointer(t))
642 verbose(env, ",r=%d", reg->range);
643 else if (t == CONST_PTR_TO_MAP ||
644 t == PTR_TO_MAP_KEY ||
645 t == PTR_TO_MAP_VALUE ||
646 t == PTR_TO_MAP_VALUE_OR_NULL)
647 verbose(env, ",ks=%d,vs=%d",
648 reg->map_ptr->key_size,
649 reg->map_ptr->value_size);
650 if (tnum_is_const(reg->var_off)) {
651 /* Typically an immediate SCALAR_VALUE, but
652 * could be a pointer whose offset is too big
655 verbose(env, ",imm=%llx", reg->var_off.value);
657 if (reg->smin_value != reg->umin_value &&
658 reg->smin_value != S64_MIN)
659 verbose(env, ",smin_value=%lld",
660 (long long)reg->smin_value);
661 if (reg->smax_value != reg->umax_value &&
662 reg->smax_value != S64_MAX)
663 verbose(env, ",smax_value=%lld",
664 (long long)reg->smax_value);
665 if (reg->umin_value != 0)
666 verbose(env, ",umin_value=%llu",
667 (unsigned long long)reg->umin_value);
668 if (reg->umax_value != U64_MAX)
669 verbose(env, ",umax_value=%llu",
670 (unsigned long long)reg->umax_value);
671 if (!tnum_is_unknown(reg->var_off)) {
674 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
675 verbose(env, ",var_off=%s", tn_buf);
677 if (reg->s32_min_value != reg->smin_value &&
678 reg->s32_min_value != S32_MIN)
679 verbose(env, ",s32_min_value=%d",
680 (int)(reg->s32_min_value));
681 if (reg->s32_max_value != reg->smax_value &&
682 reg->s32_max_value != S32_MAX)
683 verbose(env, ",s32_max_value=%d",
684 (int)(reg->s32_max_value));
685 if (reg->u32_min_value != reg->umin_value &&
686 reg->u32_min_value != U32_MIN)
687 verbose(env, ",u32_min_value=%d",
688 (int)(reg->u32_min_value));
689 if (reg->u32_max_value != reg->umax_value &&
690 reg->u32_max_value != U32_MAX)
691 verbose(env, ",u32_max_value=%d",
692 (int)(reg->u32_max_value));
697 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
698 char types_buf[BPF_REG_SIZE + 1];
702 for (j = 0; j < BPF_REG_SIZE; j++) {
703 if (state->stack[i].slot_type[j] != STACK_INVALID)
705 types_buf[j] = slot_type_char[
706 state->stack[i].slot_type[j]];
708 types_buf[BPF_REG_SIZE] = 0;
711 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
712 print_liveness(env, state->stack[i].spilled_ptr.live);
713 if (state->stack[i].slot_type[0] == STACK_SPILL) {
714 reg = &state->stack[i].spilled_ptr;
716 verbose(env, "=%s", reg_type_str[t]);
717 if (t == SCALAR_VALUE && reg->precise)
719 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
720 verbose(env, "%lld", reg->var_off.value + reg->off);
722 verbose(env, "=%s", types_buf);
725 if (state->acquired_refs && state->refs[0].id) {
726 verbose(env, " refs=%d", state->refs[0].id);
727 for (i = 1; i < state->acquired_refs; i++)
728 if (state->refs[i].id)
729 verbose(env, ",%d", state->refs[i].id);
734 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
735 static int copy_##NAME##_state(struct bpf_func_state *dst, \
736 const struct bpf_func_state *src) \
740 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
741 /* internal bug, make state invalid to reject the program */ \
742 memset(dst, 0, sizeof(*dst)); \
745 memcpy(dst->FIELD, src->FIELD, \
746 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
749 /* copy_reference_state() */
750 COPY_STATE_FN(reference, acquired_refs, refs, 1)
751 /* copy_stack_state() */
752 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
755 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
756 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
759 u32 old_size = state->COUNT; \
760 struct bpf_##NAME##_state *new_##FIELD; \
761 int slot = size / SIZE; \
763 if (size <= old_size || !size) { \
766 state->COUNT = slot * SIZE; \
767 if (!size && old_size) { \
768 kfree(state->FIELD); \
769 state->FIELD = NULL; \
773 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
779 memcpy(new_##FIELD, state->FIELD, \
780 sizeof(*new_##FIELD) * (old_size / SIZE)); \
781 memset(new_##FIELD + old_size / SIZE, 0, \
782 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
784 state->COUNT = slot * SIZE; \
785 kfree(state->FIELD); \
786 state->FIELD = new_##FIELD; \
789 /* realloc_reference_state() */
790 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
791 /* realloc_stack_state() */
792 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
793 #undef REALLOC_STATE_FN
795 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
796 * make it consume minimal amount of memory. check_stack_write() access from
797 * the program calls into realloc_func_state() to grow the stack size.
798 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
799 * which realloc_stack_state() copies over. It points to previous
800 * bpf_verifier_state which is never reallocated.
802 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
803 int refs_size, bool copy_old)
805 int err = realloc_reference_state(state, refs_size, copy_old);
808 return realloc_stack_state(state, stack_size, copy_old);
811 /* Acquire a pointer id from the env and update the state->refs to include
812 * this new pointer reference.
813 * On success, returns a valid pointer id to associate with the register
814 * On failure, returns a negative errno.
816 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
818 struct bpf_func_state *state = cur_func(env);
819 int new_ofs = state->acquired_refs;
822 err = realloc_reference_state(state, state->acquired_refs + 1, true);
826 state->refs[new_ofs].id = id;
827 state->refs[new_ofs].insn_idx = insn_idx;
832 /* release function corresponding to acquire_reference_state(). Idempotent. */
833 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
837 last_idx = state->acquired_refs - 1;
838 for (i = 0; i < state->acquired_refs; i++) {
839 if (state->refs[i].id == ptr_id) {
840 if (last_idx && i != last_idx)
841 memcpy(&state->refs[i], &state->refs[last_idx],
842 sizeof(*state->refs));
843 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
844 state->acquired_refs--;
851 static int transfer_reference_state(struct bpf_func_state *dst,
852 struct bpf_func_state *src)
854 int err = realloc_reference_state(dst, src->acquired_refs, false);
857 err = copy_reference_state(dst, src);
863 static void free_func_state(struct bpf_func_state *state)
872 static void clear_jmp_history(struct bpf_verifier_state *state)
874 kfree(state->jmp_history);
875 state->jmp_history = NULL;
876 state->jmp_history_cnt = 0;
879 static void free_verifier_state(struct bpf_verifier_state *state,
884 for (i = 0; i <= state->curframe; i++) {
885 free_func_state(state->frame[i]);
886 state->frame[i] = NULL;
888 clear_jmp_history(state);
893 /* copy verifier state from src to dst growing dst stack space
894 * when necessary to accommodate larger src stack
896 static int copy_func_state(struct bpf_func_state *dst,
897 const struct bpf_func_state *src)
901 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
905 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
906 err = copy_reference_state(dst, src);
909 return copy_stack_state(dst, src);
912 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
913 const struct bpf_verifier_state *src)
915 struct bpf_func_state *dst;
916 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
919 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
920 kfree(dst_state->jmp_history);
921 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
922 if (!dst_state->jmp_history)
925 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
926 dst_state->jmp_history_cnt = src->jmp_history_cnt;
928 /* if dst has more stack frames then src frame, free them */
929 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
930 free_func_state(dst_state->frame[i]);
931 dst_state->frame[i] = NULL;
933 dst_state->speculative = src->speculative;
934 dst_state->curframe = src->curframe;
935 dst_state->active_spin_lock = src->active_spin_lock;
936 dst_state->branches = src->branches;
937 dst_state->parent = src->parent;
938 dst_state->first_insn_idx = src->first_insn_idx;
939 dst_state->last_insn_idx = src->last_insn_idx;
940 for (i = 0; i <= src->curframe; i++) {
941 dst = dst_state->frame[i];
943 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
946 dst_state->frame[i] = dst;
948 err = copy_func_state(dst, src->frame[i]);
955 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
958 u32 br = --st->branches;
960 /* WARN_ON(br > 1) technically makes sense here,
961 * but see comment in push_stack(), hence:
963 WARN_ONCE((int)br < 0,
964 "BUG update_branch_counts:branches_to_explore=%d\n",
972 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
973 int *insn_idx, bool pop_log)
975 struct bpf_verifier_state *cur = env->cur_state;
976 struct bpf_verifier_stack_elem *elem, *head = env->head;
979 if (env->head == NULL)
983 err = copy_verifier_state(cur, &head->st);
988 bpf_vlog_reset(&env->log, head->log_pos);
990 *insn_idx = head->insn_idx;
992 *prev_insn_idx = head->prev_insn_idx;
994 free_verifier_state(&head->st, false);
1001 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1002 int insn_idx, int prev_insn_idx,
1005 struct bpf_verifier_state *cur = env->cur_state;
1006 struct bpf_verifier_stack_elem *elem;
1009 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1013 elem->insn_idx = insn_idx;
1014 elem->prev_insn_idx = prev_insn_idx;
1015 elem->next = env->head;
1016 elem->log_pos = env->log.len_used;
1019 err = copy_verifier_state(&elem->st, cur);
1022 elem->st.speculative |= speculative;
1023 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1024 verbose(env, "The sequence of %d jumps is too complex.\n",
1028 if (elem->st.parent) {
1029 ++elem->st.parent->branches;
1030 /* WARN_ON(branches > 2) technically makes sense here,
1032 * 1. speculative states will bump 'branches' for non-branch
1034 * 2. is_state_visited() heuristics may decide not to create
1035 * a new state for a sequence of branches and all such current
1036 * and cloned states will be pointing to a single parent state
1037 * which might have large 'branches' count.
1042 free_verifier_state(env->cur_state, true);
1043 env->cur_state = NULL;
1044 /* pop all elements and return */
1045 while (!pop_stack(env, NULL, NULL, false));
1049 #define CALLER_SAVED_REGS 6
1050 static const int caller_saved[CALLER_SAVED_REGS] = {
1051 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1054 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1055 struct bpf_reg_state *reg);
1057 /* This helper doesn't clear reg->id */
1058 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1060 reg->var_off = tnum_const(imm);
1061 reg->smin_value = (s64)imm;
1062 reg->smax_value = (s64)imm;
1063 reg->umin_value = imm;
1064 reg->umax_value = imm;
1066 reg->s32_min_value = (s32)imm;
1067 reg->s32_max_value = (s32)imm;
1068 reg->u32_min_value = (u32)imm;
1069 reg->u32_max_value = (u32)imm;
1072 /* Mark the unknown part of a register (variable offset or scalar value) as
1073 * known to have the value @imm.
1075 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1077 /* Clear id, off, and union(map_ptr, range) */
1078 memset(((u8 *)reg) + sizeof(reg->type), 0,
1079 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1080 ___mark_reg_known(reg, imm);
1083 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1085 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1086 reg->s32_min_value = (s32)imm;
1087 reg->s32_max_value = (s32)imm;
1088 reg->u32_min_value = (u32)imm;
1089 reg->u32_max_value = (u32)imm;
1092 /* Mark the 'variable offset' part of a register as zero. This should be
1093 * used only on registers holding a pointer type.
1095 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1097 __mark_reg_known(reg, 0);
1100 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1102 __mark_reg_known(reg, 0);
1103 reg->type = SCALAR_VALUE;
1106 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1107 struct bpf_reg_state *regs, u32 regno)
1109 if (WARN_ON(regno >= MAX_BPF_REG)) {
1110 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1111 /* Something bad happened, let's kill all regs */
1112 for (regno = 0; regno < MAX_BPF_REG; regno++)
1113 __mark_reg_not_init(env, regs + regno);
1116 __mark_reg_known_zero(regs + regno);
1119 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1121 switch (reg->type) {
1122 case PTR_TO_MAP_VALUE_OR_NULL: {
1123 const struct bpf_map *map = reg->map_ptr;
1125 if (map->inner_map_meta) {
1126 reg->type = CONST_PTR_TO_MAP;
1127 reg->map_ptr = map->inner_map_meta;
1128 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1129 reg->type = PTR_TO_XDP_SOCK;
1130 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1131 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1132 reg->type = PTR_TO_SOCKET;
1134 reg->type = PTR_TO_MAP_VALUE;
1138 case PTR_TO_SOCKET_OR_NULL:
1139 reg->type = PTR_TO_SOCKET;
1141 case PTR_TO_SOCK_COMMON_OR_NULL:
1142 reg->type = PTR_TO_SOCK_COMMON;
1144 case PTR_TO_TCP_SOCK_OR_NULL:
1145 reg->type = PTR_TO_TCP_SOCK;
1147 case PTR_TO_BTF_ID_OR_NULL:
1148 reg->type = PTR_TO_BTF_ID;
1150 case PTR_TO_MEM_OR_NULL:
1151 reg->type = PTR_TO_MEM;
1153 case PTR_TO_RDONLY_BUF_OR_NULL:
1154 reg->type = PTR_TO_RDONLY_BUF;
1156 case PTR_TO_RDWR_BUF_OR_NULL:
1157 reg->type = PTR_TO_RDWR_BUF;
1160 WARN_ONCE(1, "unknown nullable register type");
1164 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1166 return type_is_pkt_pointer(reg->type);
1169 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1171 return reg_is_pkt_pointer(reg) ||
1172 reg->type == PTR_TO_PACKET_END;
1175 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1176 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1177 enum bpf_reg_type which)
1179 /* The register can already have a range from prior markings.
1180 * This is fine as long as it hasn't been advanced from its
1183 return reg->type == which &&
1186 tnum_equals_const(reg->var_off, 0);
1189 /* Reset the min/max bounds of a register */
1190 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1192 reg->smin_value = S64_MIN;
1193 reg->smax_value = S64_MAX;
1194 reg->umin_value = 0;
1195 reg->umax_value = U64_MAX;
1197 reg->s32_min_value = S32_MIN;
1198 reg->s32_max_value = S32_MAX;
1199 reg->u32_min_value = 0;
1200 reg->u32_max_value = U32_MAX;
1203 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1205 reg->smin_value = S64_MIN;
1206 reg->smax_value = S64_MAX;
1207 reg->umin_value = 0;
1208 reg->umax_value = U64_MAX;
1211 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1213 reg->s32_min_value = S32_MIN;
1214 reg->s32_max_value = S32_MAX;
1215 reg->u32_min_value = 0;
1216 reg->u32_max_value = U32_MAX;
1219 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1221 struct tnum var32_off = tnum_subreg(reg->var_off);
1223 /* min signed is max(sign bit) | min(other bits) */
1224 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1225 var32_off.value | (var32_off.mask & S32_MIN));
1226 /* max signed is min(sign bit) | max(other bits) */
1227 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1228 var32_off.value | (var32_off.mask & S32_MAX));
1229 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1230 reg->u32_max_value = min(reg->u32_max_value,
1231 (u32)(var32_off.value | var32_off.mask));
1234 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1236 /* min signed is max(sign bit) | min(other bits) */
1237 reg->smin_value = max_t(s64, reg->smin_value,
1238 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1239 /* max signed is min(sign bit) | max(other bits) */
1240 reg->smax_value = min_t(s64, reg->smax_value,
1241 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1242 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1243 reg->umax_value = min(reg->umax_value,
1244 reg->var_off.value | reg->var_off.mask);
1247 static void __update_reg_bounds(struct bpf_reg_state *reg)
1249 __update_reg32_bounds(reg);
1250 __update_reg64_bounds(reg);
1253 /* Uses signed min/max values to inform unsigned, and vice-versa */
1254 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1256 /* Learn sign from signed bounds.
1257 * If we cannot cross the sign boundary, then signed and unsigned bounds
1258 * are the same, so combine. This works even in the negative case, e.g.
1259 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1261 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1262 reg->s32_min_value = reg->u32_min_value =
1263 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1264 reg->s32_max_value = reg->u32_max_value =
1265 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1268 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1269 * boundary, so we must be careful.
1271 if ((s32)reg->u32_max_value >= 0) {
1272 /* Positive. We can't learn anything from the smin, but smax
1273 * is positive, hence safe.
1275 reg->s32_min_value = reg->u32_min_value;
1276 reg->s32_max_value = reg->u32_max_value =
1277 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1278 } else if ((s32)reg->u32_min_value < 0) {
1279 /* Negative. We can't learn anything from the smax, but smin
1280 * is negative, hence safe.
1282 reg->s32_min_value = reg->u32_min_value =
1283 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1284 reg->s32_max_value = reg->u32_max_value;
1288 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1290 /* Learn sign from signed bounds.
1291 * If we cannot cross the sign boundary, then signed and unsigned bounds
1292 * are the same, so combine. This works even in the negative case, e.g.
1293 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1295 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1296 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1298 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1302 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1303 * boundary, so we must be careful.
1305 if ((s64)reg->umax_value >= 0) {
1306 /* Positive. We can't learn anything from the smin, but smax
1307 * is positive, hence safe.
1309 reg->smin_value = reg->umin_value;
1310 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1312 } else if ((s64)reg->umin_value < 0) {
1313 /* Negative. We can't learn anything from the smax, but smin
1314 * is negative, hence safe.
1316 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1318 reg->smax_value = reg->umax_value;
1322 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1324 __reg32_deduce_bounds(reg);
1325 __reg64_deduce_bounds(reg);
1328 /* Attempts to improve var_off based on unsigned min/max information */
1329 static void __reg_bound_offset(struct bpf_reg_state *reg)
1331 struct tnum var64_off = tnum_intersect(reg->var_off,
1332 tnum_range(reg->umin_value,
1334 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1335 tnum_range(reg->u32_min_value,
1336 reg->u32_max_value));
1338 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1341 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1343 reg->umin_value = reg->u32_min_value;
1344 reg->umax_value = reg->u32_max_value;
1345 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1346 * but must be positive otherwise set to worse case bounds
1347 * and refine later from tnum.
1349 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1350 reg->smax_value = reg->s32_max_value;
1352 reg->smax_value = U32_MAX;
1353 if (reg->s32_min_value >= 0)
1354 reg->smin_value = reg->s32_min_value;
1356 reg->smin_value = 0;
1359 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1361 /* special case when 64-bit register has upper 32-bit register
1362 * zeroed. Typically happens after zext or <<32, >>32 sequence
1363 * allowing us to use 32-bit bounds directly,
1365 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1366 __reg_assign_32_into_64(reg);
1368 /* Otherwise the best we can do is push lower 32bit known and
1369 * unknown bits into register (var_off set from jmp logic)
1370 * then learn as much as possible from the 64-bit tnum
1371 * known and unknown bits. The previous smin/smax bounds are
1372 * invalid here because of jmp32 compare so mark them unknown
1373 * so they do not impact tnum bounds calculation.
1375 __mark_reg64_unbounded(reg);
1376 __update_reg_bounds(reg);
1379 /* Intersecting with the old var_off might have improved our bounds
1380 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1381 * then new var_off is (0; 0x7f...fc) which improves our umax.
1383 __reg_deduce_bounds(reg);
1384 __reg_bound_offset(reg);
1385 __update_reg_bounds(reg);
1388 static bool __reg64_bound_s32(s64 a)
1390 return a > S32_MIN && a < S32_MAX;
1393 static bool __reg64_bound_u32(u64 a)
1395 if (a > U32_MIN && a < U32_MAX)
1400 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1402 __mark_reg32_unbounded(reg);
1404 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1405 reg->s32_min_value = (s32)reg->smin_value;
1406 reg->s32_max_value = (s32)reg->smax_value;
1408 if (__reg64_bound_u32(reg->umin_value))
1409 reg->u32_min_value = (u32)reg->umin_value;
1410 if (__reg64_bound_u32(reg->umax_value))
1411 reg->u32_max_value = (u32)reg->umax_value;
1413 /* Intersecting with the old var_off might have improved our bounds
1414 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1415 * then new var_off is (0; 0x7f...fc) which improves our umax.
1417 __reg_deduce_bounds(reg);
1418 __reg_bound_offset(reg);
1419 __update_reg_bounds(reg);
1422 /* Mark a register as having a completely unknown (scalar) value. */
1423 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1424 struct bpf_reg_state *reg)
1427 * Clear type, id, off, and union(map_ptr, range) and
1428 * padding between 'type' and union
1430 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1431 reg->type = SCALAR_VALUE;
1432 reg->var_off = tnum_unknown;
1434 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1435 __mark_reg_unbounded(reg);
1438 static void mark_reg_unknown(struct bpf_verifier_env *env,
1439 struct bpf_reg_state *regs, u32 regno)
1441 if (WARN_ON(regno >= MAX_BPF_REG)) {
1442 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1443 /* Something bad happened, let's kill all regs except FP */
1444 for (regno = 0; regno < BPF_REG_FP; regno++)
1445 __mark_reg_not_init(env, regs + regno);
1448 __mark_reg_unknown(env, regs + regno);
1451 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1452 struct bpf_reg_state *reg)
1454 __mark_reg_unknown(env, reg);
1455 reg->type = NOT_INIT;
1458 static void mark_reg_not_init(struct bpf_verifier_env *env,
1459 struct bpf_reg_state *regs, u32 regno)
1461 if (WARN_ON(regno >= MAX_BPF_REG)) {
1462 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1463 /* Something bad happened, let's kill all regs except FP */
1464 for (regno = 0; regno < BPF_REG_FP; regno++)
1465 __mark_reg_not_init(env, regs + regno);
1468 __mark_reg_not_init(env, regs + regno);
1471 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1472 struct bpf_reg_state *regs, u32 regno,
1473 enum bpf_reg_type reg_type,
1474 struct btf *btf, u32 btf_id)
1476 if (reg_type == SCALAR_VALUE) {
1477 mark_reg_unknown(env, regs, regno);
1480 mark_reg_known_zero(env, regs, regno);
1481 regs[regno].type = PTR_TO_BTF_ID;
1482 regs[regno].btf = btf;
1483 regs[regno].btf_id = btf_id;
1486 #define DEF_NOT_SUBREG (0)
1487 static void init_reg_state(struct bpf_verifier_env *env,
1488 struct bpf_func_state *state)
1490 struct bpf_reg_state *regs = state->regs;
1493 for (i = 0; i < MAX_BPF_REG; i++) {
1494 mark_reg_not_init(env, regs, i);
1495 regs[i].live = REG_LIVE_NONE;
1496 regs[i].parent = NULL;
1497 regs[i].subreg_def = DEF_NOT_SUBREG;
1501 regs[BPF_REG_FP].type = PTR_TO_STACK;
1502 mark_reg_known_zero(env, regs, BPF_REG_FP);
1503 regs[BPF_REG_FP].frameno = state->frameno;
1506 #define BPF_MAIN_FUNC (-1)
1507 static void init_func_state(struct bpf_verifier_env *env,
1508 struct bpf_func_state *state,
1509 int callsite, int frameno, int subprogno)
1511 state->callsite = callsite;
1512 state->frameno = frameno;
1513 state->subprogno = subprogno;
1514 init_reg_state(env, state);
1518 SRC_OP, /* register is used as source operand */
1519 DST_OP, /* register is used as destination operand */
1520 DST_OP_NO_MARK /* same as above, check only, don't mark */
1523 static int cmp_subprogs(const void *a, const void *b)
1525 return ((struct bpf_subprog_info *)a)->start -
1526 ((struct bpf_subprog_info *)b)->start;
1529 static int find_subprog(struct bpf_verifier_env *env, int off)
1531 struct bpf_subprog_info *p;
1533 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1534 sizeof(env->subprog_info[0]), cmp_subprogs);
1537 return p - env->subprog_info;
1541 static int add_subprog(struct bpf_verifier_env *env, int off)
1543 int insn_cnt = env->prog->len;
1546 if (off >= insn_cnt || off < 0) {
1547 verbose(env, "call to invalid destination\n");
1550 ret = find_subprog(env, off);
1553 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1554 verbose(env, "too many subprograms\n");
1557 env->subprog_info[env->subprog_cnt++].start = off;
1558 sort(env->subprog_info, env->subprog_cnt,
1559 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1560 return env->subprog_cnt - 1;
1563 static int check_subprogs(struct bpf_verifier_env *env)
1565 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1566 struct bpf_subprog_info *subprog = env->subprog_info;
1567 struct bpf_insn *insn = env->prog->insnsi;
1568 int insn_cnt = env->prog->len;
1570 /* Add entry function. */
1571 ret = add_subprog(env, 0);
1575 /* determine subprog starts. The end is one before the next starts */
1576 for (i = 0; i < insn_cnt; i++) {
1577 if (bpf_pseudo_func(insn + i)) {
1578 if (!env->bpf_capable) {
1580 "function pointers are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1583 ret = add_subprog(env, i + insn[i].imm + 1);
1586 /* remember subprog */
1587 insn[i + 1].imm = ret;
1590 if (!bpf_pseudo_call(insn + i))
1592 if (!env->bpf_capable) {
1594 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1597 ret = add_subprog(env, i + insn[i].imm + 1);
1602 /* Add a fake 'exit' subprog which could simplify subprog iteration
1603 * logic. 'subprog_cnt' should not be increased.
1605 subprog[env->subprog_cnt].start = insn_cnt;
1607 if (env->log.level & BPF_LOG_LEVEL2)
1608 for (i = 0; i < env->subprog_cnt; i++)
1609 verbose(env, "func#%d @%d\n", i, subprog[i].start);
1611 /* now check that all jumps are within the same subprog */
1612 subprog_start = subprog[cur_subprog].start;
1613 subprog_end = subprog[cur_subprog + 1].start;
1614 for (i = 0; i < insn_cnt; i++) {
1615 u8 code = insn[i].code;
1617 if (code == (BPF_JMP | BPF_CALL) &&
1618 insn[i].imm == BPF_FUNC_tail_call &&
1619 insn[i].src_reg != BPF_PSEUDO_CALL)
1620 subprog[cur_subprog].has_tail_call = true;
1621 if (BPF_CLASS(code) == BPF_LD &&
1622 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1623 subprog[cur_subprog].has_ld_abs = true;
1624 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1626 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1628 off = i + insn[i].off + 1;
1629 if (off < subprog_start || off >= subprog_end) {
1630 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1634 if (i == subprog_end - 1) {
1635 /* to avoid fall-through from one subprog into another
1636 * the last insn of the subprog should be either exit
1637 * or unconditional jump back
1639 if (code != (BPF_JMP | BPF_EXIT) &&
1640 code != (BPF_JMP | BPF_JA)) {
1641 verbose(env, "last insn is not an exit or jmp\n");
1644 subprog_start = subprog_end;
1646 if (cur_subprog < env->subprog_cnt)
1647 subprog_end = subprog[cur_subprog + 1].start;
1653 /* Parentage chain of this register (or stack slot) should take care of all
1654 * issues like callee-saved registers, stack slot allocation time, etc.
1656 static int mark_reg_read(struct bpf_verifier_env *env,
1657 const struct bpf_reg_state *state,
1658 struct bpf_reg_state *parent, u8 flag)
1660 bool writes = parent == state->parent; /* Observe write marks */
1664 /* if read wasn't screened by an earlier write ... */
1665 if (writes && state->live & REG_LIVE_WRITTEN)
1667 if (parent->live & REG_LIVE_DONE) {
1668 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1669 reg_type_str[parent->type],
1670 parent->var_off.value, parent->off);
1673 /* The first condition is more likely to be true than the
1674 * second, checked it first.
1676 if ((parent->live & REG_LIVE_READ) == flag ||
1677 parent->live & REG_LIVE_READ64)
1678 /* The parentage chain never changes and
1679 * this parent was already marked as LIVE_READ.
1680 * There is no need to keep walking the chain again and
1681 * keep re-marking all parents as LIVE_READ.
1682 * This case happens when the same register is read
1683 * multiple times without writes into it in-between.
1684 * Also, if parent has the stronger REG_LIVE_READ64 set,
1685 * then no need to set the weak REG_LIVE_READ32.
1688 /* ... then we depend on parent's value */
1689 parent->live |= flag;
1690 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1691 if (flag == REG_LIVE_READ64)
1692 parent->live &= ~REG_LIVE_READ32;
1694 parent = state->parent;
1699 if (env->longest_mark_read_walk < cnt)
1700 env->longest_mark_read_walk = cnt;
1704 /* This function is supposed to be used by the following 32-bit optimization
1705 * code only. It returns TRUE if the source or destination register operates
1706 * on 64-bit, otherwise return FALSE.
1708 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1709 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1714 class = BPF_CLASS(code);
1716 if (class == BPF_JMP) {
1717 /* BPF_EXIT for "main" will reach here. Return TRUE
1722 if (op == BPF_CALL) {
1723 /* BPF to BPF call will reach here because of marking
1724 * caller saved clobber with DST_OP_NO_MARK for which we
1725 * don't care the register def because they are anyway
1726 * marked as NOT_INIT already.
1728 if (insn->src_reg == BPF_PSEUDO_CALL)
1730 /* Helper call will reach here because of arg type
1731 * check, conservatively return TRUE.
1740 if (class == BPF_ALU64 || class == BPF_JMP ||
1741 /* BPF_END always use BPF_ALU class. */
1742 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1745 if (class == BPF_ALU || class == BPF_JMP32)
1748 if (class == BPF_LDX) {
1750 return BPF_SIZE(code) == BPF_DW;
1751 /* LDX source must be ptr. */
1755 if (class == BPF_STX) {
1756 /* BPF_STX (including atomic variants) has multiple source
1757 * operands, one of which is a ptr. Check whether the caller is
1760 if (t == SRC_OP && reg->type != SCALAR_VALUE)
1762 return BPF_SIZE(code) == BPF_DW;
1765 if (class == BPF_LD) {
1766 u8 mode = BPF_MODE(code);
1769 if (mode == BPF_IMM)
1772 /* Both LD_IND and LD_ABS return 32-bit data. */
1776 /* Implicit ctx ptr. */
1777 if (regno == BPF_REG_6)
1780 /* Explicit source could be any width. */
1784 if (class == BPF_ST)
1785 /* The only source register for BPF_ST is a ptr. */
1788 /* Conservatively return true at default. */
1792 /* Return the regno defined by the insn, or -1. */
1793 static int insn_def_regno(const struct bpf_insn *insn)
1795 switch (BPF_CLASS(insn->code)) {
1801 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1802 (insn->imm & BPF_FETCH)) {
1803 if (insn->imm == BPF_CMPXCHG)
1806 return insn->src_reg;
1811 return insn->dst_reg;
1815 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1816 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1818 int dst_reg = insn_def_regno(insn);
1823 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
1826 static void mark_insn_zext(struct bpf_verifier_env *env,
1827 struct bpf_reg_state *reg)
1829 s32 def_idx = reg->subreg_def;
1831 if (def_idx == DEF_NOT_SUBREG)
1834 env->insn_aux_data[def_idx - 1].zext_dst = true;
1835 /* The dst will be zero extended, so won't be sub-register anymore. */
1836 reg->subreg_def = DEF_NOT_SUBREG;
1839 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1840 enum reg_arg_type t)
1842 struct bpf_verifier_state *vstate = env->cur_state;
1843 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1844 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1845 struct bpf_reg_state *reg, *regs = state->regs;
1848 if (regno >= MAX_BPF_REG) {
1849 verbose(env, "R%d is invalid\n", regno);
1854 rw64 = is_reg64(env, insn, regno, reg, t);
1856 /* check whether register used as source operand can be read */
1857 if (reg->type == NOT_INIT) {
1858 verbose(env, "R%d !read_ok\n", regno);
1861 /* We don't need to worry about FP liveness because it's read-only */
1862 if (regno == BPF_REG_FP)
1866 mark_insn_zext(env, reg);
1868 return mark_reg_read(env, reg, reg->parent,
1869 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1871 /* check whether register used as dest operand can be written to */
1872 if (regno == BPF_REG_FP) {
1873 verbose(env, "frame pointer is read only\n");
1876 reg->live |= REG_LIVE_WRITTEN;
1877 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1879 mark_reg_unknown(env, regs, regno);
1884 /* for any branch, call, exit record the history of jmps in the given state */
1885 static int push_jmp_history(struct bpf_verifier_env *env,
1886 struct bpf_verifier_state *cur)
1888 u32 cnt = cur->jmp_history_cnt;
1889 struct bpf_idx_pair *p;
1892 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1895 p[cnt - 1].idx = env->insn_idx;
1896 p[cnt - 1].prev_idx = env->prev_insn_idx;
1897 cur->jmp_history = p;
1898 cur->jmp_history_cnt = cnt;
1902 /* Backtrack one insn at a time. If idx is not at the top of recorded
1903 * history then previous instruction came from straight line execution.
1905 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1910 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1911 i = st->jmp_history[cnt - 1].prev_idx;
1919 /* For given verifier state backtrack_insn() is called from the last insn to
1920 * the first insn. Its purpose is to compute a bitmask of registers and
1921 * stack slots that needs precision in the parent verifier state.
1923 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1924 u32 *reg_mask, u64 *stack_mask)
1926 const struct bpf_insn_cbs cbs = {
1927 .cb_print = verbose,
1928 .private_data = env,
1930 struct bpf_insn *insn = env->prog->insnsi + idx;
1931 u8 class = BPF_CLASS(insn->code);
1932 u8 opcode = BPF_OP(insn->code);
1933 u8 mode = BPF_MODE(insn->code);
1934 u32 dreg = 1u << insn->dst_reg;
1935 u32 sreg = 1u << insn->src_reg;
1938 if (insn->code == 0)
1940 if (env->log.level & BPF_LOG_LEVEL) {
1941 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1942 verbose(env, "%d: ", idx);
1943 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1946 if (class == BPF_ALU || class == BPF_ALU64) {
1947 if (!(*reg_mask & dreg))
1949 if (opcode == BPF_MOV) {
1950 if (BPF_SRC(insn->code) == BPF_X) {
1952 * dreg needs precision after this insn
1953 * sreg needs precision before this insn
1959 * dreg needs precision after this insn.
1960 * Corresponding register is already marked
1961 * as precise=true in this verifier state.
1962 * No further markings in parent are necessary
1967 if (BPF_SRC(insn->code) == BPF_X) {
1969 * both dreg and sreg need precision
1974 * dreg still needs precision before this insn
1977 } else if (class == BPF_LDX) {
1978 if (!(*reg_mask & dreg))
1982 /* scalars can only be spilled into stack w/o losing precision.
1983 * Load from any other memory can be zero extended.
1984 * The desire to keep that precision is already indicated
1985 * by 'precise' mark in corresponding register of this state.
1986 * No further tracking necessary.
1988 if (insn->src_reg != BPF_REG_FP)
1990 if (BPF_SIZE(insn->code) != BPF_DW)
1993 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1994 * that [fp - off] slot contains scalar that needs to be
1995 * tracked with precision
1997 spi = (-insn->off - 1) / BPF_REG_SIZE;
1999 verbose(env, "BUG spi %d\n", spi);
2000 WARN_ONCE(1, "verifier backtracking bug");
2003 *stack_mask |= 1ull << spi;
2004 } else if (class == BPF_STX || class == BPF_ST) {
2005 if (*reg_mask & dreg)
2006 /* stx & st shouldn't be using _scalar_ dst_reg
2007 * to access memory. It means backtracking
2008 * encountered a case of pointer subtraction.
2011 /* scalars can only be spilled into stack */
2012 if (insn->dst_reg != BPF_REG_FP)
2014 if (BPF_SIZE(insn->code) != BPF_DW)
2016 spi = (-insn->off - 1) / BPF_REG_SIZE;
2018 verbose(env, "BUG spi %d\n", spi);
2019 WARN_ONCE(1, "verifier backtracking bug");
2022 if (!(*stack_mask & (1ull << spi)))
2024 *stack_mask &= ~(1ull << spi);
2025 if (class == BPF_STX)
2027 } else if (class == BPF_JMP || class == BPF_JMP32) {
2028 if (opcode == BPF_CALL) {
2029 if (insn->src_reg == BPF_PSEUDO_CALL)
2031 /* regular helper call sets R0 */
2033 if (*reg_mask & 0x3f) {
2034 /* if backtracing was looking for registers R1-R5
2035 * they should have been found already.
2037 verbose(env, "BUG regs %x\n", *reg_mask);
2038 WARN_ONCE(1, "verifier backtracking bug");
2041 } else if (opcode == BPF_EXIT) {
2044 } else if (class == BPF_LD) {
2045 if (!(*reg_mask & dreg))
2048 /* It's ld_imm64 or ld_abs or ld_ind.
2049 * For ld_imm64 no further tracking of precision
2050 * into parent is necessary
2052 if (mode == BPF_IND || mode == BPF_ABS)
2053 /* to be analyzed */
2059 /* the scalar precision tracking algorithm:
2060 * . at the start all registers have precise=false.
2061 * . scalar ranges are tracked as normal through alu and jmp insns.
2062 * . once precise value of the scalar register is used in:
2063 * . ptr + scalar alu
2064 * . if (scalar cond K|scalar)
2065 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2066 * backtrack through the verifier states and mark all registers and
2067 * stack slots with spilled constants that these scalar regisers
2068 * should be precise.
2069 * . during state pruning two registers (or spilled stack slots)
2070 * are equivalent if both are not precise.
2072 * Note the verifier cannot simply walk register parentage chain,
2073 * since many different registers and stack slots could have been
2074 * used to compute single precise scalar.
2076 * The approach of starting with precise=true for all registers and then
2077 * backtrack to mark a register as not precise when the verifier detects
2078 * that program doesn't care about specific value (e.g., when helper
2079 * takes register as ARG_ANYTHING parameter) is not safe.
2081 * It's ok to walk single parentage chain of the verifier states.
2082 * It's possible that this backtracking will go all the way till 1st insn.
2083 * All other branches will be explored for needing precision later.
2085 * The backtracking needs to deal with cases like:
2086 * 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)
2089 * if r5 > 0x79f goto pc+7
2090 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2093 * call bpf_perf_event_output#25
2094 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2098 * call foo // uses callee's r6 inside to compute r0
2102 * to track above reg_mask/stack_mask needs to be independent for each frame.
2104 * Also if parent's curframe > frame where backtracking started,
2105 * the verifier need to mark registers in both frames, otherwise callees
2106 * may incorrectly prune callers. This is similar to
2107 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2109 * For now backtracking falls back into conservative marking.
2111 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2112 struct bpf_verifier_state *st)
2114 struct bpf_func_state *func;
2115 struct bpf_reg_state *reg;
2118 /* big hammer: mark all scalars precise in this path.
2119 * pop_stack may still get !precise scalars.
2121 for (; st; st = st->parent)
2122 for (i = 0; i <= st->curframe; i++) {
2123 func = st->frame[i];
2124 for (j = 0; j < BPF_REG_FP; j++) {
2125 reg = &func->regs[j];
2126 if (reg->type != SCALAR_VALUE)
2128 reg->precise = true;
2130 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2131 if (func->stack[j].slot_type[0] != STACK_SPILL)
2133 reg = &func->stack[j].spilled_ptr;
2134 if (reg->type != SCALAR_VALUE)
2136 reg->precise = true;
2141 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2144 struct bpf_verifier_state *st = env->cur_state;
2145 int first_idx = st->first_insn_idx;
2146 int last_idx = env->insn_idx;
2147 struct bpf_func_state *func;
2148 struct bpf_reg_state *reg;
2149 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2150 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2151 bool skip_first = true;
2152 bool new_marks = false;
2155 if (!env->bpf_capable)
2158 func = st->frame[st->curframe];
2160 reg = &func->regs[regno];
2161 if (reg->type != SCALAR_VALUE) {
2162 WARN_ONCE(1, "backtracing misuse");
2169 reg->precise = true;
2173 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2177 reg = &func->stack[spi].spilled_ptr;
2178 if (reg->type != SCALAR_VALUE) {
2186 reg->precise = true;
2192 if (!reg_mask && !stack_mask)
2195 DECLARE_BITMAP(mask, 64);
2196 u32 history = st->jmp_history_cnt;
2198 if (env->log.level & BPF_LOG_LEVEL)
2199 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2200 for (i = last_idx;;) {
2205 err = backtrack_insn(env, i, ®_mask, &stack_mask);
2207 if (err == -ENOTSUPP) {
2208 mark_all_scalars_precise(env, st);
2213 if (!reg_mask && !stack_mask)
2214 /* Found assignment(s) into tracked register in this state.
2215 * Since this state is already marked, just return.
2216 * Nothing to be tracked further in the parent state.
2221 i = get_prev_insn_idx(st, i, &history);
2222 if (i >= env->prog->len) {
2223 /* This can happen if backtracking reached insn 0
2224 * and there are still reg_mask or stack_mask
2226 * It means the backtracking missed the spot where
2227 * particular register was initialized with a constant.
2229 verbose(env, "BUG backtracking idx %d\n", i);
2230 WARN_ONCE(1, "verifier backtracking bug");
2239 func = st->frame[st->curframe];
2240 bitmap_from_u64(mask, reg_mask);
2241 for_each_set_bit(i, mask, 32) {
2242 reg = &func->regs[i];
2243 if (reg->type != SCALAR_VALUE) {
2244 reg_mask &= ~(1u << i);
2249 reg->precise = true;
2252 bitmap_from_u64(mask, stack_mask);
2253 for_each_set_bit(i, mask, 64) {
2254 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2255 /* the sequence of instructions:
2257 * 3: (7b) *(u64 *)(r3 -8) = r0
2258 * 4: (79) r4 = *(u64 *)(r10 -8)
2259 * doesn't contain jmps. It's backtracked
2260 * as a single block.
2261 * During backtracking insn 3 is not recognized as
2262 * stack access, so at the end of backtracking
2263 * stack slot fp-8 is still marked in stack_mask.
2264 * However the parent state may not have accessed
2265 * fp-8 and it's "unallocated" stack space.
2266 * In such case fallback to conservative.
2268 mark_all_scalars_precise(env, st);
2272 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2273 stack_mask &= ~(1ull << i);
2276 reg = &func->stack[i].spilled_ptr;
2277 if (reg->type != SCALAR_VALUE) {
2278 stack_mask &= ~(1ull << i);
2283 reg->precise = true;
2285 if (env->log.level & BPF_LOG_LEVEL) {
2286 print_verifier_state(env, func);
2287 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2288 new_marks ? "didn't have" : "already had",
2289 reg_mask, stack_mask);
2292 if (!reg_mask && !stack_mask)
2297 last_idx = st->last_insn_idx;
2298 first_idx = st->first_insn_idx;
2303 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2305 return __mark_chain_precision(env, regno, -1);
2308 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2310 return __mark_chain_precision(env, -1, spi);
2313 static bool is_spillable_regtype(enum bpf_reg_type type)
2316 case PTR_TO_MAP_VALUE:
2317 case PTR_TO_MAP_VALUE_OR_NULL:
2321 case PTR_TO_PACKET_META:
2322 case PTR_TO_PACKET_END:
2323 case PTR_TO_FLOW_KEYS:
2324 case CONST_PTR_TO_MAP:
2326 case PTR_TO_SOCKET_OR_NULL:
2327 case PTR_TO_SOCK_COMMON:
2328 case PTR_TO_SOCK_COMMON_OR_NULL:
2329 case PTR_TO_TCP_SOCK:
2330 case PTR_TO_TCP_SOCK_OR_NULL:
2331 case PTR_TO_XDP_SOCK:
2333 case PTR_TO_BTF_ID_OR_NULL:
2334 case PTR_TO_RDONLY_BUF:
2335 case PTR_TO_RDONLY_BUF_OR_NULL:
2336 case PTR_TO_RDWR_BUF:
2337 case PTR_TO_RDWR_BUF_OR_NULL:
2338 case PTR_TO_PERCPU_BTF_ID:
2340 case PTR_TO_MEM_OR_NULL:
2342 case PTR_TO_MAP_KEY:
2349 /* Does this register contain a constant zero? */
2350 static bool register_is_null(struct bpf_reg_state *reg)
2352 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2355 static bool register_is_const(struct bpf_reg_state *reg)
2357 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2360 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2362 return tnum_is_unknown(reg->var_off) &&
2363 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2364 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2365 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2366 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2369 static bool register_is_bounded(struct bpf_reg_state *reg)
2371 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2374 static bool __is_pointer_value(bool allow_ptr_leaks,
2375 const struct bpf_reg_state *reg)
2377 if (allow_ptr_leaks)
2380 return reg->type != SCALAR_VALUE;
2383 static void save_register_state(struct bpf_func_state *state,
2384 int spi, struct bpf_reg_state *reg)
2388 state->stack[spi].spilled_ptr = *reg;
2389 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2391 for (i = 0; i < BPF_REG_SIZE; i++)
2392 state->stack[spi].slot_type[i] = STACK_SPILL;
2395 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2396 * stack boundary and alignment are checked in check_mem_access()
2398 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2399 /* stack frame we're writing to */
2400 struct bpf_func_state *state,
2401 int off, int size, int value_regno,
2404 struct bpf_func_state *cur; /* state of the current function */
2405 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2406 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2407 struct bpf_reg_state *reg = NULL;
2409 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2410 state->acquired_refs, true);
2413 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2414 * so it's aligned access and [off, off + size) are within stack limits
2416 if (!env->allow_ptr_leaks &&
2417 state->stack[spi].slot_type[0] == STACK_SPILL &&
2418 size != BPF_REG_SIZE) {
2419 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2423 cur = env->cur_state->frame[env->cur_state->curframe];
2424 if (value_regno >= 0)
2425 reg = &cur->regs[value_regno];
2427 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2428 !register_is_null(reg) && env->bpf_capable) {
2429 if (dst_reg != BPF_REG_FP) {
2430 /* The backtracking logic can only recognize explicit
2431 * stack slot address like [fp - 8]. Other spill of
2432 * scalar via different register has to be conervative.
2433 * Backtrack from here and mark all registers as precise
2434 * that contributed into 'reg' being a constant.
2436 err = mark_chain_precision(env, value_regno);
2440 save_register_state(state, spi, reg);
2441 } else if (reg && is_spillable_regtype(reg->type)) {
2442 /* register containing pointer is being spilled into stack */
2443 if (size != BPF_REG_SIZE) {
2444 verbose_linfo(env, insn_idx, "; ");
2445 verbose(env, "invalid size of register spill\n");
2449 if (state != cur && reg->type == PTR_TO_STACK) {
2450 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2454 if (!env->bypass_spec_v4) {
2455 bool sanitize = false;
2457 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2458 register_is_const(&state->stack[spi].spilled_ptr))
2460 for (i = 0; i < BPF_REG_SIZE; i++)
2461 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2466 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2467 int soff = (-spi - 1) * BPF_REG_SIZE;
2469 /* detected reuse of integer stack slot with a pointer
2470 * which means either llvm is reusing stack slot or
2471 * an attacker is trying to exploit CVE-2018-3639
2472 * (speculative store bypass)
2473 * Have to sanitize that slot with preemptive
2476 if (*poff && *poff != soff) {
2477 /* disallow programs where single insn stores
2478 * into two different stack slots, since verifier
2479 * cannot sanitize them
2482 "insn %d cannot access two stack slots fp%d and fp%d",
2483 insn_idx, *poff, soff);
2489 save_register_state(state, spi, reg);
2491 u8 type = STACK_MISC;
2493 /* regular write of data into stack destroys any spilled ptr */
2494 state->stack[spi].spilled_ptr.type = NOT_INIT;
2495 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2496 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2497 for (i = 0; i < BPF_REG_SIZE; i++)
2498 state->stack[spi].slot_type[i] = STACK_MISC;
2500 /* only mark the slot as written if all 8 bytes were written
2501 * otherwise read propagation may incorrectly stop too soon
2502 * when stack slots are partially written.
2503 * This heuristic means that read propagation will be
2504 * conservative, since it will add reg_live_read marks
2505 * to stack slots all the way to first state when programs
2506 * writes+reads less than 8 bytes
2508 if (size == BPF_REG_SIZE)
2509 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2511 /* when we zero initialize stack slots mark them as such */
2512 if (reg && register_is_null(reg)) {
2513 /* backtracking doesn't work for STACK_ZERO yet. */
2514 err = mark_chain_precision(env, value_regno);
2520 /* Mark slots affected by this stack write. */
2521 for (i = 0; i < size; i++)
2522 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2528 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2529 * known to contain a variable offset.
2530 * This function checks whether the write is permitted and conservatively
2531 * tracks the effects of the write, considering that each stack slot in the
2532 * dynamic range is potentially written to.
2534 * 'off' includes 'regno->off'.
2535 * 'value_regno' can be -1, meaning that an unknown value is being written to
2538 * Spilled pointers in range are not marked as written because we don't know
2539 * what's going to be actually written. This means that read propagation for
2540 * future reads cannot be terminated by this write.
2542 * For privileged programs, uninitialized stack slots are considered
2543 * initialized by this write (even though we don't know exactly what offsets
2544 * are going to be written to). The idea is that we don't want the verifier to
2545 * reject future reads that access slots written to through variable offsets.
2547 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2548 /* func where register points to */
2549 struct bpf_func_state *state,
2550 int ptr_regno, int off, int size,
2551 int value_regno, int insn_idx)
2553 struct bpf_func_state *cur; /* state of the current function */
2554 int min_off, max_off;
2556 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2557 bool writing_zero = false;
2558 /* set if the fact that we're writing a zero is used to let any
2559 * stack slots remain STACK_ZERO
2561 bool zero_used = false;
2563 cur = env->cur_state->frame[env->cur_state->curframe];
2564 ptr_reg = &cur->regs[ptr_regno];
2565 min_off = ptr_reg->smin_value + off;
2566 max_off = ptr_reg->smax_value + off + size;
2567 if (value_regno >= 0)
2568 value_reg = &cur->regs[value_regno];
2569 if (value_reg && register_is_null(value_reg))
2570 writing_zero = true;
2572 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2573 state->acquired_refs, true);
2578 /* Variable offset writes destroy any spilled pointers in range. */
2579 for (i = min_off; i < max_off; i++) {
2580 u8 new_type, *stype;
2584 spi = slot / BPF_REG_SIZE;
2585 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2587 if (!env->allow_ptr_leaks
2588 && *stype != NOT_INIT
2589 && *stype != SCALAR_VALUE) {
2590 /* Reject the write if there's are spilled pointers in
2591 * range. If we didn't reject here, the ptr status
2592 * would be erased below (even though not all slots are
2593 * actually overwritten), possibly opening the door to
2596 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2601 /* Erase all spilled pointers. */
2602 state->stack[spi].spilled_ptr.type = NOT_INIT;
2604 /* Update the slot type. */
2605 new_type = STACK_MISC;
2606 if (writing_zero && *stype == STACK_ZERO) {
2607 new_type = STACK_ZERO;
2610 /* If the slot is STACK_INVALID, we check whether it's OK to
2611 * pretend that it will be initialized by this write. The slot
2612 * might not actually be written to, and so if we mark it as
2613 * initialized future reads might leak uninitialized memory.
2614 * For privileged programs, we will accept such reads to slots
2615 * that may or may not be written because, if we're reject
2616 * them, the error would be too confusing.
2618 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2619 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2626 /* backtracking doesn't work for STACK_ZERO yet. */
2627 err = mark_chain_precision(env, value_regno);
2634 /* When register 'dst_regno' is assigned some values from stack[min_off,
2635 * max_off), we set the register's type according to the types of the
2636 * respective stack slots. If all the stack values are known to be zeros, then
2637 * so is the destination reg. Otherwise, the register is considered to be
2638 * SCALAR. This function does not deal with register filling; the caller must
2639 * ensure that all spilled registers in the stack range have been marked as
2642 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2643 /* func where src register points to */
2644 struct bpf_func_state *ptr_state,
2645 int min_off, int max_off, int dst_regno)
2647 struct bpf_verifier_state *vstate = env->cur_state;
2648 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2653 for (i = min_off; i < max_off; i++) {
2655 spi = slot / BPF_REG_SIZE;
2656 stype = ptr_state->stack[spi].slot_type;
2657 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2661 if (zeros == max_off - min_off) {
2662 /* any access_size read into register is zero extended,
2663 * so the whole register == const_zero
2665 __mark_reg_const_zero(&state->regs[dst_regno]);
2666 /* backtracking doesn't support STACK_ZERO yet,
2667 * so mark it precise here, so that later
2668 * backtracking can stop here.
2669 * Backtracking may not need this if this register
2670 * doesn't participate in pointer adjustment.
2671 * Forward propagation of precise flag is not
2672 * necessary either. This mark is only to stop
2673 * backtracking. Any register that contributed
2674 * to const 0 was marked precise before spill.
2676 state->regs[dst_regno].precise = true;
2678 /* have read misc data from the stack */
2679 mark_reg_unknown(env, state->regs, dst_regno);
2681 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2684 /* Read the stack at 'off' and put the results into the register indicated by
2685 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2688 * 'dst_regno' can be -1, meaning that the read value is not going to a
2691 * The access is assumed to be within the current stack bounds.
2693 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2694 /* func where src register points to */
2695 struct bpf_func_state *reg_state,
2696 int off, int size, int dst_regno)
2698 struct bpf_verifier_state *vstate = env->cur_state;
2699 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2700 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2701 struct bpf_reg_state *reg;
2704 stype = reg_state->stack[spi].slot_type;
2705 reg = ®_state->stack[spi].spilled_ptr;
2707 if (stype[0] == STACK_SPILL) {
2708 if (size != BPF_REG_SIZE) {
2709 if (reg->type != SCALAR_VALUE) {
2710 verbose_linfo(env, env->insn_idx, "; ");
2711 verbose(env, "invalid size of register fill\n");
2714 if (dst_regno >= 0) {
2715 mark_reg_unknown(env, state->regs, dst_regno);
2716 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2718 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2721 for (i = 1; i < BPF_REG_SIZE; i++) {
2722 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2723 verbose(env, "corrupted spill memory\n");
2728 if (dst_regno >= 0) {
2729 /* restore register state from stack */
2730 state->regs[dst_regno] = *reg;
2731 /* mark reg as written since spilled pointer state likely
2732 * has its liveness marks cleared by is_state_visited()
2733 * which resets stack/reg liveness for state transitions
2735 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2736 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2737 /* If dst_regno==-1, the caller is asking us whether
2738 * it is acceptable to use this value as a SCALAR_VALUE
2740 * We must not allow unprivileged callers to do that
2741 * with spilled pointers.
2743 verbose(env, "leaking pointer from stack off %d\n",
2747 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2751 for (i = 0; i < size; i++) {
2752 type = stype[(slot - i) % BPF_REG_SIZE];
2753 if (type == STACK_MISC)
2755 if (type == STACK_ZERO)
2757 verbose(env, "invalid read from stack off %d+%d size %d\n",
2761 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2763 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2768 enum stack_access_src {
2769 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2770 ACCESS_HELPER = 2, /* the access is performed by a helper */
2773 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2774 int regno, int off, int access_size,
2775 bool zero_size_allowed,
2776 enum stack_access_src type,
2777 struct bpf_call_arg_meta *meta);
2779 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2781 return cur_regs(env) + regno;
2784 /* Read the stack at 'ptr_regno + off' and put the result into the register
2786 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2787 * but not its variable offset.
2788 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2790 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2791 * filling registers (i.e. reads of spilled register cannot be detected when
2792 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2793 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2794 * offset; for a fixed offset check_stack_read_fixed_off should be used
2797 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2798 int ptr_regno, int off, int size, int dst_regno)
2800 /* The state of the source register. */
2801 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2802 struct bpf_func_state *ptr_state = func(env, reg);
2804 int min_off, max_off;
2806 /* Note that we pass a NULL meta, so raw access will not be permitted.
2808 err = check_stack_range_initialized(env, ptr_regno, off, size,
2809 false, ACCESS_DIRECT, NULL);
2813 min_off = reg->smin_value + off;
2814 max_off = reg->smax_value + off;
2815 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2819 /* check_stack_read dispatches to check_stack_read_fixed_off or
2820 * check_stack_read_var_off.
2822 * The caller must ensure that the offset falls within the allocated stack
2825 * 'dst_regno' is a register which will receive the value from the stack. It
2826 * can be -1, meaning that the read value is not going to a register.
2828 static int check_stack_read(struct bpf_verifier_env *env,
2829 int ptr_regno, int off, int size,
2832 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2833 struct bpf_func_state *state = func(env, reg);
2835 /* Some accesses are only permitted with a static offset. */
2836 bool var_off = !tnum_is_const(reg->var_off);
2838 /* The offset is required to be static when reads don't go to a
2839 * register, in order to not leak pointers (see
2840 * check_stack_read_fixed_off).
2842 if (dst_regno < 0 && var_off) {
2845 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2846 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2850 /* Variable offset is prohibited for unprivileged mode for simplicity
2851 * since it requires corresponding support in Spectre masking for stack
2852 * ALU. See also retrieve_ptr_limit().
2854 if (!env->bypass_spec_v1 && var_off) {
2857 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2858 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2864 off += reg->var_off.value;
2865 err = check_stack_read_fixed_off(env, state, off, size,
2868 /* Variable offset stack reads need more conservative handling
2869 * than fixed offset ones. Note that dst_regno >= 0 on this
2872 err = check_stack_read_var_off(env, ptr_regno, off, size,
2879 /* check_stack_write dispatches to check_stack_write_fixed_off or
2880 * check_stack_write_var_off.
2882 * 'ptr_regno' is the register used as a pointer into the stack.
2883 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2884 * 'value_regno' is the register whose value we're writing to the stack. It can
2885 * be -1, meaning that we're not writing from a register.
2887 * The caller must ensure that the offset falls within the maximum stack size.
2889 static int check_stack_write(struct bpf_verifier_env *env,
2890 int ptr_regno, int off, int size,
2891 int value_regno, int insn_idx)
2893 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2894 struct bpf_func_state *state = func(env, reg);
2897 if (tnum_is_const(reg->var_off)) {
2898 off += reg->var_off.value;
2899 err = check_stack_write_fixed_off(env, state, off, size,
2900 value_regno, insn_idx);
2902 /* Variable offset stack reads need more conservative handling
2903 * than fixed offset ones.
2905 err = check_stack_write_var_off(env, state,
2906 ptr_regno, off, size,
2907 value_regno, insn_idx);
2912 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2913 int off, int size, enum bpf_access_type type)
2915 struct bpf_reg_state *regs = cur_regs(env);
2916 struct bpf_map *map = regs[regno].map_ptr;
2917 u32 cap = bpf_map_flags_to_cap(map);
2919 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2920 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2921 map->value_size, off, size);
2925 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2926 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2927 map->value_size, off, size);
2934 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2935 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2936 int off, int size, u32 mem_size,
2937 bool zero_size_allowed)
2939 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2940 struct bpf_reg_state *reg;
2942 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2945 reg = &cur_regs(env)[regno];
2946 switch (reg->type) {
2947 case PTR_TO_MAP_KEY:
2948 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
2949 mem_size, off, size);
2951 case PTR_TO_MAP_VALUE:
2952 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2953 mem_size, off, size);
2956 case PTR_TO_PACKET_META:
2957 case PTR_TO_PACKET_END:
2958 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2959 off, size, regno, reg->id, off, mem_size);
2963 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2964 mem_size, off, size);
2970 /* check read/write into a memory region with possible variable offset */
2971 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2972 int off, int size, u32 mem_size,
2973 bool zero_size_allowed)
2975 struct bpf_verifier_state *vstate = env->cur_state;
2976 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2977 struct bpf_reg_state *reg = &state->regs[regno];
2980 /* We may have adjusted the register pointing to memory region, so we
2981 * need to try adding each of min_value and max_value to off
2982 * to make sure our theoretical access will be safe.
2984 if (env->log.level & BPF_LOG_LEVEL)
2985 print_verifier_state(env, state);
2987 /* The minimum value is only important with signed
2988 * comparisons where we can't assume the floor of a
2989 * value is 0. If we are using signed variables for our
2990 * index'es we need to make sure that whatever we use
2991 * will have a set floor within our range.
2993 if (reg->smin_value < 0 &&
2994 (reg->smin_value == S64_MIN ||
2995 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2996 reg->smin_value + off < 0)) {
2997 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3001 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3002 mem_size, zero_size_allowed);
3004 verbose(env, "R%d min value is outside of the allowed memory range\n",
3009 /* If we haven't set a max value then we need to bail since we can't be
3010 * sure we won't do bad things.
3011 * If reg->umax_value + off could overflow, treat that as unbounded too.
3013 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3014 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3018 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3019 mem_size, zero_size_allowed);
3021 verbose(env, "R%d max value is outside of the allowed memory range\n",
3029 /* check read/write into a map element with possible variable offset */
3030 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3031 int off, int size, bool zero_size_allowed)
3033 struct bpf_verifier_state *vstate = env->cur_state;
3034 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3035 struct bpf_reg_state *reg = &state->regs[regno];
3036 struct bpf_map *map = reg->map_ptr;
3039 err = check_mem_region_access(env, regno, off, size, map->value_size,
3044 if (map_value_has_spin_lock(map)) {
3045 u32 lock = map->spin_lock_off;
3047 /* if any part of struct bpf_spin_lock can be touched by
3048 * load/store reject this program.
3049 * To check that [x1, x2) overlaps with [y1, y2)
3050 * it is sufficient to check x1 < y2 && y1 < x2.
3052 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3053 lock < reg->umax_value + off + size) {
3054 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3061 #define MAX_PACKET_OFF 0xffff
3063 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3065 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3068 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3069 const struct bpf_call_arg_meta *meta,
3070 enum bpf_access_type t)
3072 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3074 switch (prog_type) {
3075 /* Program types only with direct read access go here! */
3076 case BPF_PROG_TYPE_LWT_IN:
3077 case BPF_PROG_TYPE_LWT_OUT:
3078 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3079 case BPF_PROG_TYPE_SK_REUSEPORT:
3080 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3081 case BPF_PROG_TYPE_CGROUP_SKB:
3086 /* Program types with direct read + write access go here! */
3087 case BPF_PROG_TYPE_SCHED_CLS:
3088 case BPF_PROG_TYPE_SCHED_ACT:
3089 case BPF_PROG_TYPE_XDP:
3090 case BPF_PROG_TYPE_LWT_XMIT:
3091 case BPF_PROG_TYPE_SK_SKB:
3092 case BPF_PROG_TYPE_SK_MSG:
3094 return meta->pkt_access;
3096 env->seen_direct_write = true;
3099 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3101 env->seen_direct_write = true;
3110 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3111 int size, bool zero_size_allowed)
3113 struct bpf_reg_state *regs = cur_regs(env);
3114 struct bpf_reg_state *reg = ®s[regno];
3117 /* We may have added a variable offset to the packet pointer; but any
3118 * reg->range we have comes after that. We are only checking the fixed
3122 /* We don't allow negative numbers, because we aren't tracking enough
3123 * detail to prove they're safe.
3125 if (reg->smin_value < 0) {
3126 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3131 err = reg->range < 0 ? -EINVAL :
3132 __check_mem_access(env, regno, off, size, reg->range,
3135 verbose(env, "R%d offset is outside of the packet\n", regno);
3139 /* __check_mem_access has made sure "off + size - 1" is within u16.
3140 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3141 * otherwise find_good_pkt_pointers would have refused to set range info
3142 * that __check_mem_access would have rejected this pkt access.
3143 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3145 env->prog->aux->max_pkt_offset =
3146 max_t(u32, env->prog->aux->max_pkt_offset,
3147 off + reg->umax_value + size - 1);
3152 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
3153 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3154 enum bpf_access_type t, enum bpf_reg_type *reg_type,
3155 struct btf **btf, u32 *btf_id)
3157 struct bpf_insn_access_aux info = {
3158 .reg_type = *reg_type,
3162 if (env->ops->is_valid_access &&
3163 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3164 /* A non zero info.ctx_field_size indicates that this field is a
3165 * candidate for later verifier transformation to load the whole
3166 * field and then apply a mask when accessed with a narrower
3167 * access than actual ctx access size. A zero info.ctx_field_size
3168 * will only allow for whole field access and rejects any other
3169 * type of narrower access.
3171 *reg_type = info.reg_type;
3173 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3175 *btf_id = info.btf_id;
3177 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3179 /* remember the offset of last byte accessed in ctx */
3180 if (env->prog->aux->max_ctx_offset < off + size)
3181 env->prog->aux->max_ctx_offset = off + size;
3185 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3189 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3192 if (size < 0 || off < 0 ||
3193 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3194 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3201 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3202 u32 regno, int off, int size,
3203 enum bpf_access_type t)
3205 struct bpf_reg_state *regs = cur_regs(env);
3206 struct bpf_reg_state *reg = ®s[regno];
3207 struct bpf_insn_access_aux info = {};
3210 if (reg->smin_value < 0) {
3211 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3216 switch (reg->type) {
3217 case PTR_TO_SOCK_COMMON:
3218 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3221 valid = bpf_sock_is_valid_access(off, size, t, &info);
3223 case PTR_TO_TCP_SOCK:
3224 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3226 case PTR_TO_XDP_SOCK:
3227 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3235 env->insn_aux_data[insn_idx].ctx_field_size =
3236 info.ctx_field_size;
3240 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3241 regno, reg_type_str[reg->type], off, size);
3246 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3248 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3251 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3253 const struct bpf_reg_state *reg = reg_state(env, regno);
3255 return reg->type == PTR_TO_CTX;
3258 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3260 const struct bpf_reg_state *reg = reg_state(env, regno);
3262 return type_is_sk_pointer(reg->type);
3265 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3267 const struct bpf_reg_state *reg = reg_state(env, regno);
3269 return type_is_pkt_pointer(reg->type);
3272 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3274 const struct bpf_reg_state *reg = reg_state(env, regno);
3276 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3277 return reg->type == PTR_TO_FLOW_KEYS;
3280 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3281 const struct bpf_reg_state *reg,
3282 int off, int size, bool strict)
3284 struct tnum reg_off;
3287 /* Byte size accesses are always allowed. */
3288 if (!strict || size == 1)
3291 /* For platforms that do not have a Kconfig enabling
3292 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3293 * NET_IP_ALIGN is universally set to '2'. And on platforms
3294 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3295 * to this code only in strict mode where we want to emulate
3296 * the NET_IP_ALIGN==2 checking. Therefore use an
3297 * unconditional IP align value of '2'.
3301 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3302 if (!tnum_is_aligned(reg_off, size)) {
3305 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3307 "misaligned packet access off %d+%s+%d+%d size %d\n",
3308 ip_align, tn_buf, reg->off, off, size);
3315 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3316 const struct bpf_reg_state *reg,
3317 const char *pointer_desc,
3318 int off, int size, bool strict)
3320 struct tnum reg_off;
3322 /* Byte size accesses are always allowed. */
3323 if (!strict || size == 1)
3326 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3327 if (!tnum_is_aligned(reg_off, size)) {
3330 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3331 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3332 pointer_desc, tn_buf, reg->off, off, size);
3339 static int check_ptr_alignment(struct bpf_verifier_env *env,
3340 const struct bpf_reg_state *reg, int off,
3341 int size, bool strict_alignment_once)
3343 bool strict = env->strict_alignment || strict_alignment_once;
3344 const char *pointer_desc = "";
3346 switch (reg->type) {
3348 case PTR_TO_PACKET_META:
3349 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3350 * right in front, treat it the very same way.
3352 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3353 case PTR_TO_FLOW_KEYS:
3354 pointer_desc = "flow keys ";
3356 case PTR_TO_MAP_KEY:
3357 pointer_desc = "key ";
3359 case PTR_TO_MAP_VALUE:
3360 pointer_desc = "value ";
3363 pointer_desc = "context ";
3366 pointer_desc = "stack ";
3367 /* The stack spill tracking logic in check_stack_write_fixed_off()
3368 * and check_stack_read_fixed_off() relies on stack accesses being
3374 pointer_desc = "sock ";
3376 case PTR_TO_SOCK_COMMON:
3377 pointer_desc = "sock_common ";
3379 case PTR_TO_TCP_SOCK:
3380 pointer_desc = "tcp_sock ";
3382 case PTR_TO_XDP_SOCK:
3383 pointer_desc = "xdp_sock ";
3388 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3392 static int update_stack_depth(struct bpf_verifier_env *env,
3393 const struct bpf_func_state *func,
3396 u16 stack = env->subprog_info[func->subprogno].stack_depth;
3401 /* update known max for given subprogram */
3402 env->subprog_info[func->subprogno].stack_depth = -off;
3406 /* starting from main bpf function walk all instructions of the function
3407 * and recursively walk all callees that given function can call.
3408 * Ignore jump and exit insns.
3409 * Since recursion is prevented by check_cfg() this algorithm
3410 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3412 static int check_max_stack_depth(struct bpf_verifier_env *env)
3414 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3415 struct bpf_subprog_info *subprog = env->subprog_info;
3416 struct bpf_insn *insn = env->prog->insnsi;
3417 bool tail_call_reachable = false;
3418 int ret_insn[MAX_CALL_FRAMES];
3419 int ret_prog[MAX_CALL_FRAMES];
3423 /* protect against potential stack overflow that might happen when
3424 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3425 * depth for such case down to 256 so that the worst case scenario
3426 * would result in 8k stack size (32 which is tailcall limit * 256 =
3429 * To get the idea what might happen, see an example:
3430 * func1 -> sub rsp, 128
3431 * subfunc1 -> sub rsp, 256
3432 * tailcall1 -> add rsp, 256
3433 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3434 * subfunc2 -> sub rsp, 64
3435 * subfunc22 -> sub rsp, 128
3436 * tailcall2 -> add rsp, 128
3437 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3439 * tailcall will unwind the current stack frame but it will not get rid
3440 * of caller's stack as shown on the example above.
3442 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3444 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3448 /* round up to 32-bytes, since this is granularity
3449 * of interpreter stack size
3451 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3452 if (depth > MAX_BPF_STACK) {
3453 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3458 subprog_end = subprog[idx + 1].start;
3459 for (; i < subprog_end; i++) {
3460 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3462 /* remember insn and function to return to */
3463 ret_insn[frame] = i + 1;
3464 ret_prog[frame] = idx;
3466 /* find the callee */
3467 i = i + insn[i].imm + 1;
3468 idx = find_subprog(env, i);
3470 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3475 if (subprog[idx].has_tail_call)
3476 tail_call_reachable = true;
3479 if (frame >= MAX_CALL_FRAMES) {
3480 verbose(env, "the call stack of %d frames is too deep !\n",
3486 /* if tail call got detected across bpf2bpf calls then mark each of the
3487 * currently present subprog frames as tail call reachable subprogs;
3488 * this info will be utilized by JIT so that we will be preserving the
3489 * tail call counter throughout bpf2bpf calls combined with tailcalls
3491 if (tail_call_reachable)
3492 for (j = 0; j < frame; j++)
3493 subprog[ret_prog[j]].tail_call_reachable = true;
3495 /* end of for() loop means the last insn of the 'subprog'
3496 * was reached. Doesn't matter whether it was JA or EXIT
3500 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3502 i = ret_insn[frame];
3503 idx = ret_prog[frame];
3507 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3508 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3509 const struct bpf_insn *insn, int idx)
3511 int start = idx + insn->imm + 1, subprog;
3513 subprog = find_subprog(env, start);
3515 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3519 return env->subprog_info[subprog].stack_depth;
3523 int check_ctx_reg(struct bpf_verifier_env *env,
3524 const struct bpf_reg_state *reg, int regno)
3526 /* Access to ctx or passing it to a helper is only allowed in
3527 * its original, unmodified form.
3531 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3536 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3539 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3540 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3547 static int __check_buffer_access(struct bpf_verifier_env *env,
3548 const char *buf_info,
3549 const struct bpf_reg_state *reg,
3550 int regno, int off, int size)
3554 "R%d invalid %s buffer access: off=%d, size=%d\n",
3555 regno, buf_info, off, size);
3558 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3561 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3563 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3564 regno, off, tn_buf);
3571 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3572 const struct bpf_reg_state *reg,
3573 int regno, int off, int size)
3577 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3581 if (off + size > env->prog->aux->max_tp_access)
3582 env->prog->aux->max_tp_access = off + size;
3587 static int check_buffer_access(struct bpf_verifier_env *env,
3588 const struct bpf_reg_state *reg,
3589 int regno, int off, int size,
3590 bool zero_size_allowed,
3591 const char *buf_info,
3596 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3600 if (off + size > *max_access)
3601 *max_access = off + size;
3606 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3607 static void zext_32_to_64(struct bpf_reg_state *reg)
3609 reg->var_off = tnum_subreg(reg->var_off);
3610 __reg_assign_32_into_64(reg);
3613 /* truncate register to smaller size (in bytes)
3614 * must be called with size < BPF_REG_SIZE
3616 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3620 /* clear high bits in bit representation */
3621 reg->var_off = tnum_cast(reg->var_off, size);
3623 /* fix arithmetic bounds */
3624 mask = ((u64)1 << (size * 8)) - 1;
3625 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3626 reg->umin_value &= mask;
3627 reg->umax_value &= mask;
3629 reg->umin_value = 0;
3630 reg->umax_value = mask;
3632 reg->smin_value = reg->umin_value;
3633 reg->smax_value = reg->umax_value;
3635 /* If size is smaller than 32bit register the 32bit register
3636 * values are also truncated so we push 64-bit bounds into
3637 * 32-bit bounds. Above were truncated < 32-bits already.
3641 __reg_combine_64_into_32(reg);
3644 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3646 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3649 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3655 err = map->ops->map_direct_value_addr(map, &addr, off);
3658 ptr = (void *)(long)addr + off;
3662 *val = (u64)*(u8 *)ptr;
3665 *val = (u64)*(u16 *)ptr;
3668 *val = (u64)*(u32 *)ptr;
3679 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3680 struct bpf_reg_state *regs,
3681 int regno, int off, int size,
3682 enum bpf_access_type atype,
3685 struct bpf_reg_state *reg = regs + regno;
3686 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3687 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3693 "R%d is ptr_%s invalid negative access: off=%d\n",
3697 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3700 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3702 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3703 regno, tname, off, tn_buf);
3707 if (env->ops->btf_struct_access) {
3708 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3709 off, size, atype, &btf_id);
3711 if (atype != BPF_READ) {
3712 verbose(env, "only read is supported\n");
3716 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3723 if (atype == BPF_READ && value_regno >= 0)
3724 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3729 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3730 struct bpf_reg_state *regs,
3731 int regno, int off, int size,
3732 enum bpf_access_type atype,
3735 struct bpf_reg_state *reg = regs + regno;
3736 struct bpf_map *map = reg->map_ptr;
3737 const struct btf_type *t;
3743 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3747 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3748 verbose(env, "map_ptr access not supported for map type %d\n",
3753 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3754 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3756 if (!env->allow_ptr_to_map_access) {
3758 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3764 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3769 if (atype != BPF_READ) {
3770 verbose(env, "only read from %s is supported\n", tname);
3774 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
3778 if (value_regno >= 0)
3779 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
3784 /* Check that the stack access at the given offset is within bounds. The
3785 * maximum valid offset is -1.
3787 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3788 * -state->allocated_stack for reads.
3790 static int check_stack_slot_within_bounds(int off,
3791 struct bpf_func_state *state,
3792 enum bpf_access_type t)
3797 min_valid_off = -MAX_BPF_STACK;
3799 min_valid_off = -state->allocated_stack;
3801 if (off < min_valid_off || off > -1)
3806 /* Check that the stack access at 'regno + off' falls within the maximum stack
3809 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3811 static int check_stack_access_within_bounds(
3812 struct bpf_verifier_env *env,
3813 int regno, int off, int access_size,
3814 enum stack_access_src src, enum bpf_access_type type)
3816 struct bpf_reg_state *regs = cur_regs(env);
3817 struct bpf_reg_state *reg = regs + regno;
3818 struct bpf_func_state *state = func(env, reg);
3819 int min_off, max_off;
3823 if (src == ACCESS_HELPER)
3824 /* We don't know if helpers are reading or writing (or both). */
3825 err_extra = " indirect access to";
3826 else if (type == BPF_READ)
3827 err_extra = " read from";
3829 err_extra = " write to";
3831 if (tnum_is_const(reg->var_off)) {
3832 min_off = reg->var_off.value + off;
3833 if (access_size > 0)
3834 max_off = min_off + access_size - 1;
3838 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3839 reg->smin_value <= -BPF_MAX_VAR_OFF) {
3840 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3844 min_off = reg->smin_value + off;
3845 if (access_size > 0)
3846 max_off = reg->smax_value + off + access_size - 1;
3851 err = check_stack_slot_within_bounds(min_off, state, type);
3853 err = check_stack_slot_within_bounds(max_off, state, type);
3856 if (tnum_is_const(reg->var_off)) {
3857 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3858 err_extra, regno, off, access_size);
3862 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3863 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3864 err_extra, regno, tn_buf, access_size);
3870 /* check whether memory at (regno + off) is accessible for t = (read | write)
3871 * if t==write, value_regno is a register which value is stored into memory
3872 * if t==read, value_regno is a register which will receive the value from memory
3873 * if t==write && value_regno==-1, some unknown value is stored into memory
3874 * if t==read && value_regno==-1, don't care what we read from memory
3876 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3877 int off, int bpf_size, enum bpf_access_type t,
3878 int value_regno, bool strict_alignment_once)
3880 struct bpf_reg_state *regs = cur_regs(env);
3881 struct bpf_reg_state *reg = regs + regno;
3882 struct bpf_func_state *state;
3885 size = bpf_size_to_bytes(bpf_size);
3889 /* alignment checks will add in reg->off themselves */
3890 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3894 /* for access checks, reg->off is just part of off */
3897 if (reg->type == PTR_TO_MAP_KEY) {
3898 if (t == BPF_WRITE) {
3899 verbose(env, "write to change key R%d not allowed\n", regno);
3903 err = check_mem_region_access(env, regno, off, size,
3904 reg->map_ptr->key_size, false);
3907 if (value_regno >= 0)
3908 mark_reg_unknown(env, regs, value_regno);
3909 } else if (reg->type == PTR_TO_MAP_VALUE) {
3910 if (t == BPF_WRITE && value_regno >= 0 &&
3911 is_pointer_value(env, value_regno)) {
3912 verbose(env, "R%d leaks addr into map\n", value_regno);
3915 err = check_map_access_type(env, regno, off, size, t);
3918 err = check_map_access(env, regno, off, size, false);
3919 if (!err && t == BPF_READ && value_regno >= 0) {
3920 struct bpf_map *map = reg->map_ptr;
3922 /* if map is read-only, track its contents as scalars */
3923 if (tnum_is_const(reg->var_off) &&
3924 bpf_map_is_rdonly(map) &&
3925 map->ops->map_direct_value_addr) {
3926 int map_off = off + reg->var_off.value;
3929 err = bpf_map_direct_read(map, map_off, size,
3934 regs[value_regno].type = SCALAR_VALUE;
3935 __mark_reg_known(®s[value_regno], val);
3937 mark_reg_unknown(env, regs, value_regno);
3940 } else if (reg->type == PTR_TO_MEM) {
3941 if (t == BPF_WRITE && value_regno >= 0 &&
3942 is_pointer_value(env, value_regno)) {
3943 verbose(env, "R%d leaks addr into mem\n", value_regno);
3946 err = check_mem_region_access(env, regno, off, size,
3947 reg->mem_size, false);
3948 if (!err && t == BPF_READ && value_regno >= 0)
3949 mark_reg_unknown(env, regs, value_regno);
3950 } else if (reg->type == PTR_TO_CTX) {
3951 enum bpf_reg_type reg_type = SCALAR_VALUE;
3952 struct btf *btf = NULL;
3955 if (t == BPF_WRITE && value_regno >= 0 &&
3956 is_pointer_value(env, value_regno)) {
3957 verbose(env, "R%d leaks addr into ctx\n", value_regno);
3961 err = check_ctx_reg(env, reg, regno);
3965 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, &btf_id);
3967 verbose_linfo(env, insn_idx, "; ");
3968 if (!err && t == BPF_READ && value_regno >= 0) {
3969 /* ctx access returns either a scalar, or a
3970 * PTR_TO_PACKET[_META,_END]. In the latter
3971 * case, we know the offset is zero.
3973 if (reg_type == SCALAR_VALUE) {
3974 mark_reg_unknown(env, regs, value_regno);
3976 mark_reg_known_zero(env, regs,
3978 if (reg_type_may_be_null(reg_type))
3979 regs[value_regno].id = ++env->id_gen;
3980 /* A load of ctx field could have different
3981 * actual load size with the one encoded in the
3982 * insn. When the dst is PTR, it is for sure not
3985 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
3986 if (reg_type == PTR_TO_BTF_ID ||
3987 reg_type == PTR_TO_BTF_ID_OR_NULL) {
3988 regs[value_regno].btf = btf;
3989 regs[value_regno].btf_id = btf_id;
3992 regs[value_regno].type = reg_type;
3995 } else if (reg->type == PTR_TO_STACK) {
3996 /* Basic bounds checks. */
3997 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4001 state = func(env, reg);
4002 err = update_stack_depth(env, state, off);
4007 err = check_stack_read(env, regno, off, size,
4010 err = check_stack_write(env, regno, off, size,
4011 value_regno, insn_idx);
4012 } else if (reg_is_pkt_pointer(reg)) {
4013 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4014 verbose(env, "cannot write into packet\n");
4017 if (t == BPF_WRITE && value_regno >= 0 &&
4018 is_pointer_value(env, value_regno)) {
4019 verbose(env, "R%d leaks addr into packet\n",
4023 err = check_packet_access(env, regno, off, size, false);
4024 if (!err && t == BPF_READ && value_regno >= 0)
4025 mark_reg_unknown(env, regs, value_regno);
4026 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4027 if (t == BPF_WRITE && value_regno >= 0 &&
4028 is_pointer_value(env, value_regno)) {
4029 verbose(env, "R%d leaks addr into flow keys\n",
4034 err = check_flow_keys_access(env, off, size);
4035 if (!err && t == BPF_READ && value_regno >= 0)
4036 mark_reg_unknown(env, regs, value_regno);
4037 } else if (type_is_sk_pointer(reg->type)) {
4038 if (t == BPF_WRITE) {
4039 verbose(env, "R%d cannot write into %s\n",
4040 regno, reg_type_str[reg->type]);
4043 err = check_sock_access(env, insn_idx, regno, off, size, t);
4044 if (!err && value_regno >= 0)
4045 mark_reg_unknown(env, regs, value_regno);
4046 } else if (reg->type == PTR_TO_TP_BUFFER) {
4047 err = check_tp_buffer_access(env, reg, regno, off, size);
4048 if (!err && t == BPF_READ && value_regno >= 0)
4049 mark_reg_unknown(env, regs, value_regno);
4050 } else if (reg->type == PTR_TO_BTF_ID) {
4051 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4053 } else if (reg->type == CONST_PTR_TO_MAP) {
4054 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4056 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4057 if (t == BPF_WRITE) {
4058 verbose(env, "R%d cannot write into %s\n",
4059 regno, reg_type_str[reg->type]);
4062 err = check_buffer_access(env, reg, regno, off, size, false,
4064 &env->prog->aux->max_rdonly_access);
4065 if (!err && value_regno >= 0)
4066 mark_reg_unknown(env, regs, value_regno);
4067 } else if (reg->type == PTR_TO_RDWR_BUF) {
4068 err = check_buffer_access(env, reg, regno, off, size, false,
4070 &env->prog->aux->max_rdwr_access);
4071 if (!err && t == BPF_READ && value_regno >= 0)
4072 mark_reg_unknown(env, regs, value_regno);
4074 verbose(env, "R%d invalid mem access '%s'\n", regno,
4075 reg_type_str[reg->type]);
4079 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4080 regs[value_regno].type == SCALAR_VALUE) {
4081 /* b/h/w load zero-extends, mark upper bits as known 0 */
4082 coerce_reg_to_size(®s[value_regno], size);
4087 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4092 switch (insn->imm) {
4094 case BPF_ADD | BPF_FETCH:
4096 case BPF_AND | BPF_FETCH:
4098 case BPF_OR | BPF_FETCH:
4100 case BPF_XOR | BPF_FETCH:
4105 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4109 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4110 verbose(env, "invalid atomic operand size\n");
4114 /* check src1 operand */
4115 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4119 /* check src2 operand */
4120 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4124 if (insn->imm == BPF_CMPXCHG) {
4125 /* Check comparison of R0 with memory location */
4126 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4131 if (is_pointer_value(env, insn->src_reg)) {
4132 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4136 if (is_ctx_reg(env, insn->dst_reg) ||
4137 is_pkt_reg(env, insn->dst_reg) ||
4138 is_flow_key_reg(env, insn->dst_reg) ||
4139 is_sk_reg(env, insn->dst_reg)) {
4140 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4142 reg_type_str[reg_state(env, insn->dst_reg)->type]);
4146 if (insn->imm & BPF_FETCH) {
4147 if (insn->imm == BPF_CMPXCHG)
4148 load_reg = BPF_REG_0;
4150 load_reg = insn->src_reg;
4152 /* check and record load of old value */
4153 err = check_reg_arg(env, load_reg, DST_OP);
4157 /* This instruction accesses a memory location but doesn't
4158 * actually load it into a register.
4163 /* check whether we can read the memory */
4164 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4165 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4169 /* check whether we can write into the same memory */
4170 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4171 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4178 /* When register 'regno' is used to read the stack (either directly or through
4179 * a helper function) make sure that it's within stack boundary and, depending
4180 * on the access type, that all elements of the stack are initialized.
4182 * 'off' includes 'regno->off', but not its dynamic part (if any).
4184 * All registers that have been spilled on the stack in the slots within the
4185 * read offsets are marked as read.
4187 static int check_stack_range_initialized(
4188 struct bpf_verifier_env *env, int regno, int off,
4189 int access_size, bool zero_size_allowed,
4190 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4192 struct bpf_reg_state *reg = reg_state(env, regno);
4193 struct bpf_func_state *state = func(env, reg);
4194 int err, min_off, max_off, i, j, slot, spi;
4195 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4196 enum bpf_access_type bounds_check_type;
4197 /* Some accesses can write anything into the stack, others are
4200 bool clobber = false;
4202 if (access_size == 0 && !zero_size_allowed) {
4203 verbose(env, "invalid zero-sized read\n");
4207 if (type == ACCESS_HELPER) {
4208 /* The bounds checks for writes are more permissive than for
4209 * reads. However, if raw_mode is not set, we'll do extra
4212 bounds_check_type = BPF_WRITE;
4215 bounds_check_type = BPF_READ;
4217 err = check_stack_access_within_bounds(env, regno, off, access_size,
4218 type, bounds_check_type);
4223 if (tnum_is_const(reg->var_off)) {
4224 min_off = max_off = reg->var_off.value + off;
4226 /* Variable offset is prohibited for unprivileged mode for
4227 * simplicity since it requires corresponding support in
4228 * Spectre masking for stack ALU.
4229 * See also retrieve_ptr_limit().
4231 if (!env->bypass_spec_v1) {
4234 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4235 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4236 regno, err_extra, tn_buf);
4239 /* Only initialized buffer on stack is allowed to be accessed
4240 * with variable offset. With uninitialized buffer it's hard to
4241 * guarantee that whole memory is marked as initialized on
4242 * helper return since specific bounds are unknown what may
4243 * cause uninitialized stack leaking.
4245 if (meta && meta->raw_mode)
4248 min_off = reg->smin_value + off;
4249 max_off = reg->smax_value + off;
4252 if (meta && meta->raw_mode) {
4253 meta->access_size = access_size;
4254 meta->regno = regno;
4258 for (i = min_off; i < max_off + access_size; i++) {
4262 spi = slot / BPF_REG_SIZE;
4263 if (state->allocated_stack <= slot)
4265 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4266 if (*stype == STACK_MISC)
4268 if (*stype == STACK_ZERO) {
4270 /* helper can write anything into the stack */
4271 *stype = STACK_MISC;
4276 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4277 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4280 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4281 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4282 env->allow_ptr_leaks)) {
4284 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4285 for (j = 0; j < BPF_REG_SIZE; j++)
4286 state->stack[spi].slot_type[j] = STACK_MISC;
4292 if (tnum_is_const(reg->var_off)) {
4293 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4294 err_extra, regno, min_off, i - min_off, access_size);
4298 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4299 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4300 err_extra, regno, tn_buf, i - min_off, access_size);
4304 /* reading any byte out of 8-byte 'spill_slot' will cause
4305 * the whole slot to be marked as 'read'
4307 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4308 state->stack[spi].spilled_ptr.parent,
4311 return update_stack_depth(env, state, min_off);
4314 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4315 int access_size, bool zero_size_allowed,
4316 struct bpf_call_arg_meta *meta)
4318 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4320 switch (reg->type) {
4322 case PTR_TO_PACKET_META:
4323 return check_packet_access(env, regno, reg->off, access_size,
4325 case PTR_TO_MAP_KEY:
4326 return check_mem_region_access(env, regno, reg->off, access_size,
4327 reg->map_ptr->key_size, false);
4328 case PTR_TO_MAP_VALUE:
4329 if (check_map_access_type(env, regno, reg->off, access_size,
4330 meta && meta->raw_mode ? BPF_WRITE :
4333 return check_map_access(env, regno, reg->off, access_size,
4336 return check_mem_region_access(env, regno, reg->off,
4337 access_size, reg->mem_size,
4339 case PTR_TO_RDONLY_BUF:
4340 if (meta && meta->raw_mode)
4342 return check_buffer_access(env, reg, regno, reg->off,
4343 access_size, zero_size_allowed,
4345 &env->prog->aux->max_rdonly_access);
4346 case PTR_TO_RDWR_BUF:
4347 return check_buffer_access(env, reg, regno, reg->off,
4348 access_size, zero_size_allowed,
4350 &env->prog->aux->max_rdwr_access);
4352 return check_stack_range_initialized(
4354 regno, reg->off, access_size,
4355 zero_size_allowed, ACCESS_HELPER, meta);
4356 default: /* scalar_value or invalid ptr */
4357 /* Allow zero-byte read from NULL, regardless of pointer type */
4358 if (zero_size_allowed && access_size == 0 &&
4359 register_is_null(reg))
4362 verbose(env, "R%d type=%s expected=%s\n", regno,
4363 reg_type_str[reg->type],
4364 reg_type_str[PTR_TO_STACK]);
4369 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4370 u32 regno, u32 mem_size)
4372 if (register_is_null(reg))
4375 if (reg_type_may_be_null(reg->type)) {
4376 /* Assuming that the register contains a value check if the memory
4377 * access is safe. Temporarily save and restore the register's state as
4378 * the conversion shouldn't be visible to a caller.
4380 const struct bpf_reg_state saved_reg = *reg;
4383 mark_ptr_not_null_reg(reg);
4384 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4389 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4392 /* Implementation details:
4393 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4394 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4395 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4396 * value_or_null->value transition, since the verifier only cares about
4397 * the range of access to valid map value pointer and doesn't care about actual
4398 * address of the map element.
4399 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4400 * reg->id > 0 after value_or_null->value transition. By doing so
4401 * two bpf_map_lookups will be considered two different pointers that
4402 * point to different bpf_spin_locks.
4403 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4405 * Since only one bpf_spin_lock is allowed the checks are simpler than
4406 * reg_is_refcounted() logic. The verifier needs to remember only
4407 * one spin_lock instead of array of acquired_refs.
4408 * cur_state->active_spin_lock remembers which map value element got locked
4409 * and clears it after bpf_spin_unlock.
4411 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4414 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4415 struct bpf_verifier_state *cur = env->cur_state;
4416 bool is_const = tnum_is_const(reg->var_off);
4417 struct bpf_map *map = reg->map_ptr;
4418 u64 val = reg->var_off.value;
4422 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4428 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4432 if (!map_value_has_spin_lock(map)) {
4433 if (map->spin_lock_off == -E2BIG)
4435 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4437 else if (map->spin_lock_off == -ENOENT)
4439 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4443 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4447 if (map->spin_lock_off != val + reg->off) {
4448 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4453 if (cur->active_spin_lock) {
4455 "Locking two bpf_spin_locks are not allowed\n");
4458 cur->active_spin_lock = reg->id;
4460 if (!cur->active_spin_lock) {
4461 verbose(env, "bpf_spin_unlock without taking a lock\n");
4464 if (cur->active_spin_lock != reg->id) {
4465 verbose(env, "bpf_spin_unlock of different lock\n");
4468 cur->active_spin_lock = 0;
4473 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4475 return type == ARG_PTR_TO_MEM ||
4476 type == ARG_PTR_TO_MEM_OR_NULL ||
4477 type == ARG_PTR_TO_UNINIT_MEM;
4480 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4482 return type == ARG_CONST_SIZE ||
4483 type == ARG_CONST_SIZE_OR_ZERO;
4486 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4488 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4491 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4493 return type == ARG_PTR_TO_INT ||
4494 type == ARG_PTR_TO_LONG;
4497 static int int_ptr_type_to_size(enum bpf_arg_type type)
4499 if (type == ARG_PTR_TO_INT)
4501 else if (type == ARG_PTR_TO_LONG)
4507 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4508 const struct bpf_call_arg_meta *meta,
4509 enum bpf_arg_type *arg_type)
4511 if (!meta->map_ptr) {
4512 /* kernel subsystem misconfigured verifier */
4513 verbose(env, "invalid map_ptr to access map->type\n");
4517 switch (meta->map_ptr->map_type) {
4518 case BPF_MAP_TYPE_SOCKMAP:
4519 case BPF_MAP_TYPE_SOCKHASH:
4520 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4521 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4523 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4534 struct bpf_reg_types {
4535 const enum bpf_reg_type types[10];
4539 static const struct bpf_reg_types map_key_value_types = {
4549 static const struct bpf_reg_types sock_types = {
4559 static const struct bpf_reg_types btf_id_sock_common_types = {
4567 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4571 static const struct bpf_reg_types mem_types = {
4584 static const struct bpf_reg_types int_ptr_types = {
4594 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4595 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4596 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4597 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4598 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4599 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4600 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4601 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4602 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4603 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
4605 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4606 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4607 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4608 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4609 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4610 [ARG_CONST_SIZE] = &scalar_types,
4611 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4612 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4613 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4614 [ARG_PTR_TO_CTX] = &context_types,
4615 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4616 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
4618 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4620 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4621 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4622 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4623 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4624 [ARG_PTR_TO_MEM] = &mem_types,
4625 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4626 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4627 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4628 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4629 [ARG_PTR_TO_INT] = &int_ptr_types,
4630 [ARG_PTR_TO_LONG] = &int_ptr_types,
4631 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
4632 [ARG_PTR_TO_FUNC] = &func_ptr_types,
4633 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types,
4636 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4637 enum bpf_arg_type arg_type,
4638 const u32 *arg_btf_id)
4640 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4641 enum bpf_reg_type expected, type = reg->type;
4642 const struct bpf_reg_types *compatible;
4645 compatible = compatible_reg_types[arg_type];
4647 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4651 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4652 expected = compatible->types[i];
4653 if (expected == NOT_INIT)
4656 if (type == expected)
4660 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4661 for (j = 0; j + 1 < i; j++)
4662 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4663 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4667 if (type == PTR_TO_BTF_ID) {
4669 if (!compatible->btf_id) {
4670 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4673 arg_btf_id = compatible->btf_id;
4676 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4677 btf_vmlinux, *arg_btf_id)) {
4678 verbose(env, "R%d is of type %s but %s is expected\n",
4679 regno, kernel_type_name(reg->btf, reg->btf_id),
4680 kernel_type_name(btf_vmlinux, *arg_btf_id));
4684 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4685 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4694 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4695 struct bpf_call_arg_meta *meta,
4696 const struct bpf_func_proto *fn)
4698 u32 regno = BPF_REG_1 + arg;
4699 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4700 enum bpf_arg_type arg_type = fn->arg_type[arg];
4701 enum bpf_reg_type type = reg->type;
4704 if (arg_type == ARG_DONTCARE)
4707 err = check_reg_arg(env, regno, SRC_OP);
4711 if (arg_type == ARG_ANYTHING) {
4712 if (is_pointer_value(env, regno)) {
4713 verbose(env, "R%d leaks addr into helper function\n",
4720 if (type_is_pkt_pointer(type) &&
4721 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4722 verbose(env, "helper access to the packet is not allowed\n");
4726 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4727 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4728 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4729 err = resolve_map_arg_type(env, meta, &arg_type);
4734 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4735 /* A NULL register has a SCALAR_VALUE type, so skip
4738 goto skip_type_check;
4740 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4744 if (type == PTR_TO_CTX) {
4745 err = check_ctx_reg(env, reg, regno);
4751 if (reg->ref_obj_id) {
4752 if (meta->ref_obj_id) {
4753 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4754 regno, reg->ref_obj_id,
4758 meta->ref_obj_id = reg->ref_obj_id;
4761 if (arg_type == ARG_CONST_MAP_PTR) {
4762 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4763 meta->map_ptr = reg->map_ptr;
4764 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4765 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4766 * check that [key, key + map->key_size) are within
4767 * stack limits and initialized
4769 if (!meta->map_ptr) {
4770 /* in function declaration map_ptr must come before
4771 * map_key, so that it's verified and known before
4772 * we have to check map_key here. Otherwise it means
4773 * that kernel subsystem misconfigured verifier
4775 verbose(env, "invalid map_ptr to access map->key\n");
4778 err = check_helper_mem_access(env, regno,
4779 meta->map_ptr->key_size, false,
4781 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4782 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4783 !register_is_null(reg)) ||
4784 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4785 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4786 * check [value, value + map->value_size) validity
4788 if (!meta->map_ptr) {
4789 /* kernel subsystem misconfigured verifier */
4790 verbose(env, "invalid map_ptr to access map->value\n");
4793 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4794 err = check_helper_mem_access(env, regno,
4795 meta->map_ptr->value_size, false,
4797 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4799 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4802 meta->ret_btf = reg->btf;
4803 meta->ret_btf_id = reg->btf_id;
4804 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4805 if (meta->func_id == BPF_FUNC_spin_lock) {
4806 if (process_spin_lock(env, regno, true))
4808 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4809 if (process_spin_lock(env, regno, false))
4812 verbose(env, "verifier internal error\n");
4815 } else if (arg_type == ARG_PTR_TO_FUNC) {
4816 meta->subprogno = reg->subprogno;
4817 } else if (arg_type_is_mem_ptr(arg_type)) {
4818 /* The access to this pointer is only checked when we hit the
4819 * next is_mem_size argument below.
4821 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4822 } else if (arg_type_is_mem_size(arg_type)) {
4823 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4825 /* This is used to refine r0 return value bounds for helpers
4826 * that enforce this value as an upper bound on return values.
4827 * See do_refine_retval_range() for helpers that can refine
4828 * the return value. C type of helper is u32 so we pull register
4829 * bound from umax_value however, if negative verifier errors
4830 * out. Only upper bounds can be learned because retval is an
4831 * int type and negative retvals are allowed.
4833 meta->msize_max_value = reg->umax_value;
4835 /* The register is SCALAR_VALUE; the access check
4836 * happens using its boundaries.
4838 if (!tnum_is_const(reg->var_off))
4839 /* For unprivileged variable accesses, disable raw
4840 * mode so that the program is required to
4841 * initialize all the memory that the helper could
4842 * just partially fill up.
4846 if (reg->smin_value < 0) {
4847 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4852 if (reg->umin_value == 0) {
4853 err = check_helper_mem_access(env, regno - 1, 0,
4860 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4861 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4865 err = check_helper_mem_access(env, regno - 1,
4867 zero_size_allowed, meta);
4869 err = mark_chain_precision(env, regno);
4870 } else if (arg_type_is_alloc_size(arg_type)) {
4871 if (!tnum_is_const(reg->var_off)) {
4872 verbose(env, "R%d is not a known constant'\n",
4876 meta->mem_size = reg->var_off.value;
4877 } else if (arg_type_is_int_ptr(arg_type)) {
4878 int size = int_ptr_type_to_size(arg_type);
4880 err = check_helper_mem_access(env, regno, size, false, meta);
4883 err = check_ptr_alignment(env, reg, 0, size, true);
4889 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4891 enum bpf_attach_type eatype = env->prog->expected_attach_type;
4892 enum bpf_prog_type type = resolve_prog_type(env->prog);
4894 if (func_id != BPF_FUNC_map_update_elem)
4897 /* It's not possible to get access to a locked struct sock in these
4898 * contexts, so updating is safe.
4901 case BPF_PROG_TYPE_TRACING:
4902 if (eatype == BPF_TRACE_ITER)
4905 case BPF_PROG_TYPE_SOCKET_FILTER:
4906 case BPF_PROG_TYPE_SCHED_CLS:
4907 case BPF_PROG_TYPE_SCHED_ACT:
4908 case BPF_PROG_TYPE_XDP:
4909 case BPF_PROG_TYPE_SK_REUSEPORT:
4910 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4911 case BPF_PROG_TYPE_SK_LOOKUP:
4917 verbose(env, "cannot update sockmap in this context\n");
4921 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4923 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4926 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4927 struct bpf_map *map, int func_id)
4932 /* We need a two way check, first is from map perspective ... */
4933 switch (map->map_type) {
4934 case BPF_MAP_TYPE_PROG_ARRAY:
4935 if (func_id != BPF_FUNC_tail_call)
4938 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4939 if (func_id != BPF_FUNC_perf_event_read &&
4940 func_id != BPF_FUNC_perf_event_output &&
4941 func_id != BPF_FUNC_skb_output &&
4942 func_id != BPF_FUNC_perf_event_read_value &&
4943 func_id != BPF_FUNC_xdp_output)
4946 case BPF_MAP_TYPE_RINGBUF:
4947 if (func_id != BPF_FUNC_ringbuf_output &&
4948 func_id != BPF_FUNC_ringbuf_reserve &&
4949 func_id != BPF_FUNC_ringbuf_submit &&
4950 func_id != BPF_FUNC_ringbuf_discard &&
4951 func_id != BPF_FUNC_ringbuf_query)
4954 case BPF_MAP_TYPE_STACK_TRACE:
4955 if (func_id != BPF_FUNC_get_stackid)
4958 case BPF_MAP_TYPE_CGROUP_ARRAY:
4959 if (func_id != BPF_FUNC_skb_under_cgroup &&
4960 func_id != BPF_FUNC_current_task_under_cgroup)
4963 case BPF_MAP_TYPE_CGROUP_STORAGE:
4964 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4965 if (func_id != BPF_FUNC_get_local_storage)
4968 case BPF_MAP_TYPE_DEVMAP:
4969 case BPF_MAP_TYPE_DEVMAP_HASH:
4970 if (func_id != BPF_FUNC_redirect_map &&
4971 func_id != BPF_FUNC_map_lookup_elem)
4974 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4977 case BPF_MAP_TYPE_CPUMAP:
4978 if (func_id != BPF_FUNC_redirect_map)
4981 case BPF_MAP_TYPE_XSKMAP:
4982 if (func_id != BPF_FUNC_redirect_map &&
4983 func_id != BPF_FUNC_map_lookup_elem)
4986 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4987 case BPF_MAP_TYPE_HASH_OF_MAPS:
4988 if (func_id != BPF_FUNC_map_lookup_elem)
4991 case BPF_MAP_TYPE_SOCKMAP:
4992 if (func_id != BPF_FUNC_sk_redirect_map &&
4993 func_id != BPF_FUNC_sock_map_update &&
4994 func_id != BPF_FUNC_map_delete_elem &&
4995 func_id != BPF_FUNC_msg_redirect_map &&
4996 func_id != BPF_FUNC_sk_select_reuseport &&
4997 func_id != BPF_FUNC_map_lookup_elem &&
4998 !may_update_sockmap(env, func_id))
5001 case BPF_MAP_TYPE_SOCKHASH:
5002 if (func_id != BPF_FUNC_sk_redirect_hash &&
5003 func_id != BPF_FUNC_sock_hash_update &&
5004 func_id != BPF_FUNC_map_delete_elem &&
5005 func_id != BPF_FUNC_msg_redirect_hash &&
5006 func_id != BPF_FUNC_sk_select_reuseport &&
5007 func_id != BPF_FUNC_map_lookup_elem &&
5008 !may_update_sockmap(env, func_id))
5011 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5012 if (func_id != BPF_FUNC_sk_select_reuseport)
5015 case BPF_MAP_TYPE_QUEUE:
5016 case BPF_MAP_TYPE_STACK:
5017 if (func_id != BPF_FUNC_map_peek_elem &&
5018 func_id != BPF_FUNC_map_pop_elem &&
5019 func_id != BPF_FUNC_map_push_elem)
5022 case BPF_MAP_TYPE_SK_STORAGE:
5023 if (func_id != BPF_FUNC_sk_storage_get &&
5024 func_id != BPF_FUNC_sk_storage_delete)
5027 case BPF_MAP_TYPE_INODE_STORAGE:
5028 if (func_id != BPF_FUNC_inode_storage_get &&
5029 func_id != BPF_FUNC_inode_storage_delete)
5032 case BPF_MAP_TYPE_TASK_STORAGE:
5033 if (func_id != BPF_FUNC_task_storage_get &&
5034 func_id != BPF_FUNC_task_storage_delete)
5041 /* ... and second from the function itself. */
5043 case BPF_FUNC_tail_call:
5044 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5046 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5047 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5051 case BPF_FUNC_perf_event_read:
5052 case BPF_FUNC_perf_event_output:
5053 case BPF_FUNC_perf_event_read_value:
5054 case BPF_FUNC_skb_output:
5055 case BPF_FUNC_xdp_output:
5056 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5059 case BPF_FUNC_get_stackid:
5060 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5063 case BPF_FUNC_current_task_under_cgroup:
5064 case BPF_FUNC_skb_under_cgroup:
5065 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5068 case BPF_FUNC_redirect_map:
5069 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5070 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5071 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5072 map->map_type != BPF_MAP_TYPE_XSKMAP)
5075 case BPF_FUNC_sk_redirect_map:
5076 case BPF_FUNC_msg_redirect_map:
5077 case BPF_FUNC_sock_map_update:
5078 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5081 case BPF_FUNC_sk_redirect_hash:
5082 case BPF_FUNC_msg_redirect_hash:
5083 case BPF_FUNC_sock_hash_update:
5084 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5087 case BPF_FUNC_get_local_storage:
5088 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5089 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5092 case BPF_FUNC_sk_select_reuseport:
5093 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5094 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5095 map->map_type != BPF_MAP_TYPE_SOCKHASH)
5098 case BPF_FUNC_map_peek_elem:
5099 case BPF_FUNC_map_pop_elem:
5100 case BPF_FUNC_map_push_elem:
5101 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5102 map->map_type != BPF_MAP_TYPE_STACK)
5105 case BPF_FUNC_sk_storage_get:
5106 case BPF_FUNC_sk_storage_delete:
5107 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5110 case BPF_FUNC_inode_storage_get:
5111 case BPF_FUNC_inode_storage_delete:
5112 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5115 case BPF_FUNC_task_storage_get:
5116 case BPF_FUNC_task_storage_delete:
5117 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5126 verbose(env, "cannot pass map_type %d into func %s#%d\n",
5127 map->map_type, func_id_name(func_id), func_id);
5131 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5135 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5137 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5139 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5141 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5143 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5146 /* We only support one arg being in raw mode at the moment,
5147 * which is sufficient for the helper functions we have
5153 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5154 enum bpf_arg_type arg_next)
5156 return (arg_type_is_mem_ptr(arg_curr) &&
5157 !arg_type_is_mem_size(arg_next)) ||
5158 (!arg_type_is_mem_ptr(arg_curr) &&
5159 arg_type_is_mem_size(arg_next));
5162 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5164 /* bpf_xxx(..., buf, len) call will access 'len'
5165 * bytes from memory 'buf'. Both arg types need
5166 * to be paired, so make sure there's no buggy
5167 * helper function specification.
5169 if (arg_type_is_mem_size(fn->arg1_type) ||
5170 arg_type_is_mem_ptr(fn->arg5_type) ||
5171 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5172 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5173 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5174 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5180 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5184 if (arg_type_may_be_refcounted(fn->arg1_type))
5186 if (arg_type_may_be_refcounted(fn->arg2_type))
5188 if (arg_type_may_be_refcounted(fn->arg3_type))
5190 if (arg_type_may_be_refcounted(fn->arg4_type))
5192 if (arg_type_may_be_refcounted(fn->arg5_type))
5195 /* A reference acquiring function cannot acquire
5196 * another refcounted ptr.
5198 if (may_be_acquire_function(func_id) && count)
5201 /* We only support one arg being unreferenced at the moment,
5202 * which is sufficient for the helper functions we have right now.
5207 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5211 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5212 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5215 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5222 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5224 return check_raw_mode_ok(fn) &&
5225 check_arg_pair_ok(fn) &&
5226 check_btf_id_ok(fn) &&
5227 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5230 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5231 * are now invalid, so turn them into unknown SCALAR_VALUE.
5233 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5234 struct bpf_func_state *state)
5236 struct bpf_reg_state *regs = state->regs, *reg;
5239 for (i = 0; i < MAX_BPF_REG; i++)
5240 if (reg_is_pkt_pointer_any(®s[i]))
5241 mark_reg_unknown(env, regs, i);
5243 bpf_for_each_spilled_reg(i, state, reg) {
5246 if (reg_is_pkt_pointer_any(reg))
5247 __mark_reg_unknown(env, reg);
5251 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5253 struct bpf_verifier_state *vstate = env->cur_state;
5256 for (i = 0; i <= vstate->curframe; i++)
5257 __clear_all_pkt_pointers(env, vstate->frame[i]);
5262 BEYOND_PKT_END = -2,
5265 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5267 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5268 struct bpf_reg_state *reg = &state->regs[regn];
5270 if (reg->type != PTR_TO_PACKET)
5271 /* PTR_TO_PACKET_META is not supported yet */
5274 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5275 * How far beyond pkt_end it goes is unknown.
5276 * if (!range_open) it's the case of pkt >= pkt_end
5277 * if (range_open) it's the case of pkt > pkt_end
5278 * hence this pointer is at least 1 byte bigger than pkt_end
5281 reg->range = BEYOND_PKT_END;
5283 reg->range = AT_PKT_END;
5286 static void release_reg_references(struct bpf_verifier_env *env,
5287 struct bpf_func_state *state,
5290 struct bpf_reg_state *regs = state->regs, *reg;
5293 for (i = 0; i < MAX_BPF_REG; i++)
5294 if (regs[i].ref_obj_id == ref_obj_id)
5295 mark_reg_unknown(env, regs, i);
5297 bpf_for_each_spilled_reg(i, state, reg) {
5300 if (reg->ref_obj_id == ref_obj_id)
5301 __mark_reg_unknown(env, reg);
5305 /* The pointer with the specified id has released its reference to kernel
5306 * resources. Identify all copies of the same pointer and clear the reference.
5308 static int release_reference(struct bpf_verifier_env *env,
5311 struct bpf_verifier_state *vstate = env->cur_state;
5315 err = release_reference_state(cur_func(env), ref_obj_id);
5319 for (i = 0; i <= vstate->curframe; i++)
5320 release_reg_references(env, vstate->frame[i], ref_obj_id);
5325 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5326 struct bpf_reg_state *regs)
5330 /* after the call registers r0 - r5 were scratched */
5331 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5332 mark_reg_not_init(env, regs, caller_saved[i]);
5333 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5337 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5338 struct bpf_func_state *caller,
5339 struct bpf_func_state *callee,
5342 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5343 int *insn_idx, int subprog,
5344 set_callee_state_fn set_callee_state_cb)
5346 struct bpf_verifier_state *state = env->cur_state;
5347 struct bpf_func_info_aux *func_info_aux;
5348 struct bpf_func_state *caller, *callee;
5350 bool is_global = false;
5352 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5353 verbose(env, "the call stack of %d frames is too deep\n",
5354 state->curframe + 2);
5358 caller = state->frame[state->curframe];
5359 if (state->frame[state->curframe + 1]) {
5360 verbose(env, "verifier bug. Frame %d already allocated\n",
5361 state->curframe + 1);
5365 func_info_aux = env->prog->aux->func_info_aux;
5367 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5368 err = btf_check_func_arg_match(env, subprog, caller->regs);
5373 verbose(env, "Caller passes invalid args into func#%d\n",
5377 if (env->log.level & BPF_LOG_LEVEL)
5379 "Func#%d is global and valid. Skipping.\n",
5381 clear_caller_saved_regs(env, caller->regs);
5383 /* All global functions return a 64-bit SCALAR_VALUE */
5384 mark_reg_unknown(env, caller->regs, BPF_REG_0);
5385 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5387 /* continue with next insn after call */
5392 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5395 state->frame[state->curframe + 1] = callee;
5397 /* callee cannot access r0, r6 - r9 for reading and has to write
5398 * into its own stack before reading from it.
5399 * callee can read/write into caller's stack
5401 init_func_state(env, callee,
5402 /* remember the callsite, it will be used by bpf_exit */
5403 *insn_idx /* callsite */,
5404 state->curframe + 1 /* frameno within this callchain */,
5405 subprog /* subprog number within this prog */);
5407 /* Transfer references to the callee */
5408 err = transfer_reference_state(callee, caller);
5412 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5416 clear_caller_saved_regs(env, caller->regs);
5418 /* only increment it after check_reg_arg() finished */
5421 /* and go analyze first insn of the callee */
5422 *insn_idx = env->subprog_info[subprog].start - 1;
5424 if (env->log.level & BPF_LOG_LEVEL) {
5425 verbose(env, "caller:\n");
5426 print_verifier_state(env, caller);
5427 verbose(env, "callee:\n");
5428 print_verifier_state(env, callee);
5433 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5434 struct bpf_func_state *caller,
5435 struct bpf_func_state *callee)
5437 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5438 * void *callback_ctx, u64 flags);
5439 * callback_fn(struct bpf_map *map, void *key, void *value,
5440 * void *callback_ctx);
5442 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5444 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5445 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5446 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5448 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5449 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5450 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5452 /* pointer to stack or null */
5453 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5456 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5460 static int set_callee_state(struct bpf_verifier_env *env,
5461 struct bpf_func_state *caller,
5462 struct bpf_func_state *callee, int insn_idx)
5466 /* copy r1 - r5 args that callee can access. The copy includes parent
5467 * pointers, which connects us up to the liveness chain
5469 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5470 callee->regs[i] = caller->regs[i];
5474 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5477 int subprog, target_insn;
5479 target_insn = *insn_idx + insn->imm + 1;
5480 subprog = find_subprog(env, target_insn);
5482 verbose(env, "verifier bug. No program starts at insn %d\n",
5487 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5490 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5491 struct bpf_func_state *caller,
5492 struct bpf_func_state *callee,
5495 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5496 struct bpf_map *map;
5499 if (bpf_map_ptr_poisoned(insn_aux)) {
5500 verbose(env, "tail_call abusing map_ptr\n");
5504 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5505 if (!map->ops->map_set_for_each_callback_args ||
5506 !map->ops->map_for_each_callback) {
5507 verbose(env, "callback function not allowed for map\n");
5511 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5515 callee->in_callback_fn = true;
5519 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5521 struct bpf_verifier_state *state = env->cur_state;
5522 struct bpf_func_state *caller, *callee;
5523 struct bpf_reg_state *r0;
5526 callee = state->frame[state->curframe];
5527 r0 = &callee->regs[BPF_REG_0];
5528 if (r0->type == PTR_TO_STACK) {
5529 /* technically it's ok to return caller's stack pointer
5530 * (or caller's caller's pointer) back to the caller,
5531 * since these pointers are valid. Only current stack
5532 * pointer will be invalid as soon as function exits,
5533 * but let's be conservative
5535 verbose(env, "cannot return stack pointer to the caller\n");
5540 caller = state->frame[state->curframe];
5541 if (callee->in_callback_fn) {
5542 /* enforce R0 return value range [0, 1]. */
5543 struct tnum range = tnum_range(0, 1);
5545 if (r0->type != SCALAR_VALUE) {
5546 verbose(env, "R0 not a scalar value\n");
5549 if (!tnum_in(range, r0->var_off)) {
5550 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5554 /* return to the caller whatever r0 had in the callee */
5555 caller->regs[BPF_REG_0] = *r0;
5558 /* Transfer references to the caller */
5559 err = transfer_reference_state(caller, callee);
5563 *insn_idx = callee->callsite + 1;
5564 if (env->log.level & BPF_LOG_LEVEL) {
5565 verbose(env, "returning from callee:\n");
5566 print_verifier_state(env, callee);
5567 verbose(env, "to caller at %d:\n", *insn_idx);
5568 print_verifier_state(env, caller);
5570 /* clear everything in the callee */
5571 free_func_state(callee);
5572 state->frame[state->curframe + 1] = NULL;
5576 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5578 struct bpf_call_arg_meta *meta)
5580 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
5582 if (ret_type != RET_INTEGER ||
5583 (func_id != BPF_FUNC_get_stack &&
5584 func_id != BPF_FUNC_probe_read_str &&
5585 func_id != BPF_FUNC_probe_read_kernel_str &&
5586 func_id != BPF_FUNC_probe_read_user_str))
5589 ret_reg->smax_value = meta->msize_max_value;
5590 ret_reg->s32_max_value = meta->msize_max_value;
5591 ret_reg->smin_value = -MAX_ERRNO;
5592 ret_reg->s32_min_value = -MAX_ERRNO;
5593 __reg_deduce_bounds(ret_reg);
5594 __reg_bound_offset(ret_reg);
5595 __update_reg_bounds(ret_reg);
5599 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5600 int func_id, int insn_idx)
5602 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5603 struct bpf_map *map = meta->map_ptr;
5605 if (func_id != BPF_FUNC_tail_call &&
5606 func_id != BPF_FUNC_map_lookup_elem &&
5607 func_id != BPF_FUNC_map_update_elem &&
5608 func_id != BPF_FUNC_map_delete_elem &&
5609 func_id != BPF_FUNC_map_push_elem &&
5610 func_id != BPF_FUNC_map_pop_elem &&
5611 func_id != BPF_FUNC_map_peek_elem &&
5612 func_id != BPF_FUNC_for_each_map_elem &&
5613 func_id != BPF_FUNC_redirect_map)
5617 verbose(env, "kernel subsystem misconfigured verifier\n");
5621 /* In case of read-only, some additional restrictions
5622 * need to be applied in order to prevent altering the
5623 * state of the map from program side.
5625 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5626 (func_id == BPF_FUNC_map_delete_elem ||
5627 func_id == BPF_FUNC_map_update_elem ||
5628 func_id == BPF_FUNC_map_push_elem ||
5629 func_id == BPF_FUNC_map_pop_elem)) {
5630 verbose(env, "write into map forbidden\n");
5634 if (!BPF_MAP_PTR(aux->map_ptr_state))
5635 bpf_map_ptr_store(aux, meta->map_ptr,
5636 !meta->map_ptr->bypass_spec_v1);
5637 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5638 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5639 !meta->map_ptr->bypass_spec_v1);
5644 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5645 int func_id, int insn_idx)
5647 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5648 struct bpf_reg_state *regs = cur_regs(env), *reg;
5649 struct bpf_map *map = meta->map_ptr;
5654 if (func_id != BPF_FUNC_tail_call)
5656 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5657 verbose(env, "kernel subsystem misconfigured verifier\n");
5661 range = tnum_range(0, map->max_entries - 1);
5662 reg = ®s[BPF_REG_3];
5664 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5665 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5669 err = mark_chain_precision(env, BPF_REG_3);
5673 val = reg->var_off.value;
5674 if (bpf_map_key_unseen(aux))
5675 bpf_map_key_store(aux, val);
5676 else if (!bpf_map_key_poisoned(aux) &&
5677 bpf_map_key_immediate(aux) != val)
5678 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5682 static int check_reference_leak(struct bpf_verifier_env *env)
5684 struct bpf_func_state *state = cur_func(env);
5687 for (i = 0; i < state->acquired_refs; i++) {
5688 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5689 state->refs[i].id, state->refs[i].insn_idx);
5691 return state->acquired_refs ? -EINVAL : 0;
5694 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5697 const struct bpf_func_proto *fn = NULL;
5698 struct bpf_reg_state *regs;
5699 struct bpf_call_arg_meta meta;
5700 int insn_idx = *insn_idx_p;
5702 int i, err, func_id;
5704 /* find function prototype */
5705 func_id = insn->imm;
5706 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5707 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5712 if (env->ops->get_func_proto)
5713 fn = env->ops->get_func_proto(func_id, env->prog);
5715 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5720 /* eBPF programs must be GPL compatible to use GPL-ed functions */
5721 if (!env->prog->gpl_compatible && fn->gpl_only) {
5722 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5726 if (fn->allowed && !fn->allowed(env->prog)) {
5727 verbose(env, "helper call is not allowed in probe\n");
5731 /* With LD_ABS/IND some JITs save/restore skb from r1. */
5732 changes_data = bpf_helper_changes_pkt_data(fn->func);
5733 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5734 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5735 func_id_name(func_id), func_id);
5739 memset(&meta, 0, sizeof(meta));
5740 meta.pkt_access = fn->pkt_access;
5742 err = check_func_proto(fn, func_id);
5744 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5745 func_id_name(func_id), func_id);
5749 meta.func_id = func_id;
5751 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
5752 err = check_func_arg(env, i, &meta, fn);
5757 err = record_func_map(env, &meta, func_id, insn_idx);
5761 err = record_func_key(env, &meta, func_id, insn_idx);
5765 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5766 * is inferred from register state.
5768 for (i = 0; i < meta.access_size; i++) {
5769 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5770 BPF_WRITE, -1, false);
5775 if (func_id == BPF_FUNC_tail_call) {
5776 err = check_reference_leak(env);
5778 verbose(env, "tail_call would lead to reference leak\n");
5781 } else if (is_release_function(func_id)) {
5782 err = release_reference(env, meta.ref_obj_id);
5784 verbose(env, "func %s#%d reference has not been acquired before\n",
5785 func_id_name(func_id), func_id);
5790 regs = cur_regs(env);
5792 /* check that flags argument in get_local_storage(map, flags) is 0,
5793 * this is required because get_local_storage() can't return an error.
5795 if (func_id == BPF_FUNC_get_local_storage &&
5796 !register_is_null(®s[BPF_REG_2])) {
5797 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5801 if (func_id == BPF_FUNC_for_each_map_elem) {
5802 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
5803 set_map_elem_callback_state);
5808 /* reset caller saved regs */
5809 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5810 mark_reg_not_init(env, regs, caller_saved[i]);
5811 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5814 /* helper call returns 64-bit value. */
5815 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5817 /* update return register (already marked as written above) */
5818 if (fn->ret_type == RET_INTEGER) {
5819 /* sets type to SCALAR_VALUE */
5820 mark_reg_unknown(env, regs, BPF_REG_0);
5821 } else if (fn->ret_type == RET_VOID) {
5822 regs[BPF_REG_0].type = NOT_INIT;
5823 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5824 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5825 /* There is no offset yet applied, variable or fixed */
5826 mark_reg_known_zero(env, regs, BPF_REG_0);
5827 /* remember map_ptr, so that check_map_access()
5828 * can check 'value_size' boundary of memory access
5829 * to map element returned from bpf_map_lookup_elem()
5831 if (meta.map_ptr == NULL) {
5833 "kernel subsystem misconfigured verifier\n");
5836 regs[BPF_REG_0].map_ptr = meta.map_ptr;
5837 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5838 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
5839 if (map_value_has_spin_lock(meta.map_ptr))
5840 regs[BPF_REG_0].id = ++env->id_gen;
5842 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5844 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5845 mark_reg_known_zero(env, regs, BPF_REG_0);
5846 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
5847 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5848 mark_reg_known_zero(env, regs, BPF_REG_0);
5849 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5850 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5851 mark_reg_known_zero(env, regs, BPF_REG_0);
5852 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5853 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5854 mark_reg_known_zero(env, regs, BPF_REG_0);
5855 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5856 regs[BPF_REG_0].mem_size = meta.mem_size;
5857 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5858 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
5859 const struct btf_type *t;
5861 mark_reg_known_zero(env, regs, BPF_REG_0);
5862 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
5863 if (!btf_type_is_struct(t)) {
5865 const struct btf_type *ret;
5868 /* resolve the type size of ksym. */
5869 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
5871 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
5872 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5873 tname, PTR_ERR(ret));
5876 regs[BPF_REG_0].type =
5877 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5878 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
5879 regs[BPF_REG_0].mem_size = tsize;
5881 regs[BPF_REG_0].type =
5882 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5883 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
5884 regs[BPF_REG_0].btf = meta.ret_btf;
5885 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5887 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
5888 fn->ret_type == RET_PTR_TO_BTF_ID) {
5891 mark_reg_known_zero(env, regs, BPF_REG_0);
5892 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
5894 PTR_TO_BTF_ID_OR_NULL;
5895 ret_btf_id = *fn->ret_btf_id;
5896 if (ret_btf_id == 0) {
5897 verbose(env, "invalid return type %d of func %s#%d\n",
5898 fn->ret_type, func_id_name(func_id), func_id);
5901 /* current BPF helper definitions are only coming from
5902 * built-in code with type IDs from vmlinux BTF
5904 regs[BPF_REG_0].btf = btf_vmlinux;
5905 regs[BPF_REG_0].btf_id = ret_btf_id;
5907 verbose(env, "unknown return type %d of func %s#%d\n",
5908 fn->ret_type, func_id_name(func_id), func_id);
5912 if (reg_type_may_be_null(regs[BPF_REG_0].type))
5913 regs[BPF_REG_0].id = ++env->id_gen;
5915 if (is_ptr_cast_function(func_id)) {
5916 /* For release_reference() */
5917 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5918 } else if (is_acquire_function(func_id, meta.map_ptr)) {
5919 int id = acquire_reference_state(env, insn_idx);
5923 /* For mark_ptr_or_null_reg() */
5924 regs[BPF_REG_0].id = id;
5925 /* For release_reference() */
5926 regs[BPF_REG_0].ref_obj_id = id;
5929 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5931 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5935 if ((func_id == BPF_FUNC_get_stack ||
5936 func_id == BPF_FUNC_get_task_stack) &&
5937 !env->prog->has_callchain_buf) {
5938 const char *err_str;
5940 #ifdef CONFIG_PERF_EVENTS
5941 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5942 err_str = "cannot get callchain buffer for func %s#%d\n";
5945 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5948 verbose(env, err_str, func_id_name(func_id), func_id);
5952 env->prog->has_callchain_buf = true;
5955 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5956 env->prog->call_get_stack = true;
5959 clear_all_pkt_pointers(env);
5963 static bool signed_add_overflows(s64 a, s64 b)
5965 /* Do the add in u64, where overflow is well-defined */
5966 s64 res = (s64)((u64)a + (u64)b);
5973 static bool signed_add32_overflows(s32 a, s32 b)
5975 /* Do the add in u32, where overflow is well-defined */
5976 s32 res = (s32)((u32)a + (u32)b);
5983 static bool signed_sub_overflows(s64 a, s64 b)
5985 /* Do the sub in u64, where overflow is well-defined */
5986 s64 res = (s64)((u64)a - (u64)b);
5993 static bool signed_sub32_overflows(s32 a, s32 b)
5995 /* Do the sub in u32, where overflow is well-defined */
5996 s32 res = (s32)((u32)a - (u32)b);
6003 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6004 const struct bpf_reg_state *reg,
6005 enum bpf_reg_type type)
6007 bool known = tnum_is_const(reg->var_off);
6008 s64 val = reg->var_off.value;
6009 s64 smin = reg->smin_value;
6011 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6012 verbose(env, "math between %s pointer and %lld is not allowed\n",
6013 reg_type_str[type], val);
6017 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6018 verbose(env, "%s pointer offset %d is not allowed\n",
6019 reg_type_str[type], reg->off);
6023 if (smin == S64_MIN) {
6024 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6025 reg_type_str[type]);
6029 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6030 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6031 smin, reg_type_str[type]);
6038 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6040 return &env->insn_aux_data[env->insn_idx];
6043 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6044 u32 *ptr_limit, u8 opcode, bool off_is_neg)
6046 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
6047 (opcode == BPF_SUB && !off_is_neg);
6050 switch (ptr_reg->type) {
6052 /* Indirect variable offset stack access is prohibited in
6053 * unprivileged mode so it's not handled here.
6055 off = ptr_reg->off + ptr_reg->var_off.value;
6057 *ptr_limit = MAX_BPF_STACK + off;
6061 case PTR_TO_MAP_KEY:
6062 /* Currently, this code is not exercised as the only use
6063 * is bpf_for_each_map_elem() helper which requires
6064 * bpf_capble. The code has been tested manually for
6068 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
6070 off = ptr_reg->smin_value + ptr_reg->off;
6071 *ptr_limit = ptr_reg->map_ptr->key_size - off;
6074 case PTR_TO_MAP_VALUE:
6076 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
6078 off = ptr_reg->smin_value + ptr_reg->off;
6079 *ptr_limit = ptr_reg->map_ptr->value_size - off;
6087 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6088 const struct bpf_insn *insn)
6090 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6093 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6094 u32 alu_state, u32 alu_limit)
6096 /* If we arrived here from different branches with different
6097 * state or limits to sanitize, then this won't work.
6099 if (aux->alu_state &&
6100 (aux->alu_state != alu_state ||
6101 aux->alu_limit != alu_limit))
6104 /* Corresponding fixup done in do_misc_fixups(). */
6105 aux->alu_state = alu_state;
6106 aux->alu_limit = alu_limit;
6110 static int sanitize_val_alu(struct bpf_verifier_env *env,
6111 struct bpf_insn *insn)
6113 struct bpf_insn_aux_data *aux = cur_aux(env);
6115 if (can_skip_alu_sanitation(env, insn))
6118 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6121 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6122 struct bpf_insn *insn,
6123 const struct bpf_reg_state *ptr_reg,
6124 struct bpf_reg_state *dst_reg,
6127 struct bpf_verifier_state *vstate = env->cur_state;
6128 struct bpf_insn_aux_data *aux = cur_aux(env);
6129 bool ptr_is_dst_reg = ptr_reg == dst_reg;
6130 u8 opcode = BPF_OP(insn->code);
6131 u32 alu_state, alu_limit;
6132 struct bpf_reg_state tmp;
6135 if (can_skip_alu_sanitation(env, insn))
6138 /* We already marked aux for masking from non-speculative
6139 * paths, thus we got here in the first place. We only care
6140 * to explore bad access from here.
6142 if (vstate->speculative)
6145 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6146 alu_state |= ptr_is_dst_reg ?
6147 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6149 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
6151 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
6154 /* Simulate and find potential out-of-bounds access under
6155 * speculative execution from truncation as a result of
6156 * masking when off was not within expected range. If off
6157 * sits in dst, then we temporarily need to move ptr there
6158 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6159 * for cases where we use K-based arithmetic in one direction
6160 * and truncated reg-based in the other in order to explore
6163 if (!ptr_is_dst_reg) {
6165 *dst_reg = *ptr_reg;
6167 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
6168 if (!ptr_is_dst_reg && ret)
6170 return !ret ? -EFAULT : 0;
6173 /* check that stack access falls within stack limits and that 'reg' doesn't
6174 * have a variable offset.
6176 * Variable offset is prohibited for unprivileged mode for simplicity since it
6177 * requires corresponding support in Spectre masking for stack ALU. See also
6178 * retrieve_ptr_limit().
6181 * 'off' includes 'reg->off'.
6183 static int check_stack_access_for_ptr_arithmetic(
6184 struct bpf_verifier_env *env,
6186 const struct bpf_reg_state *reg,
6189 if (!tnum_is_const(reg->var_off)) {
6192 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6193 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6194 regno, tn_buf, off);
6198 if (off >= 0 || off < -MAX_BPF_STACK) {
6199 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6200 "prohibited for !root; off=%d\n", regno, off);
6208 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6209 * Caller should also handle BPF_MOV case separately.
6210 * If we return -EACCES, caller may want to try again treating pointer as a
6211 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6213 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6214 struct bpf_insn *insn,
6215 const struct bpf_reg_state *ptr_reg,
6216 const struct bpf_reg_state *off_reg)
6218 struct bpf_verifier_state *vstate = env->cur_state;
6219 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6220 struct bpf_reg_state *regs = state->regs, *dst_reg;
6221 bool known = tnum_is_const(off_reg->var_off);
6222 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6223 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6224 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6225 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6226 u32 dst = insn->dst_reg, src = insn->src_reg;
6227 u8 opcode = BPF_OP(insn->code);
6230 dst_reg = ®s[dst];
6232 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6233 smin_val > smax_val || umin_val > umax_val) {
6234 /* Taint dst register if offset had invalid bounds derived from
6235 * e.g. dead branches.
6237 __mark_reg_unknown(env, dst_reg);
6241 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6242 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6243 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6244 __mark_reg_unknown(env, dst_reg);
6249 "R%d 32-bit pointer arithmetic prohibited\n",
6254 switch (ptr_reg->type) {
6255 case PTR_TO_MAP_VALUE_OR_NULL:
6256 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6257 dst, reg_type_str[ptr_reg->type]);
6259 case CONST_PTR_TO_MAP:
6260 /* smin_val represents the known value */
6261 if (known && smin_val == 0 && opcode == BPF_ADD)
6264 case PTR_TO_PACKET_END:
6266 case PTR_TO_SOCKET_OR_NULL:
6267 case PTR_TO_SOCK_COMMON:
6268 case PTR_TO_SOCK_COMMON_OR_NULL:
6269 case PTR_TO_TCP_SOCK:
6270 case PTR_TO_TCP_SOCK_OR_NULL:
6271 case PTR_TO_XDP_SOCK:
6272 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6273 dst, reg_type_str[ptr_reg->type]);
6275 case PTR_TO_MAP_KEY:
6276 case PTR_TO_MAP_VALUE:
6277 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
6278 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
6279 off_reg == dst_reg ? dst : src);
6287 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6288 * The id may be overwritten later if we create a new variable offset.
6290 dst_reg->type = ptr_reg->type;
6291 dst_reg->id = ptr_reg->id;
6293 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6294 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6297 /* pointer types do not carry 32-bit bounds at the moment. */
6298 __mark_reg32_unbounded(dst_reg);
6302 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6304 verbose(env, "R%d tried to add from different maps or paths\n", dst);
6307 /* We can take a fixed offset as long as it doesn't overflow
6308 * the s32 'off' field
6310 if (known && (ptr_reg->off + smin_val ==
6311 (s64)(s32)(ptr_reg->off + smin_val))) {
6312 /* pointer += K. Accumulate it into fixed offset */
6313 dst_reg->smin_value = smin_ptr;
6314 dst_reg->smax_value = smax_ptr;
6315 dst_reg->umin_value = umin_ptr;
6316 dst_reg->umax_value = umax_ptr;
6317 dst_reg->var_off = ptr_reg->var_off;
6318 dst_reg->off = ptr_reg->off + smin_val;
6319 dst_reg->raw = ptr_reg->raw;
6322 /* A new variable offset is created. Note that off_reg->off
6323 * == 0, since it's a scalar.
6324 * dst_reg gets the pointer type and since some positive
6325 * integer value was added to the pointer, give it a new 'id'
6326 * if it's a PTR_TO_PACKET.
6327 * this creates a new 'base' pointer, off_reg (variable) gets
6328 * added into the variable offset, and we copy the fixed offset
6331 if (signed_add_overflows(smin_ptr, smin_val) ||
6332 signed_add_overflows(smax_ptr, smax_val)) {
6333 dst_reg->smin_value = S64_MIN;
6334 dst_reg->smax_value = S64_MAX;
6336 dst_reg->smin_value = smin_ptr + smin_val;
6337 dst_reg->smax_value = smax_ptr + smax_val;
6339 if (umin_ptr + umin_val < umin_ptr ||
6340 umax_ptr + umax_val < umax_ptr) {
6341 dst_reg->umin_value = 0;
6342 dst_reg->umax_value = U64_MAX;
6344 dst_reg->umin_value = umin_ptr + umin_val;
6345 dst_reg->umax_value = umax_ptr + umax_val;
6347 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6348 dst_reg->off = ptr_reg->off;
6349 dst_reg->raw = ptr_reg->raw;
6350 if (reg_is_pkt_pointer(ptr_reg)) {
6351 dst_reg->id = ++env->id_gen;
6352 /* something was added to pkt_ptr, set range to zero */
6353 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6357 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6359 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
6362 if (dst_reg == off_reg) {
6363 /* scalar -= pointer. Creates an unknown scalar */
6364 verbose(env, "R%d tried to subtract pointer from scalar\n",
6368 /* We don't allow subtraction from FP, because (according to
6369 * test_verifier.c test "invalid fp arithmetic", JITs might not
6370 * be able to deal with it.
6372 if (ptr_reg->type == PTR_TO_STACK) {
6373 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6377 if (known && (ptr_reg->off - smin_val ==
6378 (s64)(s32)(ptr_reg->off - smin_val))) {
6379 /* pointer -= K. Subtract it from fixed offset */
6380 dst_reg->smin_value = smin_ptr;
6381 dst_reg->smax_value = smax_ptr;
6382 dst_reg->umin_value = umin_ptr;
6383 dst_reg->umax_value = umax_ptr;
6384 dst_reg->var_off = ptr_reg->var_off;
6385 dst_reg->id = ptr_reg->id;
6386 dst_reg->off = ptr_reg->off - smin_val;
6387 dst_reg->raw = ptr_reg->raw;
6390 /* A new variable offset is created. If the subtrahend is known
6391 * nonnegative, then any reg->range we had before is still good.
6393 if (signed_sub_overflows(smin_ptr, smax_val) ||
6394 signed_sub_overflows(smax_ptr, smin_val)) {
6395 /* Overflow possible, we know nothing */
6396 dst_reg->smin_value = S64_MIN;
6397 dst_reg->smax_value = S64_MAX;
6399 dst_reg->smin_value = smin_ptr - smax_val;
6400 dst_reg->smax_value = smax_ptr - smin_val;
6402 if (umin_ptr < umax_val) {
6403 /* Overflow possible, we know nothing */
6404 dst_reg->umin_value = 0;
6405 dst_reg->umax_value = U64_MAX;
6407 /* Cannot overflow (as long as bounds are consistent) */
6408 dst_reg->umin_value = umin_ptr - umax_val;
6409 dst_reg->umax_value = umax_ptr - umin_val;
6411 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6412 dst_reg->off = ptr_reg->off;
6413 dst_reg->raw = ptr_reg->raw;
6414 if (reg_is_pkt_pointer(ptr_reg)) {
6415 dst_reg->id = ++env->id_gen;
6416 /* something was added to pkt_ptr, set range to zero */
6418 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6424 /* bitwise ops on pointers are troublesome, prohibit. */
6425 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6426 dst, bpf_alu_string[opcode >> 4]);
6429 /* other operators (e.g. MUL,LSH) produce non-pointer results */
6430 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6431 dst, bpf_alu_string[opcode >> 4]);
6435 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6438 __update_reg_bounds(dst_reg);
6439 __reg_deduce_bounds(dst_reg);
6440 __reg_bound_offset(dst_reg);
6442 /* For unprivileged we require that resulting offset must be in bounds
6443 * in order to be able to sanitize access later on.
6445 if (!env->bypass_spec_v1) {
6446 if (dst_reg->type == PTR_TO_MAP_VALUE &&
6447 check_map_access(env, dst, dst_reg->off, 1, false)) {
6448 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6449 "prohibited for !root\n", dst);
6451 } else if (dst_reg->type == PTR_TO_STACK &&
6452 check_stack_access_for_ptr_arithmetic(
6453 env, dst, dst_reg, dst_reg->off +
6454 dst_reg->var_off.value)) {
6462 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6463 struct bpf_reg_state *src_reg)
6465 s32 smin_val = src_reg->s32_min_value;
6466 s32 smax_val = src_reg->s32_max_value;
6467 u32 umin_val = src_reg->u32_min_value;
6468 u32 umax_val = src_reg->u32_max_value;
6470 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6471 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6472 dst_reg->s32_min_value = S32_MIN;
6473 dst_reg->s32_max_value = S32_MAX;
6475 dst_reg->s32_min_value += smin_val;
6476 dst_reg->s32_max_value += smax_val;
6478 if (dst_reg->u32_min_value + umin_val < umin_val ||
6479 dst_reg->u32_max_value + umax_val < umax_val) {
6480 dst_reg->u32_min_value = 0;
6481 dst_reg->u32_max_value = U32_MAX;
6483 dst_reg->u32_min_value += umin_val;
6484 dst_reg->u32_max_value += umax_val;
6488 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6489 struct bpf_reg_state *src_reg)
6491 s64 smin_val = src_reg->smin_value;
6492 s64 smax_val = src_reg->smax_value;
6493 u64 umin_val = src_reg->umin_value;
6494 u64 umax_val = src_reg->umax_value;
6496 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6497 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6498 dst_reg->smin_value = S64_MIN;
6499 dst_reg->smax_value = S64_MAX;
6501 dst_reg->smin_value += smin_val;
6502 dst_reg->smax_value += smax_val;
6504 if (dst_reg->umin_value + umin_val < umin_val ||
6505 dst_reg->umax_value + umax_val < umax_val) {
6506 dst_reg->umin_value = 0;
6507 dst_reg->umax_value = U64_MAX;
6509 dst_reg->umin_value += umin_val;
6510 dst_reg->umax_value += umax_val;
6514 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6515 struct bpf_reg_state *src_reg)
6517 s32 smin_val = src_reg->s32_min_value;
6518 s32 smax_val = src_reg->s32_max_value;
6519 u32 umin_val = src_reg->u32_min_value;
6520 u32 umax_val = src_reg->u32_max_value;
6522 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6523 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6524 /* Overflow possible, we know nothing */
6525 dst_reg->s32_min_value = S32_MIN;
6526 dst_reg->s32_max_value = S32_MAX;
6528 dst_reg->s32_min_value -= smax_val;
6529 dst_reg->s32_max_value -= smin_val;
6531 if (dst_reg->u32_min_value < umax_val) {
6532 /* Overflow possible, we know nothing */
6533 dst_reg->u32_min_value = 0;
6534 dst_reg->u32_max_value = U32_MAX;
6536 /* Cannot overflow (as long as bounds are consistent) */
6537 dst_reg->u32_min_value -= umax_val;
6538 dst_reg->u32_max_value -= umin_val;
6542 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6543 struct bpf_reg_state *src_reg)
6545 s64 smin_val = src_reg->smin_value;
6546 s64 smax_val = src_reg->smax_value;
6547 u64 umin_val = src_reg->umin_value;
6548 u64 umax_val = src_reg->umax_value;
6550 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6551 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6552 /* Overflow possible, we know nothing */
6553 dst_reg->smin_value = S64_MIN;
6554 dst_reg->smax_value = S64_MAX;
6556 dst_reg->smin_value -= smax_val;
6557 dst_reg->smax_value -= smin_val;
6559 if (dst_reg->umin_value < umax_val) {
6560 /* Overflow possible, we know nothing */
6561 dst_reg->umin_value = 0;
6562 dst_reg->umax_value = U64_MAX;
6564 /* Cannot overflow (as long as bounds are consistent) */
6565 dst_reg->umin_value -= umax_val;
6566 dst_reg->umax_value -= umin_val;
6570 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6571 struct bpf_reg_state *src_reg)
6573 s32 smin_val = src_reg->s32_min_value;
6574 u32 umin_val = src_reg->u32_min_value;
6575 u32 umax_val = src_reg->u32_max_value;
6577 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6578 /* Ain't nobody got time to multiply that sign */
6579 __mark_reg32_unbounded(dst_reg);
6582 /* Both values are positive, so we can work with unsigned and
6583 * copy the result to signed (unless it exceeds S32_MAX).
6585 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6586 /* Potential overflow, we know nothing */
6587 __mark_reg32_unbounded(dst_reg);
6590 dst_reg->u32_min_value *= umin_val;
6591 dst_reg->u32_max_value *= umax_val;
6592 if (dst_reg->u32_max_value > S32_MAX) {
6593 /* Overflow possible, we know nothing */
6594 dst_reg->s32_min_value = S32_MIN;
6595 dst_reg->s32_max_value = S32_MAX;
6597 dst_reg->s32_min_value = dst_reg->u32_min_value;
6598 dst_reg->s32_max_value = dst_reg->u32_max_value;
6602 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6603 struct bpf_reg_state *src_reg)
6605 s64 smin_val = src_reg->smin_value;
6606 u64 umin_val = src_reg->umin_value;
6607 u64 umax_val = src_reg->umax_value;
6609 if (smin_val < 0 || dst_reg->smin_value < 0) {
6610 /* Ain't nobody got time to multiply that sign */
6611 __mark_reg64_unbounded(dst_reg);
6614 /* Both values are positive, so we can work with unsigned and
6615 * copy the result to signed (unless it exceeds S64_MAX).
6617 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6618 /* Potential overflow, we know nothing */
6619 __mark_reg64_unbounded(dst_reg);
6622 dst_reg->umin_value *= umin_val;
6623 dst_reg->umax_value *= umax_val;
6624 if (dst_reg->umax_value > S64_MAX) {
6625 /* Overflow possible, we know nothing */
6626 dst_reg->smin_value = S64_MIN;
6627 dst_reg->smax_value = S64_MAX;
6629 dst_reg->smin_value = dst_reg->umin_value;
6630 dst_reg->smax_value = dst_reg->umax_value;
6634 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6635 struct bpf_reg_state *src_reg)
6637 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6638 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6639 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6640 s32 smin_val = src_reg->s32_min_value;
6641 u32 umax_val = src_reg->u32_max_value;
6643 /* Assuming scalar64_min_max_and will be called so its safe
6644 * to skip updating register for known 32-bit case.
6646 if (src_known && dst_known)
6649 /* We get our minimum from the var_off, since that's inherently
6650 * bitwise. Our maximum is the minimum of the operands' maxima.
6652 dst_reg->u32_min_value = var32_off.value;
6653 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6654 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6655 /* Lose signed bounds when ANDing negative numbers,
6656 * ain't nobody got time for that.
6658 dst_reg->s32_min_value = S32_MIN;
6659 dst_reg->s32_max_value = S32_MAX;
6661 /* ANDing two positives gives a positive, so safe to
6662 * cast result into s64.
6664 dst_reg->s32_min_value = dst_reg->u32_min_value;
6665 dst_reg->s32_max_value = dst_reg->u32_max_value;
6670 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6671 struct bpf_reg_state *src_reg)
6673 bool src_known = tnum_is_const(src_reg->var_off);
6674 bool dst_known = tnum_is_const(dst_reg->var_off);
6675 s64 smin_val = src_reg->smin_value;
6676 u64 umax_val = src_reg->umax_value;
6678 if (src_known && dst_known) {
6679 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6683 /* We get our minimum from the var_off, since that's inherently
6684 * bitwise. Our maximum is the minimum of the operands' maxima.
6686 dst_reg->umin_value = dst_reg->var_off.value;
6687 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6688 if (dst_reg->smin_value < 0 || smin_val < 0) {
6689 /* Lose signed bounds when ANDing negative numbers,
6690 * ain't nobody got time for that.
6692 dst_reg->smin_value = S64_MIN;
6693 dst_reg->smax_value = S64_MAX;
6695 /* ANDing two positives gives a positive, so safe to
6696 * cast result into s64.
6698 dst_reg->smin_value = dst_reg->umin_value;
6699 dst_reg->smax_value = dst_reg->umax_value;
6701 /* We may learn something more from the var_off */
6702 __update_reg_bounds(dst_reg);
6705 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6706 struct bpf_reg_state *src_reg)
6708 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6709 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6710 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6711 s32 smin_val = src_reg->s32_min_value;
6712 u32 umin_val = src_reg->u32_min_value;
6714 /* Assuming scalar64_min_max_or will be called so it is safe
6715 * to skip updating register for known case.
6717 if (src_known && dst_known)
6720 /* We get our maximum from the var_off, and our minimum is the
6721 * maximum of the operands' minima
6723 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6724 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6725 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6726 /* Lose signed bounds when ORing negative numbers,
6727 * ain't nobody got time for that.
6729 dst_reg->s32_min_value = S32_MIN;
6730 dst_reg->s32_max_value = S32_MAX;
6732 /* ORing two positives gives a positive, so safe to
6733 * cast result into s64.
6735 dst_reg->s32_min_value = dst_reg->u32_min_value;
6736 dst_reg->s32_max_value = dst_reg->u32_max_value;
6740 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6741 struct bpf_reg_state *src_reg)
6743 bool src_known = tnum_is_const(src_reg->var_off);
6744 bool dst_known = tnum_is_const(dst_reg->var_off);
6745 s64 smin_val = src_reg->smin_value;
6746 u64 umin_val = src_reg->umin_value;
6748 if (src_known && dst_known) {
6749 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6753 /* We get our maximum from the var_off, and our minimum is the
6754 * maximum of the operands' minima
6756 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6757 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6758 if (dst_reg->smin_value < 0 || smin_val < 0) {
6759 /* Lose signed bounds when ORing negative numbers,
6760 * ain't nobody got time for that.
6762 dst_reg->smin_value = S64_MIN;
6763 dst_reg->smax_value = S64_MAX;
6765 /* ORing two positives gives a positive, so safe to
6766 * cast result into s64.
6768 dst_reg->smin_value = dst_reg->umin_value;
6769 dst_reg->smax_value = dst_reg->umax_value;
6771 /* We may learn something more from the var_off */
6772 __update_reg_bounds(dst_reg);
6775 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6776 struct bpf_reg_state *src_reg)
6778 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6779 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6780 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6781 s32 smin_val = src_reg->s32_min_value;
6783 /* Assuming scalar64_min_max_xor will be called so it is safe
6784 * to skip updating register for known case.
6786 if (src_known && dst_known)
6789 /* We get both minimum and maximum from the var32_off. */
6790 dst_reg->u32_min_value = var32_off.value;
6791 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6793 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6794 /* XORing two positive sign numbers gives a positive,
6795 * so safe to cast u32 result into s32.
6797 dst_reg->s32_min_value = dst_reg->u32_min_value;
6798 dst_reg->s32_max_value = dst_reg->u32_max_value;
6800 dst_reg->s32_min_value = S32_MIN;
6801 dst_reg->s32_max_value = S32_MAX;
6805 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6806 struct bpf_reg_state *src_reg)
6808 bool src_known = tnum_is_const(src_reg->var_off);
6809 bool dst_known = tnum_is_const(dst_reg->var_off);
6810 s64 smin_val = src_reg->smin_value;
6812 if (src_known && dst_known) {
6813 /* dst_reg->var_off.value has been updated earlier */
6814 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6818 /* We get both minimum and maximum from the var_off. */
6819 dst_reg->umin_value = dst_reg->var_off.value;
6820 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6822 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6823 /* XORing two positive sign numbers gives a positive,
6824 * so safe to cast u64 result into s64.
6826 dst_reg->smin_value = dst_reg->umin_value;
6827 dst_reg->smax_value = dst_reg->umax_value;
6829 dst_reg->smin_value = S64_MIN;
6830 dst_reg->smax_value = S64_MAX;
6833 __update_reg_bounds(dst_reg);
6836 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6837 u64 umin_val, u64 umax_val)
6839 /* We lose all sign bit information (except what we can pick
6842 dst_reg->s32_min_value = S32_MIN;
6843 dst_reg->s32_max_value = S32_MAX;
6844 /* If we might shift our top bit out, then we know nothing */
6845 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6846 dst_reg->u32_min_value = 0;
6847 dst_reg->u32_max_value = U32_MAX;
6849 dst_reg->u32_min_value <<= umin_val;
6850 dst_reg->u32_max_value <<= umax_val;
6854 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6855 struct bpf_reg_state *src_reg)
6857 u32 umax_val = src_reg->u32_max_value;
6858 u32 umin_val = src_reg->u32_min_value;
6859 /* u32 alu operation will zext upper bits */
6860 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6862 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6863 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6864 /* Not required but being careful mark reg64 bounds as unknown so
6865 * that we are forced to pick them up from tnum and zext later and
6866 * if some path skips this step we are still safe.
6868 __mark_reg64_unbounded(dst_reg);
6869 __update_reg32_bounds(dst_reg);
6872 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6873 u64 umin_val, u64 umax_val)
6875 /* Special case <<32 because it is a common compiler pattern to sign
6876 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6877 * positive we know this shift will also be positive so we can track
6878 * bounds correctly. Otherwise we lose all sign bit information except
6879 * what we can pick up from var_off. Perhaps we can generalize this
6880 * later to shifts of any length.
6882 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6883 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6885 dst_reg->smax_value = S64_MAX;
6887 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6888 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6890 dst_reg->smin_value = S64_MIN;
6892 /* If we might shift our top bit out, then we know nothing */
6893 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6894 dst_reg->umin_value = 0;
6895 dst_reg->umax_value = U64_MAX;
6897 dst_reg->umin_value <<= umin_val;
6898 dst_reg->umax_value <<= umax_val;
6902 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6903 struct bpf_reg_state *src_reg)
6905 u64 umax_val = src_reg->umax_value;
6906 u64 umin_val = src_reg->umin_value;
6908 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6909 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6910 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6912 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6913 /* We may learn something more from the var_off */
6914 __update_reg_bounds(dst_reg);
6917 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6918 struct bpf_reg_state *src_reg)
6920 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6921 u32 umax_val = src_reg->u32_max_value;
6922 u32 umin_val = src_reg->u32_min_value;
6924 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6925 * be negative, then either:
6926 * 1) src_reg might be zero, so the sign bit of the result is
6927 * unknown, so we lose our signed bounds
6928 * 2) it's known negative, thus the unsigned bounds capture the
6930 * 3) the signed bounds cross zero, so they tell us nothing
6932 * If the value in dst_reg is known nonnegative, then again the
6933 * unsigned bounds capture the signed bounds.
6934 * Thus, in all cases it suffices to blow away our signed bounds
6935 * and rely on inferring new ones from the unsigned bounds and
6936 * var_off of the result.
6938 dst_reg->s32_min_value = S32_MIN;
6939 dst_reg->s32_max_value = S32_MAX;
6941 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6942 dst_reg->u32_min_value >>= umax_val;
6943 dst_reg->u32_max_value >>= umin_val;
6945 __mark_reg64_unbounded(dst_reg);
6946 __update_reg32_bounds(dst_reg);
6949 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6950 struct bpf_reg_state *src_reg)
6952 u64 umax_val = src_reg->umax_value;
6953 u64 umin_val = src_reg->umin_value;
6955 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6956 * be negative, then either:
6957 * 1) src_reg might be zero, so the sign bit of the result is
6958 * unknown, so we lose our signed bounds
6959 * 2) it's known negative, thus the unsigned bounds capture the
6961 * 3) the signed bounds cross zero, so they tell us nothing
6963 * If the value in dst_reg is known nonnegative, then again the
6964 * unsigned bounds capture the signed bounds.
6965 * Thus, in all cases it suffices to blow away our signed bounds
6966 * and rely on inferring new ones from the unsigned bounds and
6967 * var_off of the result.
6969 dst_reg->smin_value = S64_MIN;
6970 dst_reg->smax_value = S64_MAX;
6971 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6972 dst_reg->umin_value >>= umax_val;
6973 dst_reg->umax_value >>= umin_val;
6975 /* Its not easy to operate on alu32 bounds here because it depends
6976 * on bits being shifted in. Take easy way out and mark unbounded
6977 * so we can recalculate later from tnum.
6979 __mark_reg32_unbounded(dst_reg);
6980 __update_reg_bounds(dst_reg);
6983 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6984 struct bpf_reg_state *src_reg)
6986 u64 umin_val = src_reg->u32_min_value;
6988 /* Upon reaching here, src_known is true and
6989 * umax_val is equal to umin_val.
6991 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6992 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
6994 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6996 /* blow away the dst_reg umin_value/umax_value and rely on
6997 * dst_reg var_off to refine the result.
6999 dst_reg->u32_min_value = 0;
7000 dst_reg->u32_max_value = U32_MAX;
7002 __mark_reg64_unbounded(dst_reg);
7003 __update_reg32_bounds(dst_reg);
7006 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7007 struct bpf_reg_state *src_reg)
7009 u64 umin_val = src_reg->umin_value;
7011 /* Upon reaching here, src_known is true and umax_val is equal
7014 dst_reg->smin_value >>= umin_val;
7015 dst_reg->smax_value >>= umin_val;
7017 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7019 /* blow away the dst_reg umin_value/umax_value and rely on
7020 * dst_reg var_off to refine the result.
7022 dst_reg->umin_value = 0;
7023 dst_reg->umax_value = U64_MAX;
7025 /* Its not easy to operate on alu32 bounds here because it depends
7026 * on bits being shifted in from upper 32-bits. Take easy way out
7027 * and mark unbounded so we can recalculate later from tnum.
7029 __mark_reg32_unbounded(dst_reg);
7030 __update_reg_bounds(dst_reg);
7033 /* WARNING: This function does calculations on 64-bit values, but the actual
7034 * execution may occur on 32-bit values. Therefore, things like bitshifts
7035 * need extra checks in the 32-bit case.
7037 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7038 struct bpf_insn *insn,
7039 struct bpf_reg_state *dst_reg,
7040 struct bpf_reg_state src_reg)
7042 struct bpf_reg_state *regs = cur_regs(env);
7043 u8 opcode = BPF_OP(insn->code);
7045 s64 smin_val, smax_val;
7046 u64 umin_val, umax_val;
7047 s32 s32_min_val, s32_max_val;
7048 u32 u32_min_val, u32_max_val;
7049 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7050 u32 dst = insn->dst_reg;
7052 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7054 smin_val = src_reg.smin_value;
7055 smax_val = src_reg.smax_value;
7056 umin_val = src_reg.umin_value;
7057 umax_val = src_reg.umax_value;
7059 s32_min_val = src_reg.s32_min_value;
7060 s32_max_val = src_reg.s32_max_value;
7061 u32_min_val = src_reg.u32_min_value;
7062 u32_max_val = src_reg.u32_max_value;
7065 src_known = tnum_subreg_is_const(src_reg.var_off);
7067 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7068 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7069 /* Taint dst register if offset had invalid bounds
7070 * derived from e.g. dead branches.
7072 __mark_reg_unknown(env, dst_reg);
7076 src_known = tnum_is_const(src_reg.var_off);
7078 (smin_val != smax_val || umin_val != umax_val)) ||
7079 smin_val > smax_val || umin_val > umax_val) {
7080 /* Taint dst register if offset had invalid bounds
7081 * derived from e.g. dead branches.
7083 __mark_reg_unknown(env, dst_reg);
7089 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7090 __mark_reg_unknown(env, dst_reg);
7094 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7095 * There are two classes of instructions: The first class we track both
7096 * alu32 and alu64 sign/unsigned bounds independently this provides the
7097 * greatest amount of precision when alu operations are mixed with jmp32
7098 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7099 * and BPF_OR. This is possible because these ops have fairly easy to
7100 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7101 * See alu32 verifier tests for examples. The second class of
7102 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7103 * with regards to tracking sign/unsigned bounds because the bits may
7104 * cross subreg boundaries in the alu64 case. When this happens we mark
7105 * the reg unbounded in the subreg bound space and use the resulting
7106 * tnum to calculate an approximation of the sign/unsigned bounds.
7110 ret = sanitize_val_alu(env, insn);
7112 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
7115 scalar32_min_max_add(dst_reg, &src_reg);
7116 scalar_min_max_add(dst_reg, &src_reg);
7117 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7120 ret = sanitize_val_alu(env, insn);
7122 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
7125 scalar32_min_max_sub(dst_reg, &src_reg);
7126 scalar_min_max_sub(dst_reg, &src_reg);
7127 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7130 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7131 scalar32_min_max_mul(dst_reg, &src_reg);
7132 scalar_min_max_mul(dst_reg, &src_reg);
7135 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7136 scalar32_min_max_and(dst_reg, &src_reg);
7137 scalar_min_max_and(dst_reg, &src_reg);
7140 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7141 scalar32_min_max_or(dst_reg, &src_reg);
7142 scalar_min_max_or(dst_reg, &src_reg);
7145 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7146 scalar32_min_max_xor(dst_reg, &src_reg);
7147 scalar_min_max_xor(dst_reg, &src_reg);
7150 if (umax_val >= insn_bitness) {
7151 /* Shifts greater than 31 or 63 are undefined.
7152 * This includes shifts by a negative number.
7154 mark_reg_unknown(env, regs, insn->dst_reg);
7158 scalar32_min_max_lsh(dst_reg, &src_reg);
7160 scalar_min_max_lsh(dst_reg, &src_reg);
7163 if (umax_val >= insn_bitness) {
7164 /* Shifts greater than 31 or 63 are undefined.
7165 * This includes shifts by a negative number.
7167 mark_reg_unknown(env, regs, insn->dst_reg);
7171 scalar32_min_max_rsh(dst_reg, &src_reg);
7173 scalar_min_max_rsh(dst_reg, &src_reg);
7176 if (umax_val >= insn_bitness) {
7177 /* Shifts greater than 31 or 63 are undefined.
7178 * This includes shifts by a negative number.
7180 mark_reg_unknown(env, regs, insn->dst_reg);
7184 scalar32_min_max_arsh(dst_reg, &src_reg);
7186 scalar_min_max_arsh(dst_reg, &src_reg);
7189 mark_reg_unknown(env, regs, insn->dst_reg);
7193 /* ALU32 ops are zero extended into 64bit register */
7195 zext_32_to_64(dst_reg);
7197 __update_reg_bounds(dst_reg);
7198 __reg_deduce_bounds(dst_reg);
7199 __reg_bound_offset(dst_reg);
7203 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7206 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7207 struct bpf_insn *insn)
7209 struct bpf_verifier_state *vstate = env->cur_state;
7210 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7211 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7212 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7213 u8 opcode = BPF_OP(insn->code);
7216 dst_reg = ®s[insn->dst_reg];
7218 if (dst_reg->type != SCALAR_VALUE)
7221 /* Make sure ID is cleared otherwise dst_reg min/max could be
7222 * incorrectly propagated into other registers by find_equal_scalars()
7225 if (BPF_SRC(insn->code) == BPF_X) {
7226 src_reg = ®s[insn->src_reg];
7227 if (src_reg->type != SCALAR_VALUE) {
7228 if (dst_reg->type != SCALAR_VALUE) {
7229 /* Combining two pointers by any ALU op yields
7230 * an arbitrary scalar. Disallow all math except
7231 * pointer subtraction
7233 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7234 mark_reg_unknown(env, regs, insn->dst_reg);
7237 verbose(env, "R%d pointer %s pointer prohibited\n",
7239 bpf_alu_string[opcode >> 4]);
7242 /* scalar += pointer
7243 * This is legal, but we have to reverse our
7244 * src/dest handling in computing the range
7246 err = mark_chain_precision(env, insn->dst_reg);
7249 return adjust_ptr_min_max_vals(env, insn,
7252 } else if (ptr_reg) {
7253 /* pointer += scalar */
7254 err = mark_chain_precision(env, insn->src_reg);
7257 return adjust_ptr_min_max_vals(env, insn,
7261 /* Pretend the src is a reg with a known value, since we only
7262 * need to be able to read from this state.
7264 off_reg.type = SCALAR_VALUE;
7265 __mark_reg_known(&off_reg, insn->imm);
7267 if (ptr_reg) /* pointer += K */
7268 return adjust_ptr_min_max_vals(env, insn,
7272 /* Got here implies adding two SCALAR_VALUEs */
7273 if (WARN_ON_ONCE(ptr_reg)) {
7274 print_verifier_state(env, state);
7275 verbose(env, "verifier internal error: unexpected ptr_reg\n");
7278 if (WARN_ON(!src_reg)) {
7279 print_verifier_state(env, state);
7280 verbose(env, "verifier internal error: no src_reg\n");
7283 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7286 /* check validity of 32-bit and 64-bit arithmetic operations */
7287 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7289 struct bpf_reg_state *regs = cur_regs(env);
7290 u8 opcode = BPF_OP(insn->code);
7293 if (opcode == BPF_END || opcode == BPF_NEG) {
7294 if (opcode == BPF_NEG) {
7295 if (BPF_SRC(insn->code) != 0 ||
7296 insn->src_reg != BPF_REG_0 ||
7297 insn->off != 0 || insn->imm != 0) {
7298 verbose(env, "BPF_NEG uses reserved fields\n");
7302 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7303 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7304 BPF_CLASS(insn->code) == BPF_ALU64) {
7305 verbose(env, "BPF_END uses reserved fields\n");
7310 /* check src operand */
7311 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7315 if (is_pointer_value(env, insn->dst_reg)) {
7316 verbose(env, "R%d pointer arithmetic prohibited\n",
7321 /* check dest operand */
7322 err = check_reg_arg(env, insn->dst_reg, DST_OP);
7326 } else if (opcode == BPF_MOV) {
7328 if (BPF_SRC(insn->code) == BPF_X) {
7329 if (insn->imm != 0 || insn->off != 0) {
7330 verbose(env, "BPF_MOV uses reserved fields\n");
7334 /* check src operand */
7335 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7339 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7340 verbose(env, "BPF_MOV uses reserved fields\n");
7345 /* check dest operand, mark as required later */
7346 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7350 if (BPF_SRC(insn->code) == BPF_X) {
7351 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7352 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7354 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7356 * copy register state to dest reg
7358 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7359 /* Assign src and dst registers the same ID
7360 * that will be used by find_equal_scalars()
7361 * to propagate min/max range.
7363 src_reg->id = ++env->id_gen;
7364 *dst_reg = *src_reg;
7365 dst_reg->live |= REG_LIVE_WRITTEN;
7366 dst_reg->subreg_def = DEF_NOT_SUBREG;
7369 if (is_pointer_value(env, insn->src_reg)) {
7371 "R%d partial copy of pointer\n",
7374 } else if (src_reg->type == SCALAR_VALUE) {
7375 *dst_reg = *src_reg;
7376 /* Make sure ID is cleared otherwise
7377 * dst_reg min/max could be incorrectly
7378 * propagated into src_reg by find_equal_scalars()
7381 dst_reg->live |= REG_LIVE_WRITTEN;
7382 dst_reg->subreg_def = env->insn_idx + 1;
7384 mark_reg_unknown(env, regs,
7387 zext_32_to_64(dst_reg);
7391 * remember the value we stored into this reg
7393 /* clear any state __mark_reg_known doesn't set */
7394 mark_reg_unknown(env, regs, insn->dst_reg);
7395 regs[insn->dst_reg].type = SCALAR_VALUE;
7396 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7397 __mark_reg_known(regs + insn->dst_reg,
7400 __mark_reg_known(regs + insn->dst_reg,
7405 } else if (opcode > BPF_END) {
7406 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7409 } else { /* all other ALU ops: and, sub, xor, add, ... */
7411 if (BPF_SRC(insn->code) == BPF_X) {
7412 if (insn->imm != 0 || insn->off != 0) {
7413 verbose(env, "BPF_ALU uses reserved fields\n");
7416 /* check src1 operand */
7417 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7421 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7422 verbose(env, "BPF_ALU uses reserved fields\n");
7427 /* check src2 operand */
7428 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7432 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7433 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7434 verbose(env, "div by zero\n");
7438 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7439 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7440 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7442 if (insn->imm < 0 || insn->imm >= size) {
7443 verbose(env, "invalid shift %d\n", insn->imm);
7448 /* check dest operand */
7449 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7453 return adjust_reg_min_max_vals(env, insn);
7459 static void __find_good_pkt_pointers(struct bpf_func_state *state,
7460 struct bpf_reg_state *dst_reg,
7461 enum bpf_reg_type type, int new_range)
7463 struct bpf_reg_state *reg;
7466 for (i = 0; i < MAX_BPF_REG; i++) {
7467 reg = &state->regs[i];
7468 if (reg->type == type && reg->id == dst_reg->id)
7469 /* keep the maximum range already checked */
7470 reg->range = max(reg->range, new_range);
7473 bpf_for_each_spilled_reg(i, state, reg) {
7476 if (reg->type == type && reg->id == dst_reg->id)
7477 reg->range = max(reg->range, new_range);
7481 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7482 struct bpf_reg_state *dst_reg,
7483 enum bpf_reg_type type,
7484 bool range_right_open)
7488 if (dst_reg->off < 0 ||
7489 (dst_reg->off == 0 && range_right_open))
7490 /* This doesn't give us any range */
7493 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7494 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7495 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7496 * than pkt_end, but that's because it's also less than pkt.
7500 new_range = dst_reg->off;
7501 if (range_right_open)
7504 /* Examples for register markings:
7506 * pkt_data in dst register:
7510 * if (r2 > pkt_end) goto <handle exception>
7515 * if (r2 < pkt_end) goto <access okay>
7516 * <handle exception>
7519 * r2 == dst_reg, pkt_end == src_reg
7520 * r2=pkt(id=n,off=8,r=0)
7521 * r3=pkt(id=n,off=0,r=0)
7523 * pkt_data in src register:
7527 * if (pkt_end >= r2) goto <access okay>
7528 * <handle exception>
7532 * if (pkt_end <= r2) goto <handle exception>
7536 * pkt_end == dst_reg, r2 == src_reg
7537 * r2=pkt(id=n,off=8,r=0)
7538 * r3=pkt(id=n,off=0,r=0)
7540 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7541 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7542 * and [r3, r3 + 8-1) respectively is safe to access depending on
7546 /* If our ids match, then we must have the same max_value. And we
7547 * don't care about the other reg's fixed offset, since if it's too big
7548 * the range won't allow anything.
7549 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7551 for (i = 0; i <= vstate->curframe; i++)
7552 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7556 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7558 struct tnum subreg = tnum_subreg(reg->var_off);
7559 s32 sval = (s32)val;
7563 if (tnum_is_const(subreg))
7564 return !!tnum_equals_const(subreg, val);
7567 if (tnum_is_const(subreg))
7568 return !tnum_equals_const(subreg, val);
7571 if ((~subreg.mask & subreg.value) & val)
7573 if (!((subreg.mask | subreg.value) & val))
7577 if (reg->u32_min_value > val)
7579 else if (reg->u32_max_value <= val)
7583 if (reg->s32_min_value > sval)
7585 else if (reg->s32_max_value <= sval)
7589 if (reg->u32_max_value < val)
7591 else if (reg->u32_min_value >= val)
7595 if (reg->s32_max_value < sval)
7597 else if (reg->s32_min_value >= sval)
7601 if (reg->u32_min_value >= val)
7603 else if (reg->u32_max_value < val)
7607 if (reg->s32_min_value >= sval)
7609 else if (reg->s32_max_value < sval)
7613 if (reg->u32_max_value <= val)
7615 else if (reg->u32_min_value > val)
7619 if (reg->s32_max_value <= sval)
7621 else if (reg->s32_min_value > sval)
7630 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7632 s64 sval = (s64)val;
7636 if (tnum_is_const(reg->var_off))
7637 return !!tnum_equals_const(reg->var_off, val);
7640 if (tnum_is_const(reg->var_off))
7641 return !tnum_equals_const(reg->var_off, val);
7644 if ((~reg->var_off.mask & reg->var_off.value) & val)
7646 if (!((reg->var_off.mask | reg->var_off.value) & val))
7650 if (reg->umin_value > val)
7652 else if (reg->umax_value <= val)
7656 if (reg->smin_value > sval)
7658 else if (reg->smax_value <= sval)
7662 if (reg->umax_value < val)
7664 else if (reg->umin_value >= val)
7668 if (reg->smax_value < sval)
7670 else if (reg->smin_value >= sval)
7674 if (reg->umin_value >= val)
7676 else if (reg->umax_value < val)
7680 if (reg->smin_value >= sval)
7682 else if (reg->smax_value < sval)
7686 if (reg->umax_value <= val)
7688 else if (reg->umin_value > val)
7692 if (reg->smax_value <= sval)
7694 else if (reg->smin_value > sval)
7702 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7704 * 1 - branch will be taken and "goto target" will be executed
7705 * 0 - branch will not be taken and fall-through to next insn
7706 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7709 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7712 if (__is_pointer_value(false, reg)) {
7713 if (!reg_type_not_null(reg->type))
7716 /* If pointer is valid tests against zero will fail so we can
7717 * use this to direct branch taken.
7733 return is_branch32_taken(reg, val, opcode);
7734 return is_branch64_taken(reg, val, opcode);
7737 static int flip_opcode(u32 opcode)
7739 /* How can we transform "a <op> b" into "b <op> a"? */
7740 static const u8 opcode_flip[16] = {
7741 /* these stay the same */
7742 [BPF_JEQ >> 4] = BPF_JEQ,
7743 [BPF_JNE >> 4] = BPF_JNE,
7744 [BPF_JSET >> 4] = BPF_JSET,
7745 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7746 [BPF_JGE >> 4] = BPF_JLE,
7747 [BPF_JGT >> 4] = BPF_JLT,
7748 [BPF_JLE >> 4] = BPF_JGE,
7749 [BPF_JLT >> 4] = BPF_JGT,
7750 [BPF_JSGE >> 4] = BPF_JSLE,
7751 [BPF_JSGT >> 4] = BPF_JSLT,
7752 [BPF_JSLE >> 4] = BPF_JSGE,
7753 [BPF_JSLT >> 4] = BPF_JSGT
7755 return opcode_flip[opcode >> 4];
7758 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7759 struct bpf_reg_state *src_reg,
7762 struct bpf_reg_state *pkt;
7764 if (src_reg->type == PTR_TO_PACKET_END) {
7766 } else if (dst_reg->type == PTR_TO_PACKET_END) {
7768 opcode = flip_opcode(opcode);
7773 if (pkt->range >= 0)
7778 /* pkt <= pkt_end */
7782 if (pkt->range == BEYOND_PKT_END)
7783 /* pkt has at last one extra byte beyond pkt_end */
7784 return opcode == BPF_JGT;
7790 /* pkt >= pkt_end */
7791 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7792 return opcode == BPF_JGE;
7798 /* Adjusts the register min/max values in the case that the dst_reg is the
7799 * variable register that we are working on, and src_reg is a constant or we're
7800 * simply doing a BPF_K check.
7801 * In JEQ/JNE cases we also adjust the var_off values.
7803 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7804 struct bpf_reg_state *false_reg,
7806 u8 opcode, bool is_jmp32)
7808 struct tnum false_32off = tnum_subreg(false_reg->var_off);
7809 struct tnum false_64off = false_reg->var_off;
7810 struct tnum true_32off = tnum_subreg(true_reg->var_off);
7811 struct tnum true_64off = true_reg->var_off;
7812 s64 sval = (s64)val;
7813 s32 sval32 = (s32)val32;
7815 /* If the dst_reg is a pointer, we can't learn anything about its
7816 * variable offset from the compare (unless src_reg were a pointer into
7817 * the same object, but we don't bother with that.
7818 * Since false_reg and true_reg have the same type by construction, we
7819 * only need to check one of them for pointerness.
7821 if (__is_pointer_value(false, false_reg))
7828 struct bpf_reg_state *reg =
7829 opcode == BPF_JEQ ? true_reg : false_reg;
7831 /* JEQ/JNE comparison doesn't change the register equivalence.
7833 * if (r1 == 42) goto label;
7835 * label: // here both r1 and r2 are known to be 42.
7837 * Hence when marking register as known preserve it's ID.
7840 __mark_reg32_known(reg, val32);
7842 ___mark_reg_known(reg, val);
7847 false_32off = tnum_and(false_32off, tnum_const(~val32));
7848 if (is_power_of_2(val32))
7849 true_32off = tnum_or(true_32off,
7852 false_64off = tnum_and(false_64off, tnum_const(~val));
7853 if (is_power_of_2(val))
7854 true_64off = tnum_or(true_64off,
7862 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7863 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7865 false_reg->u32_max_value = min(false_reg->u32_max_value,
7867 true_reg->u32_min_value = max(true_reg->u32_min_value,
7870 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7871 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7873 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7874 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7882 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7883 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7885 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7886 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7888 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7889 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7891 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7892 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7900 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7901 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7903 false_reg->u32_min_value = max(false_reg->u32_min_value,
7905 true_reg->u32_max_value = min(true_reg->u32_max_value,
7908 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7909 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7911 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7912 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7920 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7921 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7923 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7924 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7926 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7927 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7929 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7930 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7939 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7940 tnum_subreg(false_32off));
7941 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7942 tnum_subreg(true_32off));
7943 __reg_combine_32_into_64(false_reg);
7944 __reg_combine_32_into_64(true_reg);
7946 false_reg->var_off = false_64off;
7947 true_reg->var_off = true_64off;
7948 __reg_combine_64_into_32(false_reg);
7949 __reg_combine_64_into_32(true_reg);
7953 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7956 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7957 struct bpf_reg_state *false_reg,
7959 u8 opcode, bool is_jmp32)
7961 opcode = flip_opcode(opcode);
7962 /* This uses zero as "not present in table"; luckily the zero opcode,
7963 * BPF_JA, can't get here.
7966 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7969 /* Regs are known to be equal, so intersect their min/max/var_off */
7970 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7971 struct bpf_reg_state *dst_reg)
7973 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7974 dst_reg->umin_value);
7975 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7976 dst_reg->umax_value);
7977 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7978 dst_reg->smin_value);
7979 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7980 dst_reg->smax_value);
7981 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7983 /* We might have learned new bounds from the var_off. */
7984 __update_reg_bounds(src_reg);
7985 __update_reg_bounds(dst_reg);
7986 /* We might have learned something about the sign bit. */
7987 __reg_deduce_bounds(src_reg);
7988 __reg_deduce_bounds(dst_reg);
7989 /* We might have learned some bits from the bounds. */
7990 __reg_bound_offset(src_reg);
7991 __reg_bound_offset(dst_reg);
7992 /* Intersecting with the old var_off might have improved our bounds
7993 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7994 * then new var_off is (0; 0x7f...fc) which improves our umax.
7996 __update_reg_bounds(src_reg);
7997 __update_reg_bounds(dst_reg);
8000 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8001 struct bpf_reg_state *true_dst,
8002 struct bpf_reg_state *false_src,
8003 struct bpf_reg_state *false_dst,
8008 __reg_combine_min_max(true_src, true_dst);
8011 __reg_combine_min_max(false_src, false_dst);
8016 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8017 struct bpf_reg_state *reg, u32 id,
8020 if (reg_type_may_be_null(reg->type) && reg->id == id &&
8021 !WARN_ON_ONCE(!reg->id)) {
8022 /* Old offset (both fixed and variable parts) should
8023 * have been known-zero, because we don't allow pointer
8024 * arithmetic on pointers that might be NULL.
8026 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8027 !tnum_equals_const(reg->var_off, 0) ||
8029 __mark_reg_known_zero(reg);
8033 reg->type = SCALAR_VALUE;
8034 /* We don't need id and ref_obj_id from this point
8035 * onwards anymore, thus we should better reset it,
8036 * so that state pruning has chances to take effect.
8039 reg->ref_obj_id = 0;
8044 mark_ptr_not_null_reg(reg);
8046 if (!reg_may_point_to_spin_lock(reg)) {
8047 /* For not-NULL ptr, reg->ref_obj_id will be reset
8048 * in release_reg_references().
8050 * reg->id is still used by spin_lock ptr. Other
8051 * than spin_lock ptr type, reg->id can be reset.
8058 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8061 struct bpf_reg_state *reg;
8064 for (i = 0; i < MAX_BPF_REG; i++)
8065 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8067 bpf_for_each_spilled_reg(i, state, reg) {
8070 mark_ptr_or_null_reg(state, reg, id, is_null);
8074 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8075 * be folded together at some point.
8077 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8080 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8081 struct bpf_reg_state *regs = state->regs;
8082 u32 ref_obj_id = regs[regno].ref_obj_id;
8083 u32 id = regs[regno].id;
8086 if (ref_obj_id && ref_obj_id == id && is_null)
8087 /* regs[regno] is in the " == NULL" branch.
8088 * No one could have freed the reference state before
8089 * doing the NULL check.
8091 WARN_ON_ONCE(release_reference_state(state, id));
8093 for (i = 0; i <= vstate->curframe; i++)
8094 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
8097 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8098 struct bpf_reg_state *dst_reg,
8099 struct bpf_reg_state *src_reg,
8100 struct bpf_verifier_state *this_branch,
8101 struct bpf_verifier_state *other_branch)
8103 if (BPF_SRC(insn->code) != BPF_X)
8106 /* Pointers are always 64-bit. */
8107 if (BPF_CLASS(insn->code) == BPF_JMP32)
8110 switch (BPF_OP(insn->code)) {
8112 if ((dst_reg->type == PTR_TO_PACKET &&
8113 src_reg->type == PTR_TO_PACKET_END) ||
8114 (dst_reg->type == PTR_TO_PACKET_META &&
8115 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8116 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8117 find_good_pkt_pointers(this_branch, dst_reg,
8118 dst_reg->type, false);
8119 mark_pkt_end(other_branch, insn->dst_reg, true);
8120 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8121 src_reg->type == PTR_TO_PACKET) ||
8122 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8123 src_reg->type == PTR_TO_PACKET_META)) {
8124 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8125 find_good_pkt_pointers(other_branch, src_reg,
8126 src_reg->type, true);
8127 mark_pkt_end(this_branch, insn->src_reg, false);
8133 if ((dst_reg->type == PTR_TO_PACKET &&
8134 src_reg->type == PTR_TO_PACKET_END) ||
8135 (dst_reg->type == PTR_TO_PACKET_META &&
8136 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8137 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8138 find_good_pkt_pointers(other_branch, dst_reg,
8139 dst_reg->type, true);
8140 mark_pkt_end(this_branch, insn->dst_reg, false);
8141 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8142 src_reg->type == PTR_TO_PACKET) ||
8143 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8144 src_reg->type == PTR_TO_PACKET_META)) {
8145 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8146 find_good_pkt_pointers(this_branch, src_reg,
8147 src_reg->type, false);
8148 mark_pkt_end(other_branch, insn->src_reg, true);
8154 if ((dst_reg->type == PTR_TO_PACKET &&
8155 src_reg->type == PTR_TO_PACKET_END) ||
8156 (dst_reg->type == PTR_TO_PACKET_META &&
8157 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8158 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8159 find_good_pkt_pointers(this_branch, dst_reg,
8160 dst_reg->type, true);
8161 mark_pkt_end(other_branch, insn->dst_reg, false);
8162 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8163 src_reg->type == PTR_TO_PACKET) ||
8164 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8165 src_reg->type == PTR_TO_PACKET_META)) {
8166 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8167 find_good_pkt_pointers(other_branch, src_reg,
8168 src_reg->type, false);
8169 mark_pkt_end(this_branch, insn->src_reg, true);
8175 if ((dst_reg->type == PTR_TO_PACKET &&
8176 src_reg->type == PTR_TO_PACKET_END) ||
8177 (dst_reg->type == PTR_TO_PACKET_META &&
8178 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8179 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8180 find_good_pkt_pointers(other_branch, dst_reg,
8181 dst_reg->type, false);
8182 mark_pkt_end(this_branch, insn->dst_reg, true);
8183 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8184 src_reg->type == PTR_TO_PACKET) ||
8185 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8186 src_reg->type == PTR_TO_PACKET_META)) {
8187 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8188 find_good_pkt_pointers(this_branch, src_reg,
8189 src_reg->type, true);
8190 mark_pkt_end(other_branch, insn->src_reg, false);
8202 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8203 struct bpf_reg_state *known_reg)
8205 struct bpf_func_state *state;
8206 struct bpf_reg_state *reg;
8209 for (i = 0; i <= vstate->curframe; i++) {
8210 state = vstate->frame[i];
8211 for (j = 0; j < MAX_BPF_REG; j++) {
8212 reg = &state->regs[j];
8213 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8217 bpf_for_each_spilled_reg(j, state, reg) {
8220 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8226 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8227 struct bpf_insn *insn, int *insn_idx)
8229 struct bpf_verifier_state *this_branch = env->cur_state;
8230 struct bpf_verifier_state *other_branch;
8231 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8232 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8233 u8 opcode = BPF_OP(insn->code);
8238 /* Only conditional jumps are expected to reach here. */
8239 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8240 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8244 if (BPF_SRC(insn->code) == BPF_X) {
8245 if (insn->imm != 0) {
8246 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8250 /* check src1 operand */
8251 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8255 if (is_pointer_value(env, insn->src_reg)) {
8256 verbose(env, "R%d pointer comparison prohibited\n",
8260 src_reg = ®s[insn->src_reg];
8262 if (insn->src_reg != BPF_REG_0) {
8263 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8268 /* check src2 operand */
8269 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8273 dst_reg = ®s[insn->dst_reg];
8274 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8276 if (BPF_SRC(insn->code) == BPF_K) {
8277 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8278 } else if (src_reg->type == SCALAR_VALUE &&
8279 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8280 pred = is_branch_taken(dst_reg,
8281 tnum_subreg(src_reg->var_off).value,
8284 } else if (src_reg->type == SCALAR_VALUE &&
8285 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8286 pred = is_branch_taken(dst_reg,
8287 src_reg->var_off.value,
8290 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8291 reg_is_pkt_pointer_any(src_reg) &&
8293 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8297 /* If we get here with a dst_reg pointer type it is because
8298 * above is_branch_taken() special cased the 0 comparison.
8300 if (!__is_pointer_value(false, dst_reg))
8301 err = mark_chain_precision(env, insn->dst_reg);
8302 if (BPF_SRC(insn->code) == BPF_X && !err &&
8303 !__is_pointer_value(false, src_reg))
8304 err = mark_chain_precision(env, insn->src_reg);
8309 /* only follow the goto, ignore fall-through */
8310 *insn_idx += insn->off;
8312 } else if (pred == 0) {
8313 /* only follow fall-through branch, since
8314 * that's where the program will go
8319 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8323 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8325 /* detect if we are comparing against a constant value so we can adjust
8326 * our min/max values for our dst register.
8327 * this is only legit if both are scalars (or pointers to the same
8328 * object, I suppose, but we don't support that right now), because
8329 * otherwise the different base pointers mean the offsets aren't
8332 if (BPF_SRC(insn->code) == BPF_X) {
8333 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
8335 if (dst_reg->type == SCALAR_VALUE &&
8336 src_reg->type == SCALAR_VALUE) {
8337 if (tnum_is_const(src_reg->var_off) ||
8339 tnum_is_const(tnum_subreg(src_reg->var_off))))
8340 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8342 src_reg->var_off.value,
8343 tnum_subreg(src_reg->var_off).value,
8345 else if (tnum_is_const(dst_reg->var_off) ||
8347 tnum_is_const(tnum_subreg(dst_reg->var_off))))
8348 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8350 dst_reg->var_off.value,
8351 tnum_subreg(dst_reg->var_off).value,
8353 else if (!is_jmp32 &&
8354 (opcode == BPF_JEQ || opcode == BPF_JNE))
8355 /* Comparing for equality, we can combine knowledge */
8356 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8357 &other_branch_regs[insn->dst_reg],
8358 src_reg, dst_reg, opcode);
8360 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8361 find_equal_scalars(this_branch, src_reg);
8362 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8366 } else if (dst_reg->type == SCALAR_VALUE) {
8367 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8368 dst_reg, insn->imm, (u32)insn->imm,
8372 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8373 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8374 find_equal_scalars(this_branch, dst_reg);
8375 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8378 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8379 * NOTE: these optimizations below are related with pointer comparison
8380 * which will never be JMP32.
8382 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8383 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8384 reg_type_may_be_null(dst_reg->type)) {
8385 /* Mark all identical registers in each branch as either
8386 * safe or unknown depending R == 0 or R != 0 conditional.
8388 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8390 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8392 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
8393 this_branch, other_branch) &&
8394 is_pointer_value(env, insn->dst_reg)) {
8395 verbose(env, "R%d pointer comparison prohibited\n",
8399 if (env->log.level & BPF_LOG_LEVEL)
8400 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8404 /* verify BPF_LD_IMM64 instruction */
8405 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8407 struct bpf_insn_aux_data *aux = cur_aux(env);
8408 struct bpf_reg_state *regs = cur_regs(env);
8409 struct bpf_reg_state *dst_reg;
8410 struct bpf_map *map;
8413 if (BPF_SIZE(insn->code) != BPF_DW) {
8414 verbose(env, "invalid BPF_LD_IMM insn\n");
8417 if (insn->off != 0) {
8418 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8422 err = check_reg_arg(env, insn->dst_reg, DST_OP);
8426 dst_reg = ®s[insn->dst_reg];
8427 if (insn->src_reg == 0) {
8428 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8430 dst_reg->type = SCALAR_VALUE;
8431 __mark_reg_known(®s[insn->dst_reg], imm);
8435 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8436 mark_reg_known_zero(env, regs, insn->dst_reg);
8438 dst_reg->type = aux->btf_var.reg_type;
8439 switch (dst_reg->type) {
8441 dst_reg->mem_size = aux->btf_var.mem_size;
8444 case PTR_TO_PERCPU_BTF_ID:
8445 dst_reg->btf = aux->btf_var.btf;
8446 dst_reg->btf_id = aux->btf_var.btf_id;
8449 verbose(env, "bpf verifier is misconfigured\n");
8455 if (insn->src_reg == BPF_PSEUDO_FUNC) {
8456 struct bpf_prog_aux *aux = env->prog->aux;
8457 u32 subprogno = insn[1].imm;
8459 if (!aux->func_info) {
8460 verbose(env, "missing btf func_info\n");
8463 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8464 verbose(env, "callback function not static\n");
8468 dst_reg->type = PTR_TO_FUNC;
8469 dst_reg->subprogno = subprogno;
8473 map = env->used_maps[aux->map_index];
8474 mark_reg_known_zero(env, regs, insn->dst_reg);
8475 dst_reg->map_ptr = map;
8477 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8478 dst_reg->type = PTR_TO_MAP_VALUE;
8479 dst_reg->off = aux->map_off;
8480 if (map_value_has_spin_lock(map))
8481 dst_reg->id = ++env->id_gen;
8482 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8483 dst_reg->type = CONST_PTR_TO_MAP;
8485 verbose(env, "bpf verifier is misconfigured\n");
8492 static bool may_access_skb(enum bpf_prog_type type)
8495 case BPF_PROG_TYPE_SOCKET_FILTER:
8496 case BPF_PROG_TYPE_SCHED_CLS:
8497 case BPF_PROG_TYPE_SCHED_ACT:
8504 /* verify safety of LD_ABS|LD_IND instructions:
8505 * - they can only appear in the programs where ctx == skb
8506 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8507 * preserve R6-R9, and store return value into R0
8510 * ctx == skb == R6 == CTX
8513 * SRC == any register
8514 * IMM == 32-bit immediate
8517 * R0 - 8/16/32-bit skb data converted to cpu endianness
8519 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8521 struct bpf_reg_state *regs = cur_regs(env);
8522 static const int ctx_reg = BPF_REG_6;
8523 u8 mode = BPF_MODE(insn->code);
8526 if (!may_access_skb(resolve_prog_type(env->prog))) {
8527 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8531 if (!env->ops->gen_ld_abs) {
8532 verbose(env, "bpf verifier is misconfigured\n");
8536 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8537 BPF_SIZE(insn->code) == BPF_DW ||
8538 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8539 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8543 /* check whether implicit source operand (register R6) is readable */
8544 err = check_reg_arg(env, ctx_reg, SRC_OP);
8548 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8549 * gen_ld_abs() may terminate the program at runtime, leading to
8552 err = check_reference_leak(env);
8554 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8558 if (env->cur_state->active_spin_lock) {
8559 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8563 if (regs[ctx_reg].type != PTR_TO_CTX) {
8565 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8569 if (mode == BPF_IND) {
8570 /* check explicit source operand */
8571 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8576 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg);
8580 /* reset caller saved regs to unreadable */
8581 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8582 mark_reg_not_init(env, regs, caller_saved[i]);
8583 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8586 /* mark destination R0 register as readable, since it contains
8587 * the value fetched from the packet.
8588 * Already marked as written above.
8590 mark_reg_unknown(env, regs, BPF_REG_0);
8591 /* ld_abs load up to 32-bit skb data. */
8592 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8596 static int check_return_code(struct bpf_verifier_env *env)
8598 struct tnum enforce_attach_type_range = tnum_unknown;
8599 const struct bpf_prog *prog = env->prog;
8600 struct bpf_reg_state *reg;
8601 struct tnum range = tnum_range(0, 1);
8602 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8604 const bool is_subprog = env->cur_state->frame[0]->subprogno;
8606 /* LSM and struct_ops func-ptr's return type could be "void" */
8608 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8609 prog_type == BPF_PROG_TYPE_LSM) &&
8610 !prog->aux->attach_func_proto->type)
8613 /* eBPF calling convetion is such that R0 is used
8614 * to return the value from eBPF program.
8615 * Make sure that it's readable at this time
8616 * of bpf_exit, which means that program wrote
8617 * something into it earlier
8619 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8623 if (is_pointer_value(env, BPF_REG_0)) {
8624 verbose(env, "R0 leaks addr as return value\n");
8628 reg = cur_regs(env) + BPF_REG_0;
8630 if (reg->type != SCALAR_VALUE) {
8631 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8632 reg_type_str[reg->type]);
8638 switch (prog_type) {
8639 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8640 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8641 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8642 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8643 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8644 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8645 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8646 range = tnum_range(1, 1);
8647 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
8648 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
8649 range = tnum_range(0, 3);
8651 case BPF_PROG_TYPE_CGROUP_SKB:
8652 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8653 range = tnum_range(0, 3);
8654 enforce_attach_type_range = tnum_range(2, 3);
8657 case BPF_PROG_TYPE_CGROUP_SOCK:
8658 case BPF_PROG_TYPE_SOCK_OPS:
8659 case BPF_PROG_TYPE_CGROUP_DEVICE:
8660 case BPF_PROG_TYPE_CGROUP_SYSCTL:
8661 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8663 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8664 if (!env->prog->aux->attach_btf_id)
8666 range = tnum_const(0);
8668 case BPF_PROG_TYPE_TRACING:
8669 switch (env->prog->expected_attach_type) {
8670 case BPF_TRACE_FENTRY:
8671 case BPF_TRACE_FEXIT:
8672 range = tnum_const(0);
8674 case BPF_TRACE_RAW_TP:
8675 case BPF_MODIFY_RETURN:
8677 case BPF_TRACE_ITER:
8683 case BPF_PROG_TYPE_SK_LOOKUP:
8684 range = tnum_range(SK_DROP, SK_PASS);
8686 case BPF_PROG_TYPE_EXT:
8687 /* freplace program can return anything as its return value
8688 * depends on the to-be-replaced kernel func or bpf program.
8694 if (reg->type != SCALAR_VALUE) {
8695 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8696 reg_type_str[reg->type]);
8700 if (!tnum_in(range, reg->var_off)) {
8701 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
8705 if (!tnum_is_unknown(enforce_attach_type_range) &&
8706 tnum_in(enforce_attach_type_range, reg->var_off))
8707 env->prog->enforce_expected_attach_type = 1;
8711 /* non-recursive DFS pseudo code
8712 * 1 procedure DFS-iterative(G,v):
8713 * 2 label v as discovered
8714 * 3 let S be a stack
8716 * 5 while S is not empty
8718 * 7 if t is what we're looking for:
8720 * 9 for all edges e in G.adjacentEdges(t) do
8721 * 10 if edge e is already labelled
8722 * 11 continue with the next edge
8723 * 12 w <- G.adjacentVertex(t,e)
8724 * 13 if vertex w is not discovered and not explored
8725 * 14 label e as tree-edge
8726 * 15 label w as discovered
8729 * 18 else if vertex w is discovered
8730 * 19 label e as back-edge
8732 * 21 // vertex w is explored
8733 * 22 label e as forward- or cross-edge
8734 * 23 label t as explored
8739 * 0x11 - discovered and fall-through edge labelled
8740 * 0x12 - discovered and fall-through and branch edges labelled
8751 static u32 state_htab_size(struct bpf_verifier_env *env)
8753 return env->prog->len;
8756 static struct bpf_verifier_state_list **explored_state(
8757 struct bpf_verifier_env *env,
8760 struct bpf_verifier_state *cur = env->cur_state;
8761 struct bpf_func_state *state = cur->frame[cur->curframe];
8763 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8766 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8768 env->insn_aux_data[idx].prune_point = true;
8776 /* t, w, e - match pseudo-code above:
8777 * t - index of current instruction
8778 * w - next instruction
8781 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8784 int *insn_stack = env->cfg.insn_stack;
8785 int *insn_state = env->cfg.insn_state;
8787 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8788 return DONE_EXPLORING;
8790 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8791 return DONE_EXPLORING;
8793 if (w < 0 || w >= env->prog->len) {
8794 verbose_linfo(env, t, "%d: ", t);
8795 verbose(env, "jump out of range from insn %d to %d\n", t, w);
8800 /* mark branch target for state pruning */
8801 init_explored_state(env, w);
8803 if (insn_state[w] == 0) {
8805 insn_state[t] = DISCOVERED | e;
8806 insn_state[w] = DISCOVERED;
8807 if (env->cfg.cur_stack >= env->prog->len)
8809 insn_stack[env->cfg.cur_stack++] = w;
8810 return KEEP_EXPLORING;
8811 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8812 if (loop_ok && env->bpf_capable)
8813 return DONE_EXPLORING;
8814 verbose_linfo(env, t, "%d: ", t);
8815 verbose_linfo(env, w, "%d: ", w);
8816 verbose(env, "back-edge from insn %d to %d\n", t, w);
8818 } else if (insn_state[w] == EXPLORED) {
8819 /* forward- or cross-edge */
8820 insn_state[t] = DISCOVERED | e;
8822 verbose(env, "insn state internal bug\n");
8825 return DONE_EXPLORING;
8828 static int visit_func_call_insn(int t, int insn_cnt,
8829 struct bpf_insn *insns,
8830 struct bpf_verifier_env *env,
8835 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8839 if (t + 1 < insn_cnt)
8840 init_explored_state(env, t + 1);
8842 init_explored_state(env, t);
8843 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8849 /* Visits the instruction at index t and returns one of the following:
8850 * < 0 - an error occurred
8851 * DONE_EXPLORING - the instruction was fully explored
8852 * KEEP_EXPLORING - there is still work to be done before it is fully explored
8854 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
8856 struct bpf_insn *insns = env->prog->insnsi;
8859 if (bpf_pseudo_func(insns + t))
8860 return visit_func_call_insn(t, insn_cnt, insns, env, true);
8862 /* All non-branch instructions have a single fall-through edge. */
8863 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
8864 BPF_CLASS(insns[t].code) != BPF_JMP32)
8865 return push_insn(t, t + 1, FALLTHROUGH, env, false);
8867 switch (BPF_OP(insns[t].code)) {
8869 return DONE_EXPLORING;
8872 return visit_func_call_insn(t, insn_cnt, insns, env,
8873 insns[t].src_reg == BPF_PSEUDO_CALL);
8876 if (BPF_SRC(insns[t].code) != BPF_K)
8879 /* unconditional jump with single edge */
8880 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
8885 /* unconditional jmp is not a good pruning point,
8886 * but it's marked, since backtracking needs
8887 * to record jmp history in is_state_visited().
8889 init_explored_state(env, t + insns[t].off + 1);
8890 /* tell verifier to check for equivalent states
8891 * after every call and jump
8893 if (t + 1 < insn_cnt)
8894 init_explored_state(env, t + 1);
8899 /* conditional jump with two edges */
8900 init_explored_state(env, t);
8901 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8905 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8909 /* non-recursive depth-first-search to detect loops in BPF program
8910 * loop == back-edge in directed graph
8912 static int check_cfg(struct bpf_verifier_env *env)
8914 int insn_cnt = env->prog->len;
8915 int *insn_stack, *insn_state;
8919 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8923 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8929 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8930 insn_stack[0] = 0; /* 0 is the first instruction */
8931 env->cfg.cur_stack = 1;
8933 while (env->cfg.cur_stack > 0) {
8934 int t = insn_stack[env->cfg.cur_stack - 1];
8936 ret = visit_insn(t, insn_cnt, env);
8938 case DONE_EXPLORING:
8939 insn_state[t] = EXPLORED;
8940 env->cfg.cur_stack--;
8942 case KEEP_EXPLORING:
8946 verbose(env, "visit_insn internal bug\n");
8953 if (env->cfg.cur_stack < 0) {
8954 verbose(env, "pop stack internal bug\n");
8959 for (i = 0; i < insn_cnt; i++) {
8960 if (insn_state[i] != EXPLORED) {
8961 verbose(env, "unreachable insn %d\n", i);
8966 ret = 0; /* cfg looks good */
8971 env->cfg.insn_state = env->cfg.insn_stack = NULL;
8975 static int check_abnormal_return(struct bpf_verifier_env *env)
8979 for (i = 1; i < env->subprog_cnt; i++) {
8980 if (env->subprog_info[i].has_ld_abs) {
8981 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8984 if (env->subprog_info[i].has_tail_call) {
8985 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8992 /* The minimum supported BTF func info size */
8993 #define MIN_BPF_FUNCINFO_SIZE 8
8994 #define MAX_FUNCINFO_REC_SIZE 252
8996 static int check_btf_func(struct bpf_verifier_env *env,
8997 const union bpf_attr *attr,
8998 union bpf_attr __user *uattr)
9000 const struct btf_type *type, *func_proto, *ret_type;
9001 u32 i, nfuncs, urec_size, min_size;
9002 u32 krec_size = sizeof(struct bpf_func_info);
9003 struct bpf_func_info *krecord;
9004 struct bpf_func_info_aux *info_aux = NULL;
9005 struct bpf_prog *prog;
9006 const struct btf *btf;
9007 void __user *urecord;
9008 u32 prev_offset = 0;
9012 nfuncs = attr->func_info_cnt;
9014 if (check_abnormal_return(env))
9019 if (nfuncs != env->subprog_cnt) {
9020 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9024 urec_size = attr->func_info_rec_size;
9025 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9026 urec_size > MAX_FUNCINFO_REC_SIZE ||
9027 urec_size % sizeof(u32)) {
9028 verbose(env, "invalid func info rec size %u\n", urec_size);
9033 btf = prog->aux->btf;
9035 urecord = u64_to_user_ptr(attr->func_info);
9036 min_size = min_t(u32, krec_size, urec_size);
9038 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9041 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9045 for (i = 0; i < nfuncs; i++) {
9046 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9048 if (ret == -E2BIG) {
9049 verbose(env, "nonzero tailing record in func info");
9050 /* set the size kernel expects so loader can zero
9051 * out the rest of the record.
9053 if (put_user(min_size, &uattr->func_info_rec_size))
9059 if (copy_from_user(&krecord[i], urecord, min_size)) {
9064 /* check insn_off */
9067 if (krecord[i].insn_off) {
9069 "nonzero insn_off %u for the first func info record",
9070 krecord[i].insn_off);
9073 } else if (krecord[i].insn_off <= prev_offset) {
9075 "same or smaller insn offset (%u) than previous func info record (%u)",
9076 krecord[i].insn_off, prev_offset);
9080 if (env->subprog_info[i].start != krecord[i].insn_off) {
9081 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9086 type = btf_type_by_id(btf, krecord[i].type_id);
9087 if (!type || !btf_type_is_func(type)) {
9088 verbose(env, "invalid type id %d in func info",
9089 krecord[i].type_id);
9092 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9094 func_proto = btf_type_by_id(btf, type->type);
9095 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9096 /* btf_func_check() already verified it during BTF load */
9098 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9100 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9101 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9102 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9105 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9106 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9110 prev_offset = krecord[i].insn_off;
9111 urecord += urec_size;
9114 prog->aux->func_info = krecord;
9115 prog->aux->func_info_cnt = nfuncs;
9116 prog->aux->func_info_aux = info_aux;
9125 static void adjust_btf_func(struct bpf_verifier_env *env)
9127 struct bpf_prog_aux *aux = env->prog->aux;
9130 if (!aux->func_info)
9133 for (i = 0; i < env->subprog_cnt; i++)
9134 aux->func_info[i].insn_off = env->subprog_info[i].start;
9137 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9138 sizeof(((struct bpf_line_info *)(0))->line_col))
9139 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9141 static int check_btf_line(struct bpf_verifier_env *env,
9142 const union bpf_attr *attr,
9143 union bpf_attr __user *uattr)
9145 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9146 struct bpf_subprog_info *sub;
9147 struct bpf_line_info *linfo;
9148 struct bpf_prog *prog;
9149 const struct btf *btf;
9150 void __user *ulinfo;
9153 nr_linfo = attr->line_info_cnt;
9157 rec_size = attr->line_info_rec_size;
9158 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9159 rec_size > MAX_LINEINFO_REC_SIZE ||
9160 rec_size & (sizeof(u32) - 1))
9163 /* Need to zero it in case the userspace may
9164 * pass in a smaller bpf_line_info object.
9166 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9167 GFP_KERNEL | __GFP_NOWARN);
9172 btf = prog->aux->btf;
9175 sub = env->subprog_info;
9176 ulinfo = u64_to_user_ptr(attr->line_info);
9177 expected_size = sizeof(struct bpf_line_info);
9178 ncopy = min_t(u32, expected_size, rec_size);
9179 for (i = 0; i < nr_linfo; i++) {
9180 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9182 if (err == -E2BIG) {
9183 verbose(env, "nonzero tailing record in line_info");
9184 if (put_user(expected_size,
9185 &uattr->line_info_rec_size))
9191 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9197 * Check insn_off to ensure
9198 * 1) strictly increasing AND
9199 * 2) bounded by prog->len
9201 * The linfo[0].insn_off == 0 check logically falls into
9202 * the later "missing bpf_line_info for func..." case
9203 * because the first linfo[0].insn_off must be the
9204 * first sub also and the first sub must have
9205 * subprog_info[0].start == 0.
9207 if ((i && linfo[i].insn_off <= prev_offset) ||
9208 linfo[i].insn_off >= prog->len) {
9209 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9210 i, linfo[i].insn_off, prev_offset,
9216 if (!prog->insnsi[linfo[i].insn_off].code) {
9218 "Invalid insn code at line_info[%u].insn_off\n",
9224 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9225 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9226 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9231 if (s != env->subprog_cnt) {
9232 if (linfo[i].insn_off == sub[s].start) {
9233 sub[s].linfo_idx = i;
9235 } else if (sub[s].start < linfo[i].insn_off) {
9236 verbose(env, "missing bpf_line_info for func#%u\n", s);
9242 prev_offset = linfo[i].insn_off;
9246 if (s != env->subprog_cnt) {
9247 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9248 env->subprog_cnt - s, s);
9253 prog->aux->linfo = linfo;
9254 prog->aux->nr_linfo = nr_linfo;
9263 static int check_btf_info(struct bpf_verifier_env *env,
9264 const union bpf_attr *attr,
9265 union bpf_attr __user *uattr)
9270 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9271 if (check_abnormal_return(env))
9276 btf = btf_get_by_fd(attr->prog_btf_fd);
9278 return PTR_ERR(btf);
9279 env->prog->aux->btf = btf;
9281 err = check_btf_func(env, attr, uattr);
9285 err = check_btf_line(env, attr, uattr);
9292 /* check %cur's range satisfies %old's */
9293 static bool range_within(struct bpf_reg_state *old,
9294 struct bpf_reg_state *cur)
9296 return old->umin_value <= cur->umin_value &&
9297 old->umax_value >= cur->umax_value &&
9298 old->smin_value <= cur->smin_value &&
9299 old->smax_value >= cur->smax_value &&
9300 old->u32_min_value <= cur->u32_min_value &&
9301 old->u32_max_value >= cur->u32_max_value &&
9302 old->s32_min_value <= cur->s32_min_value &&
9303 old->s32_max_value >= cur->s32_max_value;
9306 /* Maximum number of register states that can exist at once */
9307 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9313 /* If in the old state two registers had the same id, then they need to have
9314 * the same id in the new state as well. But that id could be different from
9315 * the old state, so we need to track the mapping from old to new ids.
9316 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9317 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9318 * regs with a different old id could still have new id 9, we don't care about
9320 * So we look through our idmap to see if this old id has been seen before. If
9321 * so, we require the new id to match; otherwise, we add the id pair to the map.
9323 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
9327 for (i = 0; i < ID_MAP_SIZE; i++) {
9328 if (!idmap[i].old) {
9329 /* Reached an empty slot; haven't seen this id before */
9330 idmap[i].old = old_id;
9331 idmap[i].cur = cur_id;
9334 if (idmap[i].old == old_id)
9335 return idmap[i].cur == cur_id;
9337 /* We ran out of idmap slots, which should be impossible */
9342 static void clean_func_state(struct bpf_verifier_env *env,
9343 struct bpf_func_state *st)
9345 enum bpf_reg_liveness live;
9348 for (i = 0; i < BPF_REG_FP; i++) {
9349 live = st->regs[i].live;
9350 /* liveness must not touch this register anymore */
9351 st->regs[i].live |= REG_LIVE_DONE;
9352 if (!(live & REG_LIVE_READ))
9353 /* since the register is unused, clear its state
9354 * to make further comparison simpler
9356 __mark_reg_not_init(env, &st->regs[i]);
9359 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9360 live = st->stack[i].spilled_ptr.live;
9361 /* liveness must not touch this stack slot anymore */
9362 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9363 if (!(live & REG_LIVE_READ)) {
9364 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9365 for (j = 0; j < BPF_REG_SIZE; j++)
9366 st->stack[i].slot_type[j] = STACK_INVALID;
9371 static void clean_verifier_state(struct bpf_verifier_env *env,
9372 struct bpf_verifier_state *st)
9376 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9377 /* all regs in this state in all frames were already marked */
9380 for (i = 0; i <= st->curframe; i++)
9381 clean_func_state(env, st->frame[i]);
9384 /* the parentage chains form a tree.
9385 * the verifier states are added to state lists at given insn and
9386 * pushed into state stack for future exploration.
9387 * when the verifier reaches bpf_exit insn some of the verifer states
9388 * stored in the state lists have their final liveness state already,
9389 * but a lot of states will get revised from liveness point of view when
9390 * the verifier explores other branches.
9393 * 2: if r1 == 100 goto pc+1
9396 * when the verifier reaches exit insn the register r0 in the state list of
9397 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9398 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9399 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9401 * Since the verifier pushes the branch states as it sees them while exploring
9402 * the program the condition of walking the branch instruction for the second
9403 * time means that all states below this branch were already explored and
9404 * their final liveness markes are already propagated.
9405 * Hence when the verifier completes the search of state list in is_state_visited()
9406 * we can call this clean_live_states() function to mark all liveness states
9407 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9409 * This function also clears the registers and stack for states that !READ
9410 * to simplify state merging.
9412 * Important note here that walking the same branch instruction in the callee
9413 * doesn't meant that the states are DONE. The verifier has to compare
9416 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9417 struct bpf_verifier_state *cur)
9419 struct bpf_verifier_state_list *sl;
9422 sl = *explored_state(env, insn);
9424 if (sl->state.branches)
9426 if (sl->state.insn_idx != insn ||
9427 sl->state.curframe != cur->curframe)
9429 for (i = 0; i <= cur->curframe; i++)
9430 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9432 clean_verifier_state(env, &sl->state);
9438 /* Returns true if (rold safe implies rcur safe) */
9439 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9440 struct idpair *idmap)
9444 if (!(rold->live & REG_LIVE_READ))
9445 /* explored state didn't use this */
9448 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9450 if (rold->type == PTR_TO_STACK)
9451 /* two stack pointers are equal only if they're pointing to
9452 * the same stack frame, since fp-8 in foo != fp-8 in bar
9454 return equal && rold->frameno == rcur->frameno;
9459 if (rold->type == NOT_INIT)
9460 /* explored state can't have used this */
9462 if (rcur->type == NOT_INIT)
9464 switch (rold->type) {
9466 if (rcur->type == SCALAR_VALUE) {
9467 if (!rold->precise && !rcur->precise)
9469 /* new val must satisfy old val knowledge */
9470 return range_within(rold, rcur) &&
9471 tnum_in(rold->var_off, rcur->var_off);
9473 /* We're trying to use a pointer in place of a scalar.
9474 * Even if the scalar was unbounded, this could lead to
9475 * pointer leaks because scalars are allowed to leak
9476 * while pointers are not. We could make this safe in
9477 * special cases if root is calling us, but it's
9478 * probably not worth the hassle.
9482 case PTR_TO_MAP_KEY:
9483 case PTR_TO_MAP_VALUE:
9484 /* If the new min/max/var_off satisfy the old ones and
9485 * everything else matches, we are OK.
9486 * 'id' is not compared, since it's only used for maps with
9487 * bpf_spin_lock inside map element and in such cases if
9488 * the rest of the prog is valid for one map element then
9489 * it's valid for all map elements regardless of the key
9490 * used in bpf_map_lookup()
9492 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9493 range_within(rold, rcur) &&
9494 tnum_in(rold->var_off, rcur->var_off);
9495 case PTR_TO_MAP_VALUE_OR_NULL:
9496 /* a PTR_TO_MAP_VALUE could be safe to use as a
9497 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9498 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9499 * checked, doing so could have affected others with the same
9500 * id, and we can't check for that because we lost the id when
9501 * we converted to a PTR_TO_MAP_VALUE.
9503 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9505 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9507 /* Check our ids match any regs they're supposed to */
9508 return check_ids(rold->id, rcur->id, idmap);
9509 case PTR_TO_PACKET_META:
9511 if (rcur->type != rold->type)
9513 /* We must have at least as much range as the old ptr
9514 * did, so that any accesses which were safe before are
9515 * still safe. This is true even if old range < old off,
9516 * since someone could have accessed through (ptr - k), or
9517 * even done ptr -= k in a register, to get a safe access.
9519 if (rold->range > rcur->range)
9521 /* If the offsets don't match, we can't trust our alignment;
9522 * nor can we be sure that we won't fall out of range.
9524 if (rold->off != rcur->off)
9526 /* id relations must be preserved */
9527 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9529 /* new val must satisfy old val knowledge */
9530 return range_within(rold, rcur) &&
9531 tnum_in(rold->var_off, rcur->var_off);
9533 case CONST_PTR_TO_MAP:
9534 case PTR_TO_PACKET_END:
9535 case PTR_TO_FLOW_KEYS:
9537 case PTR_TO_SOCKET_OR_NULL:
9538 case PTR_TO_SOCK_COMMON:
9539 case PTR_TO_SOCK_COMMON_OR_NULL:
9540 case PTR_TO_TCP_SOCK:
9541 case PTR_TO_TCP_SOCK_OR_NULL:
9542 case PTR_TO_XDP_SOCK:
9543 /* Only valid matches are exact, which memcmp() above
9544 * would have accepted
9547 /* Don't know what's going on, just say it's not safe */
9551 /* Shouldn't get here; if we do, say it's not safe */
9556 static bool stacksafe(struct bpf_func_state *old,
9557 struct bpf_func_state *cur,
9558 struct idpair *idmap)
9562 /* walk slots of the explored stack and ignore any additional
9563 * slots in the current stack, since explored(safe) state
9566 for (i = 0; i < old->allocated_stack; i++) {
9567 spi = i / BPF_REG_SIZE;
9569 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9570 i += BPF_REG_SIZE - 1;
9571 /* explored state didn't use this */
9575 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9578 /* explored stack has more populated slots than current stack
9579 * and these slots were used
9581 if (i >= cur->allocated_stack)
9584 /* if old state was safe with misc data in the stack
9585 * it will be safe with zero-initialized stack.
9586 * The opposite is not true
9588 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9589 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9591 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9592 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9593 /* Ex: old explored (safe) state has STACK_SPILL in
9594 * this stack slot, but current has STACK_MISC ->
9595 * this verifier states are not equivalent,
9596 * return false to continue verification of this path
9599 if (i % BPF_REG_SIZE)
9601 if (old->stack[spi].slot_type[0] != STACK_SPILL)
9603 if (!regsafe(&old->stack[spi].spilled_ptr,
9604 &cur->stack[spi].spilled_ptr,
9606 /* when explored and current stack slot are both storing
9607 * spilled registers, check that stored pointers types
9608 * are the same as well.
9609 * Ex: explored safe path could have stored
9610 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9611 * but current path has stored:
9612 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9613 * such verifier states are not equivalent.
9614 * return false to continue verification of this path
9621 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9623 if (old->acquired_refs != cur->acquired_refs)
9625 return !memcmp(old->refs, cur->refs,
9626 sizeof(*old->refs) * old->acquired_refs);
9629 /* compare two verifier states
9631 * all states stored in state_list are known to be valid, since
9632 * verifier reached 'bpf_exit' instruction through them
9634 * this function is called when verifier exploring different branches of
9635 * execution popped from the state stack. If it sees an old state that has
9636 * more strict register state and more strict stack state then this execution
9637 * branch doesn't need to be explored further, since verifier already
9638 * concluded that more strict state leads to valid finish.
9640 * Therefore two states are equivalent if register state is more conservative
9641 * and explored stack state is more conservative than the current one.
9644 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9645 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9647 * In other words if current stack state (one being explored) has more
9648 * valid slots than old one that already passed validation, it means
9649 * the verifier can stop exploring and conclude that current state is valid too
9651 * Similarly with registers. If explored state has register type as invalid
9652 * whereas register type in current state is meaningful, it means that
9653 * the current state will reach 'bpf_exit' instruction safely
9655 static bool func_states_equal(struct bpf_func_state *old,
9656 struct bpf_func_state *cur)
9658 struct idpair *idmap;
9662 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
9663 /* If we failed to allocate the idmap, just say it's not safe */
9667 for (i = 0; i < MAX_BPF_REG; i++) {
9668 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
9672 if (!stacksafe(old, cur, idmap))
9675 if (!refsafe(old, cur))
9683 static bool states_equal(struct bpf_verifier_env *env,
9684 struct bpf_verifier_state *old,
9685 struct bpf_verifier_state *cur)
9689 if (old->curframe != cur->curframe)
9692 /* Verification state from speculative execution simulation
9693 * must never prune a non-speculative execution one.
9695 if (old->speculative && !cur->speculative)
9698 if (old->active_spin_lock != cur->active_spin_lock)
9701 /* for states to be equal callsites have to be the same
9702 * and all frame states need to be equivalent
9704 for (i = 0; i <= old->curframe; i++) {
9705 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9707 if (!func_states_equal(old->frame[i], cur->frame[i]))
9713 /* Return 0 if no propagation happened. Return negative error code if error
9714 * happened. Otherwise, return the propagated bit.
9716 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9717 struct bpf_reg_state *reg,
9718 struct bpf_reg_state *parent_reg)
9720 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9721 u8 flag = reg->live & REG_LIVE_READ;
9724 /* When comes here, read flags of PARENT_REG or REG could be any of
9725 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9726 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9728 if (parent_flag == REG_LIVE_READ64 ||
9729 /* Or if there is no read flag from REG. */
9731 /* Or if the read flag from REG is the same as PARENT_REG. */
9732 parent_flag == flag)
9735 err = mark_reg_read(env, reg, parent_reg, flag);
9742 /* A write screens off any subsequent reads; but write marks come from the
9743 * straight-line code between a state and its parent. When we arrive at an
9744 * equivalent state (jump target or such) we didn't arrive by the straight-line
9745 * code, so read marks in the state must propagate to the parent regardless
9746 * of the state's write marks. That's what 'parent == state->parent' comparison
9747 * in mark_reg_read() is for.
9749 static int propagate_liveness(struct bpf_verifier_env *env,
9750 const struct bpf_verifier_state *vstate,
9751 struct bpf_verifier_state *vparent)
9753 struct bpf_reg_state *state_reg, *parent_reg;
9754 struct bpf_func_state *state, *parent;
9755 int i, frame, err = 0;
9757 if (vparent->curframe != vstate->curframe) {
9758 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9759 vparent->curframe, vstate->curframe);
9762 /* Propagate read liveness of registers... */
9763 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9764 for (frame = 0; frame <= vstate->curframe; frame++) {
9765 parent = vparent->frame[frame];
9766 state = vstate->frame[frame];
9767 parent_reg = parent->regs;
9768 state_reg = state->regs;
9769 /* We don't need to worry about FP liveness, it's read-only */
9770 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9771 err = propagate_liveness_reg(env, &state_reg[i],
9775 if (err == REG_LIVE_READ64)
9776 mark_insn_zext(env, &parent_reg[i]);
9779 /* Propagate stack slots. */
9780 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9781 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9782 parent_reg = &parent->stack[i].spilled_ptr;
9783 state_reg = &state->stack[i].spilled_ptr;
9784 err = propagate_liveness_reg(env, state_reg,
9793 /* find precise scalars in the previous equivalent state and
9794 * propagate them into the current state
9796 static int propagate_precision(struct bpf_verifier_env *env,
9797 const struct bpf_verifier_state *old)
9799 struct bpf_reg_state *state_reg;
9800 struct bpf_func_state *state;
9803 state = old->frame[old->curframe];
9804 state_reg = state->regs;
9805 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9806 if (state_reg->type != SCALAR_VALUE ||
9807 !state_reg->precise)
9809 if (env->log.level & BPF_LOG_LEVEL2)
9810 verbose(env, "propagating r%d\n", i);
9811 err = mark_chain_precision(env, i);
9816 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9817 if (state->stack[i].slot_type[0] != STACK_SPILL)
9819 state_reg = &state->stack[i].spilled_ptr;
9820 if (state_reg->type != SCALAR_VALUE ||
9821 !state_reg->precise)
9823 if (env->log.level & BPF_LOG_LEVEL2)
9824 verbose(env, "propagating fp%d\n",
9825 (-i - 1) * BPF_REG_SIZE);
9826 err = mark_chain_precision_stack(env, i);
9833 static bool states_maybe_looping(struct bpf_verifier_state *old,
9834 struct bpf_verifier_state *cur)
9836 struct bpf_func_state *fold, *fcur;
9837 int i, fr = cur->curframe;
9839 if (old->curframe != fr)
9842 fold = old->frame[fr];
9843 fcur = cur->frame[fr];
9844 for (i = 0; i < MAX_BPF_REG; i++)
9845 if (memcmp(&fold->regs[i], &fcur->regs[i],
9846 offsetof(struct bpf_reg_state, parent)))
9852 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9854 struct bpf_verifier_state_list *new_sl;
9855 struct bpf_verifier_state_list *sl, **pprev;
9856 struct bpf_verifier_state *cur = env->cur_state, *new;
9857 int i, j, err, states_cnt = 0;
9858 bool add_new_state = env->test_state_freq ? true : false;
9860 cur->last_insn_idx = env->prev_insn_idx;
9861 if (!env->insn_aux_data[insn_idx].prune_point)
9862 /* this 'insn_idx' instruction wasn't marked, so we will not
9863 * be doing state search here
9867 /* bpf progs typically have pruning point every 4 instructions
9868 * http://vger.kernel.org/bpfconf2019.html#session-1
9869 * Do not add new state for future pruning if the verifier hasn't seen
9870 * at least 2 jumps and at least 8 instructions.
9871 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9872 * In tests that amounts to up to 50% reduction into total verifier
9873 * memory consumption and 20% verifier time speedup.
9875 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9876 env->insn_processed - env->prev_insn_processed >= 8)
9877 add_new_state = true;
9879 pprev = explored_state(env, insn_idx);
9882 clean_live_states(env, insn_idx, cur);
9886 if (sl->state.insn_idx != insn_idx)
9888 if (sl->state.branches) {
9889 if (states_maybe_looping(&sl->state, cur) &&
9890 states_equal(env, &sl->state, cur)) {
9891 verbose_linfo(env, insn_idx, "; ");
9892 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9895 /* if the verifier is processing a loop, avoid adding new state
9896 * too often, since different loop iterations have distinct
9897 * states and may not help future pruning.
9898 * This threshold shouldn't be too low to make sure that
9899 * a loop with large bound will be rejected quickly.
9900 * The most abusive loop will be:
9902 * if r1 < 1000000 goto pc-2
9903 * 1M insn_procssed limit / 100 == 10k peak states.
9904 * This threshold shouldn't be too high either, since states
9905 * at the end of the loop are likely to be useful in pruning.
9907 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9908 env->insn_processed - env->prev_insn_processed < 100)
9909 add_new_state = false;
9912 if (states_equal(env, &sl->state, cur)) {
9914 /* reached equivalent register/stack state,
9916 * Registers read by the continuation are read by us.
9917 * If we have any write marks in env->cur_state, they
9918 * will prevent corresponding reads in the continuation
9919 * from reaching our parent (an explored_state). Our
9920 * own state will get the read marks recorded, but
9921 * they'll be immediately forgotten as we're pruning
9922 * this state and will pop a new one.
9924 err = propagate_liveness(env, &sl->state, cur);
9926 /* if previous state reached the exit with precision and
9927 * current state is equivalent to it (except precsion marks)
9928 * the precision needs to be propagated back in
9929 * the current state.
9931 err = err ? : push_jmp_history(env, cur);
9932 err = err ? : propagate_precision(env, &sl->state);
9938 /* when new state is not going to be added do not increase miss count.
9939 * Otherwise several loop iterations will remove the state
9940 * recorded earlier. The goal of these heuristics is to have
9941 * states from some iterations of the loop (some in the beginning
9942 * and some at the end) to help pruning.
9946 /* heuristic to determine whether this state is beneficial
9947 * to keep checking from state equivalence point of view.
9948 * Higher numbers increase max_states_per_insn and verification time,
9949 * but do not meaningfully decrease insn_processed.
9951 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9952 /* the state is unlikely to be useful. Remove it to
9953 * speed up verification
9956 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9957 u32 br = sl->state.branches;
9960 "BUG live_done but branches_to_explore %d\n",
9962 free_verifier_state(&sl->state, false);
9966 /* cannot free this state, since parentage chain may
9967 * walk it later. Add it for free_list instead to
9968 * be freed at the end of verification
9970 sl->next = env->free_list;
9971 env->free_list = sl;
9981 if (env->max_states_per_insn < states_cnt)
9982 env->max_states_per_insn = states_cnt;
9984 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9985 return push_jmp_history(env, cur);
9988 return push_jmp_history(env, cur);
9990 /* There were no equivalent states, remember the current one.
9991 * Technically the current state is not proven to be safe yet,
9992 * but it will either reach outer most bpf_exit (which means it's safe)
9993 * or it will be rejected. When there are no loops the verifier won't be
9994 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9995 * again on the way to bpf_exit.
9996 * When looping the sl->state.branches will be > 0 and this state
9997 * will not be considered for equivalence until branches == 0.
9999 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
10002 env->total_states++;
10003 env->peak_states++;
10004 env->prev_jmps_processed = env->jmps_processed;
10005 env->prev_insn_processed = env->insn_processed;
10007 /* add new state to the head of linked list */
10008 new = &new_sl->state;
10009 err = copy_verifier_state(new, cur);
10011 free_verifier_state(new, false);
10015 new->insn_idx = insn_idx;
10016 WARN_ONCE(new->branches != 1,
10017 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
10020 cur->first_insn_idx = insn_idx;
10021 clear_jmp_history(cur);
10022 new_sl->next = *explored_state(env, insn_idx);
10023 *explored_state(env, insn_idx) = new_sl;
10024 /* connect new state to parentage chain. Current frame needs all
10025 * registers connected. Only r6 - r9 of the callers are alive (pushed
10026 * to the stack implicitly by JITs) so in callers' frames connect just
10027 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10028 * the state of the call instruction (with WRITTEN set), and r0 comes
10029 * from callee with its full parentage chain, anyway.
10031 /* clear write marks in current state: the writes we did are not writes
10032 * our child did, so they don't screen off its reads from us.
10033 * (There are no read marks in current state, because reads always mark
10034 * their parent and current state never has children yet. Only
10035 * explored_states can get read marks.)
10037 for (j = 0; j <= cur->curframe; j++) {
10038 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10039 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10040 for (i = 0; i < BPF_REG_FP; i++)
10041 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10044 /* all stack frames are accessible from callee, clear them all */
10045 for (j = 0; j <= cur->curframe; j++) {
10046 struct bpf_func_state *frame = cur->frame[j];
10047 struct bpf_func_state *newframe = new->frame[j];
10049 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10050 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10051 frame->stack[i].spilled_ptr.parent =
10052 &newframe->stack[i].spilled_ptr;
10058 /* Return true if it's OK to have the same insn return a different type. */
10059 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10063 case PTR_TO_SOCKET:
10064 case PTR_TO_SOCKET_OR_NULL:
10065 case PTR_TO_SOCK_COMMON:
10066 case PTR_TO_SOCK_COMMON_OR_NULL:
10067 case PTR_TO_TCP_SOCK:
10068 case PTR_TO_TCP_SOCK_OR_NULL:
10069 case PTR_TO_XDP_SOCK:
10070 case PTR_TO_BTF_ID:
10071 case PTR_TO_BTF_ID_OR_NULL:
10078 /* If an instruction was previously used with particular pointer types, then we
10079 * need to be careful to avoid cases such as the below, where it may be ok
10080 * for one branch accessing the pointer, but not ok for the other branch:
10085 * R1 = some_other_valid_ptr;
10088 * R2 = *(u32 *)(R1 + 0);
10090 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10092 return src != prev && (!reg_type_mismatch_ok(src) ||
10093 !reg_type_mismatch_ok(prev));
10096 static int do_check(struct bpf_verifier_env *env)
10098 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10099 struct bpf_verifier_state *state = env->cur_state;
10100 struct bpf_insn *insns = env->prog->insnsi;
10101 struct bpf_reg_state *regs;
10102 int insn_cnt = env->prog->len;
10103 bool do_print_state = false;
10104 int prev_insn_idx = -1;
10107 struct bpf_insn *insn;
10111 env->prev_insn_idx = prev_insn_idx;
10112 if (env->insn_idx >= insn_cnt) {
10113 verbose(env, "invalid insn idx %d insn_cnt %d\n",
10114 env->insn_idx, insn_cnt);
10118 insn = &insns[env->insn_idx];
10119 class = BPF_CLASS(insn->code);
10121 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10123 "BPF program is too large. Processed %d insn\n",
10124 env->insn_processed);
10128 err = is_state_visited(env, env->insn_idx);
10132 /* found equivalent state, can prune the search */
10133 if (env->log.level & BPF_LOG_LEVEL) {
10134 if (do_print_state)
10135 verbose(env, "\nfrom %d to %d%s: safe\n",
10136 env->prev_insn_idx, env->insn_idx,
10137 env->cur_state->speculative ?
10138 " (speculative execution)" : "");
10140 verbose(env, "%d: safe\n", env->insn_idx);
10142 goto process_bpf_exit;
10145 if (signal_pending(current))
10148 if (need_resched())
10151 if (env->log.level & BPF_LOG_LEVEL2 ||
10152 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10153 if (env->log.level & BPF_LOG_LEVEL2)
10154 verbose(env, "%d:", env->insn_idx);
10156 verbose(env, "\nfrom %d to %d%s:",
10157 env->prev_insn_idx, env->insn_idx,
10158 env->cur_state->speculative ?
10159 " (speculative execution)" : "");
10160 print_verifier_state(env, state->frame[state->curframe]);
10161 do_print_state = false;
10164 if (env->log.level & BPF_LOG_LEVEL) {
10165 const struct bpf_insn_cbs cbs = {
10166 .cb_print = verbose,
10167 .private_data = env,
10170 verbose_linfo(env, env->insn_idx, "; ");
10171 verbose(env, "%d: ", env->insn_idx);
10172 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10175 if (bpf_prog_is_dev_bound(env->prog->aux)) {
10176 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10177 env->prev_insn_idx);
10182 regs = cur_regs(env);
10183 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10184 prev_insn_idx = env->insn_idx;
10186 if (class == BPF_ALU || class == BPF_ALU64) {
10187 err = check_alu_op(env, insn);
10191 } else if (class == BPF_LDX) {
10192 enum bpf_reg_type *prev_src_type, src_reg_type;
10194 /* check for reserved fields is already done */
10196 /* check src operand */
10197 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10201 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10205 src_reg_type = regs[insn->src_reg].type;
10207 /* check that memory (src_reg + off) is readable,
10208 * the state of dst_reg will be updated by this func
10210 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10211 insn->off, BPF_SIZE(insn->code),
10212 BPF_READ, insn->dst_reg, false);
10216 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10218 if (*prev_src_type == NOT_INIT) {
10219 /* saw a valid insn
10220 * dst_reg = *(u32 *)(src_reg + off)
10221 * save type to validate intersecting paths
10223 *prev_src_type = src_reg_type;
10225 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10226 /* ABuser program is trying to use the same insn
10227 * dst_reg = *(u32*) (src_reg + off)
10228 * with different pointer types:
10229 * src_reg == ctx in one branch and
10230 * src_reg == stack|map in some other branch.
10233 verbose(env, "same insn cannot be used with different pointers\n");
10237 } else if (class == BPF_STX) {
10238 enum bpf_reg_type *prev_dst_type, dst_reg_type;
10240 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10241 err = check_atomic(env, env->insn_idx, insn);
10248 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10249 verbose(env, "BPF_STX uses reserved fields\n");
10253 /* check src1 operand */
10254 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10257 /* check src2 operand */
10258 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10262 dst_reg_type = regs[insn->dst_reg].type;
10264 /* check that memory (dst_reg + off) is writeable */
10265 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10266 insn->off, BPF_SIZE(insn->code),
10267 BPF_WRITE, insn->src_reg, false);
10271 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10273 if (*prev_dst_type == NOT_INIT) {
10274 *prev_dst_type = dst_reg_type;
10275 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10276 verbose(env, "same insn cannot be used with different pointers\n");
10280 } else if (class == BPF_ST) {
10281 if (BPF_MODE(insn->code) != BPF_MEM ||
10282 insn->src_reg != BPF_REG_0) {
10283 verbose(env, "BPF_ST uses reserved fields\n");
10286 /* check src operand */
10287 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10291 if (is_ctx_reg(env, insn->dst_reg)) {
10292 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10294 reg_type_str[reg_state(env, insn->dst_reg)->type]);
10298 /* check that memory (dst_reg + off) is writeable */
10299 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10300 insn->off, BPF_SIZE(insn->code),
10301 BPF_WRITE, -1, false);
10305 } else if (class == BPF_JMP || class == BPF_JMP32) {
10306 u8 opcode = BPF_OP(insn->code);
10308 env->jmps_processed++;
10309 if (opcode == BPF_CALL) {
10310 if (BPF_SRC(insn->code) != BPF_K ||
10312 (insn->src_reg != BPF_REG_0 &&
10313 insn->src_reg != BPF_PSEUDO_CALL) ||
10314 insn->dst_reg != BPF_REG_0 ||
10315 class == BPF_JMP32) {
10316 verbose(env, "BPF_CALL uses reserved fields\n");
10320 if (env->cur_state->active_spin_lock &&
10321 (insn->src_reg == BPF_PSEUDO_CALL ||
10322 insn->imm != BPF_FUNC_spin_unlock)) {
10323 verbose(env, "function calls are not allowed while holding a lock\n");
10326 if (insn->src_reg == BPF_PSEUDO_CALL)
10327 err = check_func_call(env, insn, &env->insn_idx);
10329 err = check_helper_call(env, insn, &env->insn_idx);
10332 } else if (opcode == BPF_JA) {
10333 if (BPF_SRC(insn->code) != BPF_K ||
10335 insn->src_reg != BPF_REG_0 ||
10336 insn->dst_reg != BPF_REG_0 ||
10337 class == BPF_JMP32) {
10338 verbose(env, "BPF_JA uses reserved fields\n");
10342 env->insn_idx += insn->off + 1;
10345 } else if (opcode == BPF_EXIT) {
10346 if (BPF_SRC(insn->code) != BPF_K ||
10348 insn->src_reg != BPF_REG_0 ||
10349 insn->dst_reg != BPF_REG_0 ||
10350 class == BPF_JMP32) {
10351 verbose(env, "BPF_EXIT uses reserved fields\n");
10355 if (env->cur_state->active_spin_lock) {
10356 verbose(env, "bpf_spin_unlock is missing\n");
10360 if (state->curframe) {
10361 /* exit from nested function */
10362 err = prepare_func_exit(env, &env->insn_idx);
10365 do_print_state = true;
10369 err = check_reference_leak(env);
10373 err = check_return_code(env);
10377 update_branch_counts(env, env->cur_state);
10378 err = pop_stack(env, &prev_insn_idx,
10379 &env->insn_idx, pop_log);
10381 if (err != -ENOENT)
10385 do_print_state = true;
10389 err = check_cond_jmp_op(env, insn, &env->insn_idx);
10393 } else if (class == BPF_LD) {
10394 u8 mode = BPF_MODE(insn->code);
10396 if (mode == BPF_ABS || mode == BPF_IND) {
10397 err = check_ld_abs(env, insn);
10401 } else if (mode == BPF_IMM) {
10402 err = check_ld_imm(env, insn);
10407 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10409 verbose(env, "invalid BPF_LD mode\n");
10413 verbose(env, "unknown insn class %d\n", class);
10423 static int find_btf_percpu_datasec(struct btf *btf)
10425 const struct btf_type *t;
10430 * Both vmlinux and module each have their own ".data..percpu"
10431 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10432 * types to look at only module's own BTF types.
10434 n = btf_nr_types(btf);
10435 if (btf_is_module(btf))
10436 i = btf_nr_types(btf_vmlinux);
10440 for(; i < n; i++) {
10441 t = btf_type_by_id(btf, i);
10442 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10445 tname = btf_name_by_offset(btf, t->name_off);
10446 if (!strcmp(tname, ".data..percpu"))
10453 /* replace pseudo btf_id with kernel symbol address */
10454 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10455 struct bpf_insn *insn,
10456 struct bpf_insn_aux_data *aux)
10458 const struct btf_var_secinfo *vsi;
10459 const struct btf_type *datasec;
10460 struct btf_mod_pair *btf_mod;
10461 const struct btf_type *t;
10462 const char *sym_name;
10463 bool percpu = false;
10464 u32 type, id = insn->imm;
10468 int i, btf_fd, err;
10470 btf_fd = insn[1].imm;
10472 btf = btf_get_by_fd(btf_fd);
10474 verbose(env, "invalid module BTF object FD specified.\n");
10478 if (!btf_vmlinux) {
10479 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10486 t = btf_type_by_id(btf, id);
10488 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10493 if (!btf_type_is_var(t)) {
10494 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10499 sym_name = btf_name_by_offset(btf, t->name_off);
10500 addr = kallsyms_lookup_name(sym_name);
10502 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10508 datasec_id = find_btf_percpu_datasec(btf);
10509 if (datasec_id > 0) {
10510 datasec = btf_type_by_id(btf, datasec_id);
10511 for_each_vsi(i, datasec, vsi) {
10512 if (vsi->type == id) {
10519 insn[0].imm = (u32)addr;
10520 insn[1].imm = addr >> 32;
10523 t = btf_type_skip_modifiers(btf, type, NULL);
10525 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10526 aux->btf_var.btf = btf;
10527 aux->btf_var.btf_id = type;
10528 } else if (!btf_type_is_struct(t)) {
10529 const struct btf_type *ret;
10533 /* resolve the type size of ksym. */
10534 ret = btf_resolve_size(btf, t, &tsize);
10536 tname = btf_name_by_offset(btf, t->name_off);
10537 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10538 tname, PTR_ERR(ret));
10542 aux->btf_var.reg_type = PTR_TO_MEM;
10543 aux->btf_var.mem_size = tsize;
10545 aux->btf_var.reg_type = PTR_TO_BTF_ID;
10546 aux->btf_var.btf = btf;
10547 aux->btf_var.btf_id = type;
10550 /* check whether we recorded this BTF (and maybe module) already */
10551 for (i = 0; i < env->used_btf_cnt; i++) {
10552 if (env->used_btfs[i].btf == btf) {
10558 if (env->used_btf_cnt >= MAX_USED_BTFS) {
10563 btf_mod = &env->used_btfs[env->used_btf_cnt];
10564 btf_mod->btf = btf;
10565 btf_mod->module = NULL;
10567 /* if we reference variables from kernel module, bump its refcount */
10568 if (btf_is_module(btf)) {
10569 btf_mod->module = btf_try_get_module(btf);
10570 if (!btf_mod->module) {
10576 env->used_btf_cnt++;
10584 static int check_map_prealloc(struct bpf_map *map)
10586 return (map->map_type != BPF_MAP_TYPE_HASH &&
10587 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10588 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10589 !(map->map_flags & BPF_F_NO_PREALLOC);
10592 static bool is_tracing_prog_type(enum bpf_prog_type type)
10595 case BPF_PROG_TYPE_KPROBE:
10596 case BPF_PROG_TYPE_TRACEPOINT:
10597 case BPF_PROG_TYPE_PERF_EVENT:
10598 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10605 static bool is_preallocated_map(struct bpf_map *map)
10607 if (!check_map_prealloc(map))
10609 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10614 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10615 struct bpf_map *map,
10616 struct bpf_prog *prog)
10619 enum bpf_prog_type prog_type = resolve_prog_type(prog);
10621 * Validate that trace type programs use preallocated hash maps.
10623 * For programs attached to PERF events this is mandatory as the
10624 * perf NMI can hit any arbitrary code sequence.
10626 * All other trace types using preallocated hash maps are unsafe as
10627 * well because tracepoint or kprobes can be inside locked regions
10628 * of the memory allocator or at a place where a recursion into the
10629 * memory allocator would see inconsistent state.
10631 * On RT enabled kernels run-time allocation of all trace type
10632 * programs is strictly prohibited due to lock type constraints. On
10633 * !RT kernels it is allowed for backwards compatibility reasons for
10634 * now, but warnings are emitted so developers are made aware of
10635 * the unsafety and can fix their programs before this is enforced.
10637 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10638 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10639 verbose(env, "perf_event programs can only use preallocated hash map\n");
10642 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10643 verbose(env, "trace type programs can only use preallocated hash map\n");
10646 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10647 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10650 if (map_value_has_spin_lock(map)) {
10651 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
10652 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
10656 if (is_tracing_prog_type(prog_type)) {
10657 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10661 if (prog->aux->sleepable) {
10662 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
10667 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10668 !bpf_offload_prog_map_match(prog, map)) {
10669 verbose(env, "offload device mismatch between prog and map\n");
10673 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10674 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10678 if (prog->aux->sleepable)
10679 switch (map->map_type) {
10680 case BPF_MAP_TYPE_HASH:
10681 case BPF_MAP_TYPE_LRU_HASH:
10682 case BPF_MAP_TYPE_ARRAY:
10683 case BPF_MAP_TYPE_PERCPU_HASH:
10684 case BPF_MAP_TYPE_PERCPU_ARRAY:
10685 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10686 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10687 case BPF_MAP_TYPE_HASH_OF_MAPS:
10688 if (!is_preallocated_map(map)) {
10690 "Sleepable programs can only use preallocated maps\n");
10694 case BPF_MAP_TYPE_RINGBUF:
10698 "Sleepable programs can only use array, hash, and ringbuf maps\n");
10705 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10707 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10708 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10711 /* find and rewrite pseudo imm in ld_imm64 instructions:
10713 * 1. if it accesses map FD, replace it with actual map pointer.
10714 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10716 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10718 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10720 struct bpf_insn *insn = env->prog->insnsi;
10721 int insn_cnt = env->prog->len;
10724 err = bpf_prog_calc_tag(env->prog);
10728 for (i = 0; i < insn_cnt; i++, insn++) {
10729 if (BPF_CLASS(insn->code) == BPF_LDX &&
10730 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10731 verbose(env, "BPF_LDX uses reserved fields\n");
10735 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10736 struct bpf_insn_aux_data *aux;
10737 struct bpf_map *map;
10741 if (i == insn_cnt - 1 || insn[1].code != 0 ||
10742 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10743 insn[1].off != 0) {
10744 verbose(env, "invalid bpf_ld_imm64 insn\n");
10748 if (insn[0].src_reg == 0)
10749 /* valid generic load 64-bit imm */
10752 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10753 aux = &env->insn_aux_data[i];
10754 err = check_pseudo_btf_id(env, insn, aux);
10760 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
10761 aux = &env->insn_aux_data[i];
10762 aux->ptr_type = PTR_TO_FUNC;
10766 /* In final convert_pseudo_ld_imm64() step, this is
10767 * converted into regular 64-bit imm load insn.
10769 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10770 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10771 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10772 insn[1].imm != 0)) {
10774 "unrecognized bpf_ld_imm64 insn\n");
10778 f = fdget(insn[0].imm);
10779 map = __bpf_map_get(f);
10781 verbose(env, "fd %d is not pointing to valid bpf_map\n",
10783 return PTR_ERR(map);
10786 err = check_map_prog_compatibility(env, map, env->prog);
10792 aux = &env->insn_aux_data[i];
10793 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10794 addr = (unsigned long)map;
10796 u32 off = insn[1].imm;
10798 if (off >= BPF_MAX_VAR_OFF) {
10799 verbose(env, "direct value offset of %u is not allowed\n", off);
10804 if (!map->ops->map_direct_value_addr) {
10805 verbose(env, "no direct value access support for this map type\n");
10810 err = map->ops->map_direct_value_addr(map, &addr, off);
10812 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10813 map->value_size, off);
10818 aux->map_off = off;
10822 insn[0].imm = (u32)addr;
10823 insn[1].imm = addr >> 32;
10825 /* check whether we recorded this map already */
10826 for (j = 0; j < env->used_map_cnt; j++) {
10827 if (env->used_maps[j] == map) {
10828 aux->map_index = j;
10834 if (env->used_map_cnt >= MAX_USED_MAPS) {
10839 /* hold the map. If the program is rejected by verifier,
10840 * the map will be released by release_maps() or it
10841 * will be used by the valid program until it's unloaded
10842 * and all maps are released in free_used_maps()
10846 aux->map_index = env->used_map_cnt;
10847 env->used_maps[env->used_map_cnt++] = map;
10849 if (bpf_map_is_cgroup_storage(map) &&
10850 bpf_cgroup_storage_assign(env->prog->aux, map)) {
10851 verbose(env, "only one cgroup storage of each type is allowed\n");
10863 /* Basic sanity check before we invest more work here. */
10864 if (!bpf_opcode_in_insntable(insn->code)) {
10865 verbose(env, "unknown opcode %02x\n", insn->code);
10870 /* now all pseudo BPF_LD_IMM64 instructions load valid
10871 * 'struct bpf_map *' into a register instead of user map_fd.
10872 * These pointers will be used later by verifier to validate map access.
10877 /* drop refcnt of maps used by the rejected program */
10878 static void release_maps(struct bpf_verifier_env *env)
10880 __bpf_free_used_maps(env->prog->aux, env->used_maps,
10881 env->used_map_cnt);
10884 /* drop refcnt of maps used by the rejected program */
10885 static void release_btfs(struct bpf_verifier_env *env)
10887 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
10888 env->used_btf_cnt);
10891 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
10892 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10894 struct bpf_insn *insn = env->prog->insnsi;
10895 int insn_cnt = env->prog->len;
10898 for (i = 0; i < insn_cnt; i++, insn++) {
10899 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
10901 if (insn->src_reg == BPF_PSEUDO_FUNC)
10907 /* single env->prog->insni[off] instruction was replaced with the range
10908 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10909 * [0, off) and [off, end) to new locations, so the patched range stays zero
10911 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
10912 struct bpf_prog *new_prog, u32 off, u32 cnt)
10914 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
10915 struct bpf_insn *insn = new_prog->insnsi;
10919 /* aux info at OFF always needs adjustment, no matter fast path
10920 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10921 * original insn at old prog.
10923 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10927 prog_len = new_prog->len;
10928 new_data = vzalloc(array_size(prog_len,
10929 sizeof(struct bpf_insn_aux_data)));
10932 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10933 memcpy(new_data + off + cnt - 1, old_data + off,
10934 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10935 for (i = off; i < off + cnt - 1; i++) {
10936 new_data[i].seen = env->pass_cnt;
10937 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10939 env->insn_aux_data = new_data;
10944 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10950 /* NOTE: fake 'exit' subprog should be updated as well. */
10951 for (i = 0; i <= env->subprog_cnt; i++) {
10952 if (env->subprog_info[i].start <= off)
10954 env->subprog_info[i].start += len - 1;
10958 static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10960 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10961 int i, sz = prog->aux->size_poke_tab;
10962 struct bpf_jit_poke_descriptor *desc;
10964 for (i = 0; i < sz; i++) {
10966 desc->insn_idx += len - 1;
10970 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10971 const struct bpf_insn *patch, u32 len)
10973 struct bpf_prog *new_prog;
10975 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10976 if (IS_ERR(new_prog)) {
10977 if (PTR_ERR(new_prog) == -ERANGE)
10979 "insn %d cannot be patched due to 16-bit range\n",
10980 env->insn_aux_data[off].orig_idx);
10983 if (adjust_insn_aux_data(env, new_prog, off, len))
10985 adjust_subprog_starts(env, off, len);
10986 adjust_poke_descs(new_prog, len);
10990 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10995 /* find first prog starting at or after off (first to remove) */
10996 for (i = 0; i < env->subprog_cnt; i++)
10997 if (env->subprog_info[i].start >= off)
10999 /* find first prog starting at or after off + cnt (first to stay) */
11000 for (j = i; j < env->subprog_cnt; j++)
11001 if (env->subprog_info[j].start >= off + cnt)
11003 /* if j doesn't start exactly at off + cnt, we are just removing
11004 * the front of previous prog
11006 if (env->subprog_info[j].start != off + cnt)
11010 struct bpf_prog_aux *aux = env->prog->aux;
11013 /* move fake 'exit' subprog as well */
11014 move = env->subprog_cnt + 1 - j;
11016 memmove(env->subprog_info + i,
11017 env->subprog_info + j,
11018 sizeof(*env->subprog_info) * move);
11019 env->subprog_cnt -= j - i;
11021 /* remove func_info */
11022 if (aux->func_info) {
11023 move = aux->func_info_cnt - j;
11025 memmove(aux->func_info + i,
11026 aux->func_info + j,
11027 sizeof(*aux->func_info) * move);
11028 aux->func_info_cnt -= j - i;
11029 /* func_info->insn_off is set after all code rewrites,
11030 * in adjust_btf_func() - no need to adjust
11034 /* convert i from "first prog to remove" to "first to adjust" */
11035 if (env->subprog_info[i].start == off)
11039 /* update fake 'exit' subprog as well */
11040 for (; i <= env->subprog_cnt; i++)
11041 env->subprog_info[i].start -= cnt;
11046 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11049 struct bpf_prog *prog = env->prog;
11050 u32 i, l_off, l_cnt, nr_linfo;
11051 struct bpf_line_info *linfo;
11053 nr_linfo = prog->aux->nr_linfo;
11057 linfo = prog->aux->linfo;
11059 /* find first line info to remove, count lines to be removed */
11060 for (i = 0; i < nr_linfo; i++)
11061 if (linfo[i].insn_off >= off)
11066 for (; i < nr_linfo; i++)
11067 if (linfo[i].insn_off < off + cnt)
11072 /* First live insn doesn't match first live linfo, it needs to "inherit"
11073 * last removed linfo. prog is already modified, so prog->len == off
11074 * means no live instructions after (tail of the program was removed).
11076 if (prog->len != off && l_cnt &&
11077 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11079 linfo[--i].insn_off = off + cnt;
11082 /* remove the line info which refer to the removed instructions */
11084 memmove(linfo + l_off, linfo + i,
11085 sizeof(*linfo) * (nr_linfo - i));
11087 prog->aux->nr_linfo -= l_cnt;
11088 nr_linfo = prog->aux->nr_linfo;
11091 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11092 for (i = l_off; i < nr_linfo; i++)
11093 linfo[i].insn_off -= cnt;
11095 /* fix up all subprogs (incl. 'exit') which start >= off */
11096 for (i = 0; i <= env->subprog_cnt; i++)
11097 if (env->subprog_info[i].linfo_idx > l_off) {
11098 /* program may have started in the removed region but
11099 * may not be fully removed
11101 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11102 env->subprog_info[i].linfo_idx -= l_cnt;
11104 env->subprog_info[i].linfo_idx = l_off;
11110 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11112 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11113 unsigned int orig_prog_len = env->prog->len;
11116 if (bpf_prog_is_dev_bound(env->prog->aux))
11117 bpf_prog_offload_remove_insns(env, off, cnt);
11119 err = bpf_remove_insns(env->prog, off, cnt);
11123 err = adjust_subprog_starts_after_remove(env, off, cnt);
11127 err = bpf_adj_linfo_after_remove(env, off, cnt);
11131 memmove(aux_data + off, aux_data + off + cnt,
11132 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11137 /* The verifier does more data flow analysis than llvm and will not
11138 * explore branches that are dead at run time. Malicious programs can
11139 * have dead code too. Therefore replace all dead at-run-time code
11142 * Just nops are not optimal, e.g. if they would sit at the end of the
11143 * program and through another bug we would manage to jump there, then
11144 * we'd execute beyond program memory otherwise. Returning exception
11145 * code also wouldn't work since we can have subprogs where the dead
11146 * code could be located.
11148 static void sanitize_dead_code(struct bpf_verifier_env *env)
11150 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11151 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
11152 struct bpf_insn *insn = env->prog->insnsi;
11153 const int insn_cnt = env->prog->len;
11156 for (i = 0; i < insn_cnt; i++) {
11157 if (aux_data[i].seen)
11159 memcpy(insn + i, &trap, sizeof(trap));
11163 static bool insn_is_cond_jump(u8 code)
11167 if (BPF_CLASS(code) == BPF_JMP32)
11170 if (BPF_CLASS(code) != BPF_JMP)
11174 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11177 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11179 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11180 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11181 struct bpf_insn *insn = env->prog->insnsi;
11182 const int insn_cnt = env->prog->len;
11185 for (i = 0; i < insn_cnt; i++, insn++) {
11186 if (!insn_is_cond_jump(insn->code))
11189 if (!aux_data[i + 1].seen)
11190 ja.off = insn->off;
11191 else if (!aux_data[i + 1 + insn->off].seen)
11196 if (bpf_prog_is_dev_bound(env->prog->aux))
11197 bpf_prog_offload_replace_insn(env, i, &ja);
11199 memcpy(insn, &ja, sizeof(ja));
11203 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11205 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11206 int insn_cnt = env->prog->len;
11209 for (i = 0; i < insn_cnt; i++) {
11213 while (i + j < insn_cnt && !aux_data[i + j].seen)
11218 err = verifier_remove_insns(env, i, j);
11221 insn_cnt = env->prog->len;
11227 static int opt_remove_nops(struct bpf_verifier_env *env)
11229 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11230 struct bpf_insn *insn = env->prog->insnsi;
11231 int insn_cnt = env->prog->len;
11234 for (i = 0; i < insn_cnt; i++) {
11235 if (memcmp(&insn[i], &ja, sizeof(ja)))
11238 err = verifier_remove_insns(env, i, 1);
11248 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11249 const union bpf_attr *attr)
11251 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
11252 struct bpf_insn_aux_data *aux = env->insn_aux_data;
11253 int i, patch_len, delta = 0, len = env->prog->len;
11254 struct bpf_insn *insns = env->prog->insnsi;
11255 struct bpf_prog *new_prog;
11258 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11259 zext_patch[1] = BPF_ZEXT_REG(0);
11260 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11261 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11262 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11263 for (i = 0; i < len; i++) {
11264 int adj_idx = i + delta;
11265 struct bpf_insn insn;
11268 insn = insns[adj_idx];
11269 load_reg = insn_def_regno(&insn);
11270 if (!aux[adj_idx].zext_dst) {
11278 class = BPF_CLASS(code);
11279 if (load_reg == -1)
11282 /* NOTE: arg "reg" (the fourth one) is only used for
11283 * BPF_STX + SRC_OP, so it is safe to pass NULL
11286 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
11287 if (class == BPF_LD &&
11288 BPF_MODE(code) == BPF_IMM)
11293 /* ctx load could be transformed into wider load. */
11294 if (class == BPF_LDX &&
11295 aux[adj_idx].ptr_type == PTR_TO_CTX)
11298 imm_rnd = get_random_int();
11299 rnd_hi32_patch[0] = insn;
11300 rnd_hi32_patch[1].imm = imm_rnd;
11301 rnd_hi32_patch[3].dst_reg = load_reg;
11302 patch = rnd_hi32_patch;
11304 goto apply_patch_buffer;
11307 /* Add in an zero-extend instruction if a) the JIT has requested
11308 * it or b) it's a CMPXCHG.
11310 * The latter is because: BPF_CMPXCHG always loads a value into
11311 * R0, therefore always zero-extends. However some archs'
11312 * equivalent instruction only does this load when the
11313 * comparison is successful. This detail of CMPXCHG is
11314 * orthogonal to the general zero-extension behaviour of the
11315 * CPU, so it's treated independently of bpf_jit_needs_zext.
11317 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
11320 if (WARN_ON(load_reg == -1)) {
11321 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11325 zext_patch[0] = insn;
11326 zext_patch[1].dst_reg = load_reg;
11327 zext_patch[1].src_reg = load_reg;
11328 patch = zext_patch;
11330 apply_patch_buffer:
11331 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11334 env->prog = new_prog;
11335 insns = new_prog->insnsi;
11336 aux = env->insn_aux_data;
11337 delta += patch_len - 1;
11343 /* convert load instructions that access fields of a context type into a
11344 * sequence of instructions that access fields of the underlying structure:
11345 * struct __sk_buff -> struct sk_buff
11346 * struct bpf_sock_ops -> struct sock
11348 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11350 const struct bpf_verifier_ops *ops = env->ops;
11351 int i, cnt, size, ctx_field_size, delta = 0;
11352 const int insn_cnt = env->prog->len;
11353 struct bpf_insn insn_buf[16], *insn;
11354 u32 target_size, size_default, off;
11355 struct bpf_prog *new_prog;
11356 enum bpf_access_type type;
11357 bool is_narrower_load;
11359 if (ops->gen_prologue || env->seen_direct_write) {
11360 if (!ops->gen_prologue) {
11361 verbose(env, "bpf verifier is misconfigured\n");
11364 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11366 if (cnt >= ARRAY_SIZE(insn_buf)) {
11367 verbose(env, "bpf verifier is misconfigured\n");
11370 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11374 env->prog = new_prog;
11379 if (bpf_prog_is_dev_bound(env->prog->aux))
11382 insn = env->prog->insnsi + delta;
11384 for (i = 0; i < insn_cnt; i++, insn++) {
11385 bpf_convert_ctx_access_t convert_ctx_access;
11387 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11388 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11389 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11390 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
11392 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11393 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11394 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11395 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
11400 if (type == BPF_WRITE &&
11401 env->insn_aux_data[i + delta].sanitize_stack_off) {
11402 struct bpf_insn patch[] = {
11403 /* Sanitize suspicious stack slot with zero.
11404 * There are no memory dependencies for this store,
11405 * since it's only using frame pointer and immediate
11408 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11409 env->insn_aux_data[i + delta].sanitize_stack_off,
11411 /* the original STX instruction will immediately
11412 * overwrite the same stack slot with appropriate value
11417 cnt = ARRAY_SIZE(patch);
11418 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11423 env->prog = new_prog;
11424 insn = new_prog->insnsi + i + delta;
11428 switch (env->insn_aux_data[i + delta].ptr_type) {
11430 if (!ops->convert_ctx_access)
11432 convert_ctx_access = ops->convert_ctx_access;
11434 case PTR_TO_SOCKET:
11435 case PTR_TO_SOCK_COMMON:
11436 convert_ctx_access = bpf_sock_convert_ctx_access;
11438 case PTR_TO_TCP_SOCK:
11439 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11441 case PTR_TO_XDP_SOCK:
11442 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11444 case PTR_TO_BTF_ID:
11445 if (type == BPF_READ) {
11446 insn->code = BPF_LDX | BPF_PROBE_MEM |
11447 BPF_SIZE((insn)->code);
11448 env->prog->aux->num_exentries++;
11449 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11450 verbose(env, "Writes through BTF pointers are not allowed\n");
11458 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11459 size = BPF_LDST_BYTES(insn);
11461 /* If the read access is a narrower load of the field,
11462 * convert to a 4/8-byte load, to minimum program type specific
11463 * convert_ctx_access changes. If conversion is successful,
11464 * we will apply proper mask to the result.
11466 is_narrower_load = size < ctx_field_size;
11467 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11469 if (is_narrower_load) {
11472 if (type == BPF_WRITE) {
11473 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11478 if (ctx_field_size == 4)
11480 else if (ctx_field_size == 8)
11481 size_code = BPF_DW;
11483 insn->off = off & ~(size_default - 1);
11484 insn->code = BPF_LDX | BPF_MEM | size_code;
11488 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11490 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11491 (ctx_field_size && !target_size)) {
11492 verbose(env, "bpf verifier is misconfigured\n");
11496 if (is_narrower_load && size < target_size) {
11497 u8 shift = bpf_ctx_narrow_access_offset(
11498 off, size, size_default) * 8;
11499 if (ctx_field_size <= 4) {
11501 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11504 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11505 (1 << size * 8) - 1);
11508 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11511 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
11512 (1ULL << size * 8) - 1);
11516 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11522 /* keep walking new program and skip insns we just inserted */
11523 env->prog = new_prog;
11524 insn = new_prog->insnsi + i + delta;
11530 static int jit_subprogs(struct bpf_verifier_env *env)
11532 struct bpf_prog *prog = env->prog, **func, *tmp;
11533 int i, j, subprog_start, subprog_end = 0, len, subprog;
11534 struct bpf_map *map_ptr;
11535 struct bpf_insn *insn;
11536 void *old_bpf_func;
11537 int err, num_exentries;
11539 if (env->subprog_cnt <= 1)
11542 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11543 if (bpf_pseudo_func(insn)) {
11544 env->insn_aux_data[i].call_imm = insn->imm;
11545 /* subprog is encoded in insn[1].imm */
11549 if (!bpf_pseudo_call(insn))
11551 /* Upon error here we cannot fall back to interpreter but
11552 * need a hard reject of the program. Thus -EFAULT is
11553 * propagated in any case.
11555 subprog = find_subprog(env, i + insn->imm + 1);
11557 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11558 i + insn->imm + 1);
11561 /* temporarily remember subprog id inside insn instead of
11562 * aux_data, since next loop will split up all insns into funcs
11564 insn->off = subprog;
11565 /* remember original imm in case JIT fails and fallback
11566 * to interpreter will be needed
11568 env->insn_aux_data[i].call_imm = insn->imm;
11569 /* point imm to __bpf_call_base+1 from JITs point of view */
11573 err = bpf_prog_alloc_jited_linfo(prog);
11575 goto out_undo_insn;
11578 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11580 goto out_undo_insn;
11582 for (i = 0; i < env->subprog_cnt; i++) {
11583 subprog_start = subprog_end;
11584 subprog_end = env->subprog_info[i + 1].start;
11586 len = subprog_end - subprog_start;
11587 /* BPF_PROG_RUN doesn't call subprogs directly,
11588 * hence main prog stats include the runtime of subprogs.
11589 * subprogs don't have IDs and not reachable via prog_get_next_id
11590 * func[i]->stats will never be accessed and stays NULL
11592 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11595 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11596 len * sizeof(struct bpf_insn));
11597 func[i]->type = prog->type;
11598 func[i]->len = len;
11599 if (bpf_prog_calc_tag(func[i]))
11601 func[i]->is_func = 1;
11602 func[i]->aux->func_idx = i;
11603 /* the btf and func_info will be freed only at prog->aux */
11604 func[i]->aux->btf = prog->aux->btf;
11605 func[i]->aux->func_info = prog->aux->func_info;
11607 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11608 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11611 if (!(insn_idx >= subprog_start &&
11612 insn_idx <= subprog_end))
11615 ret = bpf_jit_add_poke_descriptor(func[i],
11616 &prog->aux->poke_tab[j]);
11618 verbose(env, "adding tail call poke descriptor failed\n");
11622 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11624 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11625 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11627 verbose(env, "tracking tail call prog failed\n");
11632 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11633 * Long term would need debug info to populate names
11635 func[i]->aux->name[0] = 'F';
11636 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11637 func[i]->jit_requested = 1;
11638 func[i]->aux->linfo = prog->aux->linfo;
11639 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11640 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11641 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11643 insn = func[i]->insnsi;
11644 for (j = 0; j < func[i]->len; j++, insn++) {
11645 if (BPF_CLASS(insn->code) == BPF_LDX &&
11646 BPF_MODE(insn->code) == BPF_PROBE_MEM)
11649 func[i]->aux->num_exentries = num_exentries;
11650 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11651 func[i] = bpf_int_jit_compile(func[i]);
11652 if (!func[i]->jited) {
11659 /* Untrack main program's aux structs so that during map_poke_run()
11660 * we will not stumble upon the unfilled poke descriptors; each
11661 * of the main program's poke descs got distributed across subprogs
11662 * and got tracked onto map, so we are sure that none of them will
11663 * be missed after the operation below
11665 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11666 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11668 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11671 /* at this point all bpf functions were successfully JITed
11672 * now populate all bpf_calls with correct addresses and
11673 * run last pass of JIT
11675 for (i = 0; i < env->subprog_cnt; i++) {
11676 insn = func[i]->insnsi;
11677 for (j = 0; j < func[i]->len; j++, insn++) {
11678 if (bpf_pseudo_func(insn)) {
11679 subprog = insn[1].imm;
11680 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
11681 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
11684 if (!bpf_pseudo_call(insn))
11686 subprog = insn->off;
11687 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11691 /* we use the aux data to keep a list of the start addresses
11692 * of the JITed images for each function in the program
11694 * for some architectures, such as powerpc64, the imm field
11695 * might not be large enough to hold the offset of the start
11696 * address of the callee's JITed image from __bpf_call_base
11698 * in such cases, we can lookup the start address of a callee
11699 * by using its subprog id, available from the off field of
11700 * the call instruction, as an index for this list
11702 func[i]->aux->func = func;
11703 func[i]->aux->func_cnt = env->subprog_cnt;
11705 for (i = 0; i < env->subprog_cnt; i++) {
11706 old_bpf_func = func[i]->bpf_func;
11707 tmp = bpf_int_jit_compile(func[i]);
11708 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11709 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11716 /* finally lock prog and jit images for all functions and
11717 * populate kallsysm
11719 for (i = 0; i < env->subprog_cnt; i++) {
11720 bpf_prog_lock_ro(func[i]);
11721 bpf_prog_kallsyms_add(func[i]);
11724 /* Last step: make now unused interpreter insns from main
11725 * prog consistent for later dump requests, so they can
11726 * later look the same as if they were interpreted only.
11728 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11729 if (bpf_pseudo_func(insn)) {
11730 insn[0].imm = env->insn_aux_data[i].call_imm;
11731 insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
11734 if (!bpf_pseudo_call(insn))
11736 insn->off = env->insn_aux_data[i].call_imm;
11737 subprog = find_subprog(env, i + insn->off + 1);
11738 insn->imm = subprog;
11742 prog->bpf_func = func[0]->bpf_func;
11743 prog->aux->func = func;
11744 prog->aux->func_cnt = env->subprog_cnt;
11745 bpf_prog_free_unused_jited_linfo(prog);
11748 for (i = 0; i < env->subprog_cnt; i++) {
11752 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
11753 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
11754 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
11756 bpf_jit_free(func[i]);
11760 /* cleanup main prog to be interpreted */
11761 prog->jit_requested = 0;
11762 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11763 if (!bpf_pseudo_call(insn))
11766 insn->imm = env->insn_aux_data[i].call_imm;
11768 bpf_prog_free_jited_linfo(prog);
11772 static int fixup_call_args(struct bpf_verifier_env *env)
11774 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11775 struct bpf_prog *prog = env->prog;
11776 struct bpf_insn *insn = prog->insnsi;
11781 if (env->prog->jit_requested &&
11782 !bpf_prog_is_dev_bound(env->prog->aux)) {
11783 err = jit_subprogs(env);
11786 if (err == -EFAULT)
11789 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11790 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11791 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11792 * have to be rejected, since interpreter doesn't support them yet.
11794 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11797 for (i = 0; i < prog->len; i++, insn++) {
11798 if (bpf_pseudo_func(insn)) {
11799 /* When JIT fails the progs with callback calls
11800 * have to be rejected, since interpreter doesn't support them yet.
11802 verbose(env, "callbacks are not allowed in non-JITed programs\n");
11806 if (!bpf_pseudo_call(insn))
11808 depth = get_callee_stack_depth(env, insn, i);
11811 bpf_patch_call_args(insn, depth);
11818 /* Do various post-verification rewrites in a single program pass.
11819 * These rewrites simplify JIT and interpreter implementations.
11821 static int do_misc_fixups(struct bpf_verifier_env *env)
11823 struct bpf_prog *prog = env->prog;
11824 bool expect_blinding = bpf_jit_blinding_enabled(prog);
11825 struct bpf_insn *insn = prog->insnsi;
11826 const struct bpf_func_proto *fn;
11827 const int insn_cnt = prog->len;
11828 const struct bpf_map_ops *ops;
11829 struct bpf_insn_aux_data *aux;
11830 struct bpf_insn insn_buf[16];
11831 struct bpf_prog *new_prog;
11832 struct bpf_map *map_ptr;
11833 int i, ret, cnt, delta = 0;
11835 for (i = 0; i < insn_cnt; i++, insn++) {
11836 /* Make divide-by-zero exceptions impossible. */
11837 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11838 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11839 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11840 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11841 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11842 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11843 struct bpf_insn *patchlet;
11844 struct bpf_insn chk_and_div[] = {
11845 /* [R,W]x div 0 -> 0 */
11846 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11847 BPF_JNE | BPF_K, insn->src_reg,
11849 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11850 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11853 struct bpf_insn chk_and_mod[] = {
11854 /* [R,W]x mod 0 -> [R,W]x */
11855 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11856 BPF_JEQ | BPF_K, insn->src_reg,
11857 0, 1 + (is64 ? 0 : 1), 0),
11859 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11860 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11863 patchlet = isdiv ? chk_and_div : chk_and_mod;
11864 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11865 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11867 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11872 env->prog = prog = new_prog;
11873 insn = new_prog->insnsi + i + delta;
11877 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
11878 if (BPF_CLASS(insn->code) == BPF_LD &&
11879 (BPF_MODE(insn->code) == BPF_ABS ||
11880 BPF_MODE(insn->code) == BPF_IND)) {
11881 cnt = env->ops->gen_ld_abs(insn, insn_buf);
11882 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11883 verbose(env, "bpf verifier is misconfigured\n");
11887 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11892 env->prog = prog = new_prog;
11893 insn = new_prog->insnsi + i + delta;
11897 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
11898 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11899 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11900 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11901 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11902 struct bpf_insn insn_buf[16];
11903 struct bpf_insn *patch = &insn_buf[0];
11907 aux = &env->insn_aux_data[i + delta];
11908 if (!aux->alu_state ||
11909 aux->alu_state == BPF_ALU_NON_POINTER)
11912 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11913 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11914 BPF_ALU_SANITIZE_SRC;
11916 off_reg = issrc ? insn->src_reg : insn->dst_reg;
11918 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11919 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
11920 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11921 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11922 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11923 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11925 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
11927 insn->src_reg = BPF_REG_AX;
11929 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
11933 insn->code = insn->code == code_add ?
11934 code_sub : code_add;
11936 if (issrc && isneg)
11937 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11938 cnt = patch - insn_buf;
11940 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11945 env->prog = prog = new_prog;
11946 insn = new_prog->insnsi + i + delta;
11950 if (insn->code != (BPF_JMP | BPF_CALL))
11952 if (insn->src_reg == BPF_PSEUDO_CALL)
11955 if (insn->imm == BPF_FUNC_get_route_realm)
11956 prog->dst_needed = 1;
11957 if (insn->imm == BPF_FUNC_get_prandom_u32)
11958 bpf_user_rnd_init_once();
11959 if (insn->imm == BPF_FUNC_override_return)
11960 prog->kprobe_override = 1;
11961 if (insn->imm == BPF_FUNC_tail_call) {
11962 /* If we tail call into other programs, we
11963 * cannot make any assumptions since they can
11964 * be replaced dynamically during runtime in
11965 * the program array.
11967 prog->cb_access = 1;
11968 if (!allow_tail_call_in_subprogs(env))
11969 prog->aux->stack_depth = MAX_BPF_STACK;
11970 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11972 /* mark bpf_tail_call as different opcode to avoid
11973 * conditional branch in the interpeter for every normal
11974 * call and to prevent accidental JITing by JIT compiler
11975 * that doesn't support bpf_tail_call yet
11978 insn->code = BPF_JMP | BPF_TAIL_CALL;
11980 aux = &env->insn_aux_data[i + delta];
11981 if (env->bpf_capable && !expect_blinding &&
11982 prog->jit_requested &&
11983 !bpf_map_key_poisoned(aux) &&
11984 !bpf_map_ptr_poisoned(aux) &&
11985 !bpf_map_ptr_unpriv(aux)) {
11986 struct bpf_jit_poke_descriptor desc = {
11987 .reason = BPF_POKE_REASON_TAIL_CALL,
11988 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11989 .tail_call.key = bpf_map_key_immediate(aux),
11990 .insn_idx = i + delta,
11993 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11995 verbose(env, "adding tail call poke descriptor failed\n");
11999 insn->imm = ret + 1;
12003 if (!bpf_map_ptr_unpriv(aux))
12006 /* instead of changing every JIT dealing with tail_call
12007 * emit two extra insns:
12008 * if (index >= max_entries) goto out;
12009 * index &= array->index_mask;
12010 * to avoid out-of-bounds cpu speculation
12012 if (bpf_map_ptr_poisoned(aux)) {
12013 verbose(env, "tail_call abusing map_ptr\n");
12017 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12018 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12019 map_ptr->max_entries, 2);
12020 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12021 container_of(map_ptr,
12024 insn_buf[2] = *insn;
12026 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12031 env->prog = prog = new_prog;
12032 insn = new_prog->insnsi + i + delta;
12036 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
12037 * and other inlining handlers are currently limited to 64 bit
12040 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12041 (insn->imm == BPF_FUNC_map_lookup_elem ||
12042 insn->imm == BPF_FUNC_map_update_elem ||
12043 insn->imm == BPF_FUNC_map_delete_elem ||
12044 insn->imm == BPF_FUNC_map_push_elem ||
12045 insn->imm == BPF_FUNC_map_pop_elem ||
12046 insn->imm == BPF_FUNC_map_peek_elem ||
12047 insn->imm == BPF_FUNC_redirect_map)) {
12048 aux = &env->insn_aux_data[i + delta];
12049 if (bpf_map_ptr_poisoned(aux))
12050 goto patch_call_imm;
12052 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12053 ops = map_ptr->ops;
12054 if (insn->imm == BPF_FUNC_map_lookup_elem &&
12055 ops->map_gen_lookup) {
12056 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
12057 if (cnt == -EOPNOTSUPP)
12058 goto patch_map_ops_generic;
12059 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12060 verbose(env, "bpf verifier is misconfigured\n");
12064 new_prog = bpf_patch_insn_data(env, i + delta,
12070 env->prog = prog = new_prog;
12071 insn = new_prog->insnsi + i + delta;
12075 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12076 (void *(*)(struct bpf_map *map, void *key))NULL));
12077 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12078 (int (*)(struct bpf_map *map, void *key))NULL));
12079 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12080 (int (*)(struct bpf_map *map, void *key, void *value,
12082 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12083 (int (*)(struct bpf_map *map, void *value,
12085 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12086 (int (*)(struct bpf_map *map, void *value))NULL));
12087 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12088 (int (*)(struct bpf_map *map, void *value))NULL));
12089 BUILD_BUG_ON(!__same_type(ops->map_redirect,
12090 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12092 patch_map_ops_generic:
12093 switch (insn->imm) {
12094 case BPF_FUNC_map_lookup_elem:
12095 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12098 case BPF_FUNC_map_update_elem:
12099 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12102 case BPF_FUNC_map_delete_elem:
12103 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12106 case BPF_FUNC_map_push_elem:
12107 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12110 case BPF_FUNC_map_pop_elem:
12111 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12114 case BPF_FUNC_map_peek_elem:
12115 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12118 case BPF_FUNC_redirect_map:
12119 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12124 goto patch_call_imm;
12127 /* Implement bpf_jiffies64 inline. */
12128 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12129 insn->imm == BPF_FUNC_jiffies64) {
12130 struct bpf_insn ld_jiffies_addr[2] = {
12131 BPF_LD_IMM64(BPF_REG_0,
12132 (unsigned long)&jiffies),
12135 insn_buf[0] = ld_jiffies_addr[0];
12136 insn_buf[1] = ld_jiffies_addr[1];
12137 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12141 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12147 env->prog = prog = new_prog;
12148 insn = new_prog->insnsi + i + delta;
12153 fn = env->ops->get_func_proto(insn->imm, env->prog);
12154 /* all functions that have prototype and verifier allowed
12155 * programs to call them, must be real in-kernel functions
12159 "kernel subsystem misconfigured func %s#%d\n",
12160 func_id_name(insn->imm), insn->imm);
12163 insn->imm = fn->func - __bpf_call_base;
12166 /* Since poke tab is now finalized, publish aux to tracker. */
12167 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12168 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12169 if (!map_ptr->ops->map_poke_track ||
12170 !map_ptr->ops->map_poke_untrack ||
12171 !map_ptr->ops->map_poke_run) {
12172 verbose(env, "bpf verifier is misconfigured\n");
12176 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12178 verbose(env, "tracking tail call prog failed\n");
12186 static void free_states(struct bpf_verifier_env *env)
12188 struct bpf_verifier_state_list *sl, *sln;
12191 sl = env->free_list;
12194 free_verifier_state(&sl->state, false);
12198 env->free_list = NULL;
12200 if (!env->explored_states)
12203 for (i = 0; i < state_htab_size(env); i++) {
12204 sl = env->explored_states[i];
12208 free_verifier_state(&sl->state, false);
12212 env->explored_states[i] = NULL;
12216 /* The verifier is using insn_aux_data[] to store temporary data during
12217 * verification and to store information for passes that run after the
12218 * verification like dead code sanitization. do_check_common() for subprogram N
12219 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
12220 * temporary data after do_check_common() finds that subprogram N cannot be
12221 * verified independently. pass_cnt counts the number of times
12222 * do_check_common() was run and insn->aux->seen tells the pass number
12223 * insn_aux_data was touched. These variables are compared to clear temporary
12224 * data from failed pass. For testing and experiments do_check_common() can be
12225 * run multiple times even when prior attempt to verify is unsuccessful.
12227 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
12229 struct bpf_insn *insn = env->prog->insnsi;
12230 struct bpf_insn_aux_data *aux;
12233 for (i = 0; i < env->prog->len; i++) {
12234 class = BPF_CLASS(insn[i].code);
12235 if (class != BPF_LDX && class != BPF_STX)
12237 aux = &env->insn_aux_data[i];
12238 if (aux->seen != env->pass_cnt)
12240 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
12244 static int do_check_common(struct bpf_verifier_env *env, int subprog)
12246 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12247 struct bpf_verifier_state *state;
12248 struct bpf_reg_state *regs;
12251 env->prev_linfo = NULL;
12254 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12257 state->curframe = 0;
12258 state->speculative = false;
12259 state->branches = 1;
12260 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12261 if (!state->frame[0]) {
12265 env->cur_state = state;
12266 init_func_state(env, state->frame[0],
12267 BPF_MAIN_FUNC /* callsite */,
12271 regs = state->frame[state->curframe]->regs;
12272 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
12273 ret = btf_prepare_func_args(env, subprog, regs);
12276 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12277 if (regs[i].type == PTR_TO_CTX)
12278 mark_reg_known_zero(env, regs, i);
12279 else if (regs[i].type == SCALAR_VALUE)
12280 mark_reg_unknown(env, regs, i);
12281 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12282 const u32 mem_size = regs[i].mem_size;
12284 mark_reg_known_zero(env, regs, i);
12285 regs[i].mem_size = mem_size;
12286 regs[i].id = ++env->id_gen;
12290 /* 1st arg to a function */
12291 regs[BPF_REG_1].type = PTR_TO_CTX;
12292 mark_reg_known_zero(env, regs, BPF_REG_1);
12293 ret = btf_check_func_arg_match(env, subprog, regs);
12294 if (ret == -EFAULT)
12295 /* unlikely verifier bug. abort.
12296 * ret == 0 and ret < 0 are sadly acceptable for
12297 * main() function due to backward compatibility.
12298 * Like socket filter program may be written as:
12299 * int bpf_prog(struct pt_regs *ctx)
12300 * and never dereference that ctx in the program.
12301 * 'struct pt_regs' is a type mismatch for socket
12302 * filter that should be using 'struct __sk_buff'.
12307 ret = do_check(env);
12309 /* check for NULL is necessary, since cur_state can be freed inside
12310 * do_check() under memory pressure.
12312 if (env->cur_state) {
12313 free_verifier_state(env->cur_state, true);
12314 env->cur_state = NULL;
12316 while (!pop_stack(env, NULL, NULL, false));
12317 if (!ret && pop_log)
12318 bpf_vlog_reset(&env->log, 0);
12321 /* clean aux data in case subprog was rejected */
12322 sanitize_insn_aux_data(env);
12326 /* Verify all global functions in a BPF program one by one based on their BTF.
12327 * All global functions must pass verification. Otherwise the whole program is rejected.
12338 * foo() will be verified first for R1=any_scalar_value. During verification it
12339 * will be assumed that bar() already verified successfully and call to bar()
12340 * from foo() will be checked for type match only. Later bar() will be verified
12341 * independently to check that it's safe for R1=any_scalar_value.
12343 static int do_check_subprogs(struct bpf_verifier_env *env)
12345 struct bpf_prog_aux *aux = env->prog->aux;
12348 if (!aux->func_info)
12351 for (i = 1; i < env->subprog_cnt; i++) {
12352 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12354 env->insn_idx = env->subprog_info[i].start;
12355 WARN_ON_ONCE(env->insn_idx == 0);
12356 ret = do_check_common(env, i);
12359 } else if (env->log.level & BPF_LOG_LEVEL) {
12361 "Func#%d is safe for any args that match its prototype\n",
12368 static int do_check_main(struct bpf_verifier_env *env)
12373 ret = do_check_common(env, 0);
12375 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12380 static void print_verification_stats(struct bpf_verifier_env *env)
12384 if (env->log.level & BPF_LOG_STATS) {
12385 verbose(env, "verification time %lld usec\n",
12386 div_u64(env->verification_time, 1000));
12387 verbose(env, "stack depth ");
12388 for (i = 0; i < env->subprog_cnt; i++) {
12389 u32 depth = env->subprog_info[i].stack_depth;
12391 verbose(env, "%d", depth);
12392 if (i + 1 < env->subprog_cnt)
12395 verbose(env, "\n");
12397 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12398 "total_states %d peak_states %d mark_read %d\n",
12399 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12400 env->max_states_per_insn, env->total_states,
12401 env->peak_states, env->longest_mark_read_walk);
12404 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12406 const struct btf_type *t, *func_proto;
12407 const struct bpf_struct_ops *st_ops;
12408 const struct btf_member *member;
12409 struct bpf_prog *prog = env->prog;
12410 u32 btf_id, member_idx;
12413 btf_id = prog->aux->attach_btf_id;
12414 st_ops = bpf_struct_ops_find(btf_id);
12416 verbose(env, "attach_btf_id %u is not a supported struct\n",
12422 member_idx = prog->expected_attach_type;
12423 if (member_idx >= btf_type_vlen(t)) {
12424 verbose(env, "attach to invalid member idx %u of struct %s\n",
12425 member_idx, st_ops->name);
12429 member = &btf_type_member(t)[member_idx];
12430 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12431 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12434 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12435 mname, member_idx, st_ops->name);
12439 if (st_ops->check_member) {
12440 int err = st_ops->check_member(t, member);
12443 verbose(env, "attach to unsupported member %s of struct %s\n",
12444 mname, st_ops->name);
12449 prog->aux->attach_func_proto = func_proto;
12450 prog->aux->attach_func_name = mname;
12451 env->ops = st_ops->verifier_ops;
12455 #define SECURITY_PREFIX "security_"
12457 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12459 if (within_error_injection_list(addr) ||
12460 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12466 /* list of non-sleepable functions that are otherwise on
12467 * ALLOW_ERROR_INJECTION list
12469 BTF_SET_START(btf_non_sleepable_error_inject)
12470 /* Three functions below can be called from sleepable and non-sleepable context.
12471 * Assume non-sleepable from bpf safety point of view.
12473 BTF_ID(func, __add_to_page_cache_locked)
12474 BTF_ID(func, should_fail_alloc_page)
12475 BTF_ID(func, should_failslab)
12476 BTF_SET_END(btf_non_sleepable_error_inject)
12478 static int check_non_sleepable_error_inject(u32 btf_id)
12480 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12483 int bpf_check_attach_target(struct bpf_verifier_log *log,
12484 const struct bpf_prog *prog,
12485 const struct bpf_prog *tgt_prog,
12487 struct bpf_attach_target_info *tgt_info)
12489 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12490 const char prefix[] = "btf_trace_";
12491 int ret = 0, subprog = -1, i;
12492 const struct btf_type *t;
12493 bool conservative = true;
12499 bpf_log(log, "Tracing programs must provide btf_id\n");
12502 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
12505 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12508 t = btf_type_by_id(btf, btf_id);
12510 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12513 tname = btf_name_by_offset(btf, t->name_off);
12515 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12519 struct bpf_prog_aux *aux = tgt_prog->aux;
12521 for (i = 0; i < aux->func_info_cnt; i++)
12522 if (aux->func_info[i].type_id == btf_id) {
12526 if (subprog == -1) {
12527 bpf_log(log, "Subprog %s doesn't exist\n", tname);
12530 conservative = aux->func_info_aux[subprog].unreliable;
12531 if (prog_extension) {
12532 if (conservative) {
12534 "Cannot replace static functions\n");
12537 if (!prog->jit_requested) {
12539 "Extension programs should be JITed\n");
12543 if (!tgt_prog->jited) {
12544 bpf_log(log, "Can attach to only JITed progs\n");
12547 if (tgt_prog->type == prog->type) {
12548 /* Cannot fentry/fexit another fentry/fexit program.
12549 * Cannot attach program extension to another extension.
12550 * It's ok to attach fentry/fexit to extension program.
12552 bpf_log(log, "Cannot recursively attach\n");
12555 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12557 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12558 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12559 /* Program extensions can extend all program types
12560 * except fentry/fexit. The reason is the following.
12561 * The fentry/fexit programs are used for performance
12562 * analysis, stats and can be attached to any program
12563 * type except themselves. When extension program is
12564 * replacing XDP function it is necessary to allow
12565 * performance analysis of all functions. Both original
12566 * XDP program and its program extension. Hence
12567 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12568 * allowed. If extending of fentry/fexit was allowed it
12569 * would be possible to create long call chain
12570 * fentry->extension->fentry->extension beyond
12571 * reasonable stack size. Hence extending fentry is not
12574 bpf_log(log, "Cannot extend fentry/fexit\n");
12578 if (prog_extension) {
12579 bpf_log(log, "Cannot replace kernel functions\n");
12584 switch (prog->expected_attach_type) {
12585 case BPF_TRACE_RAW_TP:
12588 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12591 if (!btf_type_is_typedef(t)) {
12592 bpf_log(log, "attach_btf_id %u is not a typedef\n",
12596 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12597 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12601 tname += sizeof(prefix) - 1;
12602 t = btf_type_by_id(btf, t->type);
12603 if (!btf_type_is_ptr(t))
12604 /* should never happen in valid vmlinux build */
12606 t = btf_type_by_id(btf, t->type);
12607 if (!btf_type_is_func_proto(t))
12608 /* should never happen in valid vmlinux build */
12612 case BPF_TRACE_ITER:
12613 if (!btf_type_is_func(t)) {
12614 bpf_log(log, "attach_btf_id %u is not a function\n",
12618 t = btf_type_by_id(btf, t->type);
12619 if (!btf_type_is_func_proto(t))
12621 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12626 if (!prog_extension)
12629 case BPF_MODIFY_RETURN:
12631 case BPF_TRACE_FENTRY:
12632 case BPF_TRACE_FEXIT:
12633 if (!btf_type_is_func(t)) {
12634 bpf_log(log, "attach_btf_id %u is not a function\n",
12638 if (prog_extension &&
12639 btf_check_type_match(log, prog, btf, t))
12641 t = btf_type_by_id(btf, t->type);
12642 if (!btf_type_is_func_proto(t))
12645 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12646 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12647 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12650 if (tgt_prog && conservative)
12653 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12659 addr = (long) tgt_prog->bpf_func;
12661 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12663 addr = kallsyms_lookup_name(tname);
12666 "The address of function %s cannot be found\n",
12672 if (prog->aux->sleepable) {
12674 switch (prog->type) {
12675 case BPF_PROG_TYPE_TRACING:
12676 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12677 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12679 if (!check_non_sleepable_error_inject(btf_id) &&
12680 within_error_injection_list(addr))
12683 case BPF_PROG_TYPE_LSM:
12684 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12685 * Only some of them are sleepable.
12687 if (bpf_lsm_is_sleepable_hook(btf_id))
12694 bpf_log(log, "%s is not sleepable\n", tname);
12697 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12699 bpf_log(log, "can't modify return codes of BPF programs\n");
12702 ret = check_attach_modify_return(addr, tname);
12704 bpf_log(log, "%s() is not modifiable\n", tname);
12711 tgt_info->tgt_addr = addr;
12712 tgt_info->tgt_name = tname;
12713 tgt_info->tgt_type = t;
12717 static int check_attach_btf_id(struct bpf_verifier_env *env)
12719 struct bpf_prog *prog = env->prog;
12720 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12721 struct bpf_attach_target_info tgt_info = {};
12722 u32 btf_id = prog->aux->attach_btf_id;
12723 struct bpf_trampoline *tr;
12727 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12728 prog->type != BPF_PROG_TYPE_LSM) {
12729 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12733 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12734 return check_struct_ops_btf_id(env);
12736 if (prog->type != BPF_PROG_TYPE_TRACING &&
12737 prog->type != BPF_PROG_TYPE_LSM &&
12738 prog->type != BPF_PROG_TYPE_EXT)
12741 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12745 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12746 /* to make freplace equivalent to their targets, they need to
12747 * inherit env->ops and expected_attach_type for the rest of the
12750 env->ops = bpf_verifier_ops[tgt_prog->type];
12751 prog->expected_attach_type = tgt_prog->expected_attach_type;
12754 /* store info about the attachment target that will be used later */
12755 prog->aux->attach_func_proto = tgt_info.tgt_type;
12756 prog->aux->attach_func_name = tgt_info.tgt_name;
12759 prog->aux->saved_dst_prog_type = tgt_prog->type;
12760 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12763 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12764 prog->aux->attach_btf_trace = true;
12766 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12767 if (!bpf_iter_prog_supported(prog))
12772 if (prog->type == BPF_PROG_TYPE_LSM) {
12773 ret = bpf_lsm_verify_prog(&env->log, prog);
12778 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
12779 tr = bpf_trampoline_get(key, &tgt_info);
12783 prog->aux->dst_trampoline = tr;
12787 struct btf *bpf_get_btf_vmlinux(void)
12789 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12790 mutex_lock(&bpf_verifier_lock);
12792 btf_vmlinux = btf_parse_vmlinux();
12793 mutex_unlock(&bpf_verifier_lock);
12795 return btf_vmlinux;
12798 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12799 union bpf_attr __user *uattr)
12801 u64 start_time = ktime_get_ns();
12802 struct bpf_verifier_env *env;
12803 struct bpf_verifier_log *log;
12804 int i, len, ret = -EINVAL;
12807 /* no program is valid */
12808 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12811 /* 'struct bpf_verifier_env' can be global, but since it's not small,
12812 * allocate/free it every time bpf_check() is called
12814 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12819 len = (*prog)->len;
12820 env->insn_aux_data =
12821 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12823 if (!env->insn_aux_data)
12825 for (i = 0; i < len; i++)
12826 env->insn_aux_data[i].orig_idx = i;
12828 env->ops = bpf_verifier_ops[env->prog->type];
12829 is_priv = bpf_capable();
12831 bpf_get_btf_vmlinux();
12833 /* grab the mutex to protect few globals used by verifier */
12835 mutex_lock(&bpf_verifier_lock);
12837 if (attr->log_level || attr->log_buf || attr->log_size) {
12838 /* user requested verbose verifier output
12839 * and supplied buffer to store the verification trace
12841 log->level = attr->log_level;
12842 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12843 log->len_total = attr->log_size;
12846 /* log attributes have to be sane */
12847 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
12848 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
12852 if (IS_ERR(btf_vmlinux)) {
12853 /* Either gcc or pahole or kernel are broken. */
12854 verbose(env, "in-kernel BTF is malformed\n");
12855 ret = PTR_ERR(btf_vmlinux);
12856 goto skip_full_check;
12859 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12860 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12861 env->strict_alignment = true;
12862 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12863 env->strict_alignment = false;
12865 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12866 env->allow_uninit_stack = bpf_allow_uninit_stack();
12867 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12868 env->bypass_spec_v1 = bpf_bypass_spec_v1();
12869 env->bypass_spec_v4 = bpf_bypass_spec_v4();
12870 env->bpf_capable = bpf_capable();
12873 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12875 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12876 ret = bpf_prog_offload_verifier_prep(env->prog);
12878 goto skip_full_check;
12881 env->explored_states = kvcalloc(state_htab_size(env),
12882 sizeof(struct bpf_verifier_state_list *),
12885 if (!env->explored_states)
12886 goto skip_full_check;
12888 ret = check_subprogs(env);
12890 goto skip_full_check;
12892 ret = check_btf_info(env, attr, uattr);
12894 goto skip_full_check;
12896 ret = check_attach_btf_id(env);
12898 goto skip_full_check;
12900 ret = resolve_pseudo_ldimm64(env);
12902 goto skip_full_check;
12904 ret = check_cfg(env);
12906 goto skip_full_check;
12908 ret = do_check_subprogs(env);
12909 ret = ret ?: do_check_main(env);
12911 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12912 ret = bpf_prog_offload_finalize(env);
12915 kvfree(env->explored_states);
12918 ret = check_max_stack_depth(env);
12920 /* instruction rewrites happen after this point */
12923 opt_hard_wire_dead_code_branches(env);
12925 ret = opt_remove_dead_code(env);
12927 ret = opt_remove_nops(env);
12930 sanitize_dead_code(env);
12934 /* program is valid, convert *(u32*)(ctx + off) accesses */
12935 ret = convert_ctx_accesses(env);
12938 ret = do_misc_fixups(env);
12940 /* do 32-bit optimization after insn patching has done so those patched
12941 * insns could be handled correctly.
12943 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12944 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12945 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12950 ret = fixup_call_args(env);
12952 env->verification_time = ktime_get_ns() - start_time;
12953 print_verification_stats(env);
12955 if (log->level && bpf_verifier_log_full(log))
12957 if (log->level && !log->ubuf) {
12959 goto err_release_maps;
12963 goto err_release_maps;
12965 if (env->used_map_cnt) {
12966 /* if program passed verifier, update used_maps in bpf_prog_info */
12967 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12968 sizeof(env->used_maps[0]),
12971 if (!env->prog->aux->used_maps) {
12973 goto err_release_maps;
12976 memcpy(env->prog->aux->used_maps, env->used_maps,
12977 sizeof(env->used_maps[0]) * env->used_map_cnt);
12978 env->prog->aux->used_map_cnt = env->used_map_cnt;
12980 if (env->used_btf_cnt) {
12981 /* if program passed verifier, update used_btfs in bpf_prog_aux */
12982 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
12983 sizeof(env->used_btfs[0]),
12985 if (!env->prog->aux->used_btfs) {
12987 goto err_release_maps;
12990 memcpy(env->prog->aux->used_btfs, env->used_btfs,
12991 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
12992 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
12994 if (env->used_map_cnt || env->used_btf_cnt) {
12995 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12996 * bpf_ld_imm64 instructions
12998 convert_pseudo_ld_imm64(env);
13001 adjust_btf_func(env);
13004 if (!env->prog->aux->used_maps)
13005 /* if we didn't copy map pointers into bpf_prog_info, release
13006 * them now. Otherwise free_used_maps() will release them.
13009 if (!env->prog->aux->used_btfs)
13012 /* extension progs temporarily inherit the attach_type of their targets
13013 for verification purposes, so set it back to zero before returning
13015 if (env->prog->type == BPF_PROG_TYPE_EXT)
13016 env->prog->expected_attach_type = 0;
13021 mutex_unlock(&bpf_verifier_lock);
13022 vfree(env->insn_aux_data);