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 struct bpf_call_arg_meta {
232 struct bpf_map *map_ptr;
245 struct btf *btf_vmlinux;
247 static DEFINE_MUTEX(bpf_verifier_lock);
249 static const struct bpf_line_info *
250 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
252 const struct bpf_line_info *linfo;
253 const struct bpf_prog *prog;
257 nr_linfo = prog->aux->nr_linfo;
259 if (!nr_linfo || insn_off >= prog->len)
262 linfo = prog->aux->linfo;
263 for (i = 1; i < nr_linfo; i++)
264 if (insn_off < linfo[i].insn_off)
267 return &linfo[i - 1];
270 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
275 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
277 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
278 "verifier log line truncated - local buffer too short\n");
280 n = min(log->len_total - log->len_used - 1, n);
283 if (log->level == BPF_LOG_KERNEL) {
284 pr_err("BPF:%s\n", log->kbuf);
287 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
293 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
297 if (!bpf_verifier_log_needed(log))
300 log->len_used = new_pos;
301 if (put_user(zero, log->ubuf + new_pos))
305 /* log_level controls verbosity level of eBPF verifier.
306 * bpf_verifier_log_write() is used to dump the verification trace to the log,
307 * so the user can figure out what's wrong with the program
309 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
310 const char *fmt, ...)
314 if (!bpf_verifier_log_needed(&env->log))
318 bpf_verifier_vlog(&env->log, fmt, args);
321 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
323 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
325 struct bpf_verifier_env *env = private_data;
328 if (!bpf_verifier_log_needed(&env->log))
332 bpf_verifier_vlog(&env->log, fmt, args);
336 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
337 const char *fmt, ...)
341 if (!bpf_verifier_log_needed(log))
345 bpf_verifier_vlog(log, fmt, args);
349 static const char *ltrim(const char *s)
357 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
359 const char *prefix_fmt, ...)
361 const struct bpf_line_info *linfo;
363 if (!bpf_verifier_log_needed(&env->log))
366 linfo = find_linfo(env, insn_off);
367 if (!linfo || linfo == env->prev_linfo)
373 va_start(args, prefix_fmt);
374 bpf_verifier_vlog(&env->log, prefix_fmt, args);
379 ltrim(btf_name_by_offset(env->prog->aux->btf,
382 env->prev_linfo = linfo;
385 static bool type_is_pkt_pointer(enum bpf_reg_type type)
387 return type == PTR_TO_PACKET ||
388 type == PTR_TO_PACKET_META;
391 static bool type_is_sk_pointer(enum bpf_reg_type type)
393 return type == PTR_TO_SOCKET ||
394 type == PTR_TO_SOCK_COMMON ||
395 type == PTR_TO_TCP_SOCK ||
396 type == PTR_TO_XDP_SOCK;
399 static bool reg_type_not_null(enum bpf_reg_type type)
401 return type == PTR_TO_SOCKET ||
402 type == PTR_TO_TCP_SOCK ||
403 type == PTR_TO_MAP_VALUE ||
404 type == PTR_TO_SOCK_COMMON;
407 static bool reg_type_may_be_null(enum bpf_reg_type type)
409 return type == PTR_TO_MAP_VALUE_OR_NULL ||
410 type == PTR_TO_SOCKET_OR_NULL ||
411 type == PTR_TO_SOCK_COMMON_OR_NULL ||
412 type == PTR_TO_TCP_SOCK_OR_NULL ||
413 type == PTR_TO_BTF_ID_OR_NULL ||
414 type == PTR_TO_MEM_OR_NULL ||
415 type == PTR_TO_RDONLY_BUF_OR_NULL ||
416 type == PTR_TO_RDWR_BUF_OR_NULL;
419 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
421 return reg->type == PTR_TO_MAP_VALUE &&
422 map_value_has_spin_lock(reg->map_ptr);
425 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
427 return type == PTR_TO_SOCKET ||
428 type == PTR_TO_SOCKET_OR_NULL ||
429 type == PTR_TO_TCP_SOCK ||
430 type == PTR_TO_TCP_SOCK_OR_NULL ||
431 type == PTR_TO_MEM ||
432 type == PTR_TO_MEM_OR_NULL;
435 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
437 return type == ARG_PTR_TO_SOCK_COMMON;
440 static bool arg_type_may_be_null(enum bpf_arg_type type)
442 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
443 type == ARG_PTR_TO_MEM_OR_NULL ||
444 type == ARG_PTR_TO_CTX_OR_NULL ||
445 type == ARG_PTR_TO_SOCKET_OR_NULL ||
446 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
449 /* Determine whether the function releases some resources allocated by another
450 * function call. The first reference type argument will be assumed to be
451 * released by release_reference().
453 static bool is_release_function(enum bpf_func_id func_id)
455 return func_id == BPF_FUNC_sk_release ||
456 func_id == BPF_FUNC_ringbuf_submit ||
457 func_id == BPF_FUNC_ringbuf_discard;
460 static bool may_be_acquire_function(enum bpf_func_id func_id)
462 return func_id == BPF_FUNC_sk_lookup_tcp ||
463 func_id == BPF_FUNC_sk_lookup_udp ||
464 func_id == BPF_FUNC_skc_lookup_tcp ||
465 func_id == BPF_FUNC_map_lookup_elem ||
466 func_id == BPF_FUNC_ringbuf_reserve;
469 static bool is_acquire_function(enum bpf_func_id func_id,
470 const struct bpf_map *map)
472 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
474 if (func_id == BPF_FUNC_sk_lookup_tcp ||
475 func_id == BPF_FUNC_sk_lookup_udp ||
476 func_id == BPF_FUNC_skc_lookup_tcp ||
477 func_id == BPF_FUNC_ringbuf_reserve)
480 if (func_id == BPF_FUNC_map_lookup_elem &&
481 (map_type == BPF_MAP_TYPE_SOCKMAP ||
482 map_type == BPF_MAP_TYPE_SOCKHASH))
488 static bool is_ptr_cast_function(enum bpf_func_id func_id)
490 return func_id == BPF_FUNC_tcp_sock ||
491 func_id == BPF_FUNC_sk_fullsock ||
492 func_id == BPF_FUNC_skc_to_tcp_sock ||
493 func_id == BPF_FUNC_skc_to_tcp6_sock ||
494 func_id == BPF_FUNC_skc_to_udp6_sock ||
495 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
496 func_id == BPF_FUNC_skc_to_tcp_request_sock;
499 /* string representation of 'enum bpf_reg_type' */
500 static const char * const reg_type_str[] = {
502 [SCALAR_VALUE] = "inv",
503 [PTR_TO_CTX] = "ctx",
504 [CONST_PTR_TO_MAP] = "map_ptr",
505 [PTR_TO_MAP_VALUE] = "map_value",
506 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
507 [PTR_TO_STACK] = "fp",
508 [PTR_TO_PACKET] = "pkt",
509 [PTR_TO_PACKET_META] = "pkt_meta",
510 [PTR_TO_PACKET_END] = "pkt_end",
511 [PTR_TO_FLOW_KEYS] = "flow_keys",
512 [PTR_TO_SOCKET] = "sock",
513 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
514 [PTR_TO_SOCK_COMMON] = "sock_common",
515 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
516 [PTR_TO_TCP_SOCK] = "tcp_sock",
517 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
518 [PTR_TO_TP_BUFFER] = "tp_buffer",
519 [PTR_TO_XDP_SOCK] = "xdp_sock",
520 [PTR_TO_BTF_ID] = "ptr_",
521 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
522 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
523 [PTR_TO_MEM] = "mem",
524 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
525 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
526 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
527 [PTR_TO_RDWR_BUF] = "rdwr_buf",
528 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
531 static char slot_type_char[] = {
532 [STACK_INVALID] = '?',
538 static void print_liveness(struct bpf_verifier_env *env,
539 enum bpf_reg_liveness live)
541 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
543 if (live & REG_LIVE_READ)
545 if (live & REG_LIVE_WRITTEN)
547 if (live & REG_LIVE_DONE)
551 static struct bpf_func_state *func(struct bpf_verifier_env *env,
552 const struct bpf_reg_state *reg)
554 struct bpf_verifier_state *cur = env->cur_state;
556 return cur->frame[reg->frameno];
559 const char *kernel_type_name(u32 id)
561 return btf_name_by_offset(btf_vmlinux,
562 btf_type_by_id(btf_vmlinux, id)->name_off);
565 /* The reg state of a pointer or a bounded scalar was saved when
566 * it was spilled to the stack.
568 static bool is_spilled_reg(const struct bpf_stack_state *stack)
570 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
573 static void scrub_spilled_slot(u8 *stype)
575 if (*stype != STACK_INVALID)
579 static void print_verifier_state(struct bpf_verifier_env *env,
580 const struct bpf_func_state *state)
582 const struct bpf_reg_state *reg;
587 verbose(env, " frame%d:", state->frameno);
588 for (i = 0; i < MAX_BPF_REG; i++) {
589 reg = &state->regs[i];
593 verbose(env, " R%d", i);
594 print_liveness(env, reg->live);
595 verbose(env, "=%s", reg_type_str[t]);
596 if (t == SCALAR_VALUE && reg->precise)
598 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
599 tnum_is_const(reg->var_off)) {
600 /* reg->off should be 0 for SCALAR_VALUE */
601 verbose(env, "%lld", reg->var_off.value + reg->off);
603 if (t == PTR_TO_BTF_ID ||
604 t == PTR_TO_BTF_ID_OR_NULL ||
605 t == PTR_TO_PERCPU_BTF_ID)
606 verbose(env, "%s", kernel_type_name(reg->btf_id));
607 verbose(env, "(id=%d", reg->id);
608 if (reg_type_may_be_refcounted_or_null(t))
609 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
610 if (t != SCALAR_VALUE)
611 verbose(env, ",off=%d", reg->off);
612 if (type_is_pkt_pointer(t))
613 verbose(env, ",r=%d", reg->range);
614 else if (t == CONST_PTR_TO_MAP ||
615 t == PTR_TO_MAP_VALUE ||
616 t == PTR_TO_MAP_VALUE_OR_NULL)
617 verbose(env, ",ks=%d,vs=%d",
618 reg->map_ptr->key_size,
619 reg->map_ptr->value_size);
620 if (tnum_is_const(reg->var_off)) {
621 /* Typically an immediate SCALAR_VALUE, but
622 * could be a pointer whose offset is too big
625 verbose(env, ",imm=%llx", reg->var_off.value);
627 if (reg->smin_value != reg->umin_value &&
628 reg->smin_value != S64_MIN)
629 verbose(env, ",smin_value=%lld",
630 (long long)reg->smin_value);
631 if (reg->smax_value != reg->umax_value &&
632 reg->smax_value != S64_MAX)
633 verbose(env, ",smax_value=%lld",
634 (long long)reg->smax_value);
635 if (reg->umin_value != 0)
636 verbose(env, ",umin_value=%llu",
637 (unsigned long long)reg->umin_value);
638 if (reg->umax_value != U64_MAX)
639 verbose(env, ",umax_value=%llu",
640 (unsigned long long)reg->umax_value);
641 if (!tnum_is_unknown(reg->var_off)) {
644 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
645 verbose(env, ",var_off=%s", tn_buf);
647 if (reg->s32_min_value != reg->smin_value &&
648 reg->s32_min_value != S32_MIN)
649 verbose(env, ",s32_min_value=%d",
650 (int)(reg->s32_min_value));
651 if (reg->s32_max_value != reg->smax_value &&
652 reg->s32_max_value != S32_MAX)
653 verbose(env, ",s32_max_value=%d",
654 (int)(reg->s32_max_value));
655 if (reg->u32_min_value != reg->umin_value &&
656 reg->u32_min_value != U32_MIN)
657 verbose(env, ",u32_min_value=%d",
658 (int)(reg->u32_min_value));
659 if (reg->u32_max_value != reg->umax_value &&
660 reg->u32_max_value != U32_MAX)
661 verbose(env, ",u32_max_value=%d",
662 (int)(reg->u32_max_value));
667 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
668 char types_buf[BPF_REG_SIZE + 1];
672 for (j = 0; j < BPF_REG_SIZE; j++) {
673 if (state->stack[i].slot_type[j] != STACK_INVALID)
675 types_buf[j] = slot_type_char[
676 state->stack[i].slot_type[j]];
678 types_buf[BPF_REG_SIZE] = 0;
681 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
682 print_liveness(env, state->stack[i].spilled_ptr.live);
683 if (is_spilled_reg(&state->stack[i])) {
684 reg = &state->stack[i].spilled_ptr;
686 verbose(env, "=%s", reg_type_str[t]);
687 if (t == SCALAR_VALUE && reg->precise)
689 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
690 verbose(env, "%lld", reg->var_off.value + reg->off);
692 verbose(env, "=%s", types_buf);
695 if (state->acquired_refs && state->refs[0].id) {
696 verbose(env, " refs=%d", state->refs[0].id);
697 for (i = 1; i < state->acquired_refs; i++)
698 if (state->refs[i].id)
699 verbose(env, ",%d", state->refs[i].id);
704 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
705 static int copy_##NAME##_state(struct bpf_func_state *dst, \
706 const struct bpf_func_state *src) \
710 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
711 /* internal bug, make state invalid to reject the program */ \
712 memset(dst, 0, sizeof(*dst)); \
715 memcpy(dst->FIELD, src->FIELD, \
716 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
719 /* copy_reference_state() */
720 COPY_STATE_FN(reference, acquired_refs, refs, 1)
721 /* copy_stack_state() */
722 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
725 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
726 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
729 u32 old_size = state->COUNT; \
730 struct bpf_##NAME##_state *new_##FIELD; \
731 int slot = size / SIZE; \
733 if (size <= old_size || !size) { \
736 state->COUNT = slot * SIZE; \
737 if (!size && old_size) { \
738 kfree(state->FIELD); \
739 state->FIELD = NULL; \
743 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
749 memcpy(new_##FIELD, state->FIELD, \
750 sizeof(*new_##FIELD) * (old_size / SIZE)); \
751 memset(new_##FIELD + old_size / SIZE, 0, \
752 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
754 state->COUNT = slot * SIZE; \
755 kfree(state->FIELD); \
756 state->FIELD = new_##FIELD; \
759 /* realloc_reference_state() */
760 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
761 /* realloc_stack_state() */
762 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
763 #undef REALLOC_STATE_FN
765 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
766 * make it consume minimal amount of memory. check_stack_write() access from
767 * the program calls into realloc_func_state() to grow the stack size.
768 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
769 * which realloc_stack_state() copies over. It points to previous
770 * bpf_verifier_state which is never reallocated.
772 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
773 int refs_size, bool copy_old)
775 int err = realloc_reference_state(state, refs_size, copy_old);
778 return realloc_stack_state(state, stack_size, copy_old);
781 /* Acquire a pointer id from the env and update the state->refs to include
782 * this new pointer reference.
783 * On success, returns a valid pointer id to associate with the register
784 * On failure, returns a negative errno.
786 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
788 struct bpf_func_state *state = cur_func(env);
789 int new_ofs = state->acquired_refs;
792 err = realloc_reference_state(state, state->acquired_refs + 1, true);
796 state->refs[new_ofs].id = id;
797 state->refs[new_ofs].insn_idx = insn_idx;
802 /* release function corresponding to acquire_reference_state(). Idempotent. */
803 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
807 last_idx = state->acquired_refs - 1;
808 for (i = 0; i < state->acquired_refs; i++) {
809 if (state->refs[i].id == ptr_id) {
810 if (last_idx && i != last_idx)
811 memcpy(&state->refs[i], &state->refs[last_idx],
812 sizeof(*state->refs));
813 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
814 state->acquired_refs--;
821 static int transfer_reference_state(struct bpf_func_state *dst,
822 struct bpf_func_state *src)
824 int err = realloc_reference_state(dst, src->acquired_refs, false);
827 err = copy_reference_state(dst, src);
833 static void free_func_state(struct bpf_func_state *state)
842 static void clear_jmp_history(struct bpf_verifier_state *state)
844 kfree(state->jmp_history);
845 state->jmp_history = NULL;
846 state->jmp_history_cnt = 0;
849 static void free_verifier_state(struct bpf_verifier_state *state,
854 for (i = 0; i <= state->curframe; i++) {
855 free_func_state(state->frame[i]);
856 state->frame[i] = NULL;
858 clear_jmp_history(state);
863 /* copy verifier state from src to dst growing dst stack space
864 * when necessary to accommodate larger src stack
866 static int copy_func_state(struct bpf_func_state *dst,
867 const struct bpf_func_state *src)
871 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
875 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
876 err = copy_reference_state(dst, src);
879 return copy_stack_state(dst, src);
882 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
883 const struct bpf_verifier_state *src)
885 struct bpf_func_state *dst;
886 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
889 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
890 kfree(dst_state->jmp_history);
891 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
892 if (!dst_state->jmp_history)
895 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
896 dst_state->jmp_history_cnt = src->jmp_history_cnt;
898 /* if dst has more stack frames then src frame, free them */
899 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
900 free_func_state(dst_state->frame[i]);
901 dst_state->frame[i] = NULL;
903 dst_state->speculative = src->speculative;
904 dst_state->curframe = src->curframe;
905 dst_state->active_spin_lock = src->active_spin_lock;
906 dst_state->branches = src->branches;
907 dst_state->parent = src->parent;
908 dst_state->first_insn_idx = src->first_insn_idx;
909 dst_state->last_insn_idx = src->last_insn_idx;
910 for (i = 0; i <= src->curframe; i++) {
911 dst = dst_state->frame[i];
913 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
916 dst_state->frame[i] = dst;
918 err = copy_func_state(dst, src->frame[i]);
925 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
928 u32 br = --st->branches;
930 /* WARN_ON(br > 1) technically makes sense here,
931 * but see comment in push_stack(), hence:
933 WARN_ONCE((int)br < 0,
934 "BUG update_branch_counts:branches_to_explore=%d\n",
942 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
943 int *insn_idx, bool pop_log)
945 struct bpf_verifier_state *cur = env->cur_state;
946 struct bpf_verifier_stack_elem *elem, *head = env->head;
949 if (env->head == NULL)
953 err = copy_verifier_state(cur, &head->st);
958 bpf_vlog_reset(&env->log, head->log_pos);
960 *insn_idx = head->insn_idx;
962 *prev_insn_idx = head->prev_insn_idx;
964 free_verifier_state(&head->st, false);
971 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
972 int insn_idx, int prev_insn_idx,
975 struct bpf_verifier_state *cur = env->cur_state;
976 struct bpf_verifier_stack_elem *elem;
979 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
983 elem->insn_idx = insn_idx;
984 elem->prev_insn_idx = prev_insn_idx;
985 elem->next = env->head;
986 elem->log_pos = env->log.len_used;
989 err = copy_verifier_state(&elem->st, cur);
992 elem->st.speculative |= speculative;
993 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
994 verbose(env, "The sequence of %d jumps is too complex.\n",
998 if (elem->st.parent) {
999 ++elem->st.parent->branches;
1000 /* WARN_ON(branches > 2) technically makes sense here,
1002 * 1. speculative states will bump 'branches' for non-branch
1004 * 2. is_state_visited() heuristics may decide not to create
1005 * a new state for a sequence of branches and all such current
1006 * and cloned states will be pointing to a single parent state
1007 * which might have large 'branches' count.
1012 free_verifier_state(env->cur_state, true);
1013 env->cur_state = NULL;
1014 /* pop all elements and return */
1015 while (!pop_stack(env, NULL, NULL, false));
1019 #define CALLER_SAVED_REGS 6
1020 static const int caller_saved[CALLER_SAVED_REGS] = {
1021 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1024 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1025 struct bpf_reg_state *reg);
1027 /* This helper doesn't clear reg->id */
1028 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1030 reg->var_off = tnum_const(imm);
1031 reg->smin_value = (s64)imm;
1032 reg->smax_value = (s64)imm;
1033 reg->umin_value = imm;
1034 reg->umax_value = imm;
1036 reg->s32_min_value = (s32)imm;
1037 reg->s32_max_value = (s32)imm;
1038 reg->u32_min_value = (u32)imm;
1039 reg->u32_max_value = (u32)imm;
1042 /* Mark the unknown part of a register (variable offset or scalar value) as
1043 * known to have the value @imm.
1045 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1047 /* Clear id, off, and union(map_ptr, range) */
1048 memset(((u8 *)reg) + sizeof(reg->type), 0,
1049 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1050 ___mark_reg_known(reg, imm);
1053 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1055 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1056 reg->s32_min_value = (s32)imm;
1057 reg->s32_max_value = (s32)imm;
1058 reg->u32_min_value = (u32)imm;
1059 reg->u32_max_value = (u32)imm;
1062 /* Mark the 'variable offset' part of a register as zero. This should be
1063 * used only on registers holding a pointer type.
1065 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1067 __mark_reg_known(reg, 0);
1070 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1072 __mark_reg_known(reg, 0);
1073 reg->type = SCALAR_VALUE;
1076 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1077 struct bpf_reg_state *regs, u32 regno)
1079 if (WARN_ON(regno >= MAX_BPF_REG)) {
1080 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1081 /* Something bad happened, let's kill all regs */
1082 for (regno = 0; regno < MAX_BPF_REG; regno++)
1083 __mark_reg_not_init(env, regs + regno);
1086 __mark_reg_known_zero(regs + regno);
1089 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1091 return type_is_pkt_pointer(reg->type);
1094 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1096 return reg_is_pkt_pointer(reg) ||
1097 reg->type == PTR_TO_PACKET_END;
1100 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1101 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1102 enum bpf_reg_type which)
1104 /* The register can already have a range from prior markings.
1105 * This is fine as long as it hasn't been advanced from its
1108 return reg->type == which &&
1111 tnum_equals_const(reg->var_off, 0);
1114 /* Reset the min/max bounds of a register */
1115 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1117 reg->smin_value = S64_MIN;
1118 reg->smax_value = S64_MAX;
1119 reg->umin_value = 0;
1120 reg->umax_value = U64_MAX;
1122 reg->s32_min_value = S32_MIN;
1123 reg->s32_max_value = S32_MAX;
1124 reg->u32_min_value = 0;
1125 reg->u32_max_value = U32_MAX;
1128 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1130 reg->smin_value = S64_MIN;
1131 reg->smax_value = S64_MAX;
1132 reg->umin_value = 0;
1133 reg->umax_value = U64_MAX;
1136 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1138 reg->s32_min_value = S32_MIN;
1139 reg->s32_max_value = S32_MAX;
1140 reg->u32_min_value = 0;
1141 reg->u32_max_value = U32_MAX;
1144 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1146 struct tnum var32_off = tnum_subreg(reg->var_off);
1148 /* min signed is max(sign bit) | min(other bits) */
1149 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1150 var32_off.value | (var32_off.mask & S32_MIN));
1151 /* max signed is min(sign bit) | max(other bits) */
1152 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1153 var32_off.value | (var32_off.mask & S32_MAX));
1154 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1155 reg->u32_max_value = min(reg->u32_max_value,
1156 (u32)(var32_off.value | var32_off.mask));
1159 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1161 /* min signed is max(sign bit) | min(other bits) */
1162 reg->smin_value = max_t(s64, reg->smin_value,
1163 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1164 /* max signed is min(sign bit) | max(other bits) */
1165 reg->smax_value = min_t(s64, reg->smax_value,
1166 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1167 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1168 reg->umax_value = min(reg->umax_value,
1169 reg->var_off.value | reg->var_off.mask);
1172 static void __update_reg_bounds(struct bpf_reg_state *reg)
1174 __update_reg32_bounds(reg);
1175 __update_reg64_bounds(reg);
1178 /* Uses signed min/max values to inform unsigned, and vice-versa */
1179 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1181 /* Learn sign from signed bounds.
1182 * If we cannot cross the sign boundary, then signed and unsigned bounds
1183 * are the same, so combine. This works even in the negative case, e.g.
1184 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1186 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1187 reg->s32_min_value = reg->u32_min_value =
1188 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1189 reg->s32_max_value = reg->u32_max_value =
1190 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1193 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1194 * boundary, so we must be careful.
1196 if ((s32)reg->u32_max_value >= 0) {
1197 /* Positive. We can't learn anything from the smin, but smax
1198 * is positive, hence safe.
1200 reg->s32_min_value = reg->u32_min_value;
1201 reg->s32_max_value = reg->u32_max_value =
1202 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1203 } else if ((s32)reg->u32_min_value < 0) {
1204 /* Negative. We can't learn anything from the smax, but smin
1205 * is negative, hence safe.
1207 reg->s32_min_value = reg->u32_min_value =
1208 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1209 reg->s32_max_value = reg->u32_max_value;
1213 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1215 /* Learn sign from signed bounds.
1216 * If we cannot cross the sign boundary, then signed and unsigned bounds
1217 * are the same, so combine. This works even in the negative case, e.g.
1218 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1220 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1221 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1223 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1227 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1228 * boundary, so we must be careful.
1230 if ((s64)reg->umax_value >= 0) {
1231 /* Positive. We can't learn anything from the smin, but smax
1232 * is positive, hence safe.
1234 reg->smin_value = reg->umin_value;
1235 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1237 } else if ((s64)reg->umin_value < 0) {
1238 /* Negative. We can't learn anything from the smax, but smin
1239 * is negative, hence safe.
1241 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1243 reg->smax_value = reg->umax_value;
1247 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1249 __reg32_deduce_bounds(reg);
1250 __reg64_deduce_bounds(reg);
1253 /* Attempts to improve var_off based on unsigned min/max information */
1254 static void __reg_bound_offset(struct bpf_reg_state *reg)
1256 struct tnum var64_off = tnum_intersect(reg->var_off,
1257 tnum_range(reg->umin_value,
1259 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1260 tnum_range(reg->u32_min_value,
1261 reg->u32_max_value));
1263 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1266 static void reg_bounds_sync(struct bpf_reg_state *reg)
1268 /* We might have learned new bounds from the var_off. */
1269 __update_reg_bounds(reg);
1270 /* We might have learned something about the sign bit. */
1271 __reg_deduce_bounds(reg);
1272 /* We might have learned some bits from the bounds. */
1273 __reg_bound_offset(reg);
1274 /* Intersecting with the old var_off might have improved our bounds
1275 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1276 * then new var_off is (0; 0x7f...fc) which improves our umax.
1278 __update_reg_bounds(reg);
1281 static bool __reg32_bound_s64(s32 a)
1283 return a >= 0 && a <= S32_MAX;
1286 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1288 reg->umin_value = reg->u32_min_value;
1289 reg->umax_value = reg->u32_max_value;
1291 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1292 * be positive otherwise set to worse case bounds and refine later
1295 if (__reg32_bound_s64(reg->s32_min_value) &&
1296 __reg32_bound_s64(reg->s32_max_value)) {
1297 reg->smin_value = reg->s32_min_value;
1298 reg->smax_value = reg->s32_max_value;
1300 reg->smin_value = 0;
1301 reg->smax_value = U32_MAX;
1305 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1307 /* special case when 64-bit register has upper 32-bit register
1308 * zeroed. Typically happens after zext or <<32, >>32 sequence
1309 * allowing us to use 32-bit bounds directly,
1311 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1312 __reg_assign_32_into_64(reg);
1314 /* Otherwise the best we can do is push lower 32bit known and
1315 * unknown bits into register (var_off set from jmp logic)
1316 * then learn as much as possible from the 64-bit tnum
1317 * known and unknown bits. The previous smin/smax bounds are
1318 * invalid here because of jmp32 compare so mark them unknown
1319 * so they do not impact tnum bounds calculation.
1321 __mark_reg64_unbounded(reg);
1323 reg_bounds_sync(reg);
1326 static bool __reg64_bound_s32(s64 a)
1328 return a >= S32_MIN && a <= S32_MAX;
1331 static bool __reg64_bound_u32(u64 a)
1333 return a >= U32_MIN && a <= U32_MAX;
1336 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1338 __mark_reg32_unbounded(reg);
1339 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1340 reg->s32_min_value = (s32)reg->smin_value;
1341 reg->s32_max_value = (s32)reg->smax_value;
1343 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1344 reg->u32_min_value = (u32)reg->umin_value;
1345 reg->u32_max_value = (u32)reg->umax_value;
1347 reg_bounds_sync(reg);
1350 /* Mark a register as having a completely unknown (scalar) value. */
1351 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1352 struct bpf_reg_state *reg)
1355 * Clear type, id, off, and union(map_ptr, range) and
1356 * padding between 'type' and union
1358 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1359 reg->type = SCALAR_VALUE;
1360 reg->var_off = tnum_unknown;
1362 reg->precise = !env->bpf_capable;
1363 __mark_reg_unbounded(reg);
1366 static void mark_reg_unknown(struct bpf_verifier_env *env,
1367 struct bpf_reg_state *regs, u32 regno)
1369 if (WARN_ON(regno >= MAX_BPF_REG)) {
1370 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1371 /* Something bad happened, let's kill all regs except FP */
1372 for (regno = 0; regno < BPF_REG_FP; regno++)
1373 __mark_reg_not_init(env, regs + regno);
1376 __mark_reg_unknown(env, regs + regno);
1379 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1380 struct bpf_reg_state *reg)
1382 __mark_reg_unknown(env, reg);
1383 reg->type = NOT_INIT;
1386 static void mark_reg_not_init(struct bpf_verifier_env *env,
1387 struct bpf_reg_state *regs, u32 regno)
1389 if (WARN_ON(regno >= MAX_BPF_REG)) {
1390 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1391 /* Something bad happened, let's kill all regs except FP */
1392 for (regno = 0; regno < BPF_REG_FP; regno++)
1393 __mark_reg_not_init(env, regs + regno);
1396 __mark_reg_not_init(env, regs + regno);
1399 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1400 struct bpf_reg_state *regs, u32 regno,
1401 enum bpf_reg_type reg_type, u32 btf_id)
1403 if (reg_type == SCALAR_VALUE) {
1404 mark_reg_unknown(env, regs, regno);
1407 mark_reg_known_zero(env, regs, regno);
1408 regs[regno].type = PTR_TO_BTF_ID;
1409 regs[regno].btf_id = btf_id;
1412 #define DEF_NOT_SUBREG (0)
1413 static void init_reg_state(struct bpf_verifier_env *env,
1414 struct bpf_func_state *state)
1416 struct bpf_reg_state *regs = state->regs;
1419 for (i = 0; i < MAX_BPF_REG; i++) {
1420 mark_reg_not_init(env, regs, i);
1421 regs[i].live = REG_LIVE_NONE;
1422 regs[i].parent = NULL;
1423 regs[i].subreg_def = DEF_NOT_SUBREG;
1427 regs[BPF_REG_FP].type = PTR_TO_STACK;
1428 mark_reg_known_zero(env, regs, BPF_REG_FP);
1429 regs[BPF_REG_FP].frameno = state->frameno;
1432 #define BPF_MAIN_FUNC (-1)
1433 static void init_func_state(struct bpf_verifier_env *env,
1434 struct bpf_func_state *state,
1435 int callsite, int frameno, int subprogno)
1437 state->callsite = callsite;
1438 state->frameno = frameno;
1439 state->subprogno = subprogno;
1440 init_reg_state(env, state);
1444 SRC_OP, /* register is used as source operand */
1445 DST_OP, /* register is used as destination operand */
1446 DST_OP_NO_MARK /* same as above, check only, don't mark */
1449 static int cmp_subprogs(const void *a, const void *b)
1451 return ((struct bpf_subprog_info *)a)->start -
1452 ((struct bpf_subprog_info *)b)->start;
1455 static int find_subprog(struct bpf_verifier_env *env, int off)
1457 struct bpf_subprog_info *p;
1459 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1460 sizeof(env->subprog_info[0]), cmp_subprogs);
1463 return p - env->subprog_info;
1467 static int add_subprog(struct bpf_verifier_env *env, int off)
1469 int insn_cnt = env->prog->len;
1472 if (off >= insn_cnt || off < 0) {
1473 verbose(env, "call to invalid destination\n");
1476 ret = find_subprog(env, off);
1479 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1480 verbose(env, "too many subprograms\n");
1483 env->subprog_info[env->subprog_cnt++].start = off;
1484 sort(env->subprog_info, env->subprog_cnt,
1485 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1489 static int check_subprogs(struct bpf_verifier_env *env)
1491 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1492 struct bpf_subprog_info *subprog = env->subprog_info;
1493 struct bpf_insn *insn = env->prog->insnsi;
1494 int insn_cnt = env->prog->len;
1496 /* Add entry function. */
1497 ret = add_subprog(env, 0);
1501 /* determine subprog starts. The end is one before the next starts */
1502 for (i = 0; i < insn_cnt; i++) {
1503 if (insn[i].code != (BPF_JMP | BPF_CALL))
1505 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1507 if (!env->bpf_capable) {
1509 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1512 ret = add_subprog(env, i + insn[i].imm + 1);
1517 /* Add a fake 'exit' subprog which could simplify subprog iteration
1518 * logic. 'subprog_cnt' should not be increased.
1520 subprog[env->subprog_cnt].start = insn_cnt;
1522 if (env->log.level & BPF_LOG_LEVEL2)
1523 for (i = 0; i < env->subprog_cnt; i++)
1524 verbose(env, "func#%d @%d\n", i, subprog[i].start);
1526 /* now check that all jumps are within the same subprog */
1527 subprog_start = subprog[cur_subprog].start;
1528 subprog_end = subprog[cur_subprog + 1].start;
1529 for (i = 0; i < insn_cnt; i++) {
1530 u8 code = insn[i].code;
1532 if (code == (BPF_JMP | BPF_CALL) &&
1533 insn[i].imm == BPF_FUNC_tail_call &&
1534 insn[i].src_reg != BPF_PSEUDO_CALL)
1535 subprog[cur_subprog].has_tail_call = true;
1536 if (BPF_CLASS(code) == BPF_LD &&
1537 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1538 subprog[cur_subprog].has_ld_abs = true;
1539 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1541 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1543 off = i + insn[i].off + 1;
1544 if (off < subprog_start || off >= subprog_end) {
1545 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1549 if (i == subprog_end - 1) {
1550 /* to avoid fall-through from one subprog into another
1551 * the last insn of the subprog should be either exit
1552 * or unconditional jump back
1554 if (code != (BPF_JMP | BPF_EXIT) &&
1555 code != (BPF_JMP | BPF_JA)) {
1556 verbose(env, "last insn is not an exit or jmp\n");
1559 subprog_start = subprog_end;
1561 if (cur_subprog < env->subprog_cnt)
1562 subprog_end = subprog[cur_subprog + 1].start;
1568 /* Parentage chain of this register (or stack slot) should take care of all
1569 * issues like callee-saved registers, stack slot allocation time, etc.
1571 static int mark_reg_read(struct bpf_verifier_env *env,
1572 const struct bpf_reg_state *state,
1573 struct bpf_reg_state *parent, u8 flag)
1575 bool writes = parent == state->parent; /* Observe write marks */
1579 /* if read wasn't screened by an earlier write ... */
1580 if (writes && state->live & REG_LIVE_WRITTEN)
1582 if (parent->live & REG_LIVE_DONE) {
1583 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1584 reg_type_str[parent->type],
1585 parent->var_off.value, parent->off);
1588 /* The first condition is more likely to be true than the
1589 * second, checked it first.
1591 if ((parent->live & REG_LIVE_READ) == flag ||
1592 parent->live & REG_LIVE_READ64)
1593 /* The parentage chain never changes and
1594 * this parent was already marked as LIVE_READ.
1595 * There is no need to keep walking the chain again and
1596 * keep re-marking all parents as LIVE_READ.
1597 * This case happens when the same register is read
1598 * multiple times without writes into it in-between.
1599 * Also, if parent has the stronger REG_LIVE_READ64 set,
1600 * then no need to set the weak REG_LIVE_READ32.
1603 /* ... then we depend on parent's value */
1604 parent->live |= flag;
1605 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1606 if (flag == REG_LIVE_READ64)
1607 parent->live &= ~REG_LIVE_READ32;
1609 parent = state->parent;
1614 if (env->longest_mark_read_walk < cnt)
1615 env->longest_mark_read_walk = cnt;
1619 /* This function is supposed to be used by the following 32-bit optimization
1620 * code only. It returns TRUE if the source or destination register operates
1621 * on 64-bit, otherwise return FALSE.
1623 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1624 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1629 class = BPF_CLASS(code);
1631 if (class == BPF_JMP) {
1632 /* BPF_EXIT for "main" will reach here. Return TRUE
1637 if (op == BPF_CALL) {
1638 /* BPF to BPF call will reach here because of marking
1639 * caller saved clobber with DST_OP_NO_MARK for which we
1640 * don't care the register def because they are anyway
1641 * marked as NOT_INIT already.
1643 if (insn->src_reg == BPF_PSEUDO_CALL)
1645 /* Helper call will reach here because of arg type
1646 * check, conservatively return TRUE.
1655 if (class == BPF_ALU64 || class == BPF_JMP ||
1656 /* BPF_END always use BPF_ALU class. */
1657 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1660 if (class == BPF_ALU || class == BPF_JMP32)
1663 if (class == BPF_LDX) {
1665 return BPF_SIZE(code) == BPF_DW;
1666 /* LDX source must be ptr. */
1670 if (class == BPF_STX) {
1671 if (reg->type != SCALAR_VALUE)
1673 return BPF_SIZE(code) == BPF_DW;
1676 if (class == BPF_LD) {
1677 u8 mode = BPF_MODE(code);
1680 if (mode == BPF_IMM)
1683 /* Both LD_IND and LD_ABS return 32-bit data. */
1687 /* Implicit ctx ptr. */
1688 if (regno == BPF_REG_6)
1691 /* Explicit source could be any width. */
1695 if (class == BPF_ST)
1696 /* The only source register for BPF_ST is a ptr. */
1699 /* Conservatively return true at default. */
1703 /* Return TRUE if INSN doesn't have explicit value define. */
1704 static bool insn_no_def(struct bpf_insn *insn)
1706 u8 class = BPF_CLASS(insn->code);
1708 return (class == BPF_JMP || class == BPF_JMP32 ||
1709 class == BPF_STX || class == BPF_ST);
1712 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1713 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1715 if (insn_no_def(insn))
1718 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1721 static void mark_insn_zext(struct bpf_verifier_env *env,
1722 struct bpf_reg_state *reg)
1724 s32 def_idx = reg->subreg_def;
1726 if (def_idx == DEF_NOT_SUBREG)
1729 env->insn_aux_data[def_idx - 1].zext_dst = true;
1730 /* The dst will be zero extended, so won't be sub-register anymore. */
1731 reg->subreg_def = DEF_NOT_SUBREG;
1734 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1735 enum reg_arg_type t)
1737 struct bpf_verifier_state *vstate = env->cur_state;
1738 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1739 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1740 struct bpf_reg_state *reg, *regs = state->regs;
1743 if (regno >= MAX_BPF_REG) {
1744 verbose(env, "R%d is invalid\n", regno);
1749 rw64 = is_reg64(env, insn, regno, reg, t);
1751 /* check whether register used as source operand can be read */
1752 if (reg->type == NOT_INIT) {
1753 verbose(env, "R%d !read_ok\n", regno);
1756 /* We don't need to worry about FP liveness because it's read-only */
1757 if (regno == BPF_REG_FP)
1761 mark_insn_zext(env, reg);
1763 return mark_reg_read(env, reg, reg->parent,
1764 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1766 /* check whether register used as dest operand can be written to */
1767 if (regno == BPF_REG_FP) {
1768 verbose(env, "frame pointer is read only\n");
1771 reg->live |= REG_LIVE_WRITTEN;
1772 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1774 mark_reg_unknown(env, regs, regno);
1779 /* for any branch, call, exit record the history of jmps in the given state */
1780 static int push_jmp_history(struct bpf_verifier_env *env,
1781 struct bpf_verifier_state *cur)
1783 u32 cnt = cur->jmp_history_cnt;
1784 struct bpf_idx_pair *p;
1787 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1790 p[cnt - 1].idx = env->insn_idx;
1791 p[cnt - 1].prev_idx = env->prev_insn_idx;
1792 cur->jmp_history = p;
1793 cur->jmp_history_cnt = cnt;
1797 /* Backtrack one insn at a time. If idx is not at the top of recorded
1798 * history then previous instruction came from straight line execution.
1800 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1805 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1806 i = st->jmp_history[cnt - 1].prev_idx;
1814 /* For given verifier state backtrack_insn() is called from the last insn to
1815 * the first insn. Its purpose is to compute a bitmask of registers and
1816 * stack slots that needs precision in the parent verifier state.
1818 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1819 u32 *reg_mask, u64 *stack_mask)
1821 const struct bpf_insn_cbs cbs = {
1822 .cb_print = verbose,
1823 .private_data = env,
1825 struct bpf_insn *insn = env->prog->insnsi + idx;
1826 u8 class = BPF_CLASS(insn->code);
1827 u8 opcode = BPF_OP(insn->code);
1828 u8 mode = BPF_MODE(insn->code);
1829 u32 dreg = 1u << insn->dst_reg;
1830 u32 sreg = 1u << insn->src_reg;
1833 if (insn->code == 0)
1835 if (env->log.level & BPF_LOG_LEVEL) {
1836 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1837 verbose(env, "%d: ", idx);
1838 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1841 if (class == BPF_ALU || class == BPF_ALU64) {
1842 if (!(*reg_mask & dreg))
1844 if (opcode == BPF_END || opcode == BPF_NEG) {
1845 /* sreg is reserved and unused
1846 * dreg still need precision before this insn
1849 } else if (opcode == BPF_MOV) {
1850 if (BPF_SRC(insn->code) == BPF_X) {
1852 * dreg needs precision after this insn
1853 * sreg needs precision before this insn
1859 * dreg needs precision after this insn.
1860 * Corresponding register is already marked
1861 * as precise=true in this verifier state.
1862 * No further markings in parent are necessary
1867 if (BPF_SRC(insn->code) == BPF_X) {
1869 * both dreg and sreg need precision
1874 * dreg still needs precision before this insn
1877 } else if (class == BPF_LDX) {
1878 if (!(*reg_mask & dreg))
1882 /* scalars can only be spilled into stack w/o losing precision.
1883 * Load from any other memory can be zero extended.
1884 * The desire to keep that precision is already indicated
1885 * by 'precise' mark in corresponding register of this state.
1886 * No further tracking necessary.
1888 if (insn->src_reg != BPF_REG_FP)
1891 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1892 * that [fp - off] slot contains scalar that needs to be
1893 * tracked with precision
1895 spi = (-insn->off - 1) / BPF_REG_SIZE;
1897 verbose(env, "BUG spi %d\n", spi);
1898 WARN_ONCE(1, "verifier backtracking bug");
1901 *stack_mask |= 1ull << spi;
1902 } else if (class == BPF_STX || class == BPF_ST) {
1903 if (*reg_mask & dreg)
1904 /* stx & st shouldn't be using _scalar_ dst_reg
1905 * to access memory. It means backtracking
1906 * encountered a case of pointer subtraction.
1909 /* scalars can only be spilled into stack */
1910 if (insn->dst_reg != BPF_REG_FP)
1912 spi = (-insn->off - 1) / BPF_REG_SIZE;
1914 verbose(env, "BUG spi %d\n", spi);
1915 WARN_ONCE(1, "verifier backtracking bug");
1918 if (!(*stack_mask & (1ull << spi)))
1920 *stack_mask &= ~(1ull << spi);
1921 if (class == BPF_STX)
1923 } else if (class == BPF_JMP || class == BPF_JMP32) {
1924 if (opcode == BPF_CALL) {
1925 if (insn->src_reg == BPF_PSEUDO_CALL)
1927 /* regular helper call sets R0 */
1929 if (*reg_mask & 0x3f) {
1930 /* if backtracing was looking for registers R1-R5
1931 * they should have been found already.
1933 verbose(env, "BUG regs %x\n", *reg_mask);
1934 WARN_ONCE(1, "verifier backtracking bug");
1937 } else if (opcode == BPF_EXIT) {
1939 } else if (BPF_SRC(insn->code) == BPF_X) {
1940 if (!(*reg_mask & (dreg | sreg)))
1943 * Both dreg and sreg need precision before
1944 * this insn. If only sreg was marked precise
1945 * before it would be equally necessary to
1946 * propagate it to dreg.
1948 *reg_mask |= (sreg | dreg);
1949 /* else dreg <cond> K
1950 * Only dreg still needs precision before
1951 * this insn, so for the K-based conditional
1952 * there is nothing new to be marked.
1955 } else if (class == BPF_LD) {
1956 if (!(*reg_mask & dreg))
1959 /* It's ld_imm64 or ld_abs or ld_ind.
1960 * For ld_imm64 no further tracking of precision
1961 * into parent is necessary
1963 if (mode == BPF_IND || mode == BPF_ABS)
1964 /* to be analyzed */
1970 /* the scalar precision tracking algorithm:
1971 * . at the start all registers have precise=false.
1972 * . scalar ranges are tracked as normal through alu and jmp insns.
1973 * . once precise value of the scalar register is used in:
1974 * . ptr + scalar alu
1975 * . if (scalar cond K|scalar)
1976 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1977 * backtrack through the verifier states and mark all registers and
1978 * stack slots with spilled constants that these scalar regisers
1979 * should be precise.
1980 * . during state pruning two registers (or spilled stack slots)
1981 * are equivalent if both are not precise.
1983 * Note the verifier cannot simply walk register parentage chain,
1984 * since many different registers and stack slots could have been
1985 * used to compute single precise scalar.
1987 * The approach of starting with precise=true for all registers and then
1988 * backtrack to mark a register as not precise when the verifier detects
1989 * that program doesn't care about specific value (e.g., when helper
1990 * takes register as ARG_ANYTHING parameter) is not safe.
1992 * It's ok to walk single parentage chain of the verifier states.
1993 * It's possible that this backtracking will go all the way till 1st insn.
1994 * All other branches will be explored for needing precision later.
1996 * The backtracking needs to deal with cases like:
1997 * 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)
2000 * if r5 > 0x79f goto pc+7
2001 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2004 * call bpf_perf_event_output#25
2005 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2009 * call foo // uses callee's r6 inside to compute r0
2013 * to track above reg_mask/stack_mask needs to be independent for each frame.
2015 * Also if parent's curframe > frame where backtracking started,
2016 * the verifier need to mark registers in both frames, otherwise callees
2017 * may incorrectly prune callers. This is similar to
2018 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2020 * For now backtracking falls back into conservative marking.
2022 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2023 struct bpf_verifier_state *st)
2025 struct bpf_func_state *func;
2026 struct bpf_reg_state *reg;
2029 /* big hammer: mark all scalars precise in this path.
2030 * pop_stack may still get !precise scalars.
2031 * We also skip current state and go straight to first parent state,
2032 * because precision markings in current non-checkpointed state are
2033 * not needed. See why in the comment in __mark_chain_precision below.
2035 for (st = st->parent; st; st = st->parent) {
2036 for (i = 0; i <= st->curframe; i++) {
2037 func = st->frame[i];
2038 for (j = 0; j < BPF_REG_FP; j++) {
2039 reg = &func->regs[j];
2040 if (reg->type != SCALAR_VALUE)
2042 reg->precise = true;
2044 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2045 if (!is_spilled_reg(&func->stack[j]))
2047 reg = &func->stack[j].spilled_ptr;
2048 if (reg->type != SCALAR_VALUE)
2050 reg->precise = true;
2056 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2058 struct bpf_func_state *func;
2059 struct bpf_reg_state *reg;
2062 for (i = 0; i <= st->curframe; i++) {
2063 func = st->frame[i];
2064 for (j = 0; j < BPF_REG_FP; j++) {
2065 reg = &func->regs[j];
2066 if (reg->type != SCALAR_VALUE)
2068 reg->precise = false;
2070 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2071 if (!is_spilled_reg(&func->stack[j]))
2073 reg = &func->stack[j].spilled_ptr;
2074 if (reg->type != SCALAR_VALUE)
2076 reg->precise = false;
2082 * __mark_chain_precision() backtracks BPF program instruction sequence and
2083 * chain of verifier states making sure that register *regno* (if regno >= 0)
2084 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2085 * SCALARS, as well as any other registers and slots that contribute to
2086 * a tracked state of given registers/stack slots, depending on specific BPF
2087 * assembly instructions (see backtrack_insns() for exact instruction handling
2088 * logic). This backtracking relies on recorded jmp_history and is able to
2089 * traverse entire chain of parent states. This process ends only when all the
2090 * necessary registers/slots and their transitive dependencies are marked as
2093 * One important and subtle aspect is that precise marks *do not matter* in
2094 * the currently verified state (current state). It is important to understand
2095 * why this is the case.
2097 * First, note that current state is the state that is not yet "checkpointed",
2098 * i.e., it is not yet put into env->explored_states, and it has no children
2099 * states as well. It's ephemeral, and can end up either a) being discarded if
2100 * compatible explored state is found at some point or BPF_EXIT instruction is
2101 * reached or b) checkpointed and put into env->explored_states, branching out
2102 * into one or more children states.
2104 * In the former case, precise markings in current state are completely
2105 * ignored by state comparison code (see regsafe() for details). Only
2106 * checkpointed ("old") state precise markings are important, and if old
2107 * state's register/slot is precise, regsafe() assumes current state's
2108 * register/slot as precise and checks value ranges exactly and precisely. If
2109 * states turn out to be compatible, current state's necessary precise
2110 * markings and any required parent states' precise markings are enforced
2111 * after the fact with propagate_precision() logic, after the fact. But it's
2112 * important to realize that in this case, even after marking current state
2113 * registers/slots as precise, we immediately discard current state. So what
2114 * actually matters is any of the precise markings propagated into current
2115 * state's parent states, which are always checkpointed (due to b) case above).
2116 * As such, for scenario a) it doesn't matter if current state has precise
2117 * markings set or not.
2119 * Now, for the scenario b), checkpointing and forking into child(ren)
2120 * state(s). Note that before current state gets to checkpointing step, any
2121 * processed instruction always assumes precise SCALAR register/slot
2122 * knowledge: if precise value or range is useful to prune jump branch, BPF
2123 * verifier takes this opportunity enthusiastically. Similarly, when
2124 * register's value is used to calculate offset or memory address, exact
2125 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2126 * what we mentioned above about state comparison ignoring precise markings
2127 * during state comparison, BPF verifier ignores and also assumes precise
2128 * markings *at will* during instruction verification process. But as verifier
2129 * assumes precision, it also propagates any precision dependencies across
2130 * parent states, which are not yet finalized, so can be further restricted
2131 * based on new knowledge gained from restrictions enforced by their children
2132 * states. This is so that once those parent states are finalized, i.e., when
2133 * they have no more active children state, state comparison logic in
2134 * is_state_visited() would enforce strict and precise SCALAR ranges, if
2135 * required for correctness.
2137 * To build a bit more intuition, note also that once a state is checkpointed,
2138 * the path we took to get to that state is not important. This is crucial
2139 * property for state pruning. When state is checkpointed and finalized at
2140 * some instruction index, it can be correctly and safely used to "short
2141 * circuit" any *compatible* state that reaches exactly the same instruction
2142 * index. I.e., if we jumped to that instruction from a completely different
2143 * code path than original finalized state was derived from, it doesn't
2144 * matter, current state can be discarded because from that instruction
2145 * forward having a compatible state will ensure we will safely reach the
2146 * exit. States describe preconditions for further exploration, but completely
2147 * forget the history of how we got here.
2149 * This also means that even if we needed precise SCALAR range to get to
2150 * finalized state, but from that point forward *that same* SCALAR register is
2151 * never used in a precise context (i.e., it's precise value is not needed for
2152 * correctness), it's correct and safe to mark such register as "imprecise"
2153 * (i.e., precise marking set to false). This is what we rely on when we do
2154 * not set precise marking in current state. If no child state requires
2155 * precision for any given SCALAR register, it's safe to dictate that it can
2156 * be imprecise. If any child state does require this register to be precise,
2157 * we'll mark it precise later retroactively during precise markings
2158 * propagation from child state to parent states.
2160 * Skipping precise marking setting in current state is a mild version of
2161 * relying on the above observation. But we can utilize this property even
2162 * more aggressively by proactively forgetting any precise marking in the
2163 * current state (which we inherited from the parent state), right before we
2164 * checkpoint it and branch off into new child state. This is done by
2165 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2166 * finalized states which help in short circuiting more future states.
2168 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2171 struct bpf_verifier_state *st = env->cur_state;
2172 int first_idx = st->first_insn_idx;
2173 int last_idx = env->insn_idx;
2174 struct bpf_func_state *func;
2175 struct bpf_reg_state *reg;
2176 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2177 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2178 bool skip_first = true;
2179 bool new_marks = false;
2182 if (!env->bpf_capable)
2185 /* Do sanity checks against current state of register and/or stack
2186 * slot, but don't set precise flag in current state, as precision
2187 * tracking in the current state is unnecessary.
2189 func = st->frame[frame];
2191 reg = &func->regs[regno];
2192 if (reg->type != SCALAR_VALUE) {
2193 WARN_ONCE(1, "backtracing misuse");
2200 if (!is_spilled_reg(&func->stack[spi])) {
2204 reg = &func->stack[spi].spilled_ptr;
2205 if (reg->type != SCALAR_VALUE) {
2215 if (!reg_mask && !stack_mask)
2219 DECLARE_BITMAP(mask, 64);
2220 u32 history = st->jmp_history_cnt;
2222 if (env->log.level & BPF_LOG_LEVEL)
2223 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2226 /* we are at the entry into subprog, which
2227 * is expected for global funcs, but only if
2228 * requested precise registers are R1-R5
2229 * (which are global func's input arguments)
2231 if (st->curframe == 0 &&
2232 st->frame[0]->subprogno > 0 &&
2233 st->frame[0]->callsite == BPF_MAIN_FUNC &&
2234 stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
2235 bitmap_from_u64(mask, reg_mask);
2236 for_each_set_bit(i, mask, 32) {
2237 reg = &st->frame[0]->regs[i];
2238 if (reg->type != SCALAR_VALUE) {
2239 reg_mask &= ~(1u << i);
2242 reg->precise = true;
2247 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
2248 st->frame[0]->subprogno, reg_mask, stack_mask);
2249 WARN_ONCE(1, "verifier backtracking bug");
2253 for (i = last_idx;;) {
2258 err = backtrack_insn(env, i, ®_mask, &stack_mask);
2260 if (err == -ENOTSUPP) {
2261 mark_all_scalars_precise(env, st);
2266 if (!reg_mask && !stack_mask)
2267 /* Found assignment(s) into tracked register in this state.
2268 * Since this state is already marked, just return.
2269 * Nothing to be tracked further in the parent state.
2274 i = get_prev_insn_idx(st, i, &history);
2275 if (i >= env->prog->len) {
2276 /* This can happen if backtracking reached insn 0
2277 * and there are still reg_mask or stack_mask
2279 * It means the backtracking missed the spot where
2280 * particular register was initialized with a constant.
2282 verbose(env, "BUG backtracking idx %d\n", i);
2283 WARN_ONCE(1, "verifier backtracking bug");
2292 func = st->frame[frame];
2293 bitmap_from_u64(mask, reg_mask);
2294 for_each_set_bit(i, mask, 32) {
2295 reg = &func->regs[i];
2296 if (reg->type != SCALAR_VALUE) {
2297 reg_mask &= ~(1u << i);
2302 reg->precise = true;
2305 bitmap_from_u64(mask, stack_mask);
2306 for_each_set_bit(i, mask, 64) {
2307 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2308 /* the sequence of instructions:
2310 * 3: (7b) *(u64 *)(r3 -8) = r0
2311 * 4: (79) r4 = *(u64 *)(r10 -8)
2312 * doesn't contain jmps. It's backtracked
2313 * as a single block.
2314 * During backtracking insn 3 is not recognized as
2315 * stack access, so at the end of backtracking
2316 * stack slot fp-8 is still marked in stack_mask.
2317 * However the parent state may not have accessed
2318 * fp-8 and it's "unallocated" stack space.
2319 * In such case fallback to conservative.
2321 mark_all_scalars_precise(env, st);
2325 if (!is_spilled_reg(&func->stack[i])) {
2326 stack_mask &= ~(1ull << i);
2329 reg = &func->stack[i].spilled_ptr;
2330 if (reg->type != SCALAR_VALUE) {
2331 stack_mask &= ~(1ull << i);
2336 reg->precise = true;
2338 if (env->log.level & BPF_LOG_LEVEL) {
2339 print_verifier_state(env, func);
2340 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2341 new_marks ? "didn't have" : "already had",
2342 reg_mask, stack_mask);
2345 if (!reg_mask && !stack_mask)
2350 last_idx = st->last_insn_idx;
2351 first_idx = st->first_insn_idx;
2356 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2358 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2361 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2363 return __mark_chain_precision(env, frame, regno, -1);
2366 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2368 return __mark_chain_precision(env, frame, -1, spi);
2371 static bool is_spillable_regtype(enum bpf_reg_type type)
2374 case PTR_TO_MAP_VALUE:
2375 case PTR_TO_MAP_VALUE_OR_NULL:
2379 case PTR_TO_PACKET_META:
2380 case PTR_TO_PACKET_END:
2381 case PTR_TO_FLOW_KEYS:
2382 case CONST_PTR_TO_MAP:
2384 case PTR_TO_SOCKET_OR_NULL:
2385 case PTR_TO_SOCK_COMMON:
2386 case PTR_TO_SOCK_COMMON_OR_NULL:
2387 case PTR_TO_TCP_SOCK:
2388 case PTR_TO_TCP_SOCK_OR_NULL:
2389 case PTR_TO_XDP_SOCK:
2391 case PTR_TO_BTF_ID_OR_NULL:
2392 case PTR_TO_RDONLY_BUF:
2393 case PTR_TO_RDONLY_BUF_OR_NULL:
2394 case PTR_TO_RDWR_BUF:
2395 case PTR_TO_RDWR_BUF_OR_NULL:
2396 case PTR_TO_PERCPU_BTF_ID:
2398 case PTR_TO_MEM_OR_NULL:
2405 /* Does this register contain a constant zero? */
2406 static bool register_is_null(struct bpf_reg_state *reg)
2408 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2411 static bool register_is_const(struct bpf_reg_state *reg)
2413 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2416 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2418 return tnum_is_unknown(reg->var_off) &&
2419 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2420 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2421 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2422 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2425 static bool register_is_bounded(struct bpf_reg_state *reg)
2427 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2430 static bool __is_pointer_value(bool allow_ptr_leaks,
2431 const struct bpf_reg_state *reg)
2433 if (allow_ptr_leaks)
2436 return reg->type != SCALAR_VALUE;
2439 /* Copy src state preserving dst->parent and dst->live fields */
2440 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
2442 struct bpf_reg_state *parent = dst->parent;
2443 enum bpf_reg_liveness live = dst->live;
2446 dst->parent = parent;
2450 static void save_register_state(struct bpf_func_state *state,
2451 int spi, struct bpf_reg_state *reg,
2456 copy_register_state(&state->stack[spi].spilled_ptr, reg);
2457 if (size == BPF_REG_SIZE)
2458 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2460 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2461 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2463 /* size < 8 bytes spill */
2465 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2468 static bool is_bpf_st_mem(struct bpf_insn *insn)
2470 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
2473 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2474 * stack boundary and alignment are checked in check_mem_access()
2476 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2477 /* stack frame we're writing to */
2478 struct bpf_func_state *state,
2479 int off, int size, int value_regno,
2482 struct bpf_func_state *cur; /* state of the current function */
2483 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2484 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
2485 struct bpf_reg_state *reg = NULL;
2486 u32 dst_reg = insn->dst_reg;
2488 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2489 state->acquired_refs, true);
2492 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2493 * so it's aligned access and [off, off + size) are within stack limits
2495 if (!env->allow_ptr_leaks &&
2496 is_spilled_reg(&state->stack[spi]) &&
2497 size != BPF_REG_SIZE) {
2498 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2502 cur = env->cur_state->frame[env->cur_state->curframe];
2503 if (value_regno >= 0)
2504 reg = &cur->regs[value_regno];
2505 if (!env->bypass_spec_v4) {
2506 bool sanitize = reg && is_spillable_regtype(reg->type);
2508 for (i = 0; i < size; i++) {
2509 u8 type = state->stack[spi].slot_type[i];
2511 if (type != STACK_MISC && type != STACK_ZERO) {
2518 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2521 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2522 !register_is_null(reg) && env->bpf_capable) {
2523 if (dst_reg != BPF_REG_FP) {
2524 /* The backtracking logic can only recognize explicit
2525 * stack slot address like [fp - 8]. Other spill of
2526 * scalar via different register has to be conervative.
2527 * Backtrack from here and mark all registers as precise
2528 * that contributed into 'reg' being a constant.
2530 err = mark_chain_precision(env, value_regno);
2534 save_register_state(state, spi, reg, size);
2535 /* Break the relation on a narrowing spill. */
2536 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
2537 state->stack[spi].spilled_ptr.id = 0;
2538 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
2539 insn->imm != 0 && env->bpf_capable) {
2540 struct bpf_reg_state fake_reg = {};
2542 __mark_reg_known(&fake_reg, insn->imm);
2543 fake_reg.type = SCALAR_VALUE;
2544 save_register_state(state, spi, &fake_reg, size);
2545 } else if (reg && is_spillable_regtype(reg->type)) {
2546 /* register containing pointer is being spilled into stack */
2547 if (size != BPF_REG_SIZE) {
2548 verbose_linfo(env, insn_idx, "; ");
2549 verbose(env, "invalid size of register spill\n");
2552 if (state != cur && reg->type == PTR_TO_STACK) {
2553 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2556 save_register_state(state, spi, reg, size);
2558 u8 type = STACK_MISC;
2560 /* regular write of data into stack destroys any spilled ptr */
2561 state->stack[spi].spilled_ptr.type = NOT_INIT;
2562 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2563 if (is_spilled_reg(&state->stack[spi]))
2564 for (i = 0; i < BPF_REG_SIZE; i++)
2565 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
2567 /* only mark the slot as written if all 8 bytes were written
2568 * otherwise read propagation may incorrectly stop too soon
2569 * when stack slots are partially written.
2570 * This heuristic means that read propagation will be
2571 * conservative, since it will add reg_live_read marks
2572 * to stack slots all the way to first state when programs
2573 * writes+reads less than 8 bytes
2575 if (size == BPF_REG_SIZE)
2576 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2578 /* when we zero initialize stack slots mark them as such */
2579 if ((reg && register_is_null(reg)) ||
2580 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
2581 /* backtracking doesn't work for STACK_ZERO yet. */
2582 err = mark_chain_precision(env, value_regno);
2588 /* Mark slots affected by this stack write. */
2589 for (i = 0; i < size; i++)
2590 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2596 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2597 * known to contain a variable offset.
2598 * This function checks whether the write is permitted and conservatively
2599 * tracks the effects of the write, considering that each stack slot in the
2600 * dynamic range is potentially written to.
2602 * 'off' includes 'regno->off'.
2603 * 'value_regno' can be -1, meaning that an unknown value is being written to
2606 * Spilled pointers in range are not marked as written because we don't know
2607 * what's going to be actually written. This means that read propagation for
2608 * future reads cannot be terminated by this write.
2610 * For privileged programs, uninitialized stack slots are considered
2611 * initialized by this write (even though we don't know exactly what offsets
2612 * are going to be written to). The idea is that we don't want the verifier to
2613 * reject future reads that access slots written to through variable offsets.
2615 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2616 /* func where register points to */
2617 struct bpf_func_state *state,
2618 int ptr_regno, int off, int size,
2619 int value_regno, int insn_idx)
2621 struct bpf_func_state *cur; /* state of the current function */
2622 int min_off, max_off;
2624 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2625 bool writing_zero = false;
2626 /* set if the fact that we're writing a zero is used to let any
2627 * stack slots remain STACK_ZERO
2629 bool zero_used = false;
2631 cur = env->cur_state->frame[env->cur_state->curframe];
2632 ptr_reg = &cur->regs[ptr_regno];
2633 min_off = ptr_reg->smin_value + off;
2634 max_off = ptr_reg->smax_value + off + size;
2635 if (value_regno >= 0)
2636 value_reg = &cur->regs[value_regno];
2637 if (value_reg && register_is_null(value_reg))
2638 writing_zero = true;
2640 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2641 state->acquired_refs, true);
2646 /* Variable offset writes destroy any spilled pointers in range. */
2647 for (i = min_off; i < max_off; i++) {
2648 u8 new_type, *stype;
2652 spi = slot / BPF_REG_SIZE;
2653 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2655 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
2656 /* Reject the write if range we may write to has not
2657 * been initialized beforehand. If we didn't reject
2658 * here, the ptr status would be erased below (even
2659 * though not all slots are actually overwritten),
2660 * possibly opening the door to leaks.
2662 * We do however catch STACK_INVALID case below, and
2663 * only allow reading possibly uninitialized memory
2664 * later for CAP_PERFMON, as the write may not happen to
2667 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2672 /* Erase all spilled pointers. */
2673 state->stack[spi].spilled_ptr.type = NOT_INIT;
2675 /* Update the slot type. */
2676 new_type = STACK_MISC;
2677 if (writing_zero && *stype == STACK_ZERO) {
2678 new_type = STACK_ZERO;
2681 /* If the slot is STACK_INVALID, we check whether it's OK to
2682 * pretend that it will be initialized by this write. The slot
2683 * might not actually be written to, and so if we mark it as
2684 * initialized future reads might leak uninitialized memory.
2685 * For privileged programs, we will accept such reads to slots
2686 * that may or may not be written because, if we're reject
2687 * them, the error would be too confusing.
2689 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2690 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2697 /* backtracking doesn't work for STACK_ZERO yet. */
2698 err = mark_chain_precision(env, value_regno);
2705 /* When register 'dst_regno' is assigned some values from stack[min_off,
2706 * max_off), we set the register's type according to the types of the
2707 * respective stack slots. If all the stack values are known to be zeros, then
2708 * so is the destination reg. Otherwise, the register is considered to be
2709 * SCALAR. This function does not deal with register filling; the caller must
2710 * ensure that all spilled registers in the stack range have been marked as
2713 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2714 /* func where src register points to */
2715 struct bpf_func_state *ptr_state,
2716 int min_off, int max_off, int dst_regno)
2718 struct bpf_verifier_state *vstate = env->cur_state;
2719 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2724 for (i = min_off; i < max_off; i++) {
2726 spi = slot / BPF_REG_SIZE;
2727 stype = ptr_state->stack[spi].slot_type;
2728 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2732 if (zeros == max_off - min_off) {
2733 /* any access_size read into register is zero extended,
2734 * so the whole register == const_zero
2736 __mark_reg_const_zero(&state->regs[dst_regno]);
2737 /* backtracking doesn't support STACK_ZERO yet,
2738 * so mark it precise here, so that later
2739 * backtracking can stop here.
2740 * Backtracking may not need this if this register
2741 * doesn't participate in pointer adjustment.
2742 * Forward propagation of precise flag is not
2743 * necessary either. This mark is only to stop
2744 * backtracking. Any register that contributed
2745 * to const 0 was marked precise before spill.
2747 state->regs[dst_regno].precise = true;
2749 /* have read misc data from the stack */
2750 mark_reg_unknown(env, state->regs, dst_regno);
2752 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2755 /* Read the stack at 'off' and put the results into the register indicated by
2756 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2759 * 'dst_regno' can be -1, meaning that the read value is not going to a
2762 * The access is assumed to be within the current stack bounds.
2764 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2765 /* func where src register points to */
2766 struct bpf_func_state *reg_state,
2767 int off, int size, int dst_regno)
2769 struct bpf_verifier_state *vstate = env->cur_state;
2770 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2771 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2772 struct bpf_reg_state *reg;
2775 stype = reg_state->stack[spi].slot_type;
2776 reg = ®_state->stack[spi].spilled_ptr;
2778 if (is_spilled_reg(®_state->stack[spi])) {
2781 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
2784 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
2785 if (reg->type != SCALAR_VALUE) {
2786 verbose_linfo(env, env->insn_idx, "; ");
2787 verbose(env, "invalid size of register fill\n");
2791 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2795 if (!(off % BPF_REG_SIZE) && size == spill_size) {
2796 /* The earlier check_reg_arg() has decided the
2797 * subreg_def for this insn. Save it first.
2799 s32 subreg_def = state->regs[dst_regno].subreg_def;
2801 copy_register_state(&state->regs[dst_regno], reg);
2802 state->regs[dst_regno].subreg_def = subreg_def;
2804 for (i = 0; i < size; i++) {
2805 type = stype[(slot - i) % BPF_REG_SIZE];
2806 if (type == STACK_SPILL)
2808 if (type == STACK_MISC)
2810 verbose(env, "invalid read from stack off %d+%d size %d\n",
2814 mark_reg_unknown(env, state->regs, dst_regno);
2816 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2820 if (dst_regno >= 0) {
2821 /* restore register state from stack */
2822 copy_register_state(&state->regs[dst_regno], reg);
2823 /* mark reg as written since spilled pointer state likely
2824 * has its liveness marks cleared by is_state_visited()
2825 * which resets stack/reg liveness for state transitions
2827 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2828 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2829 /* If dst_regno==-1, the caller is asking us whether
2830 * it is acceptable to use this value as a SCALAR_VALUE
2832 * We must not allow unprivileged callers to do that
2833 * with spilled pointers.
2835 verbose(env, "leaking pointer from stack off %d\n",
2839 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2841 for (i = 0; i < size; i++) {
2842 type = stype[(slot - i) % BPF_REG_SIZE];
2843 if (type == STACK_MISC)
2845 if (type == STACK_ZERO)
2847 verbose(env, "invalid read from stack off %d+%d size %d\n",
2851 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2853 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2858 enum stack_access_src {
2859 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2860 ACCESS_HELPER = 2, /* the access is performed by a helper */
2863 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2864 int regno, int off, int access_size,
2865 bool zero_size_allowed,
2866 enum stack_access_src type,
2867 struct bpf_call_arg_meta *meta);
2869 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2871 return cur_regs(env) + regno;
2874 /* Read the stack at 'ptr_regno + off' and put the result into the register
2876 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2877 * but not its variable offset.
2878 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2880 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2881 * filling registers (i.e. reads of spilled register cannot be detected when
2882 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2883 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2884 * offset; for a fixed offset check_stack_read_fixed_off should be used
2887 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2888 int ptr_regno, int off, int size, int dst_regno)
2890 /* The state of the source register. */
2891 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2892 struct bpf_func_state *ptr_state = func(env, reg);
2894 int min_off, max_off;
2896 /* Note that we pass a NULL meta, so raw access will not be permitted.
2898 err = check_stack_range_initialized(env, ptr_regno, off, size,
2899 false, ACCESS_DIRECT, NULL);
2903 min_off = reg->smin_value + off;
2904 max_off = reg->smax_value + off;
2905 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2909 /* check_stack_read dispatches to check_stack_read_fixed_off or
2910 * check_stack_read_var_off.
2912 * The caller must ensure that the offset falls within the allocated stack
2915 * 'dst_regno' is a register which will receive the value from the stack. It
2916 * can be -1, meaning that the read value is not going to a register.
2918 static int check_stack_read(struct bpf_verifier_env *env,
2919 int ptr_regno, int off, int size,
2922 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2923 struct bpf_func_state *state = func(env, reg);
2925 /* Some accesses are only permitted with a static offset. */
2926 bool var_off = !tnum_is_const(reg->var_off);
2928 /* The offset is required to be static when reads don't go to a
2929 * register, in order to not leak pointers (see
2930 * check_stack_read_fixed_off).
2932 if (dst_regno < 0 && var_off) {
2935 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2936 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2940 /* Variable offset is prohibited for unprivileged mode for simplicity
2941 * since it requires corresponding support in Spectre masking for stack
2942 * ALU. See also retrieve_ptr_limit(). The check in
2943 * check_stack_access_for_ptr_arithmetic() called by
2944 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
2945 * with variable offsets, therefore no check is required here. Further,
2946 * just checking it here would be insufficient as speculative stack
2947 * writes could still lead to unsafe speculative behaviour.
2950 off += reg->var_off.value;
2951 err = check_stack_read_fixed_off(env, state, off, size,
2954 /* Variable offset stack reads need more conservative handling
2955 * than fixed offset ones. Note that dst_regno >= 0 on this
2958 err = check_stack_read_var_off(env, ptr_regno, off, size,
2965 /* check_stack_write dispatches to check_stack_write_fixed_off or
2966 * check_stack_write_var_off.
2968 * 'ptr_regno' is the register used as a pointer into the stack.
2969 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2970 * 'value_regno' is the register whose value we're writing to the stack. It can
2971 * be -1, meaning that we're not writing from a register.
2973 * The caller must ensure that the offset falls within the maximum stack size.
2975 static int check_stack_write(struct bpf_verifier_env *env,
2976 int ptr_regno, int off, int size,
2977 int value_regno, int insn_idx)
2979 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2980 struct bpf_func_state *state = func(env, reg);
2983 if (tnum_is_const(reg->var_off)) {
2984 off += reg->var_off.value;
2985 err = check_stack_write_fixed_off(env, state, off, size,
2986 value_regno, insn_idx);
2988 /* Variable offset stack reads need more conservative handling
2989 * than fixed offset ones.
2991 err = check_stack_write_var_off(env, state,
2992 ptr_regno, off, size,
2993 value_regno, insn_idx);
2998 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2999 int off, int size, enum bpf_access_type type)
3001 struct bpf_reg_state *regs = cur_regs(env);
3002 struct bpf_map *map = regs[regno].map_ptr;
3003 u32 cap = bpf_map_flags_to_cap(map);
3005 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3006 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3007 map->value_size, off, size);
3011 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3012 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3013 map->value_size, off, size);
3020 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3021 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3022 int off, int size, u32 mem_size,
3023 bool zero_size_allowed)
3025 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3026 struct bpf_reg_state *reg;
3028 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3031 reg = &cur_regs(env)[regno];
3032 switch (reg->type) {
3033 case PTR_TO_MAP_VALUE:
3034 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3035 mem_size, off, size);
3038 case PTR_TO_PACKET_META:
3039 case PTR_TO_PACKET_END:
3040 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3041 off, size, regno, reg->id, off, mem_size);
3045 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3046 mem_size, off, size);
3052 /* check read/write into a memory region with possible variable offset */
3053 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3054 int off, int size, u32 mem_size,
3055 bool zero_size_allowed)
3057 struct bpf_verifier_state *vstate = env->cur_state;
3058 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3059 struct bpf_reg_state *reg = &state->regs[regno];
3062 /* We may have adjusted the register pointing to memory region, so we
3063 * need to try adding each of min_value and max_value to off
3064 * to make sure our theoretical access will be safe.
3066 if (env->log.level & BPF_LOG_LEVEL)
3067 print_verifier_state(env, state);
3069 /* The minimum value is only important with signed
3070 * comparisons where we can't assume the floor of a
3071 * value is 0. If we are using signed variables for our
3072 * index'es we need to make sure that whatever we use
3073 * will have a set floor within our range.
3075 if (reg->smin_value < 0 &&
3076 (reg->smin_value == S64_MIN ||
3077 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3078 reg->smin_value + off < 0)) {
3079 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3083 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3084 mem_size, zero_size_allowed);
3086 verbose(env, "R%d min value is outside of the allowed memory range\n",
3091 /* If we haven't set a max value then we need to bail since we can't be
3092 * sure we won't do bad things.
3093 * If reg->umax_value + off could overflow, treat that as unbounded too.
3095 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3096 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3100 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3101 mem_size, zero_size_allowed);
3103 verbose(env, "R%d max value is outside of the allowed memory range\n",
3111 /* check read/write into a map element with possible variable offset */
3112 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3113 int off, int size, bool zero_size_allowed)
3115 struct bpf_verifier_state *vstate = env->cur_state;
3116 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3117 struct bpf_reg_state *reg = &state->regs[regno];
3118 struct bpf_map *map = reg->map_ptr;
3121 err = check_mem_region_access(env, regno, off, size, map->value_size,
3126 if (map_value_has_spin_lock(map)) {
3127 u32 lock = map->spin_lock_off;
3129 /* if any part of struct bpf_spin_lock can be touched by
3130 * load/store reject this program.
3131 * To check that [x1, x2) overlaps with [y1, y2)
3132 * it is sufficient to check x1 < y2 && y1 < x2.
3134 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3135 lock < reg->umax_value + off + size) {
3136 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3143 #define MAX_PACKET_OFF 0xffff
3145 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3147 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3150 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3151 const struct bpf_call_arg_meta *meta,
3152 enum bpf_access_type t)
3154 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3156 switch (prog_type) {
3157 /* Program types only with direct read access go here! */
3158 case BPF_PROG_TYPE_LWT_IN:
3159 case BPF_PROG_TYPE_LWT_OUT:
3160 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3161 case BPF_PROG_TYPE_SK_REUSEPORT:
3162 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3163 case BPF_PROG_TYPE_CGROUP_SKB:
3168 /* Program types with direct read + write access go here! */
3169 case BPF_PROG_TYPE_SCHED_CLS:
3170 case BPF_PROG_TYPE_SCHED_ACT:
3171 case BPF_PROG_TYPE_XDP:
3172 case BPF_PROG_TYPE_LWT_XMIT:
3173 case BPF_PROG_TYPE_SK_SKB:
3174 case BPF_PROG_TYPE_SK_MSG:
3176 return meta->pkt_access;
3178 env->seen_direct_write = true;
3181 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3183 env->seen_direct_write = true;
3192 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3193 int size, bool zero_size_allowed)
3195 struct bpf_reg_state *regs = cur_regs(env);
3196 struct bpf_reg_state *reg = ®s[regno];
3199 /* We may have added a variable offset to the packet pointer; but any
3200 * reg->range we have comes after that. We are only checking the fixed
3204 /* We don't allow negative numbers, because we aren't tracking enough
3205 * detail to prove they're safe.
3207 if (reg->smin_value < 0) {
3208 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3213 err = reg->range < 0 ? -EINVAL :
3214 __check_mem_access(env, regno, off, size, reg->range,
3217 verbose(env, "R%d offset is outside of the packet\n", regno);
3221 /* __check_mem_access has made sure "off + size - 1" is within u16.
3222 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3223 * otherwise find_good_pkt_pointers would have refused to set range info
3224 * that __check_mem_access would have rejected this pkt access.
3225 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3227 env->prog->aux->max_pkt_offset =
3228 max_t(u32, env->prog->aux->max_pkt_offset,
3229 off + reg->umax_value + size - 1);
3234 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
3235 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3236 enum bpf_access_type t, enum bpf_reg_type *reg_type,
3239 struct bpf_insn_access_aux info = {
3240 .reg_type = *reg_type,
3244 if (env->ops->is_valid_access &&
3245 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3246 /* A non zero info.ctx_field_size indicates that this field is a
3247 * candidate for later verifier transformation to load the whole
3248 * field and then apply a mask when accessed with a narrower
3249 * access than actual ctx access size. A zero info.ctx_field_size
3250 * will only allow for whole field access and rejects any other
3251 * type of narrower access.
3253 *reg_type = info.reg_type;
3255 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
3256 *btf_id = info.btf_id;
3258 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3259 /* remember the offset of last byte accessed in ctx */
3260 if (env->prog->aux->max_ctx_offset < off + size)
3261 env->prog->aux->max_ctx_offset = off + size;
3265 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3269 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3272 if (size < 0 || off < 0 ||
3273 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3274 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3281 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3282 u32 regno, int off, int size,
3283 enum bpf_access_type t)
3285 struct bpf_reg_state *regs = cur_regs(env);
3286 struct bpf_reg_state *reg = ®s[regno];
3287 struct bpf_insn_access_aux info = {};
3290 if (reg->smin_value < 0) {
3291 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3296 switch (reg->type) {
3297 case PTR_TO_SOCK_COMMON:
3298 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3301 valid = bpf_sock_is_valid_access(off, size, t, &info);
3303 case PTR_TO_TCP_SOCK:
3304 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3306 case PTR_TO_XDP_SOCK:
3307 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3315 env->insn_aux_data[insn_idx].ctx_field_size =
3316 info.ctx_field_size;
3320 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3321 regno, reg_type_str[reg->type], off, size);
3326 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3328 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3331 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3333 const struct bpf_reg_state *reg = reg_state(env, regno);
3335 return reg->type == PTR_TO_CTX;
3338 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3340 const struct bpf_reg_state *reg = reg_state(env, regno);
3342 return type_is_sk_pointer(reg->type);
3345 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3347 const struct bpf_reg_state *reg = reg_state(env, regno);
3349 return type_is_pkt_pointer(reg->type);
3352 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3354 const struct bpf_reg_state *reg = reg_state(env, regno);
3356 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3357 return reg->type == PTR_TO_FLOW_KEYS;
3360 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3361 const struct bpf_reg_state *reg,
3362 int off, int size, bool strict)
3364 struct tnum reg_off;
3367 /* Byte size accesses are always allowed. */
3368 if (!strict || size == 1)
3371 /* For platforms that do not have a Kconfig enabling
3372 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3373 * NET_IP_ALIGN is universally set to '2'. And on platforms
3374 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3375 * to this code only in strict mode where we want to emulate
3376 * the NET_IP_ALIGN==2 checking. Therefore use an
3377 * unconditional IP align value of '2'.
3381 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3382 if (!tnum_is_aligned(reg_off, size)) {
3385 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3387 "misaligned packet access off %d+%s+%d+%d size %d\n",
3388 ip_align, tn_buf, reg->off, off, size);
3395 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3396 const struct bpf_reg_state *reg,
3397 const char *pointer_desc,
3398 int off, int size, bool strict)
3400 struct tnum reg_off;
3402 /* Byte size accesses are always allowed. */
3403 if (!strict || size == 1)
3406 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3407 if (!tnum_is_aligned(reg_off, size)) {
3410 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3411 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3412 pointer_desc, tn_buf, reg->off, off, size);
3419 static int check_ptr_alignment(struct bpf_verifier_env *env,
3420 const struct bpf_reg_state *reg, int off,
3421 int size, bool strict_alignment_once)
3423 bool strict = env->strict_alignment || strict_alignment_once;
3424 const char *pointer_desc = "";
3426 switch (reg->type) {
3428 case PTR_TO_PACKET_META:
3429 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3430 * right in front, treat it the very same way.
3432 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3433 case PTR_TO_FLOW_KEYS:
3434 pointer_desc = "flow keys ";
3436 case PTR_TO_MAP_VALUE:
3437 pointer_desc = "value ";
3440 pointer_desc = "context ";
3443 pointer_desc = "stack ";
3444 /* The stack spill tracking logic in check_stack_write_fixed_off()
3445 * and check_stack_read_fixed_off() relies on stack accesses being
3451 pointer_desc = "sock ";
3453 case PTR_TO_SOCK_COMMON:
3454 pointer_desc = "sock_common ";
3456 case PTR_TO_TCP_SOCK:
3457 pointer_desc = "tcp_sock ";
3459 case PTR_TO_XDP_SOCK:
3460 pointer_desc = "xdp_sock ";
3465 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3469 static int update_stack_depth(struct bpf_verifier_env *env,
3470 const struct bpf_func_state *func,
3473 u16 stack = env->subprog_info[func->subprogno].stack_depth;
3478 /* update known max for given subprogram */
3479 env->subprog_info[func->subprogno].stack_depth = -off;
3483 /* starting from main bpf function walk all instructions of the function
3484 * and recursively walk all callees that given function can call.
3485 * Ignore jump and exit insns.
3486 * Since recursion is prevented by check_cfg() this algorithm
3487 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3489 static int check_max_stack_depth(struct bpf_verifier_env *env)
3491 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3492 struct bpf_subprog_info *subprog = env->subprog_info;
3493 struct bpf_insn *insn = env->prog->insnsi;
3494 bool tail_call_reachable = false;
3495 int ret_insn[MAX_CALL_FRAMES];
3496 int ret_prog[MAX_CALL_FRAMES];
3500 /* protect against potential stack overflow that might happen when
3501 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3502 * depth for such case down to 256 so that the worst case scenario
3503 * would result in 8k stack size (32 which is tailcall limit * 256 =
3506 * To get the idea what might happen, see an example:
3507 * func1 -> sub rsp, 128
3508 * subfunc1 -> sub rsp, 256
3509 * tailcall1 -> add rsp, 256
3510 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3511 * subfunc2 -> sub rsp, 64
3512 * subfunc22 -> sub rsp, 128
3513 * tailcall2 -> add rsp, 128
3514 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3516 * tailcall will unwind the current stack frame but it will not get rid
3517 * of caller's stack as shown on the example above.
3519 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3521 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3525 /* round up to 32-bytes, since this is granularity
3526 * of interpreter stack size
3528 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3529 if (depth > MAX_BPF_STACK) {
3530 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3535 subprog_end = subprog[idx + 1].start;
3536 for (; i < subprog_end; i++) {
3537 if (insn[i].code != (BPF_JMP | BPF_CALL))
3539 if (insn[i].src_reg != BPF_PSEUDO_CALL)
3541 /* remember insn and function to return to */
3542 ret_insn[frame] = i + 1;
3543 ret_prog[frame] = idx;
3545 /* find the callee */
3546 i = i + insn[i].imm + 1;
3547 idx = find_subprog(env, i);
3549 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3554 if (subprog[idx].has_tail_call)
3555 tail_call_reachable = true;
3558 if (frame >= MAX_CALL_FRAMES) {
3559 verbose(env, "the call stack of %d frames is too deep !\n",
3565 /* if tail call got detected across bpf2bpf calls then mark each of the
3566 * currently present subprog frames as tail call reachable subprogs;
3567 * this info will be utilized by JIT so that we will be preserving the
3568 * tail call counter throughout bpf2bpf calls combined with tailcalls
3570 if (tail_call_reachable)
3571 for (j = 0; j < frame; j++)
3572 subprog[ret_prog[j]].tail_call_reachable = true;
3573 if (subprog[0].tail_call_reachable)
3574 env->prog->aux->tail_call_reachable = true;
3576 /* end of for() loop means the last insn of the 'subprog'
3577 * was reached. Doesn't matter whether it was JA or EXIT
3581 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3583 i = ret_insn[frame];
3584 idx = ret_prog[frame];
3588 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3589 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3590 const struct bpf_insn *insn, int idx)
3592 int start = idx + insn->imm + 1, subprog;
3594 subprog = find_subprog(env, start);
3596 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3600 return env->subprog_info[subprog].stack_depth;
3604 int check_ctx_reg(struct bpf_verifier_env *env,
3605 const struct bpf_reg_state *reg, int regno)
3607 /* Access to ctx or passing it to a helper is only allowed in
3608 * its original, unmodified form.
3612 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3617 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3620 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3621 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3628 static int __check_buffer_access(struct bpf_verifier_env *env,
3629 const char *buf_info,
3630 const struct bpf_reg_state *reg,
3631 int regno, int off, int size)
3635 "R%d invalid %s buffer access: off=%d, size=%d\n",
3636 regno, buf_info, off, size);
3639 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3642 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3644 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3645 regno, off, tn_buf);
3652 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3653 const struct bpf_reg_state *reg,
3654 int regno, int off, int size)
3658 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3662 if (off + size > env->prog->aux->max_tp_access)
3663 env->prog->aux->max_tp_access = off + size;
3668 static int check_buffer_access(struct bpf_verifier_env *env,
3669 const struct bpf_reg_state *reg,
3670 int regno, int off, int size,
3671 bool zero_size_allowed,
3672 const char *buf_info,
3677 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3681 if (off + size > *max_access)
3682 *max_access = off + size;
3687 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3688 static void zext_32_to_64(struct bpf_reg_state *reg)
3690 reg->var_off = tnum_subreg(reg->var_off);
3691 __reg_assign_32_into_64(reg);
3694 /* truncate register to smaller size (in bytes)
3695 * must be called with size < BPF_REG_SIZE
3697 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3701 /* clear high bits in bit representation */
3702 reg->var_off = tnum_cast(reg->var_off, size);
3704 /* fix arithmetic bounds */
3705 mask = ((u64)1 << (size * 8)) - 1;
3706 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3707 reg->umin_value &= mask;
3708 reg->umax_value &= mask;
3710 reg->umin_value = 0;
3711 reg->umax_value = mask;
3713 reg->smin_value = reg->umin_value;
3714 reg->smax_value = reg->umax_value;
3716 /* If size is smaller than 32bit register the 32bit register
3717 * values are also truncated so we push 64-bit bounds into
3718 * 32-bit bounds. Above were truncated < 32-bits already.
3722 __reg_combine_64_into_32(reg);
3725 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3727 /* A map is considered read-only if the following condition are true:
3729 * 1) BPF program side cannot change any of the map content. The
3730 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
3731 * and was set at map creation time.
3732 * 2) The map value(s) have been initialized from user space by a
3733 * loader and then "frozen", such that no new map update/delete
3734 * operations from syscall side are possible for the rest of
3735 * the map's lifetime from that point onwards.
3736 * 3) Any parallel/pending map update/delete operations from syscall
3737 * side have been completed. Only after that point, it's safe to
3738 * assume that map value(s) are immutable.
3740 return (map->map_flags & BPF_F_RDONLY_PROG) &&
3741 READ_ONCE(map->frozen) &&
3742 !bpf_map_write_active(map);
3745 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3751 err = map->ops->map_direct_value_addr(map, &addr, off);
3754 ptr = (void *)(long)addr + off;
3758 *val = (u64)*(u8 *)ptr;
3761 *val = (u64)*(u16 *)ptr;
3764 *val = (u64)*(u32 *)ptr;
3775 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3776 struct bpf_reg_state *regs,
3777 int regno, int off, int size,
3778 enum bpf_access_type atype,
3781 struct bpf_reg_state *reg = regs + regno;
3782 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3783 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3789 "R%d is ptr_%s invalid negative access: off=%d\n",
3793 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3796 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3798 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3799 regno, tname, off, tn_buf);
3803 if (env->ops->btf_struct_access) {
3804 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3807 if (atype != BPF_READ) {
3808 verbose(env, "only read is supported\n");
3812 ret = btf_struct_access(&env->log, t, off, size, atype,
3819 if (atype == BPF_READ && value_regno >= 0)
3820 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3825 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3826 struct bpf_reg_state *regs,
3827 int regno, int off, int size,
3828 enum bpf_access_type atype,
3831 struct bpf_reg_state *reg = regs + regno;
3832 struct bpf_map *map = reg->map_ptr;
3833 const struct btf_type *t;
3839 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3843 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3844 verbose(env, "map_ptr access not supported for map type %d\n",
3849 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3850 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3852 if (!env->allow_ptr_to_map_access) {
3854 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3860 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3865 if (atype != BPF_READ) {
3866 verbose(env, "only read from %s is supported\n", tname);
3870 ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3874 if (value_regno >= 0)
3875 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3880 /* Check that the stack access at the given offset is within bounds. The
3881 * maximum valid offset is -1.
3883 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3884 * -state->allocated_stack for reads.
3886 static int check_stack_slot_within_bounds(int off,
3887 struct bpf_func_state *state,
3888 enum bpf_access_type t)
3893 min_valid_off = -MAX_BPF_STACK;
3895 min_valid_off = -state->allocated_stack;
3897 if (off < min_valid_off || off > -1)
3902 /* Check that the stack access at 'regno + off' falls within the maximum stack
3905 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3907 static int check_stack_access_within_bounds(
3908 struct bpf_verifier_env *env,
3909 int regno, int off, int access_size,
3910 enum stack_access_src src, enum bpf_access_type type)
3912 struct bpf_reg_state *regs = cur_regs(env);
3913 struct bpf_reg_state *reg = regs + regno;
3914 struct bpf_func_state *state = func(env, reg);
3915 int min_off, max_off;
3919 if (src == ACCESS_HELPER)
3920 /* We don't know if helpers are reading or writing (or both). */
3921 err_extra = " indirect access to";
3922 else if (type == BPF_READ)
3923 err_extra = " read from";
3925 err_extra = " write to";
3927 if (tnum_is_const(reg->var_off)) {
3928 min_off = reg->var_off.value + off;
3929 max_off = min_off + access_size;
3931 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3932 reg->smin_value <= -BPF_MAX_VAR_OFF) {
3933 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3937 min_off = reg->smin_value + off;
3938 max_off = reg->smax_value + off + access_size;
3941 err = check_stack_slot_within_bounds(min_off, state, type);
3942 if (!err && max_off > 0)
3943 err = -EINVAL; /* out of stack access into non-negative offsets */
3944 if (!err && access_size < 0)
3945 /* access_size should not be negative (or overflow an int); others checks
3946 * along the way should have prevented such an access.
3948 err = -EFAULT; /* invalid negative access size; integer overflow? */
3951 if (tnum_is_const(reg->var_off)) {
3952 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3953 err_extra, regno, off, access_size);
3957 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3958 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3959 err_extra, regno, tn_buf, access_size);
3965 /* check whether memory at (regno + off) is accessible for t = (read | write)
3966 * if t==write, value_regno is a register which value is stored into memory
3967 * if t==read, value_regno is a register which will receive the value from memory
3968 * if t==write && value_regno==-1, some unknown value is stored into memory
3969 * if t==read && value_regno==-1, don't care what we read from memory
3971 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3972 int off, int bpf_size, enum bpf_access_type t,
3973 int value_regno, bool strict_alignment_once)
3975 struct bpf_reg_state *regs = cur_regs(env);
3976 struct bpf_reg_state *reg = regs + regno;
3977 struct bpf_func_state *state;
3980 size = bpf_size_to_bytes(bpf_size);
3984 /* alignment checks will add in reg->off themselves */
3985 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3989 /* for access checks, reg->off is just part of off */
3992 if (reg->type == PTR_TO_MAP_VALUE) {
3993 if (t == BPF_WRITE && value_regno >= 0 &&
3994 is_pointer_value(env, value_regno)) {
3995 verbose(env, "R%d leaks addr into map\n", value_regno);
3998 err = check_map_access_type(env, regno, off, size, t);
4001 err = check_map_access(env, regno, off, size, false);
4002 if (!err && t == BPF_READ && value_regno >= 0) {
4003 struct bpf_map *map = reg->map_ptr;
4005 /* if map is read-only, track its contents as scalars */
4006 if (tnum_is_const(reg->var_off) &&
4007 bpf_map_is_rdonly(map) &&
4008 map->ops->map_direct_value_addr) {
4009 int map_off = off + reg->var_off.value;
4012 err = bpf_map_direct_read(map, map_off, size,
4017 regs[value_regno].type = SCALAR_VALUE;
4018 __mark_reg_known(®s[value_regno], val);
4020 mark_reg_unknown(env, regs, value_regno);
4023 } else if (reg->type == PTR_TO_MEM) {
4024 if (t == BPF_WRITE && value_regno >= 0 &&
4025 is_pointer_value(env, value_regno)) {
4026 verbose(env, "R%d leaks addr into mem\n", value_regno);
4029 err = check_mem_region_access(env, regno, off, size,
4030 reg->mem_size, false);
4031 if (!err && t == BPF_READ && value_regno >= 0)
4032 mark_reg_unknown(env, regs, value_regno);
4033 } else if (reg->type == PTR_TO_CTX) {
4034 enum bpf_reg_type reg_type = SCALAR_VALUE;
4037 if (t == BPF_WRITE && value_regno >= 0 &&
4038 is_pointer_value(env, value_regno)) {
4039 verbose(env, "R%d leaks addr into ctx\n", value_regno);
4043 err = check_ctx_reg(env, reg, regno);
4047 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf_id);
4049 verbose_linfo(env, insn_idx, "; ");
4050 if (!err && t == BPF_READ && value_regno >= 0) {
4051 /* ctx access returns either a scalar, or a
4052 * PTR_TO_PACKET[_META,_END]. In the latter
4053 * case, we know the offset is zero.
4055 if (reg_type == SCALAR_VALUE) {
4056 mark_reg_unknown(env, regs, value_regno);
4058 mark_reg_known_zero(env, regs,
4060 if (reg_type_may_be_null(reg_type))
4061 regs[value_regno].id = ++env->id_gen;
4062 /* A load of ctx field could have different
4063 * actual load size with the one encoded in the
4064 * insn. When the dst is PTR, it is for sure not
4067 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4068 if (reg_type == PTR_TO_BTF_ID ||
4069 reg_type == PTR_TO_BTF_ID_OR_NULL)
4070 regs[value_regno].btf_id = btf_id;
4072 regs[value_regno].type = reg_type;
4075 } else if (reg->type == PTR_TO_STACK) {
4076 /* Basic bounds checks. */
4077 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4081 state = func(env, reg);
4082 err = update_stack_depth(env, state, off);
4087 err = check_stack_read(env, regno, off, size,
4090 err = check_stack_write(env, regno, off, size,
4091 value_regno, insn_idx);
4092 } else if (reg_is_pkt_pointer(reg)) {
4093 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4094 verbose(env, "cannot write into packet\n");
4097 if (t == BPF_WRITE && value_regno >= 0 &&
4098 is_pointer_value(env, value_regno)) {
4099 verbose(env, "R%d leaks addr into packet\n",
4103 err = check_packet_access(env, regno, off, size, false);
4104 if (!err && t == BPF_READ && value_regno >= 0)
4105 mark_reg_unknown(env, regs, value_regno);
4106 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4107 if (t == BPF_WRITE && value_regno >= 0 &&
4108 is_pointer_value(env, value_regno)) {
4109 verbose(env, "R%d leaks addr into flow keys\n",
4114 err = check_flow_keys_access(env, off, size);
4115 if (!err && t == BPF_READ && value_regno >= 0)
4116 mark_reg_unknown(env, regs, value_regno);
4117 } else if (type_is_sk_pointer(reg->type)) {
4118 if (t == BPF_WRITE) {
4119 verbose(env, "R%d cannot write into %s\n",
4120 regno, reg_type_str[reg->type]);
4123 err = check_sock_access(env, insn_idx, regno, off, size, t);
4124 if (!err && value_regno >= 0)
4125 mark_reg_unknown(env, regs, value_regno);
4126 } else if (reg->type == PTR_TO_TP_BUFFER) {
4127 err = check_tp_buffer_access(env, reg, regno, off, size);
4128 if (!err && t == BPF_READ && value_regno >= 0)
4129 mark_reg_unknown(env, regs, value_regno);
4130 } else if (reg->type == PTR_TO_BTF_ID) {
4131 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4133 } else if (reg->type == CONST_PTR_TO_MAP) {
4134 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4136 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4137 if (t == BPF_WRITE) {
4138 verbose(env, "R%d cannot write into %s\n",
4139 regno, reg_type_str[reg->type]);
4142 err = check_buffer_access(env, reg, regno, off, size, false,
4144 &env->prog->aux->max_rdonly_access);
4145 if (!err && value_regno >= 0)
4146 mark_reg_unknown(env, regs, value_regno);
4147 } else if (reg->type == PTR_TO_RDWR_BUF) {
4148 err = check_buffer_access(env, reg, regno, off, size, false,
4150 &env->prog->aux->max_rdwr_access);
4151 if (!err && t == BPF_READ && value_regno >= 0)
4152 mark_reg_unknown(env, regs, value_regno);
4154 verbose(env, "R%d invalid mem access '%s'\n", regno,
4155 reg_type_str[reg->type]);
4159 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4160 regs[value_regno].type == SCALAR_VALUE) {
4161 /* b/h/w load zero-extends, mark upper bits as known 0 */
4162 coerce_reg_to_size(®s[value_regno], size);
4167 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4171 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
4173 verbose(env, "BPF_XADD uses reserved fields\n");
4177 /* check src1 operand */
4178 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4182 /* check src2 operand */
4183 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4187 if (is_pointer_value(env, insn->src_reg)) {
4188 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4192 if (is_ctx_reg(env, insn->dst_reg) ||
4193 is_pkt_reg(env, insn->dst_reg) ||
4194 is_flow_key_reg(env, insn->dst_reg) ||
4195 is_sk_reg(env, insn->dst_reg)) {
4196 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
4198 reg_type_str[reg_state(env, insn->dst_reg)->type]);
4202 /* check whether atomic_add can read the memory */
4203 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4204 BPF_SIZE(insn->code), BPF_READ, -1, true);
4208 /* check whether atomic_add can write into the same memory */
4209 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4210 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4213 /* When register 'regno' is used to read the stack (either directly or through
4214 * a helper function) make sure that it's within stack boundary and, depending
4215 * on the access type, that all elements of the stack are initialized.
4217 * 'off' includes 'regno->off', but not its dynamic part (if any).
4219 * All registers that have been spilled on the stack in the slots within the
4220 * read offsets are marked as read.
4222 static int check_stack_range_initialized(
4223 struct bpf_verifier_env *env, int regno, int off,
4224 int access_size, bool zero_size_allowed,
4225 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4227 struct bpf_reg_state *reg = reg_state(env, regno);
4228 struct bpf_func_state *state = func(env, reg);
4229 int err, min_off, max_off, i, j, slot, spi;
4230 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4231 enum bpf_access_type bounds_check_type;
4232 /* Some accesses can write anything into the stack, others are
4235 bool clobber = false;
4237 if (access_size == 0 && !zero_size_allowed) {
4238 verbose(env, "invalid zero-sized read\n");
4242 if (type == ACCESS_HELPER) {
4243 /* The bounds checks for writes are more permissive than for
4244 * reads. However, if raw_mode is not set, we'll do extra
4247 bounds_check_type = BPF_WRITE;
4250 bounds_check_type = BPF_READ;
4252 err = check_stack_access_within_bounds(env, regno, off, access_size,
4253 type, bounds_check_type);
4258 if (tnum_is_const(reg->var_off)) {
4259 min_off = max_off = reg->var_off.value + off;
4261 /* Variable offset is prohibited for unprivileged mode for
4262 * simplicity since it requires corresponding support in
4263 * Spectre masking for stack ALU.
4264 * See also retrieve_ptr_limit().
4266 if (!env->bypass_spec_v1) {
4269 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4270 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4271 regno, err_extra, tn_buf);
4274 /* Only initialized buffer on stack is allowed to be accessed
4275 * with variable offset. With uninitialized buffer it's hard to
4276 * guarantee that whole memory is marked as initialized on
4277 * helper return since specific bounds are unknown what may
4278 * cause uninitialized stack leaking.
4280 if (meta && meta->raw_mode)
4283 min_off = reg->smin_value + off;
4284 max_off = reg->smax_value + off;
4287 if (meta && meta->raw_mode) {
4288 meta->access_size = access_size;
4289 meta->regno = regno;
4293 for (i = min_off; i < max_off + access_size; i++) {
4297 spi = slot / BPF_REG_SIZE;
4298 if (state->allocated_stack <= slot)
4300 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4301 if (*stype == STACK_MISC)
4303 if (*stype == STACK_ZERO) {
4305 /* helper can write anything into the stack */
4306 *stype = STACK_MISC;
4311 if (is_spilled_reg(&state->stack[spi]) &&
4312 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4315 if (is_spilled_reg(&state->stack[spi]) &&
4316 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4317 env->allow_ptr_leaks)) {
4319 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4320 for (j = 0; j < BPF_REG_SIZE; j++)
4321 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
4327 if (tnum_is_const(reg->var_off)) {
4328 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4329 err_extra, regno, min_off, i - min_off, access_size);
4333 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4334 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4335 err_extra, regno, tn_buf, i - min_off, access_size);
4339 /* reading any byte out of 8-byte 'spill_slot' will cause
4340 * the whole slot to be marked as 'read'
4342 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4343 state->stack[spi].spilled_ptr.parent,
4346 return update_stack_depth(env, state, min_off);
4349 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4350 int access_size, bool zero_size_allowed,
4351 struct bpf_call_arg_meta *meta)
4353 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4355 switch (reg->type) {
4357 case PTR_TO_PACKET_META:
4358 return check_packet_access(env, regno, reg->off, access_size,
4360 case PTR_TO_MAP_VALUE:
4361 if (check_map_access_type(env, regno, reg->off, access_size,
4362 meta && meta->raw_mode ? BPF_WRITE :
4365 return check_map_access(env, regno, reg->off, access_size,
4368 return check_mem_region_access(env, regno, reg->off,
4369 access_size, reg->mem_size,
4371 case PTR_TO_RDONLY_BUF:
4372 if (meta && meta->raw_mode)
4374 return check_buffer_access(env, reg, regno, reg->off,
4375 access_size, zero_size_allowed,
4377 &env->prog->aux->max_rdonly_access);
4378 case PTR_TO_RDWR_BUF:
4379 return check_buffer_access(env, reg, regno, reg->off,
4380 access_size, zero_size_allowed,
4382 &env->prog->aux->max_rdwr_access);
4384 return check_stack_range_initialized(
4386 regno, reg->off, access_size,
4387 zero_size_allowed, ACCESS_HELPER, meta);
4388 default: /* scalar_value or invalid ptr */
4389 /* Allow zero-byte read from NULL, regardless of pointer type */
4390 if (zero_size_allowed && access_size == 0 &&
4391 register_is_null(reg))
4394 verbose(env, "R%d type=%s expected=%s\n", regno,
4395 reg_type_str[reg->type],
4396 reg_type_str[PTR_TO_STACK]);
4401 /* Implementation details:
4402 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4403 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4404 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4405 * value_or_null->value transition, since the verifier only cares about
4406 * the range of access to valid map value pointer and doesn't care about actual
4407 * address of the map element.
4408 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4409 * reg->id > 0 after value_or_null->value transition. By doing so
4410 * two bpf_map_lookups will be considered two different pointers that
4411 * point to different bpf_spin_locks.
4412 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4414 * Since only one bpf_spin_lock is allowed the checks are simpler than
4415 * reg_is_refcounted() logic. The verifier needs to remember only
4416 * one spin_lock instead of array of acquired_refs.
4417 * cur_state->active_spin_lock remembers which map value element got locked
4418 * and clears it after bpf_spin_unlock.
4420 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4423 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4424 struct bpf_verifier_state *cur = env->cur_state;
4425 bool is_const = tnum_is_const(reg->var_off);
4426 struct bpf_map *map = reg->map_ptr;
4427 u64 val = reg->var_off.value;
4431 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4437 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4441 if (!map_value_has_spin_lock(map)) {
4442 if (map->spin_lock_off == -E2BIG)
4444 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4446 else if (map->spin_lock_off == -ENOENT)
4448 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4452 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4456 if (map->spin_lock_off != val + reg->off) {
4457 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4462 if (cur->active_spin_lock) {
4464 "Locking two bpf_spin_locks are not allowed\n");
4467 cur->active_spin_lock = reg->id;
4469 if (!cur->active_spin_lock) {
4470 verbose(env, "bpf_spin_unlock without taking a lock\n");
4473 if (cur->active_spin_lock != reg->id) {
4474 verbose(env, "bpf_spin_unlock of different lock\n");
4477 cur->active_spin_lock = 0;
4482 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4484 return type == ARG_PTR_TO_MEM ||
4485 type == ARG_PTR_TO_MEM_OR_NULL ||
4486 type == ARG_PTR_TO_UNINIT_MEM;
4489 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4491 return type == ARG_CONST_SIZE ||
4492 type == ARG_CONST_SIZE_OR_ZERO;
4495 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4497 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4500 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4502 return type == ARG_PTR_TO_INT ||
4503 type == ARG_PTR_TO_LONG;
4506 static int int_ptr_type_to_size(enum bpf_arg_type type)
4508 if (type == ARG_PTR_TO_INT)
4510 else if (type == ARG_PTR_TO_LONG)
4516 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4517 const struct bpf_call_arg_meta *meta,
4518 enum bpf_arg_type *arg_type)
4520 if (!meta->map_ptr) {
4521 /* kernel subsystem misconfigured verifier */
4522 verbose(env, "invalid map_ptr to access map->type\n");
4526 switch (meta->map_ptr->map_type) {
4527 case BPF_MAP_TYPE_SOCKMAP:
4528 case BPF_MAP_TYPE_SOCKHASH:
4529 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4530 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4532 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4543 struct bpf_reg_types {
4544 const enum bpf_reg_type types[10];
4548 static const struct bpf_reg_types map_key_value_types = {
4557 static const struct bpf_reg_types sock_types = {
4567 static const struct bpf_reg_types btf_id_sock_common_types = {
4575 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4579 static const struct bpf_reg_types mem_types = {
4591 static const struct bpf_reg_types int_ptr_types = {
4600 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4601 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4602 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4603 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4604 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4605 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4606 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4607 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4609 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4610 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4611 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4612 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4613 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4614 [ARG_CONST_SIZE] = &scalar_types,
4615 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4616 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4617 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4618 [ARG_PTR_TO_CTX] = &context_types,
4619 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4620 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
4622 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4624 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4625 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4626 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4627 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4628 [ARG_PTR_TO_MEM] = &mem_types,
4629 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4630 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4631 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4632 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4633 [ARG_PTR_TO_INT] = &int_ptr_types,
4634 [ARG_PTR_TO_LONG] = &int_ptr_types,
4635 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
4638 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4639 enum bpf_arg_type arg_type,
4640 const u32 *arg_btf_id)
4642 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4643 enum bpf_reg_type expected, type = reg->type;
4644 const struct bpf_reg_types *compatible;
4647 compatible = compatible_reg_types[arg_type];
4649 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4653 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4654 expected = compatible->types[i];
4655 if (expected == NOT_INIT)
4658 if (type == expected)
4662 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4663 for (j = 0; j + 1 < i; j++)
4664 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4665 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4669 if (type == PTR_TO_BTF_ID) {
4671 if (!compatible->btf_id) {
4672 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4675 arg_btf_id = compatible->btf_id;
4678 if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
4680 verbose(env, "R%d is of type %s but %s is expected\n",
4681 regno, kernel_type_name(reg->btf_id),
4682 kernel_type_name(*arg_btf_id));
4686 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4687 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4696 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4697 struct bpf_call_arg_meta *meta,
4698 const struct bpf_func_proto *fn)
4700 u32 regno = BPF_REG_1 + arg;
4701 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4702 enum bpf_arg_type arg_type = fn->arg_type[arg];
4703 enum bpf_reg_type type = reg->type;
4706 if (arg_type == ARG_DONTCARE)
4709 err = check_reg_arg(env, regno, SRC_OP);
4713 if (arg_type == ARG_ANYTHING) {
4714 if (is_pointer_value(env, regno)) {
4715 verbose(env, "R%d leaks addr into helper function\n",
4722 if (type_is_pkt_pointer(type) &&
4723 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4724 verbose(env, "helper access to the packet is not allowed\n");
4728 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4729 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4730 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4731 err = resolve_map_arg_type(env, meta, &arg_type);
4736 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4737 /* A NULL register has a SCALAR_VALUE type, so skip
4740 goto skip_type_check;
4742 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4746 if (type == PTR_TO_CTX) {
4747 err = check_ctx_reg(env, reg, regno);
4753 if (reg->ref_obj_id) {
4754 if (meta->ref_obj_id) {
4755 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4756 regno, reg->ref_obj_id,
4760 meta->ref_obj_id = reg->ref_obj_id;
4763 if (arg_type == ARG_CONST_MAP_PTR) {
4764 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4765 meta->map_ptr = reg->map_ptr;
4766 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4767 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4768 * check that [key, key + map->key_size) are within
4769 * stack limits and initialized
4771 if (!meta->map_ptr) {
4772 /* in function declaration map_ptr must come before
4773 * map_key, so that it's verified and known before
4774 * we have to check map_key here. Otherwise it means
4775 * that kernel subsystem misconfigured verifier
4777 verbose(env, "invalid map_ptr to access map->key\n");
4780 err = check_helper_mem_access(env, regno,
4781 meta->map_ptr->key_size, false,
4783 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4784 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4785 !register_is_null(reg)) ||
4786 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4787 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4788 * check [value, value + map->value_size) validity
4790 if (!meta->map_ptr) {
4791 /* kernel subsystem misconfigured verifier */
4792 verbose(env, "invalid map_ptr to access map->value\n");
4795 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4796 err = check_helper_mem_access(env, regno,
4797 meta->map_ptr->value_size, false,
4799 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4801 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4804 meta->ret_btf_id = reg->btf_id;
4805 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4806 if (meta->func_id == BPF_FUNC_spin_lock) {
4807 if (process_spin_lock(env, regno, true))
4809 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4810 if (process_spin_lock(env, regno, false))
4813 verbose(env, "verifier internal error\n");
4816 } else if (arg_type_is_mem_ptr(arg_type)) {
4817 /* The access to this pointer is only checked when we hit the
4818 * next is_mem_size argument below.
4820 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4821 } else if (arg_type_is_mem_size(arg_type)) {
4822 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4824 /* This is used to refine r0 return value bounds for helpers
4825 * that enforce this value as an upper bound on return values.
4826 * See do_refine_retval_range() for helpers that can refine
4827 * the return value. C type of helper is u32 so we pull register
4828 * bound from umax_value however, if negative verifier errors
4829 * out. Only upper bounds can be learned because retval is an
4830 * int type and negative retvals are allowed.
4832 meta->msize_max_value = reg->umax_value;
4834 /* The register is SCALAR_VALUE; the access check
4835 * happens using its boundaries.
4837 if (!tnum_is_const(reg->var_off))
4838 /* For unprivileged variable accesses, disable raw
4839 * mode so that the program is required to
4840 * initialize all the memory that the helper could
4841 * just partially fill up.
4845 if (reg->smin_value < 0) {
4846 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4851 if (reg->umin_value == 0) {
4852 err = check_helper_mem_access(env, regno - 1, 0,
4859 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4860 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4864 err = check_helper_mem_access(env, regno - 1,
4866 zero_size_allowed, meta);
4868 err = mark_chain_precision(env, regno);
4869 } else if (arg_type_is_alloc_size(arg_type)) {
4870 if (!tnum_is_const(reg->var_off)) {
4871 verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4875 meta->mem_size = reg->var_off.value;
4876 } else if (arg_type_is_int_ptr(arg_type)) {
4877 int size = int_ptr_type_to_size(arg_type);
4879 err = check_helper_mem_access(env, regno, size, false, meta);
4882 err = check_ptr_alignment(env, reg, 0, size, true);
4888 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4890 enum bpf_attach_type eatype = env->prog->expected_attach_type;
4891 enum bpf_prog_type type = resolve_prog_type(env->prog);
4893 if (func_id != BPF_FUNC_map_update_elem)
4896 /* It's not possible to get access to a locked struct sock in these
4897 * contexts, so updating is safe.
4900 case BPF_PROG_TYPE_TRACING:
4901 if (eatype == BPF_TRACE_ITER)
4904 case BPF_PROG_TYPE_SOCKET_FILTER:
4905 case BPF_PROG_TYPE_SCHED_CLS:
4906 case BPF_PROG_TYPE_SCHED_ACT:
4907 case BPF_PROG_TYPE_XDP:
4908 case BPF_PROG_TYPE_SK_REUSEPORT:
4909 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4910 case BPF_PROG_TYPE_SK_LOOKUP:
4916 verbose(env, "cannot update sockmap in this context\n");
4920 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4922 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4925 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4926 struct bpf_map *map, int func_id)
4931 /* We need a two way check, first is from map perspective ... */
4932 switch (map->map_type) {
4933 case BPF_MAP_TYPE_PROG_ARRAY:
4934 if (func_id != BPF_FUNC_tail_call)
4937 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4938 if (func_id != BPF_FUNC_perf_event_read &&
4939 func_id != BPF_FUNC_perf_event_output &&
4940 func_id != BPF_FUNC_skb_output &&
4941 func_id != BPF_FUNC_perf_event_read_value &&
4942 func_id != BPF_FUNC_xdp_output)
4945 case BPF_MAP_TYPE_RINGBUF:
4946 if (func_id != BPF_FUNC_ringbuf_output &&
4947 func_id != BPF_FUNC_ringbuf_reserve &&
4948 func_id != BPF_FUNC_ringbuf_query)
4951 case BPF_MAP_TYPE_STACK_TRACE:
4952 if (func_id != BPF_FUNC_get_stackid)
4955 case BPF_MAP_TYPE_CGROUP_ARRAY:
4956 if (func_id != BPF_FUNC_skb_under_cgroup &&
4957 func_id != BPF_FUNC_current_task_under_cgroup)
4960 case BPF_MAP_TYPE_CGROUP_STORAGE:
4961 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4962 if (func_id != BPF_FUNC_get_local_storage)
4965 case BPF_MAP_TYPE_DEVMAP:
4966 case BPF_MAP_TYPE_DEVMAP_HASH:
4967 if (func_id != BPF_FUNC_redirect_map &&
4968 func_id != BPF_FUNC_map_lookup_elem)
4971 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4974 case BPF_MAP_TYPE_CPUMAP:
4975 if (func_id != BPF_FUNC_redirect_map)
4978 case BPF_MAP_TYPE_XSKMAP:
4979 if (func_id != BPF_FUNC_redirect_map &&
4980 func_id != BPF_FUNC_map_lookup_elem)
4983 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4984 case BPF_MAP_TYPE_HASH_OF_MAPS:
4985 if (func_id != BPF_FUNC_map_lookup_elem)
4988 case BPF_MAP_TYPE_SOCKMAP:
4989 if (func_id != BPF_FUNC_sk_redirect_map &&
4990 func_id != BPF_FUNC_sock_map_update &&
4991 func_id != BPF_FUNC_map_delete_elem &&
4992 func_id != BPF_FUNC_msg_redirect_map &&
4993 func_id != BPF_FUNC_sk_select_reuseport &&
4994 func_id != BPF_FUNC_map_lookup_elem &&
4995 !may_update_sockmap(env, func_id))
4998 case BPF_MAP_TYPE_SOCKHASH:
4999 if (func_id != BPF_FUNC_sk_redirect_hash &&
5000 func_id != BPF_FUNC_sock_hash_update &&
5001 func_id != BPF_FUNC_map_delete_elem &&
5002 func_id != BPF_FUNC_msg_redirect_hash &&
5003 func_id != BPF_FUNC_sk_select_reuseport &&
5004 func_id != BPF_FUNC_map_lookup_elem &&
5005 !may_update_sockmap(env, func_id))
5008 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5009 if (func_id != BPF_FUNC_sk_select_reuseport)
5012 case BPF_MAP_TYPE_QUEUE:
5013 case BPF_MAP_TYPE_STACK:
5014 if (func_id != BPF_FUNC_map_peek_elem &&
5015 func_id != BPF_FUNC_map_pop_elem &&
5016 func_id != BPF_FUNC_map_push_elem)
5019 case BPF_MAP_TYPE_SK_STORAGE:
5020 if (func_id != BPF_FUNC_sk_storage_get &&
5021 func_id != BPF_FUNC_sk_storage_delete)
5024 case BPF_MAP_TYPE_INODE_STORAGE:
5025 if (func_id != BPF_FUNC_inode_storage_get &&
5026 func_id != BPF_FUNC_inode_storage_delete)
5033 /* ... and second from the function itself. */
5035 case BPF_FUNC_tail_call:
5036 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5038 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5039 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5043 case BPF_FUNC_perf_event_read:
5044 case BPF_FUNC_perf_event_output:
5045 case BPF_FUNC_perf_event_read_value:
5046 case BPF_FUNC_skb_output:
5047 case BPF_FUNC_xdp_output:
5048 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5051 case BPF_FUNC_ringbuf_output:
5052 case BPF_FUNC_ringbuf_reserve:
5053 case BPF_FUNC_ringbuf_query:
5054 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5057 case BPF_FUNC_get_stackid:
5058 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5061 case BPF_FUNC_current_task_under_cgroup:
5062 case BPF_FUNC_skb_under_cgroup:
5063 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5066 case BPF_FUNC_redirect_map:
5067 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5068 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5069 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5070 map->map_type != BPF_MAP_TYPE_XSKMAP)
5073 case BPF_FUNC_sk_redirect_map:
5074 case BPF_FUNC_msg_redirect_map:
5075 case BPF_FUNC_sock_map_update:
5076 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5079 case BPF_FUNC_sk_redirect_hash:
5080 case BPF_FUNC_msg_redirect_hash:
5081 case BPF_FUNC_sock_hash_update:
5082 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5085 case BPF_FUNC_get_local_storage:
5086 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5087 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5090 case BPF_FUNC_sk_select_reuseport:
5091 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5092 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5093 map->map_type != BPF_MAP_TYPE_SOCKHASH)
5096 case BPF_FUNC_map_peek_elem:
5097 case BPF_FUNC_map_pop_elem:
5098 case BPF_FUNC_map_push_elem:
5099 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5100 map->map_type != BPF_MAP_TYPE_STACK)
5103 case BPF_FUNC_sk_storage_get:
5104 case BPF_FUNC_sk_storage_delete:
5105 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5108 case BPF_FUNC_inode_storage_get:
5109 case BPF_FUNC_inode_storage_delete:
5110 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5119 verbose(env, "cannot pass map_type %d into func %s#%d\n",
5120 map->map_type, func_id_name(func_id), func_id);
5124 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5128 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5130 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5132 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5134 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5136 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5139 /* We only support one arg being in raw mode at the moment,
5140 * which is sufficient for the helper functions we have
5146 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5147 enum bpf_arg_type arg_next)
5149 return (arg_type_is_mem_ptr(arg_curr) &&
5150 !arg_type_is_mem_size(arg_next)) ||
5151 (!arg_type_is_mem_ptr(arg_curr) &&
5152 arg_type_is_mem_size(arg_next));
5155 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5157 /* bpf_xxx(..., buf, len) call will access 'len'
5158 * bytes from memory 'buf'. Both arg types need
5159 * to be paired, so make sure there's no buggy
5160 * helper function specification.
5162 if (arg_type_is_mem_size(fn->arg1_type) ||
5163 arg_type_is_mem_ptr(fn->arg5_type) ||
5164 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5165 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5166 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5167 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5173 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5177 if (arg_type_may_be_refcounted(fn->arg1_type))
5179 if (arg_type_may_be_refcounted(fn->arg2_type))
5181 if (arg_type_may_be_refcounted(fn->arg3_type))
5183 if (arg_type_may_be_refcounted(fn->arg4_type))
5185 if (arg_type_may_be_refcounted(fn->arg5_type))
5188 /* A reference acquiring function cannot acquire
5189 * another refcounted ptr.
5191 if (may_be_acquire_function(func_id) && count)
5194 /* We only support one arg being unreferenced at the moment,
5195 * which is sufficient for the helper functions we have right now.
5200 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5204 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5205 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5208 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5215 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5217 return check_raw_mode_ok(fn) &&
5218 check_arg_pair_ok(fn) &&
5219 check_btf_id_ok(fn) &&
5220 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5223 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5224 * are now invalid, so turn them into unknown SCALAR_VALUE.
5226 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5228 struct bpf_func_state *state;
5229 struct bpf_reg_state *reg;
5231 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5232 if (reg_is_pkt_pointer_any(reg))
5233 __mark_reg_unknown(env, reg);
5239 BEYOND_PKT_END = -2,
5242 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5244 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5245 struct bpf_reg_state *reg = &state->regs[regn];
5247 if (reg->type != PTR_TO_PACKET)
5248 /* PTR_TO_PACKET_META is not supported yet */
5251 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5252 * How far beyond pkt_end it goes is unknown.
5253 * if (!range_open) it's the case of pkt >= pkt_end
5254 * if (range_open) it's the case of pkt > pkt_end
5255 * hence this pointer is at least 1 byte bigger than pkt_end
5258 reg->range = BEYOND_PKT_END;
5260 reg->range = AT_PKT_END;
5263 /* The pointer with the specified id has released its reference to kernel
5264 * resources. Identify all copies of the same pointer and clear the reference.
5266 static int release_reference(struct bpf_verifier_env *env,
5269 struct bpf_func_state *state;
5270 struct bpf_reg_state *reg;
5273 err = release_reference_state(cur_func(env), ref_obj_id);
5277 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5278 if (reg->ref_obj_id == ref_obj_id) {
5279 if (!env->allow_ptr_leaks)
5280 __mark_reg_not_init(env, reg);
5282 __mark_reg_unknown(env, reg);
5289 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5290 struct bpf_reg_state *regs)
5294 /* after the call registers r0 - r5 were scratched */
5295 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5296 mark_reg_not_init(env, regs, caller_saved[i]);
5297 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5301 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5304 struct bpf_verifier_state *state = env->cur_state;
5305 struct bpf_func_info_aux *func_info_aux;
5306 struct bpf_func_state *caller, *callee;
5307 int i, err, subprog, target_insn;
5308 bool is_global = false;
5310 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5311 verbose(env, "the call stack of %d frames is too deep\n",
5312 state->curframe + 2);
5316 target_insn = *insn_idx + insn->imm;
5317 subprog = find_subprog(env, target_insn + 1);
5319 verbose(env, "verifier bug. No program starts at insn %d\n",
5324 caller = state->frame[state->curframe];
5325 if (state->frame[state->curframe + 1]) {
5326 verbose(env, "verifier bug. Frame %d already allocated\n",
5327 state->curframe + 1);
5331 func_info_aux = env->prog->aux->func_info_aux;
5333 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5334 err = btf_check_func_arg_match(env, subprog, caller->regs);
5339 verbose(env, "Caller passes invalid args into func#%d\n",
5343 if (env->log.level & BPF_LOG_LEVEL)
5345 "Func#%d is global and valid. Skipping.\n",
5347 clear_caller_saved_regs(env, caller->regs);
5349 /* All global functions return a 64-bit SCALAR_VALUE */
5350 mark_reg_unknown(env, caller->regs, BPF_REG_0);
5351 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5353 /* continue with next insn after call */
5358 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5361 state->frame[state->curframe + 1] = callee;
5363 /* callee cannot access r0, r6 - r9 for reading and has to write
5364 * into its own stack before reading from it.
5365 * callee can read/write into caller's stack
5367 init_func_state(env, callee,
5368 /* remember the callsite, it will be used by bpf_exit */
5369 *insn_idx /* callsite */,
5370 state->curframe + 1 /* frameno within this callchain */,
5371 subprog /* subprog number within this prog */);
5373 /* Transfer references to the callee */
5374 err = transfer_reference_state(callee, caller);
5378 /* copy r1 - r5 args that callee can access. The copy includes parent
5379 * pointers, which connects us up to the liveness chain
5381 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5382 callee->regs[i] = caller->regs[i];
5384 clear_caller_saved_regs(env, caller->regs);
5386 /* only increment it after check_reg_arg() finished */
5389 /* and go analyze first insn of the callee */
5390 *insn_idx = target_insn;
5392 if (env->log.level & BPF_LOG_LEVEL) {
5393 verbose(env, "caller:\n");
5394 print_verifier_state(env, caller);
5395 verbose(env, "callee:\n");
5396 print_verifier_state(env, callee);
5401 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5403 struct bpf_verifier_state *state = env->cur_state;
5404 struct bpf_func_state *caller, *callee;
5405 struct bpf_reg_state *r0;
5408 callee = state->frame[state->curframe];
5409 r0 = &callee->regs[BPF_REG_0];
5410 if (r0->type == PTR_TO_STACK) {
5411 /* technically it's ok to return caller's stack pointer
5412 * (or caller's caller's pointer) back to the caller,
5413 * since these pointers are valid. Only current stack
5414 * pointer will be invalid as soon as function exits,
5415 * but let's be conservative
5417 verbose(env, "cannot return stack pointer to the caller\n");
5422 caller = state->frame[state->curframe];
5423 /* return to the caller whatever r0 had in the callee */
5424 caller->regs[BPF_REG_0] = *r0;
5426 /* Transfer references to the caller */
5427 err = transfer_reference_state(caller, callee);
5431 *insn_idx = callee->callsite + 1;
5432 if (env->log.level & BPF_LOG_LEVEL) {
5433 verbose(env, "returning from callee:\n");
5434 print_verifier_state(env, callee);
5435 verbose(env, "to caller at %d:\n", *insn_idx);
5436 print_verifier_state(env, caller);
5438 /* clear everything in the callee */
5439 free_func_state(callee);
5440 state->frame[state->curframe + 1] = NULL;
5444 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5446 struct bpf_call_arg_meta *meta)
5448 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
5450 if (ret_type != RET_INTEGER ||
5451 (func_id != BPF_FUNC_get_stack &&
5452 func_id != BPF_FUNC_probe_read_str &&
5453 func_id != BPF_FUNC_probe_read_kernel_str &&
5454 func_id != BPF_FUNC_probe_read_user_str))
5457 ret_reg->smax_value = meta->msize_max_value;
5458 ret_reg->s32_max_value = meta->msize_max_value;
5459 ret_reg->smin_value = -MAX_ERRNO;
5460 ret_reg->s32_min_value = -MAX_ERRNO;
5461 reg_bounds_sync(ret_reg);
5465 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5466 int func_id, int insn_idx)
5468 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5469 struct bpf_map *map = meta->map_ptr;
5471 if (func_id != BPF_FUNC_tail_call &&
5472 func_id != BPF_FUNC_map_lookup_elem &&
5473 func_id != BPF_FUNC_map_update_elem &&
5474 func_id != BPF_FUNC_map_delete_elem &&
5475 func_id != BPF_FUNC_map_push_elem &&
5476 func_id != BPF_FUNC_map_pop_elem &&
5477 func_id != BPF_FUNC_map_peek_elem)
5481 verbose(env, "kernel subsystem misconfigured verifier\n");
5485 /* In case of read-only, some additional restrictions
5486 * need to be applied in order to prevent altering the
5487 * state of the map from program side.
5489 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5490 (func_id == BPF_FUNC_map_delete_elem ||
5491 func_id == BPF_FUNC_map_update_elem ||
5492 func_id == BPF_FUNC_map_push_elem ||
5493 func_id == BPF_FUNC_map_pop_elem)) {
5494 verbose(env, "write into map forbidden\n");
5498 if (!BPF_MAP_PTR(aux->map_ptr_state))
5499 bpf_map_ptr_store(aux, meta->map_ptr,
5500 !meta->map_ptr->bypass_spec_v1);
5501 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5502 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5503 !meta->map_ptr->bypass_spec_v1);
5508 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5509 int func_id, int insn_idx)
5511 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5512 struct bpf_reg_state *regs = cur_regs(env), *reg;
5513 struct bpf_map *map = meta->map_ptr;
5517 if (func_id != BPF_FUNC_tail_call)
5519 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5520 verbose(env, "kernel subsystem misconfigured verifier\n");
5524 reg = ®s[BPF_REG_3];
5525 val = reg->var_off.value;
5526 max = map->max_entries;
5528 if (!(register_is_const(reg) && val < max)) {
5529 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5533 err = mark_chain_precision(env, BPF_REG_3);
5536 if (bpf_map_key_unseen(aux))
5537 bpf_map_key_store(aux, val);
5538 else if (!bpf_map_key_poisoned(aux) &&
5539 bpf_map_key_immediate(aux) != val)
5540 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5544 static int check_reference_leak(struct bpf_verifier_env *env)
5546 struct bpf_func_state *state = cur_func(env);
5549 for (i = 0; i < state->acquired_refs; i++) {
5550 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5551 state->refs[i].id, state->refs[i].insn_idx);
5553 return state->acquired_refs ? -EINVAL : 0;
5556 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
5558 const struct bpf_func_proto *fn = NULL;
5559 struct bpf_reg_state *regs;
5560 struct bpf_call_arg_meta meta;
5564 /* find function prototype */
5565 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5566 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5571 if (env->ops->get_func_proto)
5572 fn = env->ops->get_func_proto(func_id, env->prog);
5574 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5579 /* eBPF programs must be GPL compatible to use GPL-ed functions */
5580 if (!env->prog->gpl_compatible && fn->gpl_only) {
5581 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5585 if (fn->allowed && !fn->allowed(env->prog)) {
5586 verbose(env, "helper call is not allowed in probe\n");
5590 /* With LD_ABS/IND some JITs save/restore skb from r1. */
5591 changes_data = bpf_helper_changes_pkt_data(fn->func);
5592 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5593 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5594 func_id_name(func_id), func_id);
5598 memset(&meta, 0, sizeof(meta));
5599 meta.pkt_access = fn->pkt_access;
5601 err = check_func_proto(fn, func_id);
5603 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5604 func_id_name(func_id), func_id);
5608 meta.func_id = func_id;
5610 for (i = 0; i < 5; i++) {
5611 err = check_func_arg(env, i, &meta, fn);
5616 err = record_func_map(env, &meta, func_id, insn_idx);
5620 err = record_func_key(env, &meta, func_id, insn_idx);
5624 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5625 * is inferred from register state.
5627 for (i = 0; i < meta.access_size; i++) {
5628 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5629 BPF_WRITE, -1, false);
5634 if (func_id == BPF_FUNC_tail_call) {
5635 err = check_reference_leak(env);
5637 verbose(env, "tail_call would lead to reference leak\n");
5640 } else if (is_release_function(func_id)) {
5641 err = release_reference(env, meta.ref_obj_id);
5643 verbose(env, "func %s#%d reference has not been acquired before\n",
5644 func_id_name(func_id), func_id);
5649 regs = cur_regs(env);
5651 /* check that flags argument in get_local_storage(map, flags) is 0,
5652 * this is required because get_local_storage() can't return an error.
5654 if (func_id == BPF_FUNC_get_local_storage &&
5655 !register_is_null(®s[BPF_REG_2])) {
5656 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5660 /* reset caller saved regs */
5661 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5662 mark_reg_not_init(env, regs, caller_saved[i]);
5663 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5666 /* helper call returns 64-bit value. */
5667 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5669 /* update return register (already marked as written above) */
5670 if (fn->ret_type == RET_INTEGER) {
5671 /* sets type to SCALAR_VALUE */
5672 mark_reg_unknown(env, regs, BPF_REG_0);
5673 } else if (fn->ret_type == RET_VOID) {
5674 regs[BPF_REG_0].type = NOT_INIT;
5675 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5676 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5677 /* There is no offset yet applied, variable or fixed */
5678 mark_reg_known_zero(env, regs, BPF_REG_0);
5679 /* remember map_ptr, so that check_map_access()
5680 * can check 'value_size' boundary of memory access
5681 * to map element returned from bpf_map_lookup_elem()
5683 if (meta.map_ptr == NULL) {
5685 "kernel subsystem misconfigured verifier\n");
5688 regs[BPF_REG_0].map_ptr = meta.map_ptr;
5689 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5690 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
5691 if (map_value_has_spin_lock(meta.map_ptr))
5692 regs[BPF_REG_0].id = ++env->id_gen;
5694 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5696 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5697 mark_reg_known_zero(env, regs, BPF_REG_0);
5698 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
5699 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5700 mark_reg_known_zero(env, regs, BPF_REG_0);
5701 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5702 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5703 mark_reg_known_zero(env, regs, BPF_REG_0);
5704 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5705 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5706 mark_reg_known_zero(env, regs, BPF_REG_0);
5707 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5708 regs[BPF_REG_0].mem_size = meta.mem_size;
5709 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5710 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
5711 const struct btf_type *t;
5713 mark_reg_known_zero(env, regs, BPF_REG_0);
5714 t = btf_type_skip_modifiers(btf_vmlinux, meta.ret_btf_id, NULL);
5715 if (!btf_type_is_struct(t)) {
5717 const struct btf_type *ret;
5720 /* resolve the type size of ksym. */
5721 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
5723 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5724 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5725 tname, PTR_ERR(ret));
5728 regs[BPF_REG_0].type =
5729 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5730 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
5731 regs[BPF_REG_0].mem_size = tsize;
5733 regs[BPF_REG_0].type =
5734 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5735 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
5736 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5738 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL) {
5741 mark_reg_known_zero(env, regs, BPF_REG_0);
5742 regs[BPF_REG_0].type = PTR_TO_BTF_ID_OR_NULL;
5743 ret_btf_id = *fn->ret_btf_id;
5744 if (ret_btf_id == 0) {
5745 verbose(env, "invalid return type %d of func %s#%d\n",
5746 fn->ret_type, func_id_name(func_id), func_id);
5749 regs[BPF_REG_0].btf_id = ret_btf_id;
5751 verbose(env, "unknown return type %d of func %s#%d\n",
5752 fn->ret_type, func_id_name(func_id), func_id);
5756 if (reg_type_may_be_null(regs[BPF_REG_0].type))
5757 regs[BPF_REG_0].id = ++env->id_gen;
5759 if (is_ptr_cast_function(func_id)) {
5760 /* For release_reference() */
5761 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5762 } else if (is_acquire_function(func_id, meta.map_ptr)) {
5763 int id = acquire_reference_state(env, insn_idx);
5767 /* For mark_ptr_or_null_reg() */
5768 regs[BPF_REG_0].id = id;
5769 /* For release_reference() */
5770 regs[BPF_REG_0].ref_obj_id = id;
5773 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5775 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5779 if ((func_id == BPF_FUNC_get_stack ||
5780 func_id == BPF_FUNC_get_task_stack) &&
5781 !env->prog->has_callchain_buf) {
5782 const char *err_str;
5784 #ifdef CONFIG_PERF_EVENTS
5785 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5786 err_str = "cannot get callchain buffer for func %s#%d\n";
5789 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5792 verbose(env, err_str, func_id_name(func_id), func_id);
5796 env->prog->has_callchain_buf = true;
5799 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5800 env->prog->call_get_stack = true;
5803 clear_all_pkt_pointers(env);
5807 static bool signed_add_overflows(s64 a, s64 b)
5809 /* Do the add in u64, where overflow is well-defined */
5810 s64 res = (s64)((u64)a + (u64)b);
5817 static bool signed_add32_overflows(s32 a, s32 b)
5819 /* Do the add in u32, where overflow is well-defined */
5820 s32 res = (s32)((u32)a + (u32)b);
5827 static bool signed_sub_overflows(s64 a, s64 b)
5829 /* Do the sub in u64, where overflow is well-defined */
5830 s64 res = (s64)((u64)a - (u64)b);
5837 static bool signed_sub32_overflows(s32 a, s32 b)
5839 /* Do the sub in u32, where overflow is well-defined */
5840 s32 res = (s32)((u32)a - (u32)b);
5847 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5848 const struct bpf_reg_state *reg,
5849 enum bpf_reg_type type)
5851 bool known = tnum_is_const(reg->var_off);
5852 s64 val = reg->var_off.value;
5853 s64 smin = reg->smin_value;
5855 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5856 verbose(env, "math between %s pointer and %lld is not allowed\n",
5857 reg_type_str[type], val);
5861 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5862 verbose(env, "%s pointer offset %d is not allowed\n",
5863 reg_type_str[type], reg->off);
5867 if (smin == S64_MIN) {
5868 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5869 reg_type_str[type]);
5873 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5874 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5875 smin, reg_type_str[type]);
5882 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5884 return &env->insn_aux_data[env->insn_idx];
5895 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5896 u32 *alu_limit, bool mask_to_left)
5898 u32 max = 0, ptr_limit = 0;
5900 switch (ptr_reg->type) {
5902 /* Offset 0 is out-of-bounds, but acceptable start for the
5903 * left direction, see BPF_REG_FP. Also, unknown scalar
5904 * offset where we would need to deal with min/max bounds is
5905 * currently prohibited for unprivileged.
5907 max = MAX_BPF_STACK + mask_to_left;
5908 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
5910 case PTR_TO_MAP_VALUE:
5911 max = ptr_reg->map_ptr->value_size;
5912 ptr_limit = (mask_to_left ?
5913 ptr_reg->smin_value :
5914 ptr_reg->umax_value) + ptr_reg->off;
5920 if (ptr_limit >= max)
5921 return REASON_LIMIT;
5922 *alu_limit = ptr_limit;
5926 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5927 const struct bpf_insn *insn)
5929 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
5932 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5933 u32 alu_state, u32 alu_limit)
5935 /* If we arrived here from different branches with different
5936 * state or limits to sanitize, then this won't work.
5938 if (aux->alu_state &&
5939 (aux->alu_state != alu_state ||
5940 aux->alu_limit != alu_limit))
5941 return REASON_PATHS;
5943 /* Corresponding fixup done in fixup_bpf_calls(). */
5944 aux->alu_state = alu_state;
5945 aux->alu_limit = alu_limit;
5949 static int sanitize_val_alu(struct bpf_verifier_env *env,
5950 struct bpf_insn *insn)
5952 struct bpf_insn_aux_data *aux = cur_aux(env);
5954 if (can_skip_alu_sanitation(env, insn))
5957 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5960 static bool sanitize_needed(u8 opcode)
5962 return opcode == BPF_ADD || opcode == BPF_SUB;
5965 struct bpf_sanitize_info {
5966 struct bpf_insn_aux_data aux;
5970 static struct bpf_verifier_state *
5971 sanitize_speculative_path(struct bpf_verifier_env *env,
5972 const struct bpf_insn *insn,
5973 u32 next_idx, u32 curr_idx)
5975 struct bpf_verifier_state *branch;
5976 struct bpf_reg_state *regs;
5978 branch = push_stack(env, next_idx, curr_idx, true);
5979 if (branch && insn) {
5980 regs = branch->frame[branch->curframe]->regs;
5981 if (BPF_SRC(insn->code) == BPF_K) {
5982 mark_reg_unknown(env, regs, insn->dst_reg);
5983 } else if (BPF_SRC(insn->code) == BPF_X) {
5984 mark_reg_unknown(env, regs, insn->dst_reg);
5985 mark_reg_unknown(env, regs, insn->src_reg);
5991 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5992 struct bpf_insn *insn,
5993 const struct bpf_reg_state *ptr_reg,
5994 const struct bpf_reg_state *off_reg,
5995 struct bpf_reg_state *dst_reg,
5996 struct bpf_sanitize_info *info,
5997 const bool commit_window)
5999 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6000 struct bpf_verifier_state *vstate = env->cur_state;
6001 bool off_is_imm = tnum_is_const(off_reg->var_off);
6002 bool off_is_neg = off_reg->smin_value < 0;
6003 bool ptr_is_dst_reg = ptr_reg == dst_reg;
6004 u8 opcode = BPF_OP(insn->code);
6005 u32 alu_state, alu_limit;
6006 struct bpf_reg_state tmp;
6010 if (can_skip_alu_sanitation(env, insn))
6013 /* We already marked aux for masking from non-speculative
6014 * paths, thus we got here in the first place. We only care
6015 * to explore bad access from here.
6017 if (vstate->speculative)
6020 if (!commit_window) {
6021 if (!tnum_is_const(off_reg->var_off) &&
6022 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6023 return REASON_BOUNDS;
6025 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
6026 (opcode == BPF_SUB && !off_is_neg);
6029 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6033 if (commit_window) {
6034 /* In commit phase we narrow the masking window based on
6035 * the observed pointer move after the simulated operation.
6037 alu_state = info->aux.alu_state;
6038 alu_limit = abs(info->aux.alu_limit - alu_limit);
6040 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6041 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6042 alu_state |= ptr_is_dst_reg ?
6043 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6045 /* Limit pruning on unknown scalars to enable deep search for
6046 * potential masking differences from other program paths.
6049 env->explore_alu_limits = true;
6052 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6056 /* If we're in commit phase, we're done here given we already
6057 * pushed the truncated dst_reg into the speculative verification
6060 * Also, when register is a known constant, we rewrite register-based
6061 * operation to immediate-based, and thus do not need masking (and as
6062 * a consequence, do not need to simulate the zero-truncation either).
6064 if (commit_window || off_is_imm)
6067 /* Simulate and find potential out-of-bounds access under
6068 * speculative execution from truncation as a result of
6069 * masking when off was not within expected range. If off
6070 * sits in dst, then we temporarily need to move ptr there
6071 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6072 * for cases where we use K-based arithmetic in one direction
6073 * and truncated reg-based in the other in order to explore
6076 if (!ptr_is_dst_reg) {
6078 copy_register_state(dst_reg, ptr_reg);
6080 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6082 if (!ptr_is_dst_reg && ret)
6084 return !ret ? REASON_STACK : 0;
6087 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6089 struct bpf_verifier_state *vstate = env->cur_state;
6091 /* If we simulate paths under speculation, we don't update the
6092 * insn as 'seen' such that when we verify unreachable paths in
6093 * the non-speculative domain, sanitize_dead_code() can still
6094 * rewrite/sanitize them.
6096 if (!vstate->speculative)
6097 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6100 static int sanitize_err(struct bpf_verifier_env *env,
6101 const struct bpf_insn *insn, int reason,
6102 const struct bpf_reg_state *off_reg,
6103 const struct bpf_reg_state *dst_reg)
6105 static const char *err = "pointer arithmetic with it prohibited for !root";
6106 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6107 u32 dst = insn->dst_reg, src = insn->src_reg;
6111 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6112 off_reg == dst_reg ? dst : src, err);
6115 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6116 off_reg == dst_reg ? src : dst, err);
6119 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6123 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6127 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6131 verbose(env, "verifier internal error: unknown reason (%d)\n",
6139 /* check that stack access falls within stack limits and that 'reg' doesn't
6140 * have a variable offset.
6142 * Variable offset is prohibited for unprivileged mode for simplicity since it
6143 * requires corresponding support in Spectre masking for stack ALU. See also
6144 * retrieve_ptr_limit().
6147 * 'off' includes 'reg->off'.
6149 static int check_stack_access_for_ptr_arithmetic(
6150 struct bpf_verifier_env *env,
6152 const struct bpf_reg_state *reg,
6155 if (!tnum_is_const(reg->var_off)) {
6158 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6159 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6160 regno, tn_buf, off);
6164 if (off >= 0 || off < -MAX_BPF_STACK) {
6165 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6166 "prohibited for !root; off=%d\n", regno, off);
6173 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6174 const struct bpf_insn *insn,
6175 const struct bpf_reg_state *dst_reg)
6177 u32 dst = insn->dst_reg;
6179 /* For unprivileged we require that resulting offset must be in bounds
6180 * in order to be able to sanitize access later on.
6182 if (env->bypass_spec_v1)
6185 switch (dst_reg->type) {
6187 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6188 dst_reg->off + dst_reg->var_off.value))
6191 case PTR_TO_MAP_VALUE:
6192 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6193 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6194 "prohibited for !root\n", dst);
6205 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6206 * Caller should also handle BPF_MOV case separately.
6207 * If we return -EACCES, caller may want to try again treating pointer as a
6208 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6210 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6211 struct bpf_insn *insn,
6212 const struct bpf_reg_state *ptr_reg,
6213 const struct bpf_reg_state *off_reg)
6215 struct bpf_verifier_state *vstate = env->cur_state;
6216 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6217 struct bpf_reg_state *regs = state->regs, *dst_reg;
6218 bool known = tnum_is_const(off_reg->var_off);
6219 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6220 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6221 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6222 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6223 struct bpf_sanitize_info info = {};
6224 u8 opcode = BPF_OP(insn->code);
6225 u32 dst = insn->dst_reg;
6228 dst_reg = ®s[dst];
6230 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6231 smin_val > smax_val || umin_val > umax_val) {
6232 /* Taint dst register if offset had invalid bounds derived from
6233 * e.g. dead branches.
6235 __mark_reg_unknown(env, dst_reg);
6239 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6240 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6241 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6242 __mark_reg_unknown(env, dst_reg);
6247 "R%d 32-bit pointer arithmetic prohibited\n",
6252 switch (ptr_reg->type) {
6253 case PTR_TO_MAP_VALUE_OR_NULL:
6254 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6255 dst, reg_type_str[ptr_reg->type]);
6257 case CONST_PTR_TO_MAP:
6258 /* smin_val represents the known value */
6259 if (known && smin_val == 0 && opcode == BPF_ADD)
6262 case PTR_TO_PACKET_END:
6264 case PTR_TO_SOCK_COMMON:
6265 case PTR_TO_TCP_SOCK:
6266 case PTR_TO_XDP_SOCK:
6268 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6269 dst, reg_type_str[ptr_reg->type]);
6272 if (reg_type_may_be_null(ptr_reg->type))
6277 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6278 * The id may be overwritten later if we create a new variable offset.
6280 dst_reg->type = ptr_reg->type;
6281 dst_reg->id = ptr_reg->id;
6283 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6284 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6287 /* pointer types do not carry 32-bit bounds at the moment. */
6288 __mark_reg32_unbounded(dst_reg);
6290 if (sanitize_needed(opcode)) {
6291 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6294 return sanitize_err(env, insn, ret, off_reg, dst_reg);
6299 /* We can take a fixed offset as long as it doesn't overflow
6300 * the s32 'off' field
6302 if (known && (ptr_reg->off + smin_val ==
6303 (s64)(s32)(ptr_reg->off + smin_val))) {
6304 /* pointer += K. Accumulate it into fixed offset */
6305 dst_reg->smin_value = smin_ptr;
6306 dst_reg->smax_value = smax_ptr;
6307 dst_reg->umin_value = umin_ptr;
6308 dst_reg->umax_value = umax_ptr;
6309 dst_reg->var_off = ptr_reg->var_off;
6310 dst_reg->off = ptr_reg->off + smin_val;
6311 dst_reg->raw = ptr_reg->raw;
6314 /* A new variable offset is created. Note that off_reg->off
6315 * == 0, since it's a scalar.
6316 * dst_reg gets the pointer type and since some positive
6317 * integer value was added to the pointer, give it a new 'id'
6318 * if it's a PTR_TO_PACKET.
6319 * this creates a new 'base' pointer, off_reg (variable) gets
6320 * added into the variable offset, and we copy the fixed offset
6323 if (signed_add_overflows(smin_ptr, smin_val) ||
6324 signed_add_overflows(smax_ptr, smax_val)) {
6325 dst_reg->smin_value = S64_MIN;
6326 dst_reg->smax_value = S64_MAX;
6328 dst_reg->smin_value = smin_ptr + smin_val;
6329 dst_reg->smax_value = smax_ptr + smax_val;
6331 if (umin_ptr + umin_val < umin_ptr ||
6332 umax_ptr + umax_val < umax_ptr) {
6333 dst_reg->umin_value = 0;
6334 dst_reg->umax_value = U64_MAX;
6336 dst_reg->umin_value = umin_ptr + umin_val;
6337 dst_reg->umax_value = umax_ptr + umax_val;
6339 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6340 dst_reg->off = ptr_reg->off;
6341 dst_reg->raw = ptr_reg->raw;
6342 if (reg_is_pkt_pointer(ptr_reg)) {
6343 dst_reg->id = ++env->id_gen;
6344 /* something was added to pkt_ptr, set range to zero */
6349 if (dst_reg == off_reg) {
6350 /* scalar -= pointer. Creates an unknown scalar */
6351 verbose(env, "R%d tried to subtract pointer from scalar\n",
6355 /* We don't allow subtraction from FP, because (according to
6356 * test_verifier.c test "invalid fp arithmetic", JITs might not
6357 * be able to deal with it.
6359 if (ptr_reg->type == PTR_TO_STACK) {
6360 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6364 if (known && (ptr_reg->off - smin_val ==
6365 (s64)(s32)(ptr_reg->off - smin_val))) {
6366 /* pointer -= K. Subtract it from fixed offset */
6367 dst_reg->smin_value = smin_ptr;
6368 dst_reg->smax_value = smax_ptr;
6369 dst_reg->umin_value = umin_ptr;
6370 dst_reg->umax_value = umax_ptr;
6371 dst_reg->var_off = ptr_reg->var_off;
6372 dst_reg->id = ptr_reg->id;
6373 dst_reg->off = ptr_reg->off - smin_val;
6374 dst_reg->raw = ptr_reg->raw;
6377 /* A new variable offset is created. If the subtrahend is known
6378 * nonnegative, then any reg->range we had before is still good.
6380 if (signed_sub_overflows(smin_ptr, smax_val) ||
6381 signed_sub_overflows(smax_ptr, smin_val)) {
6382 /* Overflow possible, we know nothing */
6383 dst_reg->smin_value = S64_MIN;
6384 dst_reg->smax_value = S64_MAX;
6386 dst_reg->smin_value = smin_ptr - smax_val;
6387 dst_reg->smax_value = smax_ptr - smin_val;
6389 if (umin_ptr < umax_val) {
6390 /* Overflow possible, we know nothing */
6391 dst_reg->umin_value = 0;
6392 dst_reg->umax_value = U64_MAX;
6394 /* Cannot overflow (as long as bounds are consistent) */
6395 dst_reg->umin_value = umin_ptr - umax_val;
6396 dst_reg->umax_value = umax_ptr - umin_val;
6398 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6399 dst_reg->off = ptr_reg->off;
6400 dst_reg->raw = ptr_reg->raw;
6401 if (reg_is_pkt_pointer(ptr_reg)) {
6402 dst_reg->id = ++env->id_gen;
6403 /* something was added to pkt_ptr, set range to zero */
6411 /* bitwise ops on pointers are troublesome, prohibit. */
6412 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6413 dst, bpf_alu_string[opcode >> 4]);
6416 /* other operators (e.g. MUL,LSH) produce non-pointer results */
6417 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6418 dst, bpf_alu_string[opcode >> 4]);
6422 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6424 reg_bounds_sync(dst_reg);
6425 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6427 if (sanitize_needed(opcode)) {
6428 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6431 return sanitize_err(env, insn, ret, off_reg, dst_reg);
6437 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6438 struct bpf_reg_state *src_reg)
6440 s32 smin_val = src_reg->s32_min_value;
6441 s32 smax_val = src_reg->s32_max_value;
6442 u32 umin_val = src_reg->u32_min_value;
6443 u32 umax_val = src_reg->u32_max_value;
6445 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6446 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6447 dst_reg->s32_min_value = S32_MIN;
6448 dst_reg->s32_max_value = S32_MAX;
6450 dst_reg->s32_min_value += smin_val;
6451 dst_reg->s32_max_value += smax_val;
6453 if (dst_reg->u32_min_value + umin_val < umin_val ||
6454 dst_reg->u32_max_value + umax_val < umax_val) {
6455 dst_reg->u32_min_value = 0;
6456 dst_reg->u32_max_value = U32_MAX;
6458 dst_reg->u32_min_value += umin_val;
6459 dst_reg->u32_max_value += umax_val;
6463 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6464 struct bpf_reg_state *src_reg)
6466 s64 smin_val = src_reg->smin_value;
6467 s64 smax_val = src_reg->smax_value;
6468 u64 umin_val = src_reg->umin_value;
6469 u64 umax_val = src_reg->umax_value;
6471 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6472 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6473 dst_reg->smin_value = S64_MIN;
6474 dst_reg->smax_value = S64_MAX;
6476 dst_reg->smin_value += smin_val;
6477 dst_reg->smax_value += smax_val;
6479 if (dst_reg->umin_value + umin_val < umin_val ||
6480 dst_reg->umax_value + umax_val < umax_val) {
6481 dst_reg->umin_value = 0;
6482 dst_reg->umax_value = U64_MAX;
6484 dst_reg->umin_value += umin_val;
6485 dst_reg->umax_value += umax_val;
6489 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6490 struct bpf_reg_state *src_reg)
6492 s32 smin_val = src_reg->s32_min_value;
6493 s32 smax_val = src_reg->s32_max_value;
6494 u32 umin_val = src_reg->u32_min_value;
6495 u32 umax_val = src_reg->u32_max_value;
6497 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6498 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6499 /* Overflow possible, we know nothing */
6500 dst_reg->s32_min_value = S32_MIN;
6501 dst_reg->s32_max_value = S32_MAX;
6503 dst_reg->s32_min_value -= smax_val;
6504 dst_reg->s32_max_value -= smin_val;
6506 if (dst_reg->u32_min_value < umax_val) {
6507 /* Overflow possible, we know nothing */
6508 dst_reg->u32_min_value = 0;
6509 dst_reg->u32_max_value = U32_MAX;
6511 /* Cannot overflow (as long as bounds are consistent) */
6512 dst_reg->u32_min_value -= umax_val;
6513 dst_reg->u32_max_value -= umin_val;
6517 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6518 struct bpf_reg_state *src_reg)
6520 s64 smin_val = src_reg->smin_value;
6521 s64 smax_val = src_reg->smax_value;
6522 u64 umin_val = src_reg->umin_value;
6523 u64 umax_val = src_reg->umax_value;
6525 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6526 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6527 /* Overflow possible, we know nothing */
6528 dst_reg->smin_value = S64_MIN;
6529 dst_reg->smax_value = S64_MAX;
6531 dst_reg->smin_value -= smax_val;
6532 dst_reg->smax_value -= smin_val;
6534 if (dst_reg->umin_value < umax_val) {
6535 /* Overflow possible, we know nothing */
6536 dst_reg->umin_value = 0;
6537 dst_reg->umax_value = U64_MAX;
6539 /* Cannot overflow (as long as bounds are consistent) */
6540 dst_reg->umin_value -= umax_val;
6541 dst_reg->umax_value -= umin_val;
6545 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6546 struct bpf_reg_state *src_reg)
6548 s32 smin_val = src_reg->s32_min_value;
6549 u32 umin_val = src_reg->u32_min_value;
6550 u32 umax_val = src_reg->u32_max_value;
6552 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6553 /* Ain't nobody got time to multiply that sign */
6554 __mark_reg32_unbounded(dst_reg);
6557 /* Both values are positive, so we can work with unsigned and
6558 * copy the result to signed (unless it exceeds S32_MAX).
6560 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6561 /* Potential overflow, we know nothing */
6562 __mark_reg32_unbounded(dst_reg);
6565 dst_reg->u32_min_value *= umin_val;
6566 dst_reg->u32_max_value *= umax_val;
6567 if (dst_reg->u32_max_value > S32_MAX) {
6568 /* Overflow possible, we know nothing */
6569 dst_reg->s32_min_value = S32_MIN;
6570 dst_reg->s32_max_value = S32_MAX;
6572 dst_reg->s32_min_value = dst_reg->u32_min_value;
6573 dst_reg->s32_max_value = dst_reg->u32_max_value;
6577 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6578 struct bpf_reg_state *src_reg)
6580 s64 smin_val = src_reg->smin_value;
6581 u64 umin_val = src_reg->umin_value;
6582 u64 umax_val = src_reg->umax_value;
6584 if (smin_val < 0 || dst_reg->smin_value < 0) {
6585 /* Ain't nobody got time to multiply that sign */
6586 __mark_reg64_unbounded(dst_reg);
6589 /* Both values are positive, so we can work with unsigned and
6590 * copy the result to signed (unless it exceeds S64_MAX).
6592 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6593 /* Potential overflow, we know nothing */
6594 __mark_reg64_unbounded(dst_reg);
6597 dst_reg->umin_value *= umin_val;
6598 dst_reg->umax_value *= umax_val;
6599 if (dst_reg->umax_value > S64_MAX) {
6600 /* Overflow possible, we know nothing */
6601 dst_reg->smin_value = S64_MIN;
6602 dst_reg->smax_value = S64_MAX;
6604 dst_reg->smin_value = dst_reg->umin_value;
6605 dst_reg->smax_value = dst_reg->umax_value;
6609 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6610 struct bpf_reg_state *src_reg)
6612 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6613 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6614 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6615 s32 smin_val = src_reg->s32_min_value;
6616 u32 umax_val = src_reg->u32_max_value;
6618 if (src_known && dst_known) {
6619 __mark_reg32_known(dst_reg, var32_off.value);
6623 /* We get our minimum from the var_off, since that's inherently
6624 * bitwise. Our maximum is the minimum of the operands' maxima.
6626 dst_reg->u32_min_value = var32_off.value;
6627 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6628 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6629 /* Lose signed bounds when ANDing negative numbers,
6630 * ain't nobody got time for that.
6632 dst_reg->s32_min_value = S32_MIN;
6633 dst_reg->s32_max_value = S32_MAX;
6635 /* ANDing two positives gives a positive, so safe to
6636 * cast result into s64.
6638 dst_reg->s32_min_value = dst_reg->u32_min_value;
6639 dst_reg->s32_max_value = dst_reg->u32_max_value;
6643 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6644 struct bpf_reg_state *src_reg)
6646 bool src_known = tnum_is_const(src_reg->var_off);
6647 bool dst_known = tnum_is_const(dst_reg->var_off);
6648 s64 smin_val = src_reg->smin_value;
6649 u64 umax_val = src_reg->umax_value;
6651 if (src_known && dst_known) {
6652 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6656 /* We get our minimum from the var_off, since that's inherently
6657 * bitwise. Our maximum is the minimum of the operands' maxima.
6659 dst_reg->umin_value = dst_reg->var_off.value;
6660 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6661 if (dst_reg->smin_value < 0 || smin_val < 0) {
6662 /* Lose signed bounds when ANDing negative numbers,
6663 * ain't nobody got time for that.
6665 dst_reg->smin_value = S64_MIN;
6666 dst_reg->smax_value = S64_MAX;
6668 /* ANDing two positives gives a positive, so safe to
6669 * cast result into s64.
6671 dst_reg->smin_value = dst_reg->umin_value;
6672 dst_reg->smax_value = dst_reg->umax_value;
6674 /* We may learn something more from the var_off */
6675 __update_reg_bounds(dst_reg);
6678 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6679 struct bpf_reg_state *src_reg)
6681 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6682 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6683 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6684 s32 smin_val = src_reg->s32_min_value;
6685 u32 umin_val = src_reg->u32_min_value;
6687 if (src_known && dst_known) {
6688 __mark_reg32_known(dst_reg, var32_off.value);
6692 /* We get our maximum from the var_off, and our minimum is the
6693 * maximum of the operands' minima
6695 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6696 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6697 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6698 /* Lose signed bounds when ORing negative numbers,
6699 * ain't nobody got time for that.
6701 dst_reg->s32_min_value = S32_MIN;
6702 dst_reg->s32_max_value = S32_MAX;
6704 /* ORing two positives gives a positive, so safe to
6705 * cast result into s64.
6707 dst_reg->s32_min_value = dst_reg->u32_min_value;
6708 dst_reg->s32_max_value = dst_reg->u32_max_value;
6712 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6713 struct bpf_reg_state *src_reg)
6715 bool src_known = tnum_is_const(src_reg->var_off);
6716 bool dst_known = tnum_is_const(dst_reg->var_off);
6717 s64 smin_val = src_reg->smin_value;
6718 u64 umin_val = src_reg->umin_value;
6720 if (src_known && dst_known) {
6721 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6725 /* We get our maximum from the var_off, and our minimum is the
6726 * maximum of the operands' minima
6728 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6729 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6730 if (dst_reg->smin_value < 0 || smin_val < 0) {
6731 /* Lose signed bounds when ORing negative numbers,
6732 * ain't nobody got time for that.
6734 dst_reg->smin_value = S64_MIN;
6735 dst_reg->smax_value = S64_MAX;
6737 /* ORing two positives gives a positive, so safe to
6738 * cast result into s64.
6740 dst_reg->smin_value = dst_reg->umin_value;
6741 dst_reg->smax_value = dst_reg->umax_value;
6743 /* We may learn something more from the var_off */
6744 __update_reg_bounds(dst_reg);
6747 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6748 struct bpf_reg_state *src_reg)
6750 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6751 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6752 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6753 s32 smin_val = src_reg->s32_min_value;
6755 if (src_known && dst_known) {
6756 __mark_reg32_known(dst_reg, var32_off.value);
6760 /* We get both minimum and maximum from the var32_off. */
6761 dst_reg->u32_min_value = var32_off.value;
6762 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6764 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6765 /* XORing two positive sign numbers gives a positive,
6766 * so safe to cast u32 result into s32.
6768 dst_reg->s32_min_value = dst_reg->u32_min_value;
6769 dst_reg->s32_max_value = dst_reg->u32_max_value;
6771 dst_reg->s32_min_value = S32_MIN;
6772 dst_reg->s32_max_value = S32_MAX;
6776 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6777 struct bpf_reg_state *src_reg)
6779 bool src_known = tnum_is_const(src_reg->var_off);
6780 bool dst_known = tnum_is_const(dst_reg->var_off);
6781 s64 smin_val = src_reg->smin_value;
6783 if (src_known && dst_known) {
6784 /* dst_reg->var_off.value has been updated earlier */
6785 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6789 /* We get both minimum and maximum from the var_off. */
6790 dst_reg->umin_value = dst_reg->var_off.value;
6791 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6793 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6794 /* XORing two positive sign numbers gives a positive,
6795 * so safe to cast u64 result into s64.
6797 dst_reg->smin_value = dst_reg->umin_value;
6798 dst_reg->smax_value = dst_reg->umax_value;
6800 dst_reg->smin_value = S64_MIN;
6801 dst_reg->smax_value = S64_MAX;
6804 __update_reg_bounds(dst_reg);
6807 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6808 u64 umin_val, u64 umax_val)
6810 /* We lose all sign bit information (except what we can pick
6813 dst_reg->s32_min_value = S32_MIN;
6814 dst_reg->s32_max_value = S32_MAX;
6815 /* If we might shift our top bit out, then we know nothing */
6816 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6817 dst_reg->u32_min_value = 0;
6818 dst_reg->u32_max_value = U32_MAX;
6820 dst_reg->u32_min_value <<= umin_val;
6821 dst_reg->u32_max_value <<= umax_val;
6825 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6826 struct bpf_reg_state *src_reg)
6828 u32 umax_val = src_reg->u32_max_value;
6829 u32 umin_val = src_reg->u32_min_value;
6830 /* u32 alu operation will zext upper bits */
6831 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6833 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6834 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6835 /* Not required but being careful mark reg64 bounds as unknown so
6836 * that we are forced to pick them up from tnum and zext later and
6837 * if some path skips this step we are still safe.
6839 __mark_reg64_unbounded(dst_reg);
6840 __update_reg32_bounds(dst_reg);
6843 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6844 u64 umin_val, u64 umax_val)
6846 /* Special case <<32 because it is a common compiler pattern to sign
6847 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6848 * positive we know this shift will also be positive so we can track
6849 * bounds correctly. Otherwise we lose all sign bit information except
6850 * what we can pick up from var_off. Perhaps we can generalize this
6851 * later to shifts of any length.
6853 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6854 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6856 dst_reg->smax_value = S64_MAX;
6858 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6859 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6861 dst_reg->smin_value = S64_MIN;
6863 /* If we might shift our top bit out, then we know nothing */
6864 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6865 dst_reg->umin_value = 0;
6866 dst_reg->umax_value = U64_MAX;
6868 dst_reg->umin_value <<= umin_val;
6869 dst_reg->umax_value <<= umax_val;
6873 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6874 struct bpf_reg_state *src_reg)
6876 u64 umax_val = src_reg->umax_value;
6877 u64 umin_val = src_reg->umin_value;
6879 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6880 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6881 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6883 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6884 /* We may learn something more from the var_off */
6885 __update_reg_bounds(dst_reg);
6888 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6889 struct bpf_reg_state *src_reg)
6891 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6892 u32 umax_val = src_reg->u32_max_value;
6893 u32 umin_val = src_reg->u32_min_value;
6895 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6896 * be negative, then either:
6897 * 1) src_reg might be zero, so the sign bit of the result is
6898 * unknown, so we lose our signed bounds
6899 * 2) it's known negative, thus the unsigned bounds capture the
6901 * 3) the signed bounds cross zero, so they tell us nothing
6903 * If the value in dst_reg is known nonnegative, then again the
6904 * unsigned bounts capture the signed bounds.
6905 * Thus, in all cases it suffices to blow away our signed bounds
6906 * and rely on inferring new ones from the unsigned bounds and
6907 * var_off of the result.
6909 dst_reg->s32_min_value = S32_MIN;
6910 dst_reg->s32_max_value = S32_MAX;
6912 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6913 dst_reg->u32_min_value >>= umax_val;
6914 dst_reg->u32_max_value >>= umin_val;
6916 __mark_reg64_unbounded(dst_reg);
6917 __update_reg32_bounds(dst_reg);
6920 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6921 struct bpf_reg_state *src_reg)
6923 u64 umax_val = src_reg->umax_value;
6924 u64 umin_val = src_reg->umin_value;
6926 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6927 * be negative, then either:
6928 * 1) src_reg might be zero, so the sign bit of the result is
6929 * unknown, so we lose our signed bounds
6930 * 2) it's known negative, thus the unsigned bounds capture the
6932 * 3) the signed bounds cross zero, so they tell us nothing
6934 * If the value in dst_reg is known nonnegative, then again the
6935 * unsigned bounts capture the signed bounds.
6936 * Thus, in all cases it suffices to blow away our signed bounds
6937 * and rely on inferring new ones from the unsigned bounds and
6938 * var_off of the result.
6940 dst_reg->smin_value = S64_MIN;
6941 dst_reg->smax_value = S64_MAX;
6942 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6943 dst_reg->umin_value >>= umax_val;
6944 dst_reg->umax_value >>= umin_val;
6946 /* Its not easy to operate on alu32 bounds here because it depends
6947 * on bits being shifted in. Take easy way out and mark unbounded
6948 * so we can recalculate later from tnum.
6950 __mark_reg32_unbounded(dst_reg);
6951 __update_reg_bounds(dst_reg);
6954 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6955 struct bpf_reg_state *src_reg)
6957 u64 umin_val = src_reg->u32_min_value;
6959 /* Upon reaching here, src_known is true and
6960 * umax_val is equal to umin_val.
6962 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6963 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
6965 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6967 /* blow away the dst_reg umin_value/umax_value and rely on
6968 * dst_reg var_off to refine the result.
6970 dst_reg->u32_min_value = 0;
6971 dst_reg->u32_max_value = U32_MAX;
6973 __mark_reg64_unbounded(dst_reg);
6974 __update_reg32_bounds(dst_reg);
6977 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6978 struct bpf_reg_state *src_reg)
6980 u64 umin_val = src_reg->umin_value;
6982 /* Upon reaching here, src_known is true and umax_val is equal
6985 dst_reg->smin_value >>= umin_val;
6986 dst_reg->smax_value >>= umin_val;
6988 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
6990 /* blow away the dst_reg umin_value/umax_value and rely on
6991 * dst_reg var_off to refine the result.
6993 dst_reg->umin_value = 0;
6994 dst_reg->umax_value = U64_MAX;
6996 /* Its not easy to operate on alu32 bounds here because it depends
6997 * on bits being shifted in from upper 32-bits. Take easy way out
6998 * and mark unbounded so we can recalculate later from tnum.
7000 __mark_reg32_unbounded(dst_reg);
7001 __update_reg_bounds(dst_reg);
7004 /* WARNING: This function does calculations on 64-bit values, but the actual
7005 * execution may occur on 32-bit values. Therefore, things like bitshifts
7006 * need extra checks in the 32-bit case.
7008 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7009 struct bpf_insn *insn,
7010 struct bpf_reg_state *dst_reg,
7011 struct bpf_reg_state src_reg)
7013 struct bpf_reg_state *regs = cur_regs(env);
7014 u8 opcode = BPF_OP(insn->code);
7016 s64 smin_val, smax_val;
7017 u64 umin_val, umax_val;
7018 s32 s32_min_val, s32_max_val;
7019 u32 u32_min_val, u32_max_val;
7020 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7021 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7024 smin_val = src_reg.smin_value;
7025 smax_val = src_reg.smax_value;
7026 umin_val = src_reg.umin_value;
7027 umax_val = src_reg.umax_value;
7029 s32_min_val = src_reg.s32_min_value;
7030 s32_max_val = src_reg.s32_max_value;
7031 u32_min_val = src_reg.u32_min_value;
7032 u32_max_val = src_reg.u32_max_value;
7035 src_known = tnum_subreg_is_const(src_reg.var_off);
7037 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7038 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7039 /* Taint dst register if offset had invalid bounds
7040 * derived from e.g. dead branches.
7042 __mark_reg_unknown(env, dst_reg);
7046 src_known = tnum_is_const(src_reg.var_off);
7048 (smin_val != smax_val || umin_val != umax_val)) ||
7049 smin_val > smax_val || umin_val > umax_val) {
7050 /* Taint dst register if offset had invalid bounds
7051 * derived from e.g. dead branches.
7053 __mark_reg_unknown(env, dst_reg);
7059 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7060 __mark_reg_unknown(env, dst_reg);
7064 if (sanitize_needed(opcode)) {
7065 ret = sanitize_val_alu(env, insn);
7067 return sanitize_err(env, insn, ret, NULL, NULL);
7070 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7071 * There are two classes of instructions: The first class we track both
7072 * alu32 and alu64 sign/unsigned bounds independently this provides the
7073 * greatest amount of precision when alu operations are mixed with jmp32
7074 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7075 * and BPF_OR. This is possible because these ops have fairly easy to
7076 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7077 * See alu32 verifier tests for examples. The second class of
7078 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7079 * with regards to tracking sign/unsigned bounds because the bits may
7080 * cross subreg boundaries in the alu64 case. When this happens we mark
7081 * the reg unbounded in the subreg bound space and use the resulting
7082 * tnum to calculate an approximation of the sign/unsigned bounds.
7086 scalar32_min_max_add(dst_reg, &src_reg);
7087 scalar_min_max_add(dst_reg, &src_reg);
7088 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7091 scalar32_min_max_sub(dst_reg, &src_reg);
7092 scalar_min_max_sub(dst_reg, &src_reg);
7093 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7096 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7097 scalar32_min_max_mul(dst_reg, &src_reg);
7098 scalar_min_max_mul(dst_reg, &src_reg);
7101 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7102 scalar32_min_max_and(dst_reg, &src_reg);
7103 scalar_min_max_and(dst_reg, &src_reg);
7106 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7107 scalar32_min_max_or(dst_reg, &src_reg);
7108 scalar_min_max_or(dst_reg, &src_reg);
7111 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7112 scalar32_min_max_xor(dst_reg, &src_reg);
7113 scalar_min_max_xor(dst_reg, &src_reg);
7116 if (umax_val >= insn_bitness) {
7117 /* Shifts greater than 31 or 63 are undefined.
7118 * This includes shifts by a negative number.
7120 mark_reg_unknown(env, regs, insn->dst_reg);
7124 scalar32_min_max_lsh(dst_reg, &src_reg);
7126 scalar_min_max_lsh(dst_reg, &src_reg);
7129 if (umax_val >= insn_bitness) {
7130 /* Shifts greater than 31 or 63 are undefined.
7131 * This includes shifts by a negative number.
7133 mark_reg_unknown(env, regs, insn->dst_reg);
7137 scalar32_min_max_rsh(dst_reg, &src_reg);
7139 scalar_min_max_rsh(dst_reg, &src_reg);
7142 if (umax_val >= insn_bitness) {
7143 /* Shifts greater than 31 or 63 are undefined.
7144 * This includes shifts by a negative number.
7146 mark_reg_unknown(env, regs, insn->dst_reg);
7150 scalar32_min_max_arsh(dst_reg, &src_reg);
7152 scalar_min_max_arsh(dst_reg, &src_reg);
7155 mark_reg_unknown(env, regs, insn->dst_reg);
7159 /* ALU32 ops are zero extended into 64bit register */
7161 zext_32_to_64(dst_reg);
7162 reg_bounds_sync(dst_reg);
7166 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7169 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7170 struct bpf_insn *insn)
7172 struct bpf_verifier_state *vstate = env->cur_state;
7173 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7174 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7175 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7176 u8 opcode = BPF_OP(insn->code);
7179 dst_reg = ®s[insn->dst_reg];
7181 if (dst_reg->type != SCALAR_VALUE)
7184 /* Make sure ID is cleared otherwise dst_reg min/max could be
7185 * incorrectly propagated into other registers by find_equal_scalars()
7188 if (BPF_SRC(insn->code) == BPF_X) {
7189 src_reg = ®s[insn->src_reg];
7190 if (src_reg->type != SCALAR_VALUE) {
7191 if (dst_reg->type != SCALAR_VALUE) {
7192 /* Combining two pointers by any ALU op yields
7193 * an arbitrary scalar. Disallow all math except
7194 * pointer subtraction
7196 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7197 mark_reg_unknown(env, regs, insn->dst_reg);
7200 verbose(env, "R%d pointer %s pointer prohibited\n",
7202 bpf_alu_string[opcode >> 4]);
7205 /* scalar += pointer
7206 * This is legal, but we have to reverse our
7207 * src/dest handling in computing the range
7209 err = mark_chain_precision(env, insn->dst_reg);
7212 return adjust_ptr_min_max_vals(env, insn,
7215 } else if (ptr_reg) {
7216 /* pointer += scalar */
7217 err = mark_chain_precision(env, insn->src_reg);
7220 return adjust_ptr_min_max_vals(env, insn,
7222 } else if (dst_reg->precise) {
7223 /* if dst_reg is precise, src_reg should be precise as well */
7224 err = mark_chain_precision(env, insn->src_reg);
7229 /* Pretend the src is a reg with a known value, since we only
7230 * need to be able to read from this state.
7232 off_reg.type = SCALAR_VALUE;
7233 __mark_reg_known(&off_reg, insn->imm);
7235 if (ptr_reg) /* pointer += K */
7236 return adjust_ptr_min_max_vals(env, insn,
7240 /* Got here implies adding two SCALAR_VALUEs */
7241 if (WARN_ON_ONCE(ptr_reg)) {
7242 print_verifier_state(env, state);
7243 verbose(env, "verifier internal error: unexpected ptr_reg\n");
7246 if (WARN_ON(!src_reg)) {
7247 print_verifier_state(env, state);
7248 verbose(env, "verifier internal error: no src_reg\n");
7251 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7254 /* check validity of 32-bit and 64-bit arithmetic operations */
7255 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7257 struct bpf_reg_state *regs = cur_regs(env);
7258 u8 opcode = BPF_OP(insn->code);
7261 if (opcode == BPF_END || opcode == BPF_NEG) {
7262 if (opcode == BPF_NEG) {
7263 if (BPF_SRC(insn->code) != 0 ||
7264 insn->src_reg != BPF_REG_0 ||
7265 insn->off != 0 || insn->imm != 0) {
7266 verbose(env, "BPF_NEG uses reserved fields\n");
7270 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7271 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7272 BPF_CLASS(insn->code) == BPF_ALU64) {
7273 verbose(env, "BPF_END uses reserved fields\n");
7278 /* check src operand */
7279 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7283 if (is_pointer_value(env, insn->dst_reg)) {
7284 verbose(env, "R%d pointer arithmetic prohibited\n",
7289 /* check dest operand */
7290 err = check_reg_arg(env, insn->dst_reg, DST_OP);
7294 } else if (opcode == BPF_MOV) {
7296 if (BPF_SRC(insn->code) == BPF_X) {
7297 if (insn->imm != 0 || insn->off != 0) {
7298 verbose(env, "BPF_MOV uses reserved fields\n");
7302 /* check src operand */
7303 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7307 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7308 verbose(env, "BPF_MOV uses reserved fields\n");
7313 /* check dest operand, mark as required later */
7314 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7318 if (BPF_SRC(insn->code) == BPF_X) {
7319 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7320 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7322 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7324 * copy register state to dest reg
7326 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7327 /* Assign src and dst registers the same ID
7328 * that will be used by find_equal_scalars()
7329 * to propagate min/max range.
7331 src_reg->id = ++env->id_gen;
7332 copy_register_state(dst_reg, src_reg);
7333 dst_reg->live |= REG_LIVE_WRITTEN;
7334 dst_reg->subreg_def = DEF_NOT_SUBREG;
7337 if (is_pointer_value(env, insn->src_reg)) {
7339 "R%d partial copy of pointer\n",
7342 } else if (src_reg->type == SCALAR_VALUE) {
7343 copy_register_state(dst_reg, src_reg);
7344 /* Make sure ID is cleared otherwise
7345 * dst_reg min/max could be incorrectly
7346 * propagated into src_reg by find_equal_scalars()
7349 dst_reg->live |= REG_LIVE_WRITTEN;
7350 dst_reg->subreg_def = env->insn_idx + 1;
7352 mark_reg_unknown(env, regs,
7355 zext_32_to_64(dst_reg);
7356 reg_bounds_sync(dst_reg);
7360 * remember the value we stored into this reg
7362 /* clear any state __mark_reg_known doesn't set */
7363 mark_reg_unknown(env, regs, insn->dst_reg);
7364 regs[insn->dst_reg].type = SCALAR_VALUE;
7365 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7366 __mark_reg_known(regs + insn->dst_reg,
7369 __mark_reg_known(regs + insn->dst_reg,
7374 } else if (opcode > BPF_END) {
7375 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7378 } else { /* all other ALU ops: and, sub, xor, add, ... */
7380 if (BPF_SRC(insn->code) == BPF_X) {
7381 if (insn->imm != 0 || insn->off != 0) {
7382 verbose(env, "BPF_ALU uses reserved fields\n");
7385 /* check src1 operand */
7386 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7390 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7391 verbose(env, "BPF_ALU uses reserved fields\n");
7396 /* check src2 operand */
7397 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7401 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7402 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7403 verbose(env, "div by zero\n");
7407 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7408 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7409 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7411 if (insn->imm < 0 || insn->imm >= size) {
7412 verbose(env, "invalid shift %d\n", insn->imm);
7417 /* check dest operand */
7418 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7422 return adjust_reg_min_max_vals(env, insn);
7428 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7429 struct bpf_reg_state *dst_reg,
7430 enum bpf_reg_type type,
7431 bool range_right_open)
7433 struct bpf_func_state *state;
7434 struct bpf_reg_state *reg;
7437 if (dst_reg->off < 0 ||
7438 (dst_reg->off == 0 && range_right_open))
7439 /* This doesn't give us any range */
7442 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7443 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7444 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7445 * than pkt_end, but that's because it's also less than pkt.
7449 new_range = dst_reg->off;
7450 if (range_right_open)
7453 /* Examples for register markings:
7455 * pkt_data in dst register:
7459 * if (r2 > pkt_end) goto <handle exception>
7464 * if (r2 < pkt_end) goto <access okay>
7465 * <handle exception>
7468 * r2 == dst_reg, pkt_end == src_reg
7469 * r2=pkt(id=n,off=8,r=0)
7470 * r3=pkt(id=n,off=0,r=0)
7472 * pkt_data in src register:
7476 * if (pkt_end >= r2) goto <access okay>
7477 * <handle exception>
7481 * if (pkt_end <= r2) goto <handle exception>
7485 * pkt_end == dst_reg, r2 == src_reg
7486 * r2=pkt(id=n,off=8,r=0)
7487 * r3=pkt(id=n,off=0,r=0)
7489 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7490 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7491 * and [r3, r3 + 8-1) respectively is safe to access depending on
7495 /* If our ids match, then we must have the same max_value. And we
7496 * don't care about the other reg's fixed offset, since if it's too big
7497 * the range won't allow anything.
7498 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7500 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
7501 if (reg->type == type && reg->id == dst_reg->id)
7502 /* keep the maximum range already checked */
7503 reg->range = max(reg->range, new_range);
7507 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7509 struct tnum subreg = tnum_subreg(reg->var_off);
7510 s32 sval = (s32)val;
7514 if (tnum_is_const(subreg))
7515 return !!tnum_equals_const(subreg, val);
7518 if (tnum_is_const(subreg))
7519 return !tnum_equals_const(subreg, val);
7522 if ((~subreg.mask & subreg.value) & val)
7524 if (!((subreg.mask | subreg.value) & val))
7528 if (reg->u32_min_value > val)
7530 else if (reg->u32_max_value <= val)
7534 if (reg->s32_min_value > sval)
7536 else if (reg->s32_max_value <= sval)
7540 if (reg->u32_max_value < val)
7542 else if (reg->u32_min_value >= val)
7546 if (reg->s32_max_value < sval)
7548 else if (reg->s32_min_value >= sval)
7552 if (reg->u32_min_value >= val)
7554 else if (reg->u32_max_value < val)
7558 if (reg->s32_min_value >= sval)
7560 else if (reg->s32_max_value < sval)
7564 if (reg->u32_max_value <= val)
7566 else if (reg->u32_min_value > val)
7570 if (reg->s32_max_value <= sval)
7572 else if (reg->s32_min_value > sval)
7581 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7583 s64 sval = (s64)val;
7587 if (tnum_is_const(reg->var_off))
7588 return !!tnum_equals_const(reg->var_off, val);
7591 if (tnum_is_const(reg->var_off))
7592 return !tnum_equals_const(reg->var_off, val);
7595 if ((~reg->var_off.mask & reg->var_off.value) & val)
7597 if (!((reg->var_off.mask | reg->var_off.value) & val))
7601 if (reg->umin_value > val)
7603 else if (reg->umax_value <= val)
7607 if (reg->smin_value > sval)
7609 else if (reg->smax_value <= sval)
7613 if (reg->umax_value < val)
7615 else if (reg->umin_value >= val)
7619 if (reg->smax_value < sval)
7621 else if (reg->smin_value >= sval)
7625 if (reg->umin_value >= val)
7627 else if (reg->umax_value < val)
7631 if (reg->smin_value >= sval)
7633 else if (reg->smax_value < sval)
7637 if (reg->umax_value <= val)
7639 else if (reg->umin_value > val)
7643 if (reg->smax_value <= sval)
7645 else if (reg->smin_value > sval)
7653 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7655 * 1 - branch will be taken and "goto target" will be executed
7656 * 0 - branch will not be taken and fall-through to next insn
7657 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7660 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7663 if (__is_pointer_value(false, reg)) {
7664 if (!reg_type_not_null(reg->type))
7667 /* If pointer is valid tests against zero will fail so we can
7668 * use this to direct branch taken.
7684 return is_branch32_taken(reg, val, opcode);
7685 return is_branch64_taken(reg, val, opcode);
7688 static int flip_opcode(u32 opcode)
7690 /* How can we transform "a <op> b" into "b <op> a"? */
7691 static const u8 opcode_flip[16] = {
7692 /* these stay the same */
7693 [BPF_JEQ >> 4] = BPF_JEQ,
7694 [BPF_JNE >> 4] = BPF_JNE,
7695 [BPF_JSET >> 4] = BPF_JSET,
7696 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7697 [BPF_JGE >> 4] = BPF_JLE,
7698 [BPF_JGT >> 4] = BPF_JLT,
7699 [BPF_JLE >> 4] = BPF_JGE,
7700 [BPF_JLT >> 4] = BPF_JGT,
7701 [BPF_JSGE >> 4] = BPF_JSLE,
7702 [BPF_JSGT >> 4] = BPF_JSLT,
7703 [BPF_JSLE >> 4] = BPF_JSGE,
7704 [BPF_JSLT >> 4] = BPF_JSGT
7706 return opcode_flip[opcode >> 4];
7709 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7710 struct bpf_reg_state *src_reg,
7713 struct bpf_reg_state *pkt;
7715 if (src_reg->type == PTR_TO_PACKET_END) {
7717 } else if (dst_reg->type == PTR_TO_PACKET_END) {
7719 opcode = flip_opcode(opcode);
7724 if (pkt->range >= 0)
7729 /* pkt <= pkt_end */
7733 if (pkt->range == BEYOND_PKT_END)
7734 /* pkt has at last one extra byte beyond pkt_end */
7735 return opcode == BPF_JGT;
7741 /* pkt >= pkt_end */
7742 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7743 return opcode == BPF_JGE;
7749 /* Adjusts the register min/max values in the case that the dst_reg is the
7750 * variable register that we are working on, and src_reg is a constant or we're
7751 * simply doing a BPF_K check.
7752 * In JEQ/JNE cases we also adjust the var_off values.
7754 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7755 struct bpf_reg_state *false_reg,
7757 u8 opcode, bool is_jmp32)
7759 struct tnum false_32off = tnum_subreg(false_reg->var_off);
7760 struct tnum false_64off = false_reg->var_off;
7761 struct tnum true_32off = tnum_subreg(true_reg->var_off);
7762 struct tnum true_64off = true_reg->var_off;
7763 s64 sval = (s64)val;
7764 s32 sval32 = (s32)val32;
7766 /* If the dst_reg is a pointer, we can't learn anything about its
7767 * variable offset from the compare (unless src_reg were a pointer into
7768 * the same object, but we don't bother with that.
7769 * Since false_reg and true_reg have the same type by construction, we
7770 * only need to check one of them for pointerness.
7772 if (__is_pointer_value(false, false_reg))
7776 /* JEQ/JNE comparison doesn't change the register equivalence.
7779 * if (r1 == 42) goto label;
7781 * label: // here both r1 and r2 are known to be 42.
7783 * Hence when marking register as known preserve it's ID.
7787 __mark_reg32_known(true_reg, val32);
7788 true_32off = tnum_subreg(true_reg->var_off);
7790 ___mark_reg_known(true_reg, val);
7791 true_64off = true_reg->var_off;
7796 __mark_reg32_known(false_reg, val32);
7797 false_32off = tnum_subreg(false_reg->var_off);
7799 ___mark_reg_known(false_reg, val);
7800 false_64off = false_reg->var_off;
7805 false_32off = tnum_and(false_32off, tnum_const(~val32));
7806 if (is_power_of_2(val32))
7807 true_32off = tnum_or(true_32off,
7810 false_64off = tnum_and(false_64off, tnum_const(~val));
7811 if (is_power_of_2(val))
7812 true_64off = tnum_or(true_64off,
7820 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7821 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7823 false_reg->u32_max_value = min(false_reg->u32_max_value,
7825 true_reg->u32_min_value = max(true_reg->u32_min_value,
7828 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7829 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7831 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7832 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7840 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7841 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7843 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7844 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7846 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7847 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7849 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7850 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7858 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7859 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7861 false_reg->u32_min_value = max(false_reg->u32_min_value,
7863 true_reg->u32_max_value = min(true_reg->u32_max_value,
7866 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7867 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7869 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7870 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7878 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7879 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7881 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7882 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7884 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7885 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7887 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7888 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7897 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7898 tnum_subreg(false_32off));
7899 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7900 tnum_subreg(true_32off));
7901 __reg_combine_32_into_64(false_reg);
7902 __reg_combine_32_into_64(true_reg);
7904 false_reg->var_off = false_64off;
7905 true_reg->var_off = true_64off;
7906 __reg_combine_64_into_32(false_reg);
7907 __reg_combine_64_into_32(true_reg);
7911 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7914 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7915 struct bpf_reg_state *false_reg,
7917 u8 opcode, bool is_jmp32)
7919 opcode = flip_opcode(opcode);
7920 /* This uses zero as "not present in table"; luckily the zero opcode,
7921 * BPF_JA, can't get here.
7924 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7927 /* Regs are known to be equal, so intersect their min/max/var_off */
7928 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7929 struct bpf_reg_state *dst_reg)
7931 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7932 dst_reg->umin_value);
7933 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7934 dst_reg->umax_value);
7935 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7936 dst_reg->smin_value);
7937 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7938 dst_reg->smax_value);
7939 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7941 reg_bounds_sync(src_reg);
7942 reg_bounds_sync(dst_reg);
7945 static void reg_combine_min_max(struct bpf_reg_state *true_src,
7946 struct bpf_reg_state *true_dst,
7947 struct bpf_reg_state *false_src,
7948 struct bpf_reg_state *false_dst,
7953 __reg_combine_min_max(true_src, true_dst);
7956 __reg_combine_min_max(false_src, false_dst);
7961 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7962 struct bpf_reg_state *reg, u32 id,
7965 if (reg_type_may_be_null(reg->type) && reg->id == id &&
7966 !WARN_ON_ONCE(!reg->id)) {
7967 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7968 !tnum_equals_const(reg->var_off, 0) ||
7970 /* Old offset (both fixed and variable parts) should
7971 * have been known-zero, because we don't allow pointer
7972 * arithmetic on pointers that might be NULL. If we
7973 * see this happening, don't convert the register.
7978 reg->type = SCALAR_VALUE;
7979 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
7980 const struct bpf_map *map = reg->map_ptr;
7982 if (map->inner_map_meta) {
7983 reg->type = CONST_PTR_TO_MAP;
7984 reg->map_ptr = map->inner_map_meta;
7985 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
7986 reg->type = PTR_TO_XDP_SOCK;
7987 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7988 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7989 reg->type = PTR_TO_SOCKET;
7991 reg->type = PTR_TO_MAP_VALUE;
7993 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7994 reg->type = PTR_TO_SOCKET;
7995 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7996 reg->type = PTR_TO_SOCK_COMMON;
7997 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7998 reg->type = PTR_TO_TCP_SOCK;
7999 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
8000 reg->type = PTR_TO_BTF_ID;
8001 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
8002 reg->type = PTR_TO_MEM;
8003 } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
8004 reg->type = PTR_TO_RDONLY_BUF;
8005 } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
8006 reg->type = PTR_TO_RDWR_BUF;
8009 /* We don't need id and ref_obj_id from this point
8010 * onwards anymore, thus we should better reset it,
8011 * so that state pruning has chances to take effect.
8014 reg->ref_obj_id = 0;
8015 } else if (!reg_may_point_to_spin_lock(reg)) {
8016 /* For not-NULL ptr, reg->ref_obj_id will be reset
8017 * in release_reference().
8019 * reg->id is still used by spin_lock ptr. Other
8020 * than spin_lock ptr type, reg->id can be reset.
8027 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8028 * be folded together at some point.
8030 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8033 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8034 struct bpf_reg_state *regs = state->regs, *reg;
8035 u32 ref_obj_id = regs[regno].ref_obj_id;
8036 u32 id = regs[regno].id;
8038 if (ref_obj_id && ref_obj_id == id && is_null)
8039 /* regs[regno] is in the " == NULL" branch.
8040 * No one could have freed the reference state before
8041 * doing the NULL check.
8043 WARN_ON_ONCE(release_reference_state(state, id));
8045 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8046 mark_ptr_or_null_reg(state, reg, id, is_null);
8050 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8051 struct bpf_reg_state *dst_reg,
8052 struct bpf_reg_state *src_reg,
8053 struct bpf_verifier_state *this_branch,
8054 struct bpf_verifier_state *other_branch)
8056 if (BPF_SRC(insn->code) != BPF_X)
8059 /* Pointers are always 64-bit. */
8060 if (BPF_CLASS(insn->code) == BPF_JMP32)
8063 switch (BPF_OP(insn->code)) {
8065 if ((dst_reg->type == PTR_TO_PACKET &&
8066 src_reg->type == PTR_TO_PACKET_END) ||
8067 (dst_reg->type == PTR_TO_PACKET_META &&
8068 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8069 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8070 find_good_pkt_pointers(this_branch, dst_reg,
8071 dst_reg->type, false);
8072 mark_pkt_end(other_branch, insn->dst_reg, true);
8073 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8074 src_reg->type == PTR_TO_PACKET) ||
8075 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8076 src_reg->type == PTR_TO_PACKET_META)) {
8077 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8078 find_good_pkt_pointers(other_branch, src_reg,
8079 src_reg->type, true);
8080 mark_pkt_end(this_branch, insn->src_reg, false);
8086 if ((dst_reg->type == PTR_TO_PACKET &&
8087 src_reg->type == PTR_TO_PACKET_END) ||
8088 (dst_reg->type == PTR_TO_PACKET_META &&
8089 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8090 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8091 find_good_pkt_pointers(other_branch, dst_reg,
8092 dst_reg->type, true);
8093 mark_pkt_end(this_branch, insn->dst_reg, false);
8094 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8095 src_reg->type == PTR_TO_PACKET) ||
8096 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8097 src_reg->type == PTR_TO_PACKET_META)) {
8098 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8099 find_good_pkt_pointers(this_branch, src_reg,
8100 src_reg->type, false);
8101 mark_pkt_end(other_branch, insn->src_reg, true);
8107 if ((dst_reg->type == PTR_TO_PACKET &&
8108 src_reg->type == PTR_TO_PACKET_END) ||
8109 (dst_reg->type == PTR_TO_PACKET_META &&
8110 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8111 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8112 find_good_pkt_pointers(this_branch, dst_reg,
8113 dst_reg->type, true);
8114 mark_pkt_end(other_branch, insn->dst_reg, false);
8115 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8116 src_reg->type == PTR_TO_PACKET) ||
8117 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8118 src_reg->type == PTR_TO_PACKET_META)) {
8119 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8120 find_good_pkt_pointers(other_branch, src_reg,
8121 src_reg->type, false);
8122 mark_pkt_end(this_branch, insn->src_reg, true);
8128 if ((dst_reg->type == PTR_TO_PACKET &&
8129 src_reg->type == PTR_TO_PACKET_END) ||
8130 (dst_reg->type == PTR_TO_PACKET_META &&
8131 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8132 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8133 find_good_pkt_pointers(other_branch, dst_reg,
8134 dst_reg->type, false);
8135 mark_pkt_end(this_branch, insn->dst_reg, true);
8136 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8137 src_reg->type == PTR_TO_PACKET) ||
8138 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8139 src_reg->type == PTR_TO_PACKET_META)) {
8140 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8141 find_good_pkt_pointers(this_branch, src_reg,
8142 src_reg->type, true);
8143 mark_pkt_end(other_branch, insn->src_reg, false);
8155 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8156 struct bpf_reg_state *known_reg)
8158 struct bpf_func_state *state;
8159 struct bpf_reg_state *reg;
8161 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8162 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8163 copy_register_state(reg, known_reg);
8167 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8168 struct bpf_insn *insn, int *insn_idx)
8170 struct bpf_verifier_state *this_branch = env->cur_state;
8171 struct bpf_verifier_state *other_branch;
8172 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8173 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8174 u8 opcode = BPF_OP(insn->code);
8179 /* Only conditional jumps are expected to reach here. */
8180 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8181 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8185 if (BPF_SRC(insn->code) == BPF_X) {
8186 if (insn->imm != 0) {
8187 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8191 /* check src1 operand */
8192 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8196 if (is_pointer_value(env, insn->src_reg)) {
8197 verbose(env, "R%d pointer comparison prohibited\n",
8201 src_reg = ®s[insn->src_reg];
8203 if (insn->src_reg != BPF_REG_0) {
8204 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8209 /* check src2 operand */
8210 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8214 dst_reg = ®s[insn->dst_reg];
8215 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8217 if (BPF_SRC(insn->code) == BPF_K) {
8218 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8219 } else if (src_reg->type == SCALAR_VALUE &&
8220 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8221 pred = is_branch_taken(dst_reg,
8222 tnum_subreg(src_reg->var_off).value,
8225 } else if (src_reg->type == SCALAR_VALUE &&
8226 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8227 pred = is_branch_taken(dst_reg,
8228 src_reg->var_off.value,
8231 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8232 reg_is_pkt_pointer_any(src_reg) &&
8234 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8238 /* If we get here with a dst_reg pointer type it is because
8239 * above is_branch_taken() special cased the 0 comparison.
8241 if (!__is_pointer_value(false, dst_reg))
8242 err = mark_chain_precision(env, insn->dst_reg);
8243 if (BPF_SRC(insn->code) == BPF_X && !err &&
8244 !__is_pointer_value(false, src_reg))
8245 err = mark_chain_precision(env, insn->src_reg);
8251 /* Only follow the goto, ignore fall-through. If needed, push
8252 * the fall-through branch for simulation under speculative
8255 if (!env->bypass_spec_v1 &&
8256 !sanitize_speculative_path(env, insn, *insn_idx + 1,
8259 *insn_idx += insn->off;
8261 } else if (pred == 0) {
8262 /* Only follow the fall-through branch, since that's where the
8263 * program will go. If needed, push the goto branch for
8264 * simulation under speculative execution.
8266 if (!env->bypass_spec_v1 &&
8267 !sanitize_speculative_path(env, insn,
8268 *insn_idx + insn->off + 1,
8274 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8278 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8280 /* detect if we are comparing against a constant value so we can adjust
8281 * our min/max values for our dst register.
8282 * this is only legit if both are scalars (or pointers to the same
8283 * object, I suppose, but we don't support that right now), because
8284 * otherwise the different base pointers mean the offsets aren't
8287 if (BPF_SRC(insn->code) == BPF_X) {
8288 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
8290 if (dst_reg->type == SCALAR_VALUE &&
8291 src_reg->type == SCALAR_VALUE) {
8292 if (tnum_is_const(src_reg->var_off) ||
8294 tnum_is_const(tnum_subreg(src_reg->var_off))))
8295 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8297 src_reg->var_off.value,
8298 tnum_subreg(src_reg->var_off).value,
8300 else if (tnum_is_const(dst_reg->var_off) ||
8302 tnum_is_const(tnum_subreg(dst_reg->var_off))))
8303 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8305 dst_reg->var_off.value,
8306 tnum_subreg(dst_reg->var_off).value,
8308 else if (!is_jmp32 &&
8309 (opcode == BPF_JEQ || opcode == BPF_JNE))
8310 /* Comparing for equality, we can combine knowledge */
8311 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8312 &other_branch_regs[insn->dst_reg],
8313 src_reg, dst_reg, opcode);
8315 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8316 find_equal_scalars(this_branch, src_reg);
8317 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8321 } else if (dst_reg->type == SCALAR_VALUE) {
8322 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8323 dst_reg, insn->imm, (u32)insn->imm,
8327 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8328 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8329 find_equal_scalars(this_branch, dst_reg);
8330 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8333 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8334 * NOTE: these optimizations below are related with pointer comparison
8335 * which will never be JMP32.
8337 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8338 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8339 reg_type_may_be_null(dst_reg->type)) {
8340 /* Mark all identical registers in each branch as either
8341 * safe or unknown depending R == 0 or R != 0 conditional.
8343 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8345 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8347 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
8348 this_branch, other_branch) &&
8349 is_pointer_value(env, insn->dst_reg)) {
8350 verbose(env, "R%d pointer comparison prohibited\n",
8354 if (env->log.level & BPF_LOG_LEVEL)
8355 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8359 /* verify BPF_LD_IMM64 instruction */
8360 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8362 struct bpf_insn_aux_data *aux = cur_aux(env);
8363 struct bpf_reg_state *regs = cur_regs(env);
8364 struct bpf_reg_state *dst_reg;
8365 struct bpf_map *map;
8368 if (BPF_SIZE(insn->code) != BPF_DW) {
8369 verbose(env, "invalid BPF_LD_IMM insn\n");
8372 if (insn->off != 0) {
8373 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8377 err = check_reg_arg(env, insn->dst_reg, DST_OP);
8381 dst_reg = ®s[insn->dst_reg];
8382 if (insn->src_reg == 0) {
8383 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8385 dst_reg->type = SCALAR_VALUE;
8386 __mark_reg_known(®s[insn->dst_reg], imm);
8390 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8391 mark_reg_known_zero(env, regs, insn->dst_reg);
8393 dst_reg->type = aux->btf_var.reg_type;
8394 switch (dst_reg->type) {
8396 dst_reg->mem_size = aux->btf_var.mem_size;
8399 case PTR_TO_PERCPU_BTF_ID:
8400 dst_reg->btf_id = aux->btf_var.btf_id;
8403 verbose(env, "bpf verifier is misconfigured\n");
8409 map = env->used_maps[aux->map_index];
8410 mark_reg_known_zero(env, regs, insn->dst_reg);
8411 dst_reg->map_ptr = map;
8413 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8414 dst_reg->type = PTR_TO_MAP_VALUE;
8415 dst_reg->off = aux->map_off;
8416 if (map_value_has_spin_lock(map))
8417 dst_reg->id = ++env->id_gen;
8418 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8419 dst_reg->type = CONST_PTR_TO_MAP;
8421 verbose(env, "bpf verifier is misconfigured\n");
8428 static bool may_access_skb(enum bpf_prog_type type)
8431 case BPF_PROG_TYPE_SOCKET_FILTER:
8432 case BPF_PROG_TYPE_SCHED_CLS:
8433 case BPF_PROG_TYPE_SCHED_ACT:
8440 /* verify safety of LD_ABS|LD_IND instructions:
8441 * - they can only appear in the programs where ctx == skb
8442 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8443 * preserve R6-R9, and store return value into R0
8446 * ctx == skb == R6 == CTX
8449 * SRC == any register
8450 * IMM == 32-bit immediate
8453 * R0 - 8/16/32-bit skb data converted to cpu endianness
8455 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8457 struct bpf_reg_state *regs = cur_regs(env);
8458 static const int ctx_reg = BPF_REG_6;
8459 u8 mode = BPF_MODE(insn->code);
8462 if (!may_access_skb(resolve_prog_type(env->prog))) {
8463 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8467 if (!env->ops->gen_ld_abs) {
8468 verbose(env, "bpf verifier is misconfigured\n");
8472 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8473 BPF_SIZE(insn->code) == BPF_DW ||
8474 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8475 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8479 /* check whether implicit source operand (register R6) is readable */
8480 err = check_reg_arg(env, ctx_reg, SRC_OP);
8484 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8485 * gen_ld_abs() may terminate the program at runtime, leading to
8488 err = check_reference_leak(env);
8490 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8494 if (env->cur_state->active_spin_lock) {
8495 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8499 if (regs[ctx_reg].type != PTR_TO_CTX) {
8501 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8505 if (mode == BPF_IND) {
8506 /* check explicit source operand */
8507 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8512 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg);
8516 /* reset caller saved regs to unreadable */
8517 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8518 mark_reg_not_init(env, regs, caller_saved[i]);
8519 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8522 /* mark destination R0 register as readable, since it contains
8523 * the value fetched from the packet.
8524 * Already marked as written above.
8526 mark_reg_unknown(env, regs, BPF_REG_0);
8527 /* ld_abs load up to 32-bit skb data. */
8528 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8532 static int check_return_code(struct bpf_verifier_env *env)
8534 struct tnum enforce_attach_type_range = tnum_unknown;
8535 const struct bpf_prog *prog = env->prog;
8536 struct bpf_reg_state *reg;
8537 struct tnum range = tnum_range(0, 1);
8538 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8540 const bool is_subprog = env->cur_state->frame[0]->subprogno;
8542 /* LSM and struct_ops func-ptr's return type could be "void" */
8544 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8545 prog_type == BPF_PROG_TYPE_LSM) &&
8546 !prog->aux->attach_func_proto->type)
8549 /* eBPF calling convetion is such that R0 is used
8550 * to return the value from eBPF program.
8551 * Make sure that it's readable at this time
8552 * of bpf_exit, which means that program wrote
8553 * something into it earlier
8555 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8559 if (is_pointer_value(env, BPF_REG_0)) {
8560 verbose(env, "R0 leaks addr as return value\n");
8564 reg = cur_regs(env) + BPF_REG_0;
8566 if (reg->type != SCALAR_VALUE) {
8567 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8568 reg_type_str[reg->type]);
8574 switch (prog_type) {
8575 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8576 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8577 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8578 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8579 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8580 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8581 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8582 range = tnum_range(1, 1);
8584 case BPF_PROG_TYPE_CGROUP_SKB:
8585 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8586 range = tnum_range(0, 3);
8587 enforce_attach_type_range = tnum_range(2, 3);
8590 case BPF_PROG_TYPE_CGROUP_SOCK:
8591 case BPF_PROG_TYPE_SOCK_OPS:
8592 case BPF_PROG_TYPE_CGROUP_DEVICE:
8593 case BPF_PROG_TYPE_CGROUP_SYSCTL:
8594 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8596 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8597 if (!env->prog->aux->attach_btf_id)
8599 range = tnum_const(0);
8601 case BPF_PROG_TYPE_TRACING:
8602 switch (env->prog->expected_attach_type) {
8603 case BPF_TRACE_FENTRY:
8604 case BPF_TRACE_FEXIT:
8605 range = tnum_const(0);
8607 case BPF_TRACE_RAW_TP:
8608 case BPF_MODIFY_RETURN:
8610 case BPF_TRACE_ITER:
8616 case BPF_PROG_TYPE_SK_LOOKUP:
8617 range = tnum_range(SK_DROP, SK_PASS);
8619 case BPF_PROG_TYPE_EXT:
8620 /* freplace program can return anything as its return value
8621 * depends on the to-be-replaced kernel func or bpf program.
8627 if (reg->type != SCALAR_VALUE) {
8628 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8629 reg_type_str[reg->type]);
8633 if (!tnum_in(range, reg->var_off)) {
8636 verbose(env, "At program exit the register R0 ");
8637 if (!tnum_is_unknown(reg->var_off)) {
8638 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8639 verbose(env, "has value %s", tn_buf);
8641 verbose(env, "has unknown scalar value");
8643 tnum_strn(tn_buf, sizeof(tn_buf), range);
8644 verbose(env, " should have been in %s\n", tn_buf);
8648 if (!tnum_is_unknown(enforce_attach_type_range) &&
8649 tnum_in(enforce_attach_type_range, reg->var_off))
8650 env->prog->enforce_expected_attach_type = 1;
8654 /* non-recursive DFS pseudo code
8655 * 1 procedure DFS-iterative(G,v):
8656 * 2 label v as discovered
8657 * 3 let S be a stack
8659 * 5 while S is not empty
8661 * 7 if t is what we're looking for:
8663 * 9 for all edges e in G.adjacentEdges(t) do
8664 * 10 if edge e is already labelled
8665 * 11 continue with the next edge
8666 * 12 w <- G.adjacentVertex(t,e)
8667 * 13 if vertex w is not discovered and not explored
8668 * 14 label e as tree-edge
8669 * 15 label w as discovered
8672 * 18 else if vertex w is discovered
8673 * 19 label e as back-edge
8675 * 21 // vertex w is explored
8676 * 22 label e as forward- or cross-edge
8677 * 23 label t as explored
8682 * 0x11 - discovered and fall-through edge labelled
8683 * 0x12 - discovered and fall-through and branch edges labelled
8694 static u32 state_htab_size(struct bpf_verifier_env *env)
8696 return env->prog->len;
8699 static struct bpf_verifier_state_list **explored_state(
8700 struct bpf_verifier_env *env,
8703 struct bpf_verifier_state *cur = env->cur_state;
8704 struct bpf_func_state *state = cur->frame[cur->curframe];
8706 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8709 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8711 env->insn_aux_data[idx].prune_point = true;
8714 /* t, w, e - match pseudo-code above:
8715 * t - index of current instruction
8716 * w - next instruction
8719 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8722 int *insn_stack = env->cfg.insn_stack;
8723 int *insn_state = env->cfg.insn_state;
8725 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8728 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8731 if (w < 0 || w >= env->prog->len) {
8732 verbose_linfo(env, t, "%d: ", t);
8733 verbose(env, "jump out of range from insn %d to %d\n", t, w);
8738 /* mark branch target for state pruning */
8739 init_explored_state(env, w);
8741 if (insn_state[w] == 0) {
8743 insn_state[t] = DISCOVERED | e;
8744 insn_state[w] = DISCOVERED;
8745 if (env->cfg.cur_stack >= env->prog->len)
8747 insn_stack[env->cfg.cur_stack++] = w;
8749 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8750 if (loop_ok && env->bpf_capable)
8752 verbose_linfo(env, t, "%d: ", t);
8753 verbose_linfo(env, w, "%d: ", w);
8754 verbose(env, "back-edge from insn %d to %d\n", t, w);
8756 } else if (insn_state[w] == EXPLORED) {
8757 /* forward- or cross-edge */
8758 insn_state[t] = DISCOVERED | e;
8760 verbose(env, "insn state internal bug\n");
8766 /* non-recursive depth-first-search to detect loops in BPF program
8767 * loop == back-edge in directed graph
8769 static int check_cfg(struct bpf_verifier_env *env)
8771 struct bpf_insn *insns = env->prog->insnsi;
8772 int insn_cnt = env->prog->len;
8773 int *insn_stack, *insn_state;
8777 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8781 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8787 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8788 insn_stack[0] = 0; /* 0 is the first instruction */
8789 env->cfg.cur_stack = 1;
8792 if (env->cfg.cur_stack == 0)
8794 t = insn_stack[env->cfg.cur_stack - 1];
8796 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
8797 BPF_CLASS(insns[t].code) == BPF_JMP32) {
8798 u8 opcode = BPF_OP(insns[t].code);
8800 if (opcode == BPF_EXIT) {
8802 } else if (opcode == BPF_CALL) {
8803 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8808 if (t + 1 < insn_cnt)
8809 init_explored_state(env, t + 1);
8810 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8811 init_explored_state(env, t);
8812 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8819 } else if (opcode == BPF_JA) {
8820 if (BPF_SRC(insns[t].code) != BPF_K) {
8824 /* unconditional jump with single edge */
8825 ret = push_insn(t, t + insns[t].off + 1,
8826 FALLTHROUGH, env, true);
8831 /* unconditional jmp is not a good pruning point,
8832 * but it's marked, since backtracking needs
8833 * to record jmp history in is_state_visited().
8835 init_explored_state(env, t + insns[t].off + 1);
8836 /* tell verifier to check for equivalent states
8837 * after every call and jump
8839 if (t + 1 < insn_cnt)
8840 init_explored_state(env, t + 1);
8842 /* conditional jump with two edges */
8843 init_explored_state(env, t);
8844 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8850 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8857 /* all other non-branch instructions with single
8860 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8868 insn_state[t] = EXPLORED;
8869 if (env->cfg.cur_stack-- <= 0) {
8870 verbose(env, "pop stack internal bug\n");
8877 for (i = 0; i < insn_cnt; i++) {
8878 if (insn_state[i] != EXPLORED) {
8879 verbose(env, "unreachable insn %d\n", i);
8884 ret = 0; /* cfg looks good */
8889 env->cfg.insn_state = env->cfg.insn_stack = NULL;
8893 static int check_abnormal_return(struct bpf_verifier_env *env)
8897 for (i = 1; i < env->subprog_cnt; i++) {
8898 if (env->subprog_info[i].has_ld_abs) {
8899 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8902 if (env->subprog_info[i].has_tail_call) {
8903 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8910 /* The minimum supported BTF func info size */
8911 #define MIN_BPF_FUNCINFO_SIZE 8
8912 #define MAX_FUNCINFO_REC_SIZE 252
8914 static int check_btf_func(struct bpf_verifier_env *env,
8915 const union bpf_attr *attr,
8916 union bpf_attr __user *uattr)
8918 const struct btf_type *type, *func_proto, *ret_type;
8919 u32 i, nfuncs, urec_size, min_size;
8920 u32 krec_size = sizeof(struct bpf_func_info);
8921 struct bpf_func_info *krecord;
8922 struct bpf_func_info_aux *info_aux = NULL;
8923 struct bpf_prog *prog;
8924 const struct btf *btf;
8925 void __user *urecord;
8926 u32 prev_offset = 0;
8930 nfuncs = attr->func_info_cnt;
8932 if (check_abnormal_return(env))
8937 if (nfuncs != env->subprog_cnt) {
8938 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8942 urec_size = attr->func_info_rec_size;
8943 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8944 urec_size > MAX_FUNCINFO_REC_SIZE ||
8945 urec_size % sizeof(u32)) {
8946 verbose(env, "invalid func info rec size %u\n", urec_size);
8951 btf = prog->aux->btf;
8953 urecord = u64_to_user_ptr(attr->func_info);
8954 min_size = min_t(u32, krec_size, urec_size);
8956 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
8959 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8963 for (i = 0; i < nfuncs; i++) {
8964 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8966 if (ret == -E2BIG) {
8967 verbose(env, "nonzero tailing record in func info");
8968 /* set the size kernel expects so loader can zero
8969 * out the rest of the record.
8971 if (put_user(min_size, &uattr->func_info_rec_size))
8977 if (copy_from_user(&krecord[i], urecord, min_size)) {
8982 /* check insn_off */
8985 if (krecord[i].insn_off) {
8987 "nonzero insn_off %u for the first func info record",
8988 krecord[i].insn_off);
8991 } else if (krecord[i].insn_off <= prev_offset) {
8993 "same or smaller insn offset (%u) than previous func info record (%u)",
8994 krecord[i].insn_off, prev_offset);
8998 if (env->subprog_info[i].start != krecord[i].insn_off) {
8999 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9004 type = btf_type_by_id(btf, krecord[i].type_id);
9005 if (!type || !btf_type_is_func(type)) {
9006 verbose(env, "invalid type id %d in func info",
9007 krecord[i].type_id);
9010 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9012 func_proto = btf_type_by_id(btf, type->type);
9013 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9014 /* btf_func_check() already verified it during BTF load */
9016 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9018 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9019 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9020 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9023 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9024 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9028 prev_offset = krecord[i].insn_off;
9029 urecord += urec_size;
9032 prog->aux->func_info = krecord;
9033 prog->aux->func_info_cnt = nfuncs;
9034 prog->aux->func_info_aux = info_aux;
9043 static void adjust_btf_func(struct bpf_verifier_env *env)
9045 struct bpf_prog_aux *aux = env->prog->aux;
9048 if (!aux->func_info)
9051 for (i = 0; i < env->subprog_cnt; i++)
9052 aux->func_info[i].insn_off = env->subprog_info[i].start;
9055 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9056 sizeof(((struct bpf_line_info *)(0))->line_col))
9057 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9059 static int check_btf_line(struct bpf_verifier_env *env,
9060 const union bpf_attr *attr,
9061 union bpf_attr __user *uattr)
9063 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9064 struct bpf_subprog_info *sub;
9065 struct bpf_line_info *linfo;
9066 struct bpf_prog *prog;
9067 const struct btf *btf;
9068 void __user *ulinfo;
9071 nr_linfo = attr->line_info_cnt;
9074 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
9077 rec_size = attr->line_info_rec_size;
9078 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9079 rec_size > MAX_LINEINFO_REC_SIZE ||
9080 rec_size & (sizeof(u32) - 1))
9083 /* Need to zero it in case the userspace may
9084 * pass in a smaller bpf_line_info object.
9086 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9087 GFP_KERNEL | __GFP_NOWARN);
9092 btf = prog->aux->btf;
9095 sub = env->subprog_info;
9096 ulinfo = u64_to_user_ptr(attr->line_info);
9097 expected_size = sizeof(struct bpf_line_info);
9098 ncopy = min_t(u32, expected_size, rec_size);
9099 for (i = 0; i < nr_linfo; i++) {
9100 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9102 if (err == -E2BIG) {
9103 verbose(env, "nonzero tailing record in line_info");
9104 if (put_user(expected_size,
9105 &uattr->line_info_rec_size))
9111 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9117 * Check insn_off to ensure
9118 * 1) strictly increasing AND
9119 * 2) bounded by prog->len
9121 * The linfo[0].insn_off == 0 check logically falls into
9122 * the later "missing bpf_line_info for func..." case
9123 * because the first linfo[0].insn_off must be the
9124 * first sub also and the first sub must have
9125 * subprog_info[0].start == 0.
9127 if ((i && linfo[i].insn_off <= prev_offset) ||
9128 linfo[i].insn_off >= prog->len) {
9129 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9130 i, linfo[i].insn_off, prev_offset,
9136 if (!prog->insnsi[linfo[i].insn_off].code) {
9138 "Invalid insn code at line_info[%u].insn_off\n",
9144 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9145 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9146 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9151 if (s != env->subprog_cnt) {
9152 if (linfo[i].insn_off == sub[s].start) {
9153 sub[s].linfo_idx = i;
9155 } else if (sub[s].start < linfo[i].insn_off) {
9156 verbose(env, "missing bpf_line_info for func#%u\n", s);
9162 prev_offset = linfo[i].insn_off;
9166 if (s != env->subprog_cnt) {
9167 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9168 env->subprog_cnt - s, s);
9173 prog->aux->linfo = linfo;
9174 prog->aux->nr_linfo = nr_linfo;
9183 static int check_btf_info(struct bpf_verifier_env *env,
9184 const union bpf_attr *attr,
9185 union bpf_attr __user *uattr)
9190 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9191 if (check_abnormal_return(env))
9196 btf = btf_get_by_fd(attr->prog_btf_fd);
9198 return PTR_ERR(btf);
9199 env->prog->aux->btf = btf;
9201 err = check_btf_func(env, attr, uattr);
9205 err = check_btf_line(env, attr, uattr);
9212 /* check %cur's range satisfies %old's */
9213 static bool range_within(struct bpf_reg_state *old,
9214 struct bpf_reg_state *cur)
9216 return old->umin_value <= cur->umin_value &&
9217 old->umax_value >= cur->umax_value &&
9218 old->smin_value <= cur->smin_value &&
9219 old->smax_value >= cur->smax_value &&
9220 old->u32_min_value <= cur->u32_min_value &&
9221 old->u32_max_value >= cur->u32_max_value &&
9222 old->s32_min_value <= cur->s32_min_value &&
9223 old->s32_max_value >= cur->s32_max_value;
9226 /* If in the old state two registers had the same id, then they need to have
9227 * the same id in the new state as well. But that id could be different from
9228 * the old state, so we need to track the mapping from old to new ids.
9229 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9230 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9231 * regs with a different old id could still have new id 9, we don't care about
9233 * So we look through our idmap to see if this old id has been seen before. If
9234 * so, we require the new id to match; otherwise, we add the id pair to the map.
9236 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
9240 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
9241 if (!idmap[i].old) {
9242 /* Reached an empty slot; haven't seen this id before */
9243 idmap[i].old = old_id;
9244 idmap[i].cur = cur_id;
9247 if (idmap[i].old == old_id)
9248 return idmap[i].cur == cur_id;
9250 /* We ran out of idmap slots, which should be impossible */
9255 static void clean_func_state(struct bpf_verifier_env *env,
9256 struct bpf_func_state *st)
9258 enum bpf_reg_liveness live;
9261 for (i = 0; i < BPF_REG_FP; i++) {
9262 live = st->regs[i].live;
9263 /* liveness must not touch this register anymore */
9264 st->regs[i].live |= REG_LIVE_DONE;
9265 if (!(live & REG_LIVE_READ))
9266 /* since the register is unused, clear its state
9267 * to make further comparison simpler
9269 __mark_reg_not_init(env, &st->regs[i]);
9272 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9273 live = st->stack[i].spilled_ptr.live;
9274 /* liveness must not touch this stack slot anymore */
9275 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9276 if (!(live & REG_LIVE_READ)) {
9277 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9278 for (j = 0; j < BPF_REG_SIZE; j++)
9279 st->stack[i].slot_type[j] = STACK_INVALID;
9284 static void clean_verifier_state(struct bpf_verifier_env *env,
9285 struct bpf_verifier_state *st)
9289 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9290 /* all regs in this state in all frames were already marked */
9293 for (i = 0; i <= st->curframe; i++)
9294 clean_func_state(env, st->frame[i]);
9297 /* the parentage chains form a tree.
9298 * the verifier states are added to state lists at given insn and
9299 * pushed into state stack for future exploration.
9300 * when the verifier reaches bpf_exit insn some of the verifer states
9301 * stored in the state lists have their final liveness state already,
9302 * but a lot of states will get revised from liveness point of view when
9303 * the verifier explores other branches.
9306 * 2: if r1 == 100 goto pc+1
9309 * when the verifier reaches exit insn the register r0 in the state list of
9310 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9311 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9312 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9314 * Since the verifier pushes the branch states as it sees them while exploring
9315 * the program the condition of walking the branch instruction for the second
9316 * time means that all states below this branch were already explored and
9317 * their final liveness markes are already propagated.
9318 * Hence when the verifier completes the search of state list in is_state_visited()
9319 * we can call this clean_live_states() function to mark all liveness states
9320 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9322 * This function also clears the registers and stack for states that !READ
9323 * to simplify state merging.
9325 * Important note here that walking the same branch instruction in the callee
9326 * doesn't meant that the states are DONE. The verifier has to compare
9329 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9330 struct bpf_verifier_state *cur)
9332 struct bpf_verifier_state_list *sl;
9335 sl = *explored_state(env, insn);
9337 if (sl->state.branches)
9339 if (sl->state.insn_idx != insn ||
9340 sl->state.curframe != cur->curframe)
9342 for (i = 0; i <= cur->curframe; i++)
9343 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9345 clean_verifier_state(env, &sl->state);
9351 /* Returns true if (rold safe implies rcur safe) */
9352 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
9353 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
9357 if (!(rold->live & REG_LIVE_READ))
9358 /* explored state didn't use this */
9361 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9363 if (rold->type == PTR_TO_STACK)
9364 /* two stack pointers are equal only if they're pointing to
9365 * the same stack frame, since fp-8 in foo != fp-8 in bar
9367 return equal && rold->frameno == rcur->frameno;
9372 if (rold->type == NOT_INIT)
9373 /* explored state can't have used this */
9375 if (rcur->type == NOT_INIT)
9377 switch (rold->type) {
9379 if (env->explore_alu_limits)
9381 if (rcur->type == SCALAR_VALUE) {
9384 /* new val must satisfy old val knowledge */
9385 return range_within(rold, rcur) &&
9386 tnum_in(rold->var_off, rcur->var_off);
9388 /* We're trying to use a pointer in place of a scalar.
9389 * Even if the scalar was unbounded, this could lead to
9390 * pointer leaks because scalars are allowed to leak
9391 * while pointers are not. We could make this safe in
9392 * special cases if root is calling us, but it's
9393 * probably not worth the hassle.
9397 case PTR_TO_MAP_VALUE:
9398 /* If the new min/max/var_off satisfy the old ones and
9399 * everything else matches, we are OK.
9400 * 'id' is not compared, since it's only used for maps with
9401 * bpf_spin_lock inside map element and in such cases if
9402 * the rest of the prog is valid for one map element then
9403 * it's valid for all map elements regardless of the key
9404 * used in bpf_map_lookup()
9406 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9407 range_within(rold, rcur) &&
9408 tnum_in(rold->var_off, rcur->var_off);
9409 case PTR_TO_MAP_VALUE_OR_NULL:
9410 /* a PTR_TO_MAP_VALUE could be safe to use as a
9411 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9412 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9413 * checked, doing so could have affected others with the same
9414 * id, and we can't check for that because we lost the id when
9415 * we converted to a PTR_TO_MAP_VALUE.
9417 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9419 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9421 /* Check our ids match any regs they're supposed to */
9422 return check_ids(rold->id, rcur->id, idmap);
9423 case PTR_TO_PACKET_META:
9425 if (rcur->type != rold->type)
9427 /* We must have at least as much range as the old ptr
9428 * did, so that any accesses which were safe before are
9429 * still safe. This is true even if old range < old off,
9430 * since someone could have accessed through (ptr - k), or
9431 * even done ptr -= k in a register, to get a safe access.
9433 if (rold->range > rcur->range)
9435 /* If the offsets don't match, we can't trust our alignment;
9436 * nor can we be sure that we won't fall out of range.
9438 if (rold->off != rcur->off)
9440 /* id relations must be preserved */
9441 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9443 /* new val must satisfy old val knowledge */
9444 return range_within(rold, rcur) &&
9445 tnum_in(rold->var_off, rcur->var_off);
9447 case CONST_PTR_TO_MAP:
9448 case PTR_TO_PACKET_END:
9449 case PTR_TO_FLOW_KEYS:
9451 case PTR_TO_SOCKET_OR_NULL:
9452 case PTR_TO_SOCK_COMMON:
9453 case PTR_TO_SOCK_COMMON_OR_NULL:
9454 case PTR_TO_TCP_SOCK:
9455 case PTR_TO_TCP_SOCK_OR_NULL:
9456 case PTR_TO_XDP_SOCK:
9457 /* Only valid matches are exact, which memcmp() above
9458 * would have accepted
9461 /* Don't know what's going on, just say it's not safe */
9465 /* Shouldn't get here; if we do, say it's not safe */
9470 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
9471 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
9475 /* walk slots of the explored stack and ignore any additional
9476 * slots in the current stack, since explored(safe) state
9479 for (i = 0; i < old->allocated_stack; i++) {
9480 spi = i / BPF_REG_SIZE;
9482 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9483 i += BPF_REG_SIZE - 1;
9484 /* explored state didn't use this */
9488 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9491 /* explored stack has more populated slots than current stack
9492 * and these slots were used
9494 if (i >= cur->allocated_stack)
9497 /* if old state was safe with misc data in the stack
9498 * it will be safe with zero-initialized stack.
9499 * The opposite is not true
9501 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9502 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9504 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9505 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9506 /* Ex: old explored (safe) state has STACK_SPILL in
9507 * this stack slot, but current has STACK_MISC ->
9508 * this verifier states are not equivalent,
9509 * return false to continue verification of this path
9512 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
9514 if (!is_spilled_reg(&old->stack[spi]))
9516 if (!regsafe(env, &old->stack[spi].spilled_ptr,
9517 &cur->stack[spi].spilled_ptr, idmap))
9518 /* when explored and current stack slot are both storing
9519 * spilled registers, check that stored pointers types
9520 * are the same as well.
9521 * Ex: explored safe path could have stored
9522 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9523 * but current path has stored:
9524 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9525 * such verifier states are not equivalent.
9526 * return false to continue verification of this path
9533 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9535 if (old->acquired_refs != cur->acquired_refs)
9537 return !memcmp(old->refs, cur->refs,
9538 sizeof(*old->refs) * old->acquired_refs);
9541 /* compare two verifier states
9543 * all states stored in state_list are known to be valid, since
9544 * verifier reached 'bpf_exit' instruction through them
9546 * this function is called when verifier exploring different branches of
9547 * execution popped from the state stack. If it sees an old state that has
9548 * more strict register state and more strict stack state then this execution
9549 * branch doesn't need to be explored further, since verifier already
9550 * concluded that more strict state leads to valid finish.
9552 * Therefore two states are equivalent if register state is more conservative
9553 * and explored stack state is more conservative than the current one.
9556 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9557 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9559 * In other words if current stack state (one being explored) has more
9560 * valid slots than old one that already passed validation, it means
9561 * the verifier can stop exploring and conclude that current state is valid too
9563 * Similarly with registers. If explored state has register type as invalid
9564 * whereas register type in current state is meaningful, it means that
9565 * the current state will reach 'bpf_exit' instruction safely
9567 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
9568 struct bpf_func_state *cur)
9572 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
9573 for (i = 0; i < MAX_BPF_REG; i++)
9574 if (!regsafe(env, &old->regs[i], &cur->regs[i],
9575 env->idmap_scratch))
9578 if (!stacksafe(env, old, cur, env->idmap_scratch))
9581 if (!refsafe(old, cur))
9587 static bool states_equal(struct bpf_verifier_env *env,
9588 struct bpf_verifier_state *old,
9589 struct bpf_verifier_state *cur)
9593 if (old->curframe != cur->curframe)
9596 /* Verification state from speculative execution simulation
9597 * must never prune a non-speculative execution one.
9599 if (old->speculative && !cur->speculative)
9602 if (old->active_spin_lock != cur->active_spin_lock)
9605 /* for states to be equal callsites have to be the same
9606 * and all frame states need to be equivalent
9608 for (i = 0; i <= old->curframe; i++) {
9609 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9611 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
9617 /* Return 0 if no propagation happened. Return negative error code if error
9618 * happened. Otherwise, return the propagated bit.
9620 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9621 struct bpf_reg_state *reg,
9622 struct bpf_reg_state *parent_reg)
9624 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9625 u8 flag = reg->live & REG_LIVE_READ;
9628 /* When comes here, read flags of PARENT_REG or REG could be any of
9629 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9630 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9632 if (parent_flag == REG_LIVE_READ64 ||
9633 /* Or if there is no read flag from REG. */
9635 /* Or if the read flag from REG is the same as PARENT_REG. */
9636 parent_flag == flag)
9639 err = mark_reg_read(env, reg, parent_reg, flag);
9646 /* A write screens off any subsequent reads; but write marks come from the
9647 * straight-line code between a state and its parent. When we arrive at an
9648 * equivalent state (jump target or such) we didn't arrive by the straight-line
9649 * code, so read marks in the state must propagate to the parent regardless
9650 * of the state's write marks. That's what 'parent == state->parent' comparison
9651 * in mark_reg_read() is for.
9653 static int propagate_liveness(struct bpf_verifier_env *env,
9654 const struct bpf_verifier_state *vstate,
9655 struct bpf_verifier_state *vparent)
9657 struct bpf_reg_state *state_reg, *parent_reg;
9658 struct bpf_func_state *state, *parent;
9659 int i, frame, err = 0;
9661 if (vparent->curframe != vstate->curframe) {
9662 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9663 vparent->curframe, vstate->curframe);
9666 /* Propagate read liveness of registers... */
9667 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9668 for (frame = 0; frame <= vstate->curframe; frame++) {
9669 parent = vparent->frame[frame];
9670 state = vstate->frame[frame];
9671 parent_reg = parent->regs;
9672 state_reg = state->regs;
9673 /* We don't need to worry about FP liveness, it's read-only */
9674 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9675 err = propagate_liveness_reg(env, &state_reg[i],
9679 if (err == REG_LIVE_READ64)
9680 mark_insn_zext(env, &parent_reg[i]);
9683 /* Propagate stack slots. */
9684 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9685 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9686 parent_reg = &parent->stack[i].spilled_ptr;
9687 state_reg = &state->stack[i].spilled_ptr;
9688 err = propagate_liveness_reg(env, state_reg,
9697 /* find precise scalars in the previous equivalent state and
9698 * propagate them into the current state
9700 static int propagate_precision(struct bpf_verifier_env *env,
9701 const struct bpf_verifier_state *old)
9703 struct bpf_reg_state *state_reg;
9704 struct bpf_func_state *state;
9707 for (fr = old->curframe; fr >= 0; fr--) {
9708 state = old->frame[fr];
9709 state_reg = state->regs;
9710 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9711 if (state_reg->type != SCALAR_VALUE ||
9712 !state_reg->precise ||
9713 !(state_reg->live & REG_LIVE_READ))
9715 if (env->log.level & BPF_LOG_LEVEL2)
9716 verbose(env, "frame %d: propagating r%d\n", fr, i);
9717 err = mark_chain_precision_frame(env, fr, i);
9722 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9723 if (!is_spilled_reg(&state->stack[i]))
9725 state_reg = &state->stack[i].spilled_ptr;
9726 if (state_reg->type != SCALAR_VALUE ||
9727 !state_reg->precise ||
9728 !(state_reg->live & REG_LIVE_READ))
9730 if (env->log.level & BPF_LOG_LEVEL2)
9731 verbose(env, "frame %d: propagating fp%d\n",
9732 fr, (-i - 1) * BPF_REG_SIZE);
9733 err = mark_chain_precision_stack_frame(env, fr, i);
9741 static bool states_maybe_looping(struct bpf_verifier_state *old,
9742 struct bpf_verifier_state *cur)
9744 struct bpf_func_state *fold, *fcur;
9745 int i, fr = cur->curframe;
9747 if (old->curframe != fr)
9750 fold = old->frame[fr];
9751 fcur = cur->frame[fr];
9752 for (i = 0; i < MAX_BPF_REG; i++)
9753 if (memcmp(&fold->regs[i], &fcur->regs[i],
9754 offsetof(struct bpf_reg_state, parent)))
9760 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9762 struct bpf_verifier_state_list *new_sl;
9763 struct bpf_verifier_state_list *sl, **pprev;
9764 struct bpf_verifier_state *cur = env->cur_state, *new;
9765 int i, j, err, states_cnt = 0;
9766 bool add_new_state = env->test_state_freq ? true : false;
9768 cur->last_insn_idx = env->prev_insn_idx;
9769 if (!env->insn_aux_data[insn_idx].prune_point)
9770 /* this 'insn_idx' instruction wasn't marked, so we will not
9771 * be doing state search here
9775 /* bpf progs typically have pruning point every 4 instructions
9776 * http://vger.kernel.org/bpfconf2019.html#session-1
9777 * Do not add new state for future pruning if the verifier hasn't seen
9778 * at least 2 jumps and at least 8 instructions.
9779 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9780 * In tests that amounts to up to 50% reduction into total verifier
9781 * memory consumption and 20% verifier time speedup.
9783 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9784 env->insn_processed - env->prev_insn_processed >= 8)
9785 add_new_state = true;
9787 pprev = explored_state(env, insn_idx);
9790 clean_live_states(env, insn_idx, cur);
9794 if (sl->state.insn_idx != insn_idx)
9796 if (sl->state.branches) {
9797 if (states_maybe_looping(&sl->state, cur) &&
9798 states_equal(env, &sl->state, cur)) {
9799 verbose_linfo(env, insn_idx, "; ");
9800 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9803 /* if the verifier is processing a loop, avoid adding new state
9804 * too often, since different loop iterations have distinct
9805 * states and may not help future pruning.
9806 * This threshold shouldn't be too low to make sure that
9807 * a loop with large bound will be rejected quickly.
9808 * The most abusive loop will be:
9810 * if r1 < 1000000 goto pc-2
9811 * 1M insn_procssed limit / 100 == 10k peak states.
9812 * This threshold shouldn't be too high either, since states
9813 * at the end of the loop are likely to be useful in pruning.
9815 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9816 env->insn_processed - env->prev_insn_processed < 100)
9817 add_new_state = false;
9820 if (states_equal(env, &sl->state, cur)) {
9822 /* reached equivalent register/stack state,
9824 * Registers read by the continuation are read by us.
9825 * If we have any write marks in env->cur_state, they
9826 * will prevent corresponding reads in the continuation
9827 * from reaching our parent (an explored_state). Our
9828 * own state will get the read marks recorded, but
9829 * they'll be immediately forgotten as we're pruning
9830 * this state and will pop a new one.
9832 err = propagate_liveness(env, &sl->state, cur);
9834 /* if previous state reached the exit with precision and
9835 * current state is equivalent to it (except precsion marks)
9836 * the precision needs to be propagated back in
9837 * the current state.
9839 err = err ? : push_jmp_history(env, cur);
9840 err = err ? : propagate_precision(env, &sl->state);
9846 /* when new state is not going to be added do not increase miss count.
9847 * Otherwise several loop iterations will remove the state
9848 * recorded earlier. The goal of these heuristics is to have
9849 * states from some iterations of the loop (some in the beginning
9850 * and some at the end) to help pruning.
9854 /* heuristic to determine whether this state is beneficial
9855 * to keep checking from state equivalence point of view.
9856 * Higher numbers increase max_states_per_insn and verification time,
9857 * but do not meaningfully decrease insn_processed.
9859 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9860 /* the state is unlikely to be useful. Remove it to
9861 * speed up verification
9864 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9865 u32 br = sl->state.branches;
9868 "BUG live_done but branches_to_explore %d\n",
9870 free_verifier_state(&sl->state, false);
9874 /* cannot free this state, since parentage chain may
9875 * walk it later. Add it for free_list instead to
9876 * be freed at the end of verification
9878 sl->next = env->free_list;
9879 env->free_list = sl;
9889 if (env->max_states_per_insn < states_cnt)
9890 env->max_states_per_insn = states_cnt;
9892 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9893 return push_jmp_history(env, cur);
9896 return push_jmp_history(env, cur);
9898 /* There were no equivalent states, remember the current one.
9899 * Technically the current state is not proven to be safe yet,
9900 * but it will either reach outer most bpf_exit (which means it's safe)
9901 * or it will be rejected. When there are no loops the verifier won't be
9902 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9903 * again on the way to bpf_exit.
9904 * When looping the sl->state.branches will be > 0 and this state
9905 * will not be considered for equivalence until branches == 0.
9907 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9910 env->total_states++;
9912 env->prev_jmps_processed = env->jmps_processed;
9913 env->prev_insn_processed = env->insn_processed;
9915 /* forget precise markings we inherited, see __mark_chain_precision */
9916 if (env->bpf_capable)
9917 mark_all_scalars_imprecise(env, cur);
9919 /* add new state to the head of linked list */
9920 new = &new_sl->state;
9921 err = copy_verifier_state(new, cur);
9923 free_verifier_state(new, false);
9927 new->insn_idx = insn_idx;
9928 WARN_ONCE(new->branches != 1,
9929 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9932 cur->first_insn_idx = insn_idx;
9933 clear_jmp_history(cur);
9934 new_sl->next = *explored_state(env, insn_idx);
9935 *explored_state(env, insn_idx) = new_sl;
9936 /* connect new state to parentage chain. Current frame needs all
9937 * registers connected. Only r6 - r9 of the callers are alive (pushed
9938 * to the stack implicitly by JITs) so in callers' frames connect just
9939 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9940 * the state of the call instruction (with WRITTEN set), and r0 comes
9941 * from callee with its full parentage chain, anyway.
9943 /* clear write marks in current state: the writes we did are not writes
9944 * our child did, so they don't screen off its reads from us.
9945 * (There are no read marks in current state, because reads always mark
9946 * their parent and current state never has children yet. Only
9947 * explored_states can get read marks.)
9949 for (j = 0; j <= cur->curframe; j++) {
9950 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9951 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9952 for (i = 0; i < BPF_REG_FP; i++)
9953 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9956 /* all stack frames are accessible from callee, clear them all */
9957 for (j = 0; j <= cur->curframe; j++) {
9958 struct bpf_func_state *frame = cur->frame[j];
9959 struct bpf_func_state *newframe = new->frame[j];
9961 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
9962 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
9963 frame->stack[i].spilled_ptr.parent =
9964 &newframe->stack[i].spilled_ptr;
9970 /* Return true if it's OK to have the same insn return a different type. */
9971 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9976 case PTR_TO_SOCKET_OR_NULL:
9977 case PTR_TO_SOCK_COMMON:
9978 case PTR_TO_SOCK_COMMON_OR_NULL:
9979 case PTR_TO_TCP_SOCK:
9980 case PTR_TO_TCP_SOCK_OR_NULL:
9981 case PTR_TO_XDP_SOCK:
9983 case PTR_TO_BTF_ID_OR_NULL:
9990 /* If an instruction was previously used with particular pointer types, then we
9991 * need to be careful to avoid cases such as the below, where it may be ok
9992 * for one branch accessing the pointer, but not ok for the other branch:
9997 * R1 = some_other_valid_ptr;
10000 * R2 = *(u32 *)(R1 + 0);
10002 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10004 return src != prev && (!reg_type_mismatch_ok(src) ||
10005 !reg_type_mismatch_ok(prev));
10008 static int do_check(struct bpf_verifier_env *env)
10010 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10011 struct bpf_verifier_state *state = env->cur_state;
10012 struct bpf_insn *insns = env->prog->insnsi;
10013 struct bpf_reg_state *regs;
10014 int insn_cnt = env->prog->len;
10015 bool do_print_state = false;
10016 int prev_insn_idx = -1;
10019 struct bpf_insn *insn;
10023 env->prev_insn_idx = prev_insn_idx;
10024 if (env->insn_idx >= insn_cnt) {
10025 verbose(env, "invalid insn idx %d insn_cnt %d\n",
10026 env->insn_idx, insn_cnt);
10030 insn = &insns[env->insn_idx];
10031 class = BPF_CLASS(insn->code);
10033 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10035 "BPF program is too large. Processed %d insn\n",
10036 env->insn_processed);
10040 err = is_state_visited(env, env->insn_idx);
10044 /* found equivalent state, can prune the search */
10045 if (env->log.level & BPF_LOG_LEVEL) {
10046 if (do_print_state)
10047 verbose(env, "\nfrom %d to %d%s: safe\n",
10048 env->prev_insn_idx, env->insn_idx,
10049 env->cur_state->speculative ?
10050 " (speculative execution)" : "");
10052 verbose(env, "%d: safe\n", env->insn_idx);
10054 goto process_bpf_exit;
10057 if (signal_pending(current))
10060 if (need_resched())
10063 if (env->log.level & BPF_LOG_LEVEL2 ||
10064 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10065 if (env->log.level & BPF_LOG_LEVEL2)
10066 verbose(env, "%d:", env->insn_idx);
10068 verbose(env, "\nfrom %d to %d%s:",
10069 env->prev_insn_idx, env->insn_idx,
10070 env->cur_state->speculative ?
10071 " (speculative execution)" : "");
10072 print_verifier_state(env, state->frame[state->curframe]);
10073 do_print_state = false;
10076 if (env->log.level & BPF_LOG_LEVEL) {
10077 const struct bpf_insn_cbs cbs = {
10078 .cb_print = verbose,
10079 .private_data = env,
10082 verbose_linfo(env, env->insn_idx, "; ");
10083 verbose(env, "%d: ", env->insn_idx);
10084 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10087 if (bpf_prog_is_dev_bound(env->prog->aux)) {
10088 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10089 env->prev_insn_idx);
10094 regs = cur_regs(env);
10095 sanitize_mark_insn_seen(env);
10096 prev_insn_idx = env->insn_idx;
10098 if (class == BPF_ALU || class == BPF_ALU64) {
10099 err = check_alu_op(env, insn);
10103 } else if (class == BPF_LDX) {
10104 enum bpf_reg_type *prev_src_type, src_reg_type;
10106 /* check for reserved fields is already done */
10108 /* check src operand */
10109 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10113 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10117 src_reg_type = regs[insn->src_reg].type;
10119 /* check that memory (src_reg + off) is readable,
10120 * the state of dst_reg will be updated by this func
10122 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10123 insn->off, BPF_SIZE(insn->code),
10124 BPF_READ, insn->dst_reg, false);
10128 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10130 if (*prev_src_type == NOT_INIT) {
10131 /* saw a valid insn
10132 * dst_reg = *(u32 *)(src_reg + off)
10133 * save type to validate intersecting paths
10135 *prev_src_type = src_reg_type;
10137 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10138 /* ABuser program is trying to use the same insn
10139 * dst_reg = *(u32*) (src_reg + off)
10140 * with different pointer types:
10141 * src_reg == ctx in one branch and
10142 * src_reg == stack|map in some other branch.
10145 verbose(env, "same insn cannot be used with different pointers\n");
10149 } else if (class == BPF_STX) {
10150 enum bpf_reg_type *prev_dst_type, dst_reg_type;
10152 if (BPF_MODE(insn->code) == BPF_XADD) {
10153 err = check_xadd(env, env->insn_idx, insn);
10160 /* check src1 operand */
10161 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10164 /* check src2 operand */
10165 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10169 dst_reg_type = regs[insn->dst_reg].type;
10171 /* check that memory (dst_reg + off) is writeable */
10172 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10173 insn->off, BPF_SIZE(insn->code),
10174 BPF_WRITE, insn->src_reg, false);
10178 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10180 if (*prev_dst_type == NOT_INIT) {
10181 *prev_dst_type = dst_reg_type;
10182 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10183 verbose(env, "same insn cannot be used with different pointers\n");
10187 } else if (class == BPF_ST) {
10188 if (BPF_MODE(insn->code) != BPF_MEM ||
10189 insn->src_reg != BPF_REG_0) {
10190 verbose(env, "BPF_ST uses reserved fields\n");
10193 /* check src operand */
10194 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10198 if (is_ctx_reg(env, insn->dst_reg)) {
10199 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10201 reg_type_str[reg_state(env, insn->dst_reg)->type]);
10205 /* check that memory (dst_reg + off) is writeable */
10206 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10207 insn->off, BPF_SIZE(insn->code),
10208 BPF_WRITE, -1, false);
10212 } else if (class == BPF_JMP || class == BPF_JMP32) {
10213 u8 opcode = BPF_OP(insn->code);
10215 env->jmps_processed++;
10216 if (opcode == BPF_CALL) {
10217 if (BPF_SRC(insn->code) != BPF_K ||
10219 (insn->src_reg != BPF_REG_0 &&
10220 insn->src_reg != BPF_PSEUDO_CALL) ||
10221 insn->dst_reg != BPF_REG_0 ||
10222 class == BPF_JMP32) {
10223 verbose(env, "BPF_CALL uses reserved fields\n");
10227 if (env->cur_state->active_spin_lock &&
10228 (insn->src_reg == BPF_PSEUDO_CALL ||
10229 insn->imm != BPF_FUNC_spin_unlock)) {
10230 verbose(env, "function calls are not allowed while holding a lock\n");
10233 if (insn->src_reg == BPF_PSEUDO_CALL)
10234 err = check_func_call(env, insn, &env->insn_idx);
10236 err = check_helper_call(env, insn->imm, env->insn_idx);
10240 } else if (opcode == BPF_JA) {
10241 if (BPF_SRC(insn->code) != BPF_K ||
10243 insn->src_reg != BPF_REG_0 ||
10244 insn->dst_reg != BPF_REG_0 ||
10245 class == BPF_JMP32) {
10246 verbose(env, "BPF_JA uses reserved fields\n");
10250 env->insn_idx += insn->off + 1;
10253 } else if (opcode == BPF_EXIT) {
10254 if (BPF_SRC(insn->code) != BPF_K ||
10256 insn->src_reg != BPF_REG_0 ||
10257 insn->dst_reg != BPF_REG_0 ||
10258 class == BPF_JMP32) {
10259 verbose(env, "BPF_EXIT uses reserved fields\n");
10263 if (env->cur_state->active_spin_lock) {
10264 verbose(env, "bpf_spin_unlock is missing\n");
10268 if (state->curframe) {
10269 /* exit from nested function */
10270 err = prepare_func_exit(env, &env->insn_idx);
10273 do_print_state = true;
10277 err = check_reference_leak(env);
10281 err = check_return_code(env);
10285 update_branch_counts(env, env->cur_state);
10286 err = pop_stack(env, &prev_insn_idx,
10287 &env->insn_idx, pop_log);
10289 if (err != -ENOENT)
10293 do_print_state = true;
10297 err = check_cond_jmp_op(env, insn, &env->insn_idx);
10301 } else if (class == BPF_LD) {
10302 u8 mode = BPF_MODE(insn->code);
10304 if (mode == BPF_ABS || mode == BPF_IND) {
10305 err = check_ld_abs(env, insn);
10309 } else if (mode == BPF_IMM) {
10310 err = check_ld_imm(env, insn);
10315 sanitize_mark_insn_seen(env);
10317 verbose(env, "invalid BPF_LD mode\n");
10321 verbose(env, "unknown insn class %d\n", class);
10331 /* replace pseudo btf_id with kernel symbol address */
10332 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10333 struct bpf_insn *insn,
10334 struct bpf_insn_aux_data *aux)
10336 const struct btf_var_secinfo *vsi;
10337 const struct btf_type *datasec;
10338 const struct btf_type *t;
10339 const char *sym_name;
10340 bool percpu = false;
10341 u32 type, id = insn->imm;
10346 if (!btf_vmlinux) {
10347 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10351 if (insn[1].imm != 0) {
10352 verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
10356 t = btf_type_by_id(btf_vmlinux, id);
10358 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10362 if (!btf_type_is_var(t)) {
10363 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
10368 sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
10369 addr = kallsyms_lookup_name(sym_name);
10371 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10376 datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
10378 if (datasec_id > 0) {
10379 datasec = btf_type_by_id(btf_vmlinux, datasec_id);
10380 for_each_vsi(i, datasec, vsi) {
10381 if (vsi->type == id) {
10388 insn[0].imm = (u32)addr;
10389 insn[1].imm = addr >> 32;
10392 t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
10394 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10395 aux->btf_var.btf_id = type;
10396 } else if (!btf_type_is_struct(t)) {
10397 const struct btf_type *ret;
10401 /* resolve the type size of ksym. */
10402 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
10404 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
10405 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10406 tname, PTR_ERR(ret));
10409 aux->btf_var.reg_type = PTR_TO_MEM;
10410 aux->btf_var.mem_size = tsize;
10412 aux->btf_var.reg_type = PTR_TO_BTF_ID;
10413 aux->btf_var.btf_id = type;
10418 static int check_map_prealloc(struct bpf_map *map)
10420 return (map->map_type != BPF_MAP_TYPE_HASH &&
10421 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10422 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10423 !(map->map_flags & BPF_F_NO_PREALLOC);
10426 static bool is_tracing_prog_type(enum bpf_prog_type type)
10429 case BPF_PROG_TYPE_KPROBE:
10430 case BPF_PROG_TYPE_TRACEPOINT:
10431 case BPF_PROG_TYPE_PERF_EVENT:
10432 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10439 static bool is_preallocated_map(struct bpf_map *map)
10441 if (!check_map_prealloc(map))
10443 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10448 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10449 struct bpf_map *map,
10450 struct bpf_prog *prog)
10453 enum bpf_prog_type prog_type = resolve_prog_type(prog);
10455 * Validate that trace type programs use preallocated hash maps.
10457 * For programs attached to PERF events this is mandatory as the
10458 * perf NMI can hit any arbitrary code sequence.
10460 * All other trace types using preallocated hash maps are unsafe as
10461 * well because tracepoint or kprobes can be inside locked regions
10462 * of the memory allocator or at a place where a recursion into the
10463 * memory allocator would see inconsistent state.
10465 * On RT enabled kernels run-time allocation of all trace type
10466 * programs is strictly prohibited due to lock type constraints. On
10467 * !RT kernels it is allowed for backwards compatibility reasons for
10468 * now, but warnings are emitted so developers are made aware of
10469 * the unsafety and can fix their programs before this is enforced.
10471 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10472 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10473 verbose(env, "perf_event programs can only use preallocated hash map\n");
10476 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10477 verbose(env, "trace type programs can only use preallocated hash map\n");
10480 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10481 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10484 if ((is_tracing_prog_type(prog_type) ||
10485 prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
10486 map_value_has_spin_lock(map)) {
10487 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10491 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10492 !bpf_offload_prog_map_match(prog, map)) {
10493 verbose(env, "offload device mismatch between prog and map\n");
10497 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10498 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10502 if (prog->aux->sleepable)
10503 switch (map->map_type) {
10504 case BPF_MAP_TYPE_HASH:
10505 case BPF_MAP_TYPE_LRU_HASH:
10506 case BPF_MAP_TYPE_ARRAY:
10507 if (!is_preallocated_map(map)) {
10509 "Sleepable programs can only use preallocated hash maps\n");
10515 "Sleepable programs can only use array and hash maps\n");
10522 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10524 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10525 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10528 /* find and rewrite pseudo imm in ld_imm64 instructions:
10530 * 1. if it accesses map FD, replace it with actual map pointer.
10531 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10533 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10535 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10537 struct bpf_insn *insn = env->prog->insnsi;
10538 int insn_cnt = env->prog->len;
10541 err = bpf_prog_calc_tag(env->prog);
10545 for (i = 0; i < insn_cnt; i++, insn++) {
10546 if (BPF_CLASS(insn->code) == BPF_LDX &&
10547 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10548 verbose(env, "BPF_LDX uses reserved fields\n");
10552 if (BPF_CLASS(insn->code) == BPF_STX &&
10553 ((BPF_MODE(insn->code) != BPF_MEM &&
10554 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
10555 verbose(env, "BPF_STX uses reserved fields\n");
10559 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10560 struct bpf_insn_aux_data *aux;
10561 struct bpf_map *map;
10565 if (i == insn_cnt - 1 || insn[1].code != 0 ||
10566 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10567 insn[1].off != 0) {
10568 verbose(env, "invalid bpf_ld_imm64 insn\n");
10572 if (insn[0].src_reg == 0)
10573 /* valid generic load 64-bit imm */
10576 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10577 aux = &env->insn_aux_data[i];
10578 err = check_pseudo_btf_id(env, insn, aux);
10584 /* In final convert_pseudo_ld_imm64() step, this is
10585 * converted into regular 64-bit imm load insn.
10587 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10588 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10589 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10590 insn[1].imm != 0)) {
10592 "unrecognized bpf_ld_imm64 insn\n");
10596 f = fdget(insn[0].imm);
10597 map = __bpf_map_get(f);
10599 verbose(env, "fd %d is not pointing to valid bpf_map\n",
10601 return PTR_ERR(map);
10604 err = check_map_prog_compatibility(env, map, env->prog);
10610 aux = &env->insn_aux_data[i];
10611 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10612 addr = (unsigned long)map;
10614 u32 off = insn[1].imm;
10616 if (off >= BPF_MAX_VAR_OFF) {
10617 verbose(env, "direct value offset of %u is not allowed\n", off);
10622 if (!map->ops->map_direct_value_addr) {
10623 verbose(env, "no direct value access support for this map type\n");
10628 err = map->ops->map_direct_value_addr(map, &addr, off);
10630 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10631 map->value_size, off);
10636 aux->map_off = off;
10640 insn[0].imm = (u32)addr;
10641 insn[1].imm = addr >> 32;
10643 /* check whether we recorded this map already */
10644 for (j = 0; j < env->used_map_cnt; j++) {
10645 if (env->used_maps[j] == map) {
10646 aux->map_index = j;
10652 if (env->used_map_cnt >= MAX_USED_MAPS) {
10657 /* hold the map. If the program is rejected by verifier,
10658 * the map will be released by release_maps() or it
10659 * will be used by the valid program until it's unloaded
10660 * and all maps are released in free_used_maps()
10664 aux->map_index = env->used_map_cnt;
10665 env->used_maps[env->used_map_cnt++] = map;
10667 if (bpf_map_is_cgroup_storage(map) &&
10668 bpf_cgroup_storage_assign(env->prog->aux, map)) {
10669 verbose(env, "only one cgroup storage of each type is allowed\n");
10681 /* Basic sanity check before we invest more work here. */
10682 if (!bpf_opcode_in_insntable(insn->code)) {
10683 verbose(env, "unknown opcode %02x\n", insn->code);
10688 /* now all pseudo BPF_LD_IMM64 instructions load valid
10689 * 'struct bpf_map *' into a register instead of user map_fd.
10690 * These pointers will be used later by verifier to validate map access.
10695 /* drop refcnt of maps used by the rejected program */
10696 static void release_maps(struct bpf_verifier_env *env)
10698 __bpf_free_used_maps(env->prog->aux, env->used_maps,
10699 env->used_map_cnt);
10702 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
10703 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10705 struct bpf_insn *insn = env->prog->insnsi;
10706 int insn_cnt = env->prog->len;
10709 for (i = 0; i < insn_cnt; i++, insn++)
10710 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10714 /* single env->prog->insni[off] instruction was replaced with the range
10715 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10716 * [0, off) and [off, end) to new locations, so the patched range stays zero
10718 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
10719 struct bpf_insn_aux_data *new_data,
10720 struct bpf_prog *new_prog, u32 off, u32 cnt)
10722 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
10723 struct bpf_insn *insn = new_prog->insnsi;
10724 u32 old_seen = old_data[off].seen;
10728 /* aux info at OFF always needs adjustment, no matter fast path
10729 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10730 * original insn at old prog.
10732 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10736 prog_len = new_prog->len;
10738 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10739 memcpy(new_data + off + cnt - 1, old_data + off,
10740 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10741 for (i = off; i < off + cnt - 1; i++) {
10742 /* Expand insni[off]'s seen count to the patched range. */
10743 new_data[i].seen = old_seen;
10744 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10746 env->insn_aux_data = new_data;
10750 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10756 /* NOTE: fake 'exit' subprog should be updated as well. */
10757 for (i = 0; i <= env->subprog_cnt; i++) {
10758 if (env->subprog_info[i].start <= off)
10760 env->subprog_info[i].start += len - 1;
10764 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
10766 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10767 int i, sz = prog->aux->size_poke_tab;
10768 struct bpf_jit_poke_descriptor *desc;
10770 for (i = 0; i < sz; i++) {
10772 if (desc->insn_idx <= off)
10774 desc->insn_idx += len - 1;
10778 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10779 const struct bpf_insn *patch, u32 len)
10781 struct bpf_prog *new_prog;
10782 struct bpf_insn_aux_data *new_data = NULL;
10785 new_data = vzalloc(array_size(env->prog->len + len - 1,
10786 sizeof(struct bpf_insn_aux_data)));
10791 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10792 if (IS_ERR(new_prog)) {
10793 if (PTR_ERR(new_prog) == -ERANGE)
10795 "insn %d cannot be patched due to 16-bit range\n",
10796 env->insn_aux_data[off].orig_idx);
10800 adjust_insn_aux_data(env, new_data, new_prog, off, len);
10801 adjust_subprog_starts(env, off, len);
10802 adjust_poke_descs(new_prog, off, len);
10806 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10811 /* find first prog starting at or after off (first to remove) */
10812 for (i = 0; i < env->subprog_cnt; i++)
10813 if (env->subprog_info[i].start >= off)
10815 /* find first prog starting at or after off + cnt (first to stay) */
10816 for (j = i; j < env->subprog_cnt; j++)
10817 if (env->subprog_info[j].start >= off + cnt)
10819 /* if j doesn't start exactly at off + cnt, we are just removing
10820 * the front of previous prog
10822 if (env->subprog_info[j].start != off + cnt)
10826 struct bpf_prog_aux *aux = env->prog->aux;
10829 /* move fake 'exit' subprog as well */
10830 move = env->subprog_cnt + 1 - j;
10832 memmove(env->subprog_info + i,
10833 env->subprog_info + j,
10834 sizeof(*env->subprog_info) * move);
10835 env->subprog_cnt -= j - i;
10837 /* remove func_info */
10838 if (aux->func_info) {
10839 move = aux->func_info_cnt - j;
10841 memmove(aux->func_info + i,
10842 aux->func_info + j,
10843 sizeof(*aux->func_info) * move);
10844 aux->func_info_cnt -= j - i;
10845 /* func_info->insn_off is set after all code rewrites,
10846 * in adjust_btf_func() - no need to adjust
10850 /* convert i from "first prog to remove" to "first to adjust" */
10851 if (env->subprog_info[i].start == off)
10855 /* update fake 'exit' subprog as well */
10856 for (; i <= env->subprog_cnt; i++)
10857 env->subprog_info[i].start -= cnt;
10862 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10865 struct bpf_prog *prog = env->prog;
10866 u32 i, l_off, l_cnt, nr_linfo;
10867 struct bpf_line_info *linfo;
10869 nr_linfo = prog->aux->nr_linfo;
10873 linfo = prog->aux->linfo;
10875 /* find first line info to remove, count lines to be removed */
10876 for (i = 0; i < nr_linfo; i++)
10877 if (linfo[i].insn_off >= off)
10882 for (; i < nr_linfo; i++)
10883 if (linfo[i].insn_off < off + cnt)
10888 /* First live insn doesn't match first live linfo, it needs to "inherit"
10889 * last removed linfo. prog is already modified, so prog->len == off
10890 * means no live instructions after (tail of the program was removed).
10892 if (prog->len != off && l_cnt &&
10893 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10895 linfo[--i].insn_off = off + cnt;
10898 /* remove the line info which refer to the removed instructions */
10900 memmove(linfo + l_off, linfo + i,
10901 sizeof(*linfo) * (nr_linfo - i));
10903 prog->aux->nr_linfo -= l_cnt;
10904 nr_linfo = prog->aux->nr_linfo;
10907 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10908 for (i = l_off; i < nr_linfo; i++)
10909 linfo[i].insn_off -= cnt;
10911 /* fix up all subprogs (incl. 'exit') which start >= off */
10912 for (i = 0; i <= env->subprog_cnt; i++)
10913 if (env->subprog_info[i].linfo_idx > l_off) {
10914 /* program may have started in the removed region but
10915 * may not be fully removed
10917 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10918 env->subprog_info[i].linfo_idx -= l_cnt;
10920 env->subprog_info[i].linfo_idx = l_off;
10926 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10928 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10929 unsigned int orig_prog_len = env->prog->len;
10932 if (bpf_prog_is_dev_bound(env->prog->aux))
10933 bpf_prog_offload_remove_insns(env, off, cnt);
10935 err = bpf_remove_insns(env->prog, off, cnt);
10939 err = adjust_subprog_starts_after_remove(env, off, cnt);
10943 err = bpf_adj_linfo_after_remove(env, off, cnt);
10947 memmove(aux_data + off, aux_data + off + cnt,
10948 sizeof(*aux_data) * (orig_prog_len - off - cnt));
10953 /* The verifier does more data flow analysis than llvm and will not
10954 * explore branches that are dead at run time. Malicious programs can
10955 * have dead code too. Therefore replace all dead at-run-time code
10958 * Just nops are not optimal, e.g. if they would sit at the end of the
10959 * program and through another bug we would manage to jump there, then
10960 * we'd execute beyond program memory otherwise. Returning exception
10961 * code also wouldn't work since we can have subprogs where the dead
10962 * code could be located.
10964 static void sanitize_dead_code(struct bpf_verifier_env *env)
10966 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10967 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
10968 struct bpf_insn *insn = env->prog->insnsi;
10969 const int insn_cnt = env->prog->len;
10972 for (i = 0; i < insn_cnt; i++) {
10973 if (aux_data[i].seen)
10975 memcpy(insn + i, &trap, sizeof(trap));
10976 aux_data[i].zext_dst = false;
10980 static bool insn_is_cond_jump(u8 code)
10984 if (BPF_CLASS(code) == BPF_JMP32)
10987 if (BPF_CLASS(code) != BPF_JMP)
10991 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10994 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10996 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10997 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10998 struct bpf_insn *insn = env->prog->insnsi;
10999 const int insn_cnt = env->prog->len;
11002 for (i = 0; i < insn_cnt; i++, insn++) {
11003 if (!insn_is_cond_jump(insn->code))
11006 if (!aux_data[i + 1].seen)
11007 ja.off = insn->off;
11008 else if (!aux_data[i + 1 + insn->off].seen)
11013 if (bpf_prog_is_dev_bound(env->prog->aux))
11014 bpf_prog_offload_replace_insn(env, i, &ja);
11016 memcpy(insn, &ja, sizeof(ja));
11020 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11022 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11023 int insn_cnt = env->prog->len;
11026 for (i = 0; i < insn_cnt; i++) {
11030 while (i + j < insn_cnt && !aux_data[i + j].seen)
11035 err = verifier_remove_insns(env, i, j);
11038 insn_cnt = env->prog->len;
11044 static int opt_remove_nops(struct bpf_verifier_env *env)
11046 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11047 struct bpf_insn *insn = env->prog->insnsi;
11048 int insn_cnt = env->prog->len;
11051 for (i = 0; i < insn_cnt; i++) {
11052 if (memcmp(&insn[i], &ja, sizeof(ja)))
11055 err = verifier_remove_insns(env, i, 1);
11065 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11066 const union bpf_attr *attr)
11068 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
11069 struct bpf_insn_aux_data *aux = env->insn_aux_data;
11070 int i, patch_len, delta = 0, len = env->prog->len;
11071 struct bpf_insn *insns = env->prog->insnsi;
11072 struct bpf_prog *new_prog;
11075 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11076 zext_patch[1] = BPF_ZEXT_REG(0);
11077 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11078 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11079 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11080 for (i = 0; i < len; i++) {
11081 int adj_idx = i + delta;
11082 struct bpf_insn insn;
11084 insn = insns[adj_idx];
11085 if (!aux[adj_idx].zext_dst) {
11093 class = BPF_CLASS(code);
11094 if (insn_no_def(&insn))
11097 /* NOTE: arg "reg" (the fourth one) is only used for
11098 * BPF_STX which has been ruled out in above
11099 * check, it is safe to pass NULL here.
11101 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
11102 if (class == BPF_LD &&
11103 BPF_MODE(code) == BPF_IMM)
11108 /* ctx load could be transformed into wider load. */
11109 if (class == BPF_LDX &&
11110 aux[adj_idx].ptr_type == PTR_TO_CTX)
11113 imm_rnd = get_random_int();
11114 rnd_hi32_patch[0] = insn;
11115 rnd_hi32_patch[1].imm = imm_rnd;
11116 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
11117 patch = rnd_hi32_patch;
11119 goto apply_patch_buffer;
11122 if (!bpf_jit_needs_zext())
11125 zext_patch[0] = insn;
11126 zext_patch[1].dst_reg = insn.dst_reg;
11127 zext_patch[1].src_reg = insn.dst_reg;
11128 patch = zext_patch;
11130 apply_patch_buffer:
11131 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11134 env->prog = new_prog;
11135 insns = new_prog->insnsi;
11136 aux = env->insn_aux_data;
11137 delta += patch_len - 1;
11143 /* convert load instructions that access fields of a context type into a
11144 * sequence of instructions that access fields of the underlying structure:
11145 * struct __sk_buff -> struct sk_buff
11146 * struct bpf_sock_ops -> struct sock
11148 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11150 const struct bpf_verifier_ops *ops = env->ops;
11151 int i, cnt, size, ctx_field_size, delta = 0;
11152 const int insn_cnt = env->prog->len;
11153 struct bpf_insn insn_buf[16], *insn;
11154 u32 target_size, size_default, off;
11155 struct bpf_prog *new_prog;
11156 enum bpf_access_type type;
11157 bool is_narrower_load;
11159 if (ops->gen_prologue || env->seen_direct_write) {
11160 if (!ops->gen_prologue) {
11161 verbose(env, "bpf verifier is misconfigured\n");
11164 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11166 if (cnt >= ARRAY_SIZE(insn_buf)) {
11167 verbose(env, "bpf verifier is misconfigured\n");
11170 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11174 env->prog = new_prog;
11179 if (bpf_prog_is_dev_bound(env->prog->aux))
11182 insn = env->prog->insnsi + delta;
11184 for (i = 0; i < insn_cnt; i++, insn++) {
11185 bpf_convert_ctx_access_t convert_ctx_access;
11188 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11189 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11190 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11191 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
11194 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11195 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11196 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11197 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
11198 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
11199 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
11200 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
11201 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
11203 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
11208 if (type == BPF_WRITE &&
11209 env->insn_aux_data[i + delta].sanitize_stack_spill) {
11210 struct bpf_insn patch[] = {
11215 cnt = ARRAY_SIZE(patch);
11216 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11221 env->prog = new_prog;
11222 insn = new_prog->insnsi + i + delta;
11229 switch (env->insn_aux_data[i + delta].ptr_type) {
11231 if (!ops->convert_ctx_access)
11233 convert_ctx_access = ops->convert_ctx_access;
11235 case PTR_TO_SOCKET:
11236 case PTR_TO_SOCK_COMMON:
11237 convert_ctx_access = bpf_sock_convert_ctx_access;
11239 case PTR_TO_TCP_SOCK:
11240 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11242 case PTR_TO_XDP_SOCK:
11243 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11245 case PTR_TO_BTF_ID:
11246 if (type == BPF_READ) {
11247 insn->code = BPF_LDX | BPF_PROBE_MEM |
11248 BPF_SIZE((insn)->code);
11249 env->prog->aux->num_exentries++;
11250 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11251 verbose(env, "Writes through BTF pointers are not allowed\n");
11259 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11260 size = BPF_LDST_BYTES(insn);
11262 /* If the read access is a narrower load of the field,
11263 * convert to a 4/8-byte load, to minimum program type specific
11264 * convert_ctx_access changes. If conversion is successful,
11265 * we will apply proper mask to the result.
11267 is_narrower_load = size < ctx_field_size;
11268 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11270 if (is_narrower_load) {
11273 if (type == BPF_WRITE) {
11274 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11279 if (ctx_field_size == 4)
11281 else if (ctx_field_size == 8)
11282 size_code = BPF_DW;
11284 insn->off = off & ~(size_default - 1);
11285 insn->code = BPF_LDX | BPF_MEM | size_code;
11289 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11291 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11292 (ctx_field_size && !target_size)) {
11293 verbose(env, "bpf verifier is misconfigured\n");
11297 if (is_narrower_load && size < target_size) {
11298 u8 shift = bpf_ctx_narrow_access_offset(
11299 off, size, size_default) * 8;
11300 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
11301 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
11304 if (ctx_field_size <= 4) {
11306 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11309 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11310 (1 << size * 8) - 1);
11313 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11316 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11317 (1ULL << size * 8) - 1);
11321 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11327 /* keep walking new program and skip insns we just inserted */
11328 env->prog = new_prog;
11329 insn = new_prog->insnsi + i + delta;
11335 static int jit_subprogs(struct bpf_verifier_env *env)
11337 struct bpf_prog *prog = env->prog, **func, *tmp;
11338 int i, j, subprog_start, subprog_end = 0, len, subprog;
11339 struct bpf_map *map_ptr;
11340 struct bpf_insn *insn;
11341 void *old_bpf_func;
11342 int err, num_exentries;
11344 if (env->subprog_cnt <= 1)
11347 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11348 if (insn->code != (BPF_JMP | BPF_CALL) ||
11349 insn->src_reg != BPF_PSEUDO_CALL)
11351 /* Upon error here we cannot fall back to interpreter but
11352 * need a hard reject of the program. Thus -EFAULT is
11353 * propagated in any case.
11355 subprog = find_subprog(env, i + insn->imm + 1);
11357 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11358 i + insn->imm + 1);
11361 /* temporarily remember subprog id inside insn instead of
11362 * aux_data, since next loop will split up all insns into funcs
11364 insn->off = subprog;
11365 /* remember original imm in case JIT fails and fallback
11366 * to interpreter will be needed
11368 env->insn_aux_data[i].call_imm = insn->imm;
11369 /* point imm to __bpf_call_base+1 from JITs point of view */
11373 err = bpf_prog_alloc_jited_linfo(prog);
11375 goto out_undo_insn;
11378 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11380 goto out_undo_insn;
11382 for (i = 0; i < env->subprog_cnt; i++) {
11383 subprog_start = subprog_end;
11384 subprog_end = env->subprog_info[i + 1].start;
11386 len = subprog_end - subprog_start;
11387 /* BPF_PROG_RUN doesn't call subprogs directly,
11388 * hence main prog stats include the runtime of subprogs.
11389 * subprogs don't have IDs and not reachable via prog_get_next_id
11390 * func[i]->aux->stats will never be accessed and stays NULL
11392 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11395 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11396 len * sizeof(struct bpf_insn));
11397 func[i]->type = prog->type;
11398 func[i]->len = len;
11399 if (bpf_prog_calc_tag(func[i]))
11401 func[i]->is_func = 1;
11402 func[i]->aux->func_idx = i;
11403 /* Below members will be freed only at prog->aux */
11404 func[i]->aux->btf = prog->aux->btf;
11405 func[i]->aux->func_info = prog->aux->func_info;
11406 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
11407 func[i]->aux->poke_tab = prog->aux->poke_tab;
11408 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
11410 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11411 struct bpf_jit_poke_descriptor *poke;
11413 poke = &prog->aux->poke_tab[j];
11414 if (poke->insn_idx < subprog_end &&
11415 poke->insn_idx >= subprog_start)
11416 poke->aux = func[i]->aux;
11419 func[i]->aux->name[0] = 'F';
11420 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11421 func[i]->jit_requested = 1;
11422 func[i]->aux->linfo = prog->aux->linfo;
11423 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11424 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11425 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11427 insn = func[i]->insnsi;
11428 for (j = 0; j < func[i]->len; j++, insn++) {
11429 if (BPF_CLASS(insn->code) == BPF_LDX &&
11430 BPF_MODE(insn->code) == BPF_PROBE_MEM)
11433 func[i]->aux->num_exentries = num_exentries;
11434 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11435 func[i] = bpf_int_jit_compile(func[i]);
11436 if (!func[i]->jited) {
11443 /* at this point all bpf functions were successfully JITed
11444 * now populate all bpf_calls with correct addresses and
11445 * run last pass of JIT
11447 for (i = 0; i < env->subprog_cnt; i++) {
11448 insn = func[i]->insnsi;
11449 for (j = 0; j < func[i]->len; j++, insn++) {
11450 if (insn->code != (BPF_JMP | BPF_CALL) ||
11451 insn->src_reg != BPF_PSEUDO_CALL)
11453 subprog = insn->off;
11454 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11458 /* we use the aux data to keep a list of the start addresses
11459 * of the JITed images for each function in the program
11461 * for some architectures, such as powerpc64, the imm field
11462 * might not be large enough to hold the offset of the start
11463 * address of the callee's JITed image from __bpf_call_base
11465 * in such cases, we can lookup the start address of a callee
11466 * by using its subprog id, available from the off field of
11467 * the call instruction, as an index for this list
11469 func[i]->aux->func = func;
11470 func[i]->aux->func_cnt = env->subprog_cnt;
11472 for (i = 0; i < env->subprog_cnt; i++) {
11473 old_bpf_func = func[i]->bpf_func;
11474 tmp = bpf_int_jit_compile(func[i]);
11475 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11476 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11483 /* finally lock prog and jit images for all functions and
11484 * populate kallsysm
11486 for (i = 0; i < env->subprog_cnt; i++) {
11487 bpf_prog_lock_ro(func[i]);
11488 bpf_prog_kallsyms_add(func[i]);
11491 /* Last step: make now unused interpreter insns from main
11492 * prog consistent for later dump requests, so they can
11493 * later look the same as if they were interpreted only.
11495 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11496 if (insn->code != (BPF_JMP | BPF_CALL) ||
11497 insn->src_reg != BPF_PSEUDO_CALL)
11499 insn->off = env->insn_aux_data[i].call_imm;
11500 subprog = find_subprog(env, i + insn->off + 1);
11501 insn->imm = subprog;
11505 prog->bpf_func = func[0]->bpf_func;
11506 prog->aux->func = func;
11507 prog->aux->func_cnt = env->subprog_cnt;
11508 bpf_prog_free_unused_jited_linfo(prog);
11511 /* We failed JIT'ing, so at this point we need to unregister poke
11512 * descriptors from subprogs, so that kernel is not attempting to
11513 * patch it anymore as we're freeing the subprog JIT memory.
11515 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11516 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11517 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11519 /* At this point we're guaranteed that poke descriptors are not
11520 * live anymore. We can just unlink its descriptor table as it's
11521 * released with the main prog.
11523 for (i = 0; i < env->subprog_cnt; i++) {
11526 func[i]->aux->poke_tab = NULL;
11527 bpf_jit_free(func[i]);
11531 /* cleanup main prog to be interpreted */
11532 prog->jit_requested = 0;
11533 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11534 if (insn->code != (BPF_JMP | BPF_CALL) ||
11535 insn->src_reg != BPF_PSEUDO_CALL)
11538 insn->imm = env->insn_aux_data[i].call_imm;
11540 bpf_prog_free_jited_linfo(prog);
11544 static int fixup_call_args(struct bpf_verifier_env *env)
11546 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11547 struct bpf_prog *prog = env->prog;
11548 struct bpf_insn *insn = prog->insnsi;
11553 if (env->prog->jit_requested &&
11554 !bpf_prog_is_dev_bound(env->prog->aux)) {
11555 err = jit_subprogs(env);
11558 if (err == -EFAULT)
11561 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11562 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11563 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11564 * have to be rejected, since interpreter doesn't support them yet.
11566 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11569 for (i = 0; i < prog->len; i++, insn++) {
11570 if (insn->code != (BPF_JMP | BPF_CALL) ||
11571 insn->src_reg != BPF_PSEUDO_CALL)
11573 depth = get_callee_stack_depth(env, insn, i);
11576 bpf_patch_call_args(insn, depth);
11583 /* fixup insn->imm field of bpf_call instructions
11584 * and inline eligible helpers as explicit sequence of BPF instructions
11586 * this function is called after eBPF program passed verification
11588 static int fixup_bpf_calls(struct bpf_verifier_env *env)
11590 struct bpf_prog *prog = env->prog;
11591 bool expect_blinding = bpf_jit_blinding_enabled(prog);
11592 struct bpf_insn *insn = prog->insnsi;
11593 const struct bpf_func_proto *fn;
11594 const int insn_cnt = prog->len;
11595 const struct bpf_map_ops *ops;
11596 struct bpf_insn_aux_data *aux;
11597 struct bpf_insn insn_buf[16];
11598 struct bpf_prog *new_prog;
11599 struct bpf_map *map_ptr;
11600 int i, ret, cnt, delta = 0;
11602 for (i = 0; i < insn_cnt; i++, insn++) {
11603 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11604 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11605 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11606 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11607 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11608 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11609 struct bpf_insn *patchlet;
11610 struct bpf_insn chk_and_div[] = {
11611 /* [R,W]x div 0 -> 0 */
11612 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11613 BPF_JNE | BPF_K, insn->src_reg,
11615 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11616 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11619 struct bpf_insn chk_and_mod[] = {
11620 /* [R,W]x mod 0 -> [R,W]x */
11621 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11622 BPF_JEQ | BPF_K, insn->src_reg,
11623 0, 1 + (is64 ? 0 : 1), 0),
11625 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11626 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11629 patchlet = isdiv ? chk_and_div : chk_and_mod;
11630 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11631 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11633 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11638 env->prog = prog = new_prog;
11639 insn = new_prog->insnsi + i + delta;
11643 if (BPF_CLASS(insn->code) == BPF_LD &&
11644 (BPF_MODE(insn->code) == BPF_ABS ||
11645 BPF_MODE(insn->code) == BPF_IND)) {
11646 cnt = env->ops->gen_ld_abs(insn, insn_buf);
11647 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11648 verbose(env, "bpf verifier is misconfigured\n");
11652 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11657 env->prog = prog = new_prog;
11658 insn = new_prog->insnsi + i + delta;
11662 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11663 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11664 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11665 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11666 struct bpf_insn insn_buf[16];
11667 struct bpf_insn *patch = &insn_buf[0];
11668 bool issrc, isneg, isimm;
11671 aux = &env->insn_aux_data[i + delta];
11672 if (!aux->alu_state ||
11673 aux->alu_state == BPF_ALU_NON_POINTER)
11676 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11677 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11678 BPF_ALU_SANITIZE_SRC;
11679 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
11681 off_reg = issrc ? insn->src_reg : insn->dst_reg;
11683 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11686 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11687 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11688 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11689 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11690 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11691 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11692 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
11695 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
11696 insn->src_reg = BPF_REG_AX;
11698 insn->code = insn->code == code_add ?
11699 code_sub : code_add;
11701 if (issrc && isneg && !isimm)
11702 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11703 cnt = patch - insn_buf;
11705 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11710 env->prog = prog = new_prog;
11711 insn = new_prog->insnsi + i + delta;
11715 if (insn->code != (BPF_JMP | BPF_CALL))
11717 if (insn->src_reg == BPF_PSEUDO_CALL)
11720 if (insn->imm == BPF_FUNC_get_route_realm)
11721 prog->dst_needed = 1;
11722 if (insn->imm == BPF_FUNC_get_prandom_u32)
11723 bpf_user_rnd_init_once();
11724 if (insn->imm == BPF_FUNC_override_return)
11725 prog->kprobe_override = 1;
11726 if (insn->imm == BPF_FUNC_tail_call) {
11727 /* If we tail call into other programs, we
11728 * cannot make any assumptions since they can
11729 * be replaced dynamically during runtime in
11730 * the program array.
11732 prog->cb_access = 1;
11733 if (!allow_tail_call_in_subprogs(env))
11734 prog->aux->stack_depth = MAX_BPF_STACK;
11735 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11737 /* mark bpf_tail_call as different opcode to avoid
11738 * conditional branch in the interpeter for every normal
11739 * call and to prevent accidental JITing by JIT compiler
11740 * that doesn't support bpf_tail_call yet
11743 insn->code = BPF_JMP | BPF_TAIL_CALL;
11745 aux = &env->insn_aux_data[i + delta];
11746 if (env->bpf_capable && !expect_blinding &&
11747 prog->jit_requested &&
11748 !bpf_map_key_poisoned(aux) &&
11749 !bpf_map_ptr_poisoned(aux) &&
11750 !bpf_map_ptr_unpriv(aux)) {
11751 struct bpf_jit_poke_descriptor desc = {
11752 .reason = BPF_POKE_REASON_TAIL_CALL,
11753 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11754 .tail_call.key = bpf_map_key_immediate(aux),
11755 .insn_idx = i + delta,
11758 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11760 verbose(env, "adding tail call poke descriptor failed\n");
11764 insn->imm = ret + 1;
11768 if (!bpf_map_ptr_unpriv(aux))
11771 /* instead of changing every JIT dealing with tail_call
11772 * emit two extra insns:
11773 * if (index >= max_entries) goto out;
11774 * index &= array->index_mask;
11775 * to avoid out-of-bounds cpu speculation
11777 if (bpf_map_ptr_poisoned(aux)) {
11778 verbose(env, "tail_call abusing map_ptr\n");
11782 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11783 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11784 map_ptr->max_entries, 2);
11785 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11786 container_of(map_ptr,
11789 insn_buf[2] = *insn;
11791 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11796 env->prog = prog = new_prog;
11797 insn = new_prog->insnsi + i + delta;
11801 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11802 * and other inlining handlers are currently limited to 64 bit
11805 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11806 (insn->imm == BPF_FUNC_map_lookup_elem ||
11807 insn->imm == BPF_FUNC_map_update_elem ||
11808 insn->imm == BPF_FUNC_map_delete_elem ||
11809 insn->imm == BPF_FUNC_map_push_elem ||
11810 insn->imm == BPF_FUNC_map_pop_elem ||
11811 insn->imm == BPF_FUNC_map_peek_elem)) {
11812 aux = &env->insn_aux_data[i + delta];
11813 if (bpf_map_ptr_poisoned(aux))
11814 goto patch_call_imm;
11816 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11817 ops = map_ptr->ops;
11818 if (insn->imm == BPF_FUNC_map_lookup_elem &&
11819 ops->map_gen_lookup) {
11820 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11821 if (cnt == -EOPNOTSUPP)
11822 goto patch_map_ops_generic;
11823 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11824 verbose(env, "bpf verifier is misconfigured\n");
11828 new_prog = bpf_patch_insn_data(env, i + delta,
11834 env->prog = prog = new_prog;
11835 insn = new_prog->insnsi + i + delta;
11839 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11840 (void *(*)(struct bpf_map *map, void *key))NULL));
11841 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11842 (int (*)(struct bpf_map *map, void *key))NULL));
11843 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11844 (int (*)(struct bpf_map *map, void *key, void *value,
11846 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11847 (int (*)(struct bpf_map *map, void *value,
11849 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11850 (int (*)(struct bpf_map *map, void *value))NULL));
11851 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11852 (int (*)(struct bpf_map *map, void *value))NULL));
11853 patch_map_ops_generic:
11854 switch (insn->imm) {
11855 case BPF_FUNC_map_lookup_elem:
11856 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11859 case BPF_FUNC_map_update_elem:
11860 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11863 case BPF_FUNC_map_delete_elem:
11864 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11867 case BPF_FUNC_map_push_elem:
11868 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11871 case BPF_FUNC_map_pop_elem:
11872 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11875 case BPF_FUNC_map_peek_elem:
11876 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11881 goto patch_call_imm;
11884 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11885 insn->imm == BPF_FUNC_jiffies64) {
11886 struct bpf_insn ld_jiffies_addr[2] = {
11887 BPF_LD_IMM64(BPF_REG_0,
11888 (unsigned long)&jiffies),
11891 insn_buf[0] = ld_jiffies_addr[0];
11892 insn_buf[1] = ld_jiffies_addr[1];
11893 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11897 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11903 env->prog = prog = new_prog;
11904 insn = new_prog->insnsi + i + delta;
11909 fn = env->ops->get_func_proto(insn->imm, env->prog);
11910 /* all functions that have prototype and verifier allowed
11911 * programs to call them, must be real in-kernel functions
11915 "kernel subsystem misconfigured func %s#%d\n",
11916 func_id_name(insn->imm), insn->imm);
11919 insn->imm = fn->func - __bpf_call_base;
11922 /* Since poke tab is now finalized, publish aux to tracker. */
11923 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11924 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11925 if (!map_ptr->ops->map_poke_track ||
11926 !map_ptr->ops->map_poke_untrack ||
11927 !map_ptr->ops->map_poke_run) {
11928 verbose(env, "bpf verifier is misconfigured\n");
11932 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11934 verbose(env, "tracking tail call prog failed\n");
11942 static void free_states(struct bpf_verifier_env *env)
11944 struct bpf_verifier_state_list *sl, *sln;
11947 sl = env->free_list;
11950 free_verifier_state(&sl->state, false);
11954 env->free_list = NULL;
11956 if (!env->explored_states)
11959 for (i = 0; i < state_htab_size(env); i++) {
11960 sl = env->explored_states[i];
11964 free_verifier_state(&sl->state, false);
11968 env->explored_states[i] = NULL;
11972 static int do_check_common(struct bpf_verifier_env *env, int subprog)
11974 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11975 struct bpf_verifier_state *state;
11976 struct bpf_reg_state *regs;
11979 env->prev_linfo = NULL;
11982 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11985 state->curframe = 0;
11986 state->speculative = false;
11987 state->branches = 1;
11988 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11989 if (!state->frame[0]) {
11993 env->cur_state = state;
11994 init_func_state(env, state->frame[0],
11995 BPF_MAIN_FUNC /* callsite */,
11999 state->first_insn_idx = env->subprog_info[subprog].start;
12000 state->last_insn_idx = -1;
12002 regs = state->frame[state->curframe]->regs;
12003 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
12004 ret = btf_prepare_func_args(env, subprog, regs);
12007 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12008 if (regs[i].type == PTR_TO_CTX)
12009 mark_reg_known_zero(env, regs, i);
12010 else if (regs[i].type == SCALAR_VALUE)
12011 mark_reg_unknown(env, regs, i);
12014 /* 1st arg to a function */
12015 regs[BPF_REG_1].type = PTR_TO_CTX;
12016 mark_reg_known_zero(env, regs, BPF_REG_1);
12017 ret = btf_check_func_arg_match(env, subprog, regs);
12018 if (ret == -EFAULT)
12019 /* unlikely verifier bug. abort.
12020 * ret == 0 and ret < 0 are sadly acceptable for
12021 * main() function due to backward compatibility.
12022 * Like socket filter program may be written as:
12023 * int bpf_prog(struct pt_regs *ctx)
12024 * and never dereference that ctx in the program.
12025 * 'struct pt_regs' is a type mismatch for socket
12026 * filter that should be using 'struct __sk_buff'.
12031 ret = do_check(env);
12033 /* check for NULL is necessary, since cur_state can be freed inside
12034 * do_check() under memory pressure.
12036 if (env->cur_state) {
12037 free_verifier_state(env->cur_state, true);
12038 env->cur_state = NULL;
12040 while (!pop_stack(env, NULL, NULL, false));
12041 if (!ret && pop_log)
12042 bpf_vlog_reset(&env->log, 0);
12047 /* Verify all global functions in a BPF program one by one based on their BTF.
12048 * All global functions must pass verification. Otherwise the whole program is rejected.
12059 * foo() will be verified first for R1=any_scalar_value. During verification it
12060 * will be assumed that bar() already verified successfully and call to bar()
12061 * from foo() will be checked for type match only. Later bar() will be verified
12062 * independently to check that it's safe for R1=any_scalar_value.
12064 static int do_check_subprogs(struct bpf_verifier_env *env)
12066 struct bpf_prog_aux *aux = env->prog->aux;
12069 if (!aux->func_info)
12072 for (i = 1; i < env->subprog_cnt; i++) {
12073 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12075 env->insn_idx = env->subprog_info[i].start;
12076 WARN_ON_ONCE(env->insn_idx == 0);
12077 ret = do_check_common(env, i);
12080 } else if (env->log.level & BPF_LOG_LEVEL) {
12082 "Func#%d is safe for any args that match its prototype\n",
12089 static int do_check_main(struct bpf_verifier_env *env)
12094 ret = do_check_common(env, 0);
12096 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12101 static void print_verification_stats(struct bpf_verifier_env *env)
12105 if (env->log.level & BPF_LOG_STATS) {
12106 verbose(env, "verification time %lld usec\n",
12107 div_u64(env->verification_time, 1000));
12108 verbose(env, "stack depth ");
12109 for (i = 0; i < env->subprog_cnt; i++) {
12110 u32 depth = env->subprog_info[i].stack_depth;
12112 verbose(env, "%d", depth);
12113 if (i + 1 < env->subprog_cnt)
12116 verbose(env, "\n");
12118 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12119 "total_states %d peak_states %d mark_read %d\n",
12120 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12121 env->max_states_per_insn, env->total_states,
12122 env->peak_states, env->longest_mark_read_walk);
12125 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12127 const struct btf_type *t, *func_proto;
12128 const struct bpf_struct_ops *st_ops;
12129 const struct btf_member *member;
12130 struct bpf_prog *prog = env->prog;
12131 u32 btf_id, member_idx;
12134 if (!prog->gpl_compatible) {
12135 verbose(env, "struct ops programs must have a GPL compatible license\n");
12139 btf_id = prog->aux->attach_btf_id;
12140 st_ops = bpf_struct_ops_find(btf_id);
12142 verbose(env, "attach_btf_id %u is not a supported struct\n",
12148 member_idx = prog->expected_attach_type;
12149 if (member_idx >= btf_type_vlen(t)) {
12150 verbose(env, "attach to invalid member idx %u of struct %s\n",
12151 member_idx, st_ops->name);
12155 member = &btf_type_member(t)[member_idx];
12156 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12157 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12160 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12161 mname, member_idx, st_ops->name);
12165 if (st_ops->check_member) {
12166 int err = st_ops->check_member(t, member);
12169 verbose(env, "attach to unsupported member %s of struct %s\n",
12170 mname, st_ops->name);
12175 prog->aux->attach_func_proto = func_proto;
12176 prog->aux->attach_func_name = mname;
12177 env->ops = st_ops->verifier_ops;
12181 #define SECURITY_PREFIX "security_"
12183 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12185 if (within_error_injection_list(addr) ||
12186 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12192 /* non exhaustive list of sleepable bpf_lsm_*() functions */
12193 BTF_SET_START(btf_sleepable_lsm_hooks)
12194 #ifdef CONFIG_BPF_LSM
12195 BTF_ID(func, bpf_lsm_bprm_committed_creds)
12199 BTF_SET_END(btf_sleepable_lsm_hooks)
12201 static int check_sleepable_lsm_hook(u32 btf_id)
12203 return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
12206 /* list of non-sleepable functions that are otherwise on
12207 * ALLOW_ERROR_INJECTION list
12209 BTF_SET_START(btf_non_sleepable_error_inject)
12210 /* Three functions below can be called from sleepable and non-sleepable context.
12211 * Assume non-sleepable from bpf safety point of view.
12213 BTF_ID(func, __add_to_page_cache_locked)
12214 BTF_ID(func, should_fail_alloc_page)
12215 BTF_ID(func, should_failslab)
12216 BTF_SET_END(btf_non_sleepable_error_inject)
12218 static int check_non_sleepable_error_inject(u32 btf_id)
12220 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12223 int bpf_check_attach_target(struct bpf_verifier_log *log,
12224 const struct bpf_prog *prog,
12225 const struct bpf_prog *tgt_prog,
12227 struct bpf_attach_target_info *tgt_info)
12229 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12230 const char prefix[] = "btf_trace_";
12231 int ret = 0, subprog = -1, i;
12232 const struct btf_type *t;
12233 bool conservative = true;
12239 bpf_log(log, "Tracing programs must provide btf_id\n");
12242 btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
12245 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12248 t = btf_type_by_id(btf, btf_id);
12250 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12253 tname = btf_name_by_offset(btf, t->name_off);
12255 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12259 struct bpf_prog_aux *aux = tgt_prog->aux;
12261 for (i = 0; i < aux->func_info_cnt; i++)
12262 if (aux->func_info[i].type_id == btf_id) {
12266 if (subprog == -1) {
12267 bpf_log(log, "Subprog %s doesn't exist\n", tname);
12270 conservative = aux->func_info_aux[subprog].unreliable;
12271 if (prog_extension) {
12272 if (conservative) {
12274 "Cannot replace static functions\n");
12277 if (!prog->jit_requested) {
12279 "Extension programs should be JITed\n");
12283 if (!tgt_prog->jited) {
12284 bpf_log(log, "Can attach to only JITed progs\n");
12287 if (tgt_prog->type == prog->type) {
12288 /* Cannot fentry/fexit another fentry/fexit program.
12289 * Cannot attach program extension to another extension.
12290 * It's ok to attach fentry/fexit to extension program.
12292 bpf_log(log, "Cannot recursively attach\n");
12295 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12297 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12298 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12299 /* Program extensions can extend all program types
12300 * except fentry/fexit. The reason is the following.
12301 * The fentry/fexit programs are used for performance
12302 * analysis, stats and can be attached to any program
12303 * type except themselves. When extension program is
12304 * replacing XDP function it is necessary to allow
12305 * performance analysis of all functions. Both original
12306 * XDP program and its program extension. Hence
12307 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12308 * allowed. If extending of fentry/fexit was allowed it
12309 * would be possible to create long call chain
12310 * fentry->extension->fentry->extension beyond
12311 * reasonable stack size. Hence extending fentry is not
12314 bpf_log(log, "Cannot extend fentry/fexit\n");
12318 if (prog_extension) {
12319 bpf_log(log, "Cannot replace kernel functions\n");
12324 switch (prog->expected_attach_type) {
12325 case BPF_TRACE_RAW_TP:
12328 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12331 if (!btf_type_is_typedef(t)) {
12332 bpf_log(log, "attach_btf_id %u is not a typedef\n",
12336 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12337 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12341 tname += sizeof(prefix) - 1;
12342 t = btf_type_by_id(btf, t->type);
12343 if (!btf_type_is_ptr(t))
12344 /* should never happen in valid vmlinux build */
12346 t = btf_type_by_id(btf, t->type);
12347 if (!btf_type_is_func_proto(t))
12348 /* should never happen in valid vmlinux build */
12352 case BPF_TRACE_ITER:
12353 if (!btf_type_is_func(t)) {
12354 bpf_log(log, "attach_btf_id %u is not a function\n",
12358 t = btf_type_by_id(btf, t->type);
12359 if (!btf_type_is_func_proto(t))
12361 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12366 if (!prog_extension)
12369 case BPF_MODIFY_RETURN:
12371 case BPF_TRACE_FENTRY:
12372 case BPF_TRACE_FEXIT:
12373 if (!btf_type_is_func(t)) {
12374 bpf_log(log, "attach_btf_id %u is not a function\n",
12378 if (prog_extension &&
12379 btf_check_type_match(log, prog, btf, t))
12381 t = btf_type_by_id(btf, t->type);
12382 if (!btf_type_is_func_proto(t))
12385 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12386 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12387 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12390 if (tgt_prog && conservative)
12393 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12399 addr = (long) tgt_prog->bpf_func;
12401 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12403 addr = kallsyms_lookup_name(tname);
12406 "The address of function %s cannot be found\n",
12412 if (prog->aux->sleepable) {
12414 switch (prog->type) {
12415 case BPF_PROG_TYPE_TRACING:
12416 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12417 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12419 if (!check_non_sleepable_error_inject(btf_id) &&
12420 within_error_injection_list(addr))
12423 case BPF_PROG_TYPE_LSM:
12424 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12425 * Only some of them are sleepable.
12427 if (check_sleepable_lsm_hook(btf_id))
12434 bpf_log(log, "%s is not sleepable\n", tname);
12437 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12439 bpf_log(log, "can't modify return codes of BPF programs\n");
12442 ret = check_attach_modify_return(addr, tname);
12444 bpf_log(log, "%s() is not modifiable\n", tname);
12451 tgt_info->tgt_addr = addr;
12452 tgt_info->tgt_name = tname;
12453 tgt_info->tgt_type = t;
12457 static int check_attach_btf_id(struct bpf_verifier_env *env)
12459 struct bpf_prog *prog = env->prog;
12460 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12461 struct bpf_attach_target_info tgt_info = {};
12462 u32 btf_id = prog->aux->attach_btf_id;
12463 struct bpf_trampoline *tr;
12467 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12468 prog->type != BPF_PROG_TYPE_LSM) {
12469 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12473 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12474 return check_struct_ops_btf_id(env);
12476 if (prog->type != BPF_PROG_TYPE_TRACING &&
12477 prog->type != BPF_PROG_TYPE_LSM &&
12478 prog->type != BPF_PROG_TYPE_EXT)
12481 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12485 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12486 /* to make freplace equivalent to their targets, they need to
12487 * inherit env->ops and expected_attach_type for the rest of the
12490 env->ops = bpf_verifier_ops[tgt_prog->type];
12491 prog->expected_attach_type = tgt_prog->expected_attach_type;
12494 /* store info about the attachment target that will be used later */
12495 prog->aux->attach_func_proto = tgt_info.tgt_type;
12496 prog->aux->attach_func_name = tgt_info.tgt_name;
12499 prog->aux->saved_dst_prog_type = tgt_prog->type;
12500 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12503 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12504 prog->aux->attach_btf_trace = true;
12506 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12507 if (!bpf_iter_prog_supported(prog))
12512 if (prog->type == BPF_PROG_TYPE_LSM) {
12513 ret = bpf_lsm_verify_prog(&env->log, prog);
12518 key = bpf_trampoline_compute_key(tgt_prog, btf_id);
12519 tr = bpf_trampoline_get(key, &tgt_info);
12523 prog->aux->dst_trampoline = tr;
12527 struct btf *bpf_get_btf_vmlinux(void)
12529 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12530 mutex_lock(&bpf_verifier_lock);
12532 btf_vmlinux = btf_parse_vmlinux();
12533 mutex_unlock(&bpf_verifier_lock);
12535 return btf_vmlinux;
12538 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12539 union bpf_attr __user *uattr)
12541 u64 start_time = ktime_get_ns();
12542 struct bpf_verifier_env *env;
12543 struct bpf_verifier_log *log;
12544 int i, len, ret = -EINVAL;
12547 /* no program is valid */
12548 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12551 /* 'struct bpf_verifier_env' can be global, but since it's not small,
12552 * allocate/free it every time bpf_check() is called
12554 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12559 len = (*prog)->len;
12560 env->insn_aux_data =
12561 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12563 if (!env->insn_aux_data)
12565 for (i = 0; i < len; i++)
12566 env->insn_aux_data[i].orig_idx = i;
12568 env->ops = bpf_verifier_ops[env->prog->type];
12569 is_priv = bpf_capable();
12571 bpf_get_btf_vmlinux();
12573 /* grab the mutex to protect few globals used by verifier */
12575 mutex_lock(&bpf_verifier_lock);
12577 if (attr->log_level || attr->log_buf || attr->log_size) {
12578 /* user requested verbose verifier output
12579 * and supplied buffer to store the verification trace
12581 log->level = attr->log_level;
12582 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12583 log->len_total = attr->log_size;
12585 /* log attributes have to be sane */
12586 if (!bpf_verifier_log_attr_valid(log)) {
12592 if (IS_ERR(btf_vmlinux)) {
12593 /* Either gcc or pahole or kernel are broken. */
12594 verbose(env, "in-kernel BTF is malformed\n");
12595 ret = PTR_ERR(btf_vmlinux);
12596 goto skip_full_check;
12599 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12600 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12601 env->strict_alignment = true;
12602 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12603 env->strict_alignment = false;
12605 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12606 env->allow_uninit_stack = bpf_allow_uninit_stack();
12607 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12608 env->bypass_spec_v1 = bpf_bypass_spec_v1();
12609 env->bypass_spec_v4 = bpf_bypass_spec_v4();
12610 env->bpf_capable = bpf_capable();
12613 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12615 env->explored_states = kvcalloc(state_htab_size(env),
12616 sizeof(struct bpf_verifier_state_list *),
12619 if (!env->explored_states)
12620 goto skip_full_check;
12622 ret = check_subprogs(env);
12624 goto skip_full_check;
12626 ret = check_btf_info(env, attr, uattr);
12628 goto skip_full_check;
12630 ret = check_attach_btf_id(env);
12632 goto skip_full_check;
12634 ret = resolve_pseudo_ldimm64(env);
12636 goto skip_full_check;
12638 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12639 ret = bpf_prog_offload_verifier_prep(env->prog);
12641 goto skip_full_check;
12644 ret = check_cfg(env);
12646 goto skip_full_check;
12648 ret = do_check_subprogs(env);
12649 ret = ret ?: do_check_main(env);
12651 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12652 ret = bpf_prog_offload_finalize(env);
12655 kvfree(env->explored_states);
12658 ret = check_max_stack_depth(env);
12660 /* instruction rewrites happen after this point */
12663 opt_hard_wire_dead_code_branches(env);
12665 ret = opt_remove_dead_code(env);
12667 ret = opt_remove_nops(env);
12670 sanitize_dead_code(env);
12674 /* program is valid, convert *(u32*)(ctx + off) accesses */
12675 ret = convert_ctx_accesses(env);
12678 ret = fixup_bpf_calls(env);
12680 /* do 32-bit optimization after insn patching has done so those patched
12681 * insns could be handled correctly.
12683 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12684 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12685 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12690 ret = fixup_call_args(env);
12692 env->verification_time = ktime_get_ns() - start_time;
12693 print_verification_stats(env);
12695 if (log->level && bpf_verifier_log_full(log))
12697 if (log->level && !log->ubuf) {
12699 goto err_release_maps;
12702 if (ret == 0 && env->used_map_cnt) {
12703 /* if program passed verifier, update used_maps in bpf_prog_info */
12704 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12705 sizeof(env->used_maps[0]),
12708 if (!env->prog->aux->used_maps) {
12710 goto err_release_maps;
12713 memcpy(env->prog->aux->used_maps, env->used_maps,
12714 sizeof(env->used_maps[0]) * env->used_map_cnt);
12715 env->prog->aux->used_map_cnt = env->used_map_cnt;
12717 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12718 * bpf_ld_imm64 instructions
12720 convert_pseudo_ld_imm64(env);
12724 adjust_btf_func(env);
12727 if (!env->prog->aux->used_maps)
12728 /* if we didn't copy map pointers into bpf_prog_info, release
12729 * them now. Otherwise free_used_maps() will release them.
12733 /* extension progs temporarily inherit the attach_type of their targets
12734 for verification purposes, so set it back to zero before returning
12736 if (env->prog->type == BPF_PROG_TYPE_EXT)
12737 env->prog->expected_attach_type = 0;
12742 mutex_unlock(&bpf_verifier_lock);
12743 vfree(env->insn_aux_data);